forked from FlowwStar/FlowStar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv-parser.ts
More file actions
337 lines (308 loc) · 12.1 KB
/
Copy pathcsv-parser.ts
File metadata and controls
337 lines (308 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
"use client";
/**
* A single row parsed from a batch/airdrop CSV import.
*
* ### Accepted CSV column names & aliases
*
* | Field | Required | Accepted aliases (case-insensitive) |
* |-----------------|----------|---------------------------------------------------------------------------|
* | `recipient` | yes | `recipient`, `recipient_address`, `address`, `to` |
* | `amount` | yes | `amount`, `total_amount`, `stream_amount` |
* | `start_time` | yes * | `start_time`, `start_date`, `start_timestamp` |
* | `end_time` | yes * | `end_time`, `end_date`, `end_timestamp` |
* | `cliff_time` | no | `cliff_time`, `cliff_date`, `cliff_timestamp` |
* | `cliff_amount` | no | `cliff_amount` |
* | `cliff_duration`| no | `cliff_duration`, `cliff_period` — accepts plain seconds or suffixes: `s`, `m`, `h`, `d`, `w` (e.g. `30d`) |
* | `start_date` | no | `start_date`, `start_time` |
* | `end_date` | no | `end_date`, `end_time` |
*
* \* Either `start_time`/`start_date` **or** `end_time`/`end_date` is required.
*
* All string values are raw CSV cell text; conversion to the appropriate
* type (e.g. BigInt for timestamps) happens downstream.
*/
export interface CsvBatchRow {
recipient: string;
amount: string;
start_time: string;
end_time: string;
cliff_time?: string;
cliff_amount?: string;
cliff_duration?: string;
start_date?: string;
end_date?: string;
}
/**
* Result returned by {@link parseCsvBatch}.
*
* @property rows – Successfully parsed rows (may be empty on header-only CSVs).
* @property errors – Human-readable validation error messages, if any.
* @property headerMapping – Map of logical field names to zero-based column indices
* (auto-detected or provided via `customColumnMapping`).
*/
export interface CsvParseResult {
rows: CsvBatchRow[];
errors: string[];
headerMapping?: Record<string, number>;
}
const DURATION_UNIT_SECONDS: Record<string, bigint> = {
s: 1n,
m: 60n,
h: 3600n,
d: 86400n,
w: 604800n,
};
/**
* Parses a relative cliff_duration value into a number of seconds.
* Accepts a plain integer count of seconds ("2592000") or a single unit
* suffix — s(econds), m(inutes), h(ours), d(ays), w(eeks) — e.g. "30d",
* "12h", "90m", "2w", "45s". Returns null when the value is unparseable.
*/
export function parseDuration(value: string): bigint | null {
const trimmed = value.trim().toLowerCase();
if (!trimmed) return null;
if (/^\d+$/.test(trimmed)) {
return BigInt(trimmed);
}
const match = trimmed.match(/^(\d+)\s*([smhdw])$/);
if (!match) return null;
return BigInt(match[1]) * DURATION_UNIT_SECONDS[match[2]];
}
/**
* Maps each logical CSV field to the list of accepted header aliases.
*
* During auto-detection, headers are matched case-insensitively against
* these lists in order; the first match wins. This lets users write
* headers like `to`, `address`, or `recipient_address` and have them
* all resolve to the `recipient` field.
*/
const HEADER_ALIASES = {
recipient: ["recipient", "recipient_address", "address", "to"],
amount: ["amount", "total_amount", "stream_amount"],
start_time: ["start_time", "start_date", "start_timestamp"],
end_time: ["end_time", "end_date", "end_timestamp"],
cliff_time: ["cliff_time", "cliff_date", "cliff_timestamp"],
cliff_amount: ["cliff_amount"],
cliff_duration: ["cliff_duration", "cliff_period"],
start_date: ["start_date", "start_time"],
end_date: ["end_date", "end_time"],
};
/**
* Parses a single CSV line into an array of trimmed cell values.
*
* Handles quoted fields (double-quote escaping: `""` inside a quoted field
* represents a literal `"`) and respects the CSV spec where commas inside
* quoted fields are not treated as delimiters.
*
* @param line – One line of CSV text (without the line terminator).
* @returns – Array of trimmed string values, one per column.
*/
function parseCsvLine(line: string): string[] {
const values: string[] = [];
let current = "";
let inQuotes = false;
for (let i = 0; i < line.length; i += 1) {
const char = line[i];
if (char === '"') {
const nextChar = line[i + 1];
if (inQuotes && nextChar === '"') {
current += '"';
i += 1;
} else {
inQuotes = !inQuotes;
}
continue;
}
if (char === "," && !inQuotes) {
values.push(current);
current = "";
continue;
}
current += char;
}
values.push(current);
return values.map((value) => value.trim());
}
/**
* Finds the zero-based column index for a logical field name.
*
* Normalises every header to lowercase, then tries each alias for
* `fieldName` (from {@link HEADER_ALIASES}) in order. Returns `-1`
* when no alias matches.
*
* @param headers – Raw header row values (as returned by {@link parseCsvLine}).
* @param fieldName – Logical field name whose alias list to search.
*/
function findColumnIndex(headers: string[], fieldName: string): number {
const normalized = headers.map((h) => h.trim().toLowerCase());
const aliases =
HEADER_ALIASES[fieldName as keyof typeof HEADER_ALIASES] || [];
for (const alias of aliases) {
const index = normalized.indexOf(alias);
if (index !== -1) return index;
}
return -1;
}
/**
* Resolves a cliff timestamp (in seconds) from a parsed CSV row.
*
* Priority:
* 1. `cliff_time` — an absolute timestamp (unix seconds or ISO date string).
* If present and parseable, it is returned directly.
* 2. `cliff_duration` — a relative offset from `startTime`.
* If present and parseable, `startTime + duration` is returned.
* 3. Neither present → returns null (no cliff).
*
* `parseTimestampFn` is injected so this pure helper has no dependency on
* browser/Node APIs; callers supply their own timestamp parser.
*/
export function resolveCliffTime(
row: Pick<CsvBatchRow, "cliff_time" | "cliff_duration">,
startTime: bigint | null,
parseTimestampFn: (value: string) => bigint | null,
): bigint | null {
if (row.cliff_time) {
return parseTimestampFn(row.cliff_time);
}
if (row.cliff_duration && startTime !== null) {
const duration = parseDuration(row.cliff_duration);
if (duration !== null) return startTime + duration;
}
return null;
}
/**
* Parses a CSV string into an array of batch payment rows with optional column mapping.
*
* @param csvText The raw CSV text to parse. Supports both \n and \r\n line endings.
* @param customColumnMapping Optional pre-defined column indices. When provided, skips header detection
* and uses these exact positions instead. Useful when the CSV has no header row
* or when automatic detection fails.
*
* @returns A CsvParseResult object containing:
* - rows: Array of parsed CsvBatchRow objects with extracted fields
* - errors: Array of validation error messages encountered during parsing
* - headerMapping: Record mapping field names to their column indices (auto-detected or custom)
*
* @description
* This function implements flexible CSV parsing with support for multiple header naming conventions:
*
* **Supported Header Aliases:**
* - recipient: "recipient", "recipient_address", "address", "to"
* - amount: "amount", "total_amount", "stream_amount"
* - start_time: "start_time", "start_date", "start_timestamp"
* - end_time: "end_time", "end_date", "end_timestamp"
* - cliff_time: "cliff_time", "cliff_date", "cliff_timestamp"
* - cliff_amount: "cliff_amount"
* - cliff_duration: "cliff_duration", "cliff_period"
* - start_date: "start_date", "start_time"
* - end_date: "end_date", "end_time"
*
* **Column Mapping/Detection Logic:**
* 1. Normalizes all headers to lowercase and trims whitespace
* 2. Matches each header against its field's alias list (case-insensitive)
* 3. Returns the index of the first matching alias
* 4. Auto-detection only occurs when customColumnMapping is not provided
* 5. If no matching header is found for a field, returns -1 (indicating not present)
* 6. Required columns (recipient, amount, start_time/start_date, end_time/end_date) are validated;
* missing required columns trigger an error
*
* **Malformed Input Handling:**
* - Empty CSV strings return empty rows array with no errors
* - CSV lines with mismatched column counts are returned as-is (trailing columns are undefined)
* - Invalid headers that don't match any field aliases trigger validation error
* - Missing required columns are reported in errors array; rows array remains empty
* - All errors are descriptive and can be used for user feedback
*/
export function parseCsvBatch(
csvText: string,
customColumnMapping?: Record<string, number>,
): CsvParseResult {
const lines = csvText
.replace(/\r\n/g, "\n")
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0);
const errors: string[] = [];
const rows: CsvBatchRow[] = [];
if (lines.length === 0) {
return { rows, errors };
}
let startIndex = 0;
let headerMapping: Record<string, number> = customColumnMapping ?? {};
const firstRow = parseCsvLine(lines[0]);
const firstRowLower = firstRow.map((v) => v.toLowerCase());
// Check if first row looks like a header
const isLikelyHeader = firstRowLower.some((v) =>
Object.values(HEADER_ALIASES).some((aliases) =>
aliases.some((alias) => v === alias),
),
);
if (isLikelyHeader && !customColumnMapping) {
startIndex = 1;
// Auto-detect column mapping
headerMapping = {
recipient: findColumnIndex(firstRow, "recipient"),
amount: findColumnIndex(firstRow, "amount"),
start_time: findColumnIndex(firstRow, "start_time"),
end_time: findColumnIndex(firstRow, "end_time"),
cliff_time: findColumnIndex(firstRow, "cliff_time"),
cliff_amount: findColumnIndex(firstRow, "cliff_amount"),
cliff_duration: findColumnIndex(firstRow, "cliff_duration"),
start_date: findColumnIndex(firstRow, "start_date"),
end_date: findColumnIndex(firstRow, "end_date"),
};
// Validate required columns exist
if (
headerMapping.recipient === -1 ||
headerMapping.amount === -1 ||
(headerMapping.start_time === -1 && headerMapping.start_date === -1) ||
(headerMapping.end_time === -1 && headerMapping.end_date === -1)
) {
errors.push(
"CSV must have columns for recipient, amount, and start/end times (start_time/start_date and end_time/end_date)",
);
return { rows, errors, headerMapping };
}
}
// Parse data rows
for (let index = startIndex; index < lines.length; index += 1) {
const rowNumber = index + 1;
const values = parseCsvLine(lines[index]);
const row: CsvBatchRow = {
recipient: values[headerMapping.recipient ?? 0] ?? "",
amount: values[headerMapping.amount ?? 1] ?? "",
start_time: values[headerMapping.start_time ?? 2] ?? "",
end_time: values[headerMapping.end_time ?? 3] ?? "",
};
// Add optional fields if mapped
if (
headerMapping.cliff_time !== undefined &&
headerMapping.cliff_time !== -1
) {
row.cliff_time = values[headerMapping.cliff_time];
}
if (
headerMapping.cliff_amount !== undefined &&
headerMapping.cliff_amount !== -1
) {
row.cliff_amount = values[headerMapping.cliff_amount];
}
if (
headerMapping.cliff_duration !== undefined &&
headerMapping.cliff_duration !== -1
) {
row.cliff_duration = values[headerMapping.cliff_duration];
}
if (
headerMapping.start_date !== undefined &&
headerMapping.start_date !== -1
) {
row.start_date = values[headerMapping.start_date];
}
if (headerMapping.end_date !== undefined && headerMapping.end_date !== -1) {
row.end_date = values[headerMapping.end_date];
}
rows.push(row);
}
return { rows, errors, headerMapping };
}