edf2csv 0.5.43 → 0.5.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,52 @@
3
3
  Notable changes to edf2csv. Versions follow [semantic versioning](https://semver.org); while the
4
4
  major version is 0, a minor bump may contain breaking changes.
5
5
 
6
+ ## 0.5.45
7
+
8
+ ### Fixed: 0.5.36 let a full disk take the process down with a raw stack trace
9
+
10
+ The listener that turns a stream failure into a message came off one tick too early. An
11
+ `fs.WriteStream` whose write failed emits `'error'` a second time during its own auto-destroy,
12
+ after `end()`'s callback has settled — and 0.5.36 released the listener at that callback. So a
13
+ destination that filled up during the final flush produced this:
14
+
15
+ ```
16
+ node:events:485
17
+ throw er; // Unhandled 'error' event
18
+ ^
19
+ Error: ENOSPC: no space left on device, write
20
+ ```
21
+
22
+ The process down, no `WRITE_FAILED` line, `signals.csv` truncated with no `channels.csv`
23
+ beside it and nothing saying so, and `convert()` never rejecting — a library caller's
24
+ try/catch bypassed and their process taken with it. Which is, word for word, the failure the
25
+ constructor's comment says this listener exists to prevent.
26
+
27
+ Released only from `process.stdout` and `process.stderr` now. Those are the streams that
28
+ outlive the writer, and the leak 0.5.36 fixed was only ever about them; a stream this writer
29
+ opened is finished with and about to be collected, so a listener left on it leaks nothing.
30
+
31
+ The existing disk-full tests missed it because a conversion that overshoots by a lot fails in
32
+ a mid-stream flush and reports correctly. Leaving a little under the whole output free is what
33
+ puts the failure in the last flush, and that is what the new test does.
34
+
35
+ ## 0.5.44
36
+
37
+ ### Fixed: `--info` promised nothing for a recording that converts to three files
38
+
39
+ "Would write 0 rows, roughly 0 B." — for a recording holding only EDF+ annotations, which
40
+ goes on to write `annotations.csv` with its events in it, `channels.csv`, and
41
+ `metadata.json`.
42
+
43
+ That is the sentence 0.4.51 removed, arriving by the other route. It asked only whether
44
+ `--annotations-only` had been given; a recording that simply has no signal channels has no
45
+ rate groups either, and fell past the check to the estimate line. `--info` exists to say what
46
+ a conversion will do, so asserting it will write nothing when it will write three files is
47
+ the one thing it must not do — which is what that entry said when it fixed the first route.
48
+
49
+ Both reach the same sentence now: "Would write annotations.csv and channels.csv, and no
50
+ signal data. How many events there are cannot be told from the header."
51
+
6
52
  ## 0.5.43
7
53
 
8
54
  ### Fixed: 0.5.40 made `--stdout` refuse a recording named twice, quoting a folder nobody named
@@ -142,7 +142,16 @@ export function formatInfo(file, plan) {
142
142
  to be read record by record, which is the scan --info is for avoiding. So it says which
143
143
  file, and that the count is not knowable this cheaply, rather than inventing a zero.
144
144
  */
145
- if (!plan.writeSignals) {
145
+ /*
146
+ No signal table to describe, whichever way that came about.
147
+
148
+ This asked only whether `--annotations-only` had been given. A recording that has no
149
+ signal channels — one holding nothing but EDF+ annotations — has none either, and fell
150
+ through to the estimate line: "Would write 0 rows, roughly 0 B." for a conversion that
151
+ goes on to write an annotations.csv with events in it, beside channels.csv and
152
+ metadata.json. That is the sentence 0.4.51 removed, arriving by the other route.
153
+ */
154
+ if (!plan.writeSignals || plan.groups.length === 0) {
146
155
  // Named as they will be written. --info is read to find out what a run leaves behind,
147
156
  // and a script that opens the name it was given must find a file there.
148
157
  const suffix = plan.gzip ? '.csv.gz' : '.csv';
@@ -1 +1 @@
1
- {"version":3,"file":"report.js","sourceRoot":"","sources":["../../src/cli/report.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAChF,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAElE,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAG5D,SAAS,KAAK,CAAC,IAAoC,EAAE,UAA+B;IAClF,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IACjC,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,GAA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AE,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;KACtG,EACD,IAAI,EACJ,MAAM,IAAI,SAAS,CACpB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Human-readable output for the terminal.\n *\n * Everything here is plain text with no colour codes, so piping to a file or a log\n * produces exactly what appeared on screen.\n */\n\nimport type { Diagnostic } from '../edf/errors.js';\nimport type { EdfFile } from '../edf/reader.js';\nimport { describeFormat, formatRates, formatWallClock } from '../edf/header.js';\nimport { formatBytes, formatDuration } from '../format/number.js';\nimport type { ConversionPlan } from '../convert/plan.js';\nimport { withoutFileRateWarning } from '../convert/plan.js';\nimport type { ConvertResult } from '../convert/run.js';\n\nfunction table(rows: readonly (readonly string[])[], alignRight: ReadonlySet<number>): string {\n if (rows.length === 0) return '';\n const width: number[] = [];\n for (const row of rows) {\n row.forEach((cell, i) => {\n width[i] = Math.max(width[i] ?? 0, cell.length);\n });\n }\n return rows\n .map((row) =>\n row\n .map((cell, i) => {\n const w = width[i] ?? 0;\n return alignRight.has(i) ? cell.padStart(w) : cell.padEnd(w);\n })\n .join(' ')\n .trimEnd(),\n )\n .join('\\n');\n}\n\n/**\n * Make header text safe to print to a terminal.\n *\n * EDF identification fields and channel labels are free text copied verbatim out of the\n * file, and `--info` puts them straight on stdout. A header carrying ANSI escapes could\n * therefore drive the reader's terminal — `\\x1b[2J\\x1b[H` clears the screen and homes the\n * cursor, which is enough to hide the rest of the output or repaint it as something else.\n * Nobody writes an EDF header that way on purpose, which is exactly why a file that does\n * should not be trusted with the terminal.\n *\n * Control bytes are shown as their escape instead, so a corrupt field stays diagnosable\n * rather than being silently swallowed. This affects display only: `channels.csv` and\n * `metadata.json` still copy the field verbatim, and CSV quoting already makes that safe.\n */\nexport function printable(text: string): string {\n // eslint-disable-next-line no-control-regex\n return text.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/gu, (c) =>\n `\\\\x${c.codePointAt(0)!.toString(16).padStart(2, '0')}`,\n );\n}\n\n/**\n * The same protection for text that is meant to span lines.\n *\n * `printable` escapes newlines along with everything else, which is right for a channel\n * label — one has no business containing a line break, and it would break the `--info`\n * table's alignment. It is wrong for a whole message: several are written on two lines,\n * and Node's own option errors run to three. Escaping those turned the break into text:\n *\n * error: No channel named \"ECQ\". Did you mean \"ECG\"?\\x0aRun with --info to list ...\n *\n * Each line is escaped on its own, so nothing here gains the ability to drive a terminal.\n * A carriage return is still escaped, so no line can be repainted after it is printed —\n * which is the property that mattered. A newline can only add a line, never overwrite one.\n */\nexport function printableLines(text: string, indent = ''): string {\n return text\n .split('\\n')\n .map((line, index) => (index === 0 ? '' : indent) + printable(line))\n .join('\\n');\n}\n\n/** The `--info` view: what is in this recording, and what would converting it produce. */\nexport function formatInfo(file: EdfFile, plan: ConversionPlan): string {\n const { header } = file;\n const lines: string[] = [];\n\n lines.push(`File ${file.path}`);\n lines.push(`Format ${describeFormat(header)}`);\n lines.push(\n `Recorded ${\n formatWallClock(header.startDateTime)?.replace('T', ' ') ??\n `${printable(header.startDateRaw)} ${printable(header.startTimeRaw)} (unparseable)`\n }`,\n );\n lines.push(\n `Duration ${formatDuration(file.durationSeconds)} (${file.recordCount} records of ${header.recordDuration}s)`,\n );\n const elapsedSpan = plan.range.recordingEndSeconds - plan.range.recordingStartSeconds;\n if (Math.abs(elapsedSpan - file.durationSeconds) > 1e-9) {\n lines.push(`Time span ${formatDuration(elapsedSpan)} (includes discontinuities)`);\n }\n lines.push(`Size ${formatBytes(file.fileSize)}`);\n if (header.patientId) lines.push(`Patient ${printable(header.patientId)}`);\n if (header.recordingId) lines.push(`Recording ${printable(header.recordingId)}`);\n\n const signals = file.dataSignals;\n lines.push('');\n // The signal count was pluralised but the annotation-channel count was not, so a file\n // carrying two of them read \"2 annotation channel\". EDF+ permits more than one.\n const annotationCount = file.annotationSignals.length;\n const annotationPart =\n annotationCount > 0\n ? ` + ${annotationCount} annotation channel${annotationCount === 1 ? '' : 's'}`\n : '';\n lines.push(\n `Channels ${signals.length} signal${signals.length === 1 ? '' : 's'}${annotationPart}`,\n );\n lines.push('');\n\n const rows: string[][] = [['#', 'COLUMN', 'LABEL', 'UNIT', 'RATE', 'RANGE', 'OUTPUT']];\n const fileFor = new Map<number, string>();\n for (const group of plan.groups) {\n for (const channel of group.channels) fileFor.set(channel.signal.index, group.fileName);\n }\n // Rendered as a group so that two channels recorded at different rates never show the\n // same figure in the RATE column, which is the one thing this table is asked to settle.\n const rateText = formatRates(signals.map((signal) => signal.samplingRate));\n for (const [row, signal] of signals.entries()) {\n rows.push([\n String(signal.index),\n printable(plan.columnNames.get(signal.index) ?? ''),\n printable(signal.label),\n printable(signal.physicalDimension),\n `${rateText[row]} Hz`,\n `${signal.physicalMin} to ${signal.physicalMax}`,\n /*\n A channel with no samples was reported as \"(not selected)\", which is a different\n thing and not true when it was named on --channels. `edf2csv rec.edf --info\n --channels unused` said the channel the command asked for had not been chosen, when\n what is actually the case is that the file gives it nothing to convert. The\n NO_SAMPLES warning below the table says so; the table contradicted it.\n */\n fileFor.get(signal.index) ??\n (signal.samplesPerRecord === 0 ? '(no samples)' : '(not selected)'),\n ]);\n }\n lines.push(table(rows, new Set([0])));\n\n lines.push('');\n if (plan.groups.length > 1) {\n lines.push(\n plan.layout === 'long'\n ? `Sampling rates differ, and the long layout puts them in one table anyway: each row ` +\n `carries its own time, so nothing has to line up. No channel is resampled.`\n : `Sampling rates differ, so channels are written to ${plan.groups.length} files, one per rate. ` +\n `No channel is resampled.`,\n );\n }\n /*\n The estimate describes the signal tables, and says so when that is not what will be\n written.\n\n Under --annotations-only there are no signal tables, and the line read \"Would write 0\n rows, roughly 0 B.\" for a conversion that goes on to write annotations.csv with three\n events in it. --info exists to say what a conversion will do; asserting it will write\n nothing, when it will write a file, is the one thing it must not do.\n\n How many events there are cannot be answered from the header — the annotation channel has\n to be read record by record, which is the scan --info is for avoiding. So it says which\n file, and that the count is not knowable this cheaply, rather than inventing a zero.\n */\n if (!plan.writeSignals) {\n // Named as they will be written. --info is read to find out what a run leaves behind,\n // and a script that opens the name it was given must find a file there.\n const suffix = plan.gzip ? '.csv.gz' : '.csv';\n lines.push(\n file.annotationSignals.length > 0\n ? `Would write annotations${suffix} and channels${suffix}, and no signal data. How ` +\n 'many events there are cannot be told from the header.'\n : `Would write channels${suffix} and no signal data — and no annotations${suffix} ` +\n 'either, since this recording has no annotation channel.',\n );\n return lines.join('\\n');\n }\n\n // The estimate counts the characters of the CSV, which is what --gzip then compresses.\n // Reporting it as the size on disk would overstate a compressed conversion several-fold.\n const compressing = plan.gzip;\n lines.push(\n `Would write ${plan.estimate.rows.toLocaleString('en-US')} rows, roughly ` +\n `${formatBytes(plan.estimate.bytes)}${compressing ? ' before compression' : ''}.`,\n );\n\n return lines.join('\\n');\n}\n\n/**\n * The `--info` view as JSON, for surveying files from a script.\n *\n * `indent` is 2 for a single recording, matching what this has always printed, and null for\n * a batch — several pretty-printed documents run together are readable by a streaming parser\n * but not by anything that expects one record per line, and a batch is exactly where\n * line-oriented reading is wanted. null rather than undefined because a default parameter\n * takes effect when undefined is passed, which quietly restored the indentation this was\n * meant to drop; JSON.stringify itself wants undefined, so it is translated at the call.\n *\n * `--info` answers \"what is in this recording and what would converting it cost\", which\n * is exactly the question you want to ask across a directory of hundreds of recordings —\n * and the text table is the wrong shape for that. `--json` previously applied only to\n * conversions, so scripts had to parse the aligned columns or convert files just to learn\n * what was in them.\n *\n * Field names match `metadata.json` where the two describe the same thing, so a survey and\n * a conversion can be read by the same code.\n */\nexport function infoJson(file: EdfFile, plan: ConversionPlan, indent: number | null = 2): string {\n const { header } = file;\n const fileFor = new Map<number, string>();\n for (const group of plan.groups) {\n for (const channel of group.channels) fileFor.set(channel.signal.index, group.fileName);\n }\n\n return JSON.stringify(\n {\n path: file.path,\n bytes: file.fileSize,\n format: describeFormat(header),\n start_datetime_local: formatWallClock(header.startDateTime),\n start_date_raw: header.startDateRaw,\n start_time_raw: header.startTimeRaw,\n patient_id: header.patientId,\n recording_id: header.recordingId,\n data_records: file.recordCount,\n data_records_declared: header.declaredRecordCount,\n record_duration_seconds: header.recordDuration,\n duration_seconds: file.durationSeconds,\n // For a discontinuous file this exceeds duration_seconds by the length of the gaps.\n time_span_seconds: plan.range.recordingEndSeconds - plan.range.recordingStartSeconds,\n annotation_channels: file.annotationSignals.length,\n channels: file.dataSignals.map((signal) => ({\n signal_index: signal.index,\n column: plan.columnNames.get(signal.index) ?? '',\n label: signal.label,\n unit: signal.physicalDimension,\n sampling_rate_hz: signal.samplingRate,\n samples_per_record: signal.samplesPerRecord,\n physical_min: signal.physicalMin,\n physical_max: signal.physicalMax,\n digital_min: signal.digitalMin,\n digital_max: signal.digitalMax,\n transducer: signal.transducer,\n prefiltering: signal.prefiltering,\n output_file: fileFor.get(signal.index) ?? null,\n })),\n estimate: {\n rows: plan.estimate.rows,\n // Character count of the CSV. With --gzip the file on disk is smaller than this.\n bytes: plan.estimate.bytes,\n exceeds_spreadsheet_limit: plan.estimate.exceedsSpreadsheetLimit,\n },\n // The plan's mixed-rate warning replaces the header parser's, as it does everywhere\n // else. This was the one consumer left out of that when 0.3.2 made the warning follow\n // --channels, so `--info --json` carried it twice: once counting the rates being\n // converted and once counting every rate in the file, with the same code and severity.\n warnings: plan.diagnostics\n .concat(withoutFileRateWarning(file.diagnostics))\n .map((d) => ({ code: d.code, severity: d.severity, message: d.message })),\n },\n null,\n indent ?? undefined,\n );\n}\n\n/** One line per diagnostic, prefixed so warnings are greppable. */\nexport function formatDiagnostics(diagnostics: readonly Diagnostic[]): string {\n return diagnostics\n .map((d) => {\n // Diagnostics quote channel labels, which come from the file, so they need the\n // same treatment as the --info table.\n const head = `${d.severity === 'warning' ? 'warning' : 'note'}: ${printable(d.message)}`;\n return d.hint ? `${head}\\n ${printable(d.hint)}` : head;\n })\n .join('\\n');\n}\n\nexport function formatSummary(result: ConvertResult): string {\n const lines: string[] = [];\n const rows: string[][] = [];\n for (const file of result.files) {\n // `.csv.gz` is still a CSV, and its rows are still rows. The suffix test dropped the\n // unit from every line of a --gzip summary, so the numbers stood on their own.\n rows.push([\n ` ${file.name}`,\n file.rows.toLocaleString('en-US'),\n /\\.csv(\\.gz)?$/u.test(file.name) ? 'rows' : '',\n ]);\n }\n lines.push(`Wrote ${result.outputDir}`);\n lines.push(table(rows, new Set([1])));\n lines.push(`Done in ${(result.elapsedMs / 1000).toFixed(1)}s.`);\n return lines.join('\\n');\n}\n\nexport function summaryJson(result: ConvertResult, indent: number | null = 2): string {\n return JSON.stringify(\n {\n output_dir: result.outputDir,\n files: result.files,\n annotations: result.annotationCount,\n duration_seconds: result.file.durationSeconds,\n records: result.file.recordCount,\n elapsed_ms: result.elapsedMs,\n warnings: result.diagnostics.map((d) => ({ code: d.code, severity: d.severity, message: d.message })),\n },\n null,\n indent ?? undefined,\n );\n}\n"]}
1
+ {"version":3,"file":"report.js","sourceRoot":"","sources":["../../src/cli/report.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAChF,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAElE,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAG5D,SAAS,KAAK,CAAC,IAAoC,EAAE,UAA+B;IAClF,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IACjC,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,GAAG,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE;YACtB,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC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AC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;KACtG,EACD,IAAI,EACJ,MAAM,IAAI,SAAS,CACpB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Human-readable output for the terminal.\n *\n * Everything here is plain text with no colour codes, so piping to a file or a log\n * produces exactly what appeared on screen.\n */\n\nimport type { Diagnostic } from '../edf/errors.js';\nimport type { EdfFile } from '../edf/reader.js';\nimport { describeFormat, formatRates, formatWallClock } from '../edf/header.js';\nimport { formatBytes, formatDuration } from '../format/number.js';\nimport type { ConversionPlan } from '../convert/plan.js';\nimport { withoutFileRateWarning } from '../convert/plan.js';\nimport type { ConvertResult } from '../convert/run.js';\n\nfunction table(rows: readonly (readonly string[])[], alignRight: ReadonlySet<number>): string {\n if (rows.length === 0) return '';\n const width: number[] = [];\n for (const row of rows) {\n row.forEach((cell, i) => {\n width[i] = Math.max(width[i] ?? 0, cell.length);\n });\n }\n return rows\n .map((row) =>\n row\n .map((cell, i) => {\n const w = width[i] ?? 0;\n return alignRight.has(i) ? cell.padStart(w) : cell.padEnd(w);\n })\n .join(' ')\n .trimEnd(),\n )\n .join('\\n');\n}\n\n/**\n * Make header text safe to print to a terminal.\n *\n * EDF identification fields and channel labels are free text copied verbatim out of the\n * file, and `--info` puts them straight on stdout. A header carrying ANSI escapes could\n * therefore drive the reader's terminal — `\\x1b[2J\\x1b[H` clears the screen and homes the\n * cursor, which is enough to hide the rest of the output or repaint it as something else.\n * Nobody writes an EDF header that way on purpose, which is exactly why a file that does\n * should not be trusted with the terminal.\n *\n * Control bytes are shown as their escape instead, so a corrupt field stays diagnosable\n * rather than being silently swallowed. This affects display only: `channels.csv` and\n * `metadata.json` still copy the field verbatim, and CSV quoting already makes that safe.\n */\nexport function printable(text: string): string {\n // eslint-disable-next-line no-control-regex\n return text.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/gu, (c) =>\n `\\\\x${c.codePointAt(0)!.toString(16).padStart(2, '0')}`,\n );\n}\n\n/**\n * The same protection for text that is meant to span lines.\n *\n * `printable` escapes newlines along with everything else, which is right for a channel\n * label — one has no business containing a line break, and it would break the `--info`\n * table's alignment. It is wrong for a whole message: several are written on two lines,\n * and Node's own option errors run to three. Escaping those turned the break into text:\n *\n * error: No channel named \"ECQ\". Did you mean \"ECG\"?\\x0aRun with --info to list ...\n *\n * Each line is escaped on its own, so nothing here gains the ability to drive a terminal.\n * A carriage return is still escaped, so no line can be repainted after it is printed —\n * which is the property that mattered. A newline can only add a line, never overwrite one.\n */\nexport function printableLines(text: string, indent = ''): string {\n return text\n .split('\\n')\n .map((line, index) => (index === 0 ? '' : indent) + printable(line))\n .join('\\n');\n}\n\n/** The `--info` view: what is in this recording, and what would converting it produce. */\nexport function formatInfo(file: EdfFile, plan: ConversionPlan): string {\n const { header } = file;\n const lines: string[] = [];\n\n lines.push(`File ${file.path}`);\n lines.push(`Format ${describeFormat(header)}`);\n lines.push(\n `Recorded ${\n formatWallClock(header.startDateTime)?.replace('T', ' ') ??\n `${printable(header.startDateRaw)} ${printable(header.startTimeRaw)} (unparseable)`\n }`,\n );\n lines.push(\n `Duration ${formatDuration(file.durationSeconds)} (${file.recordCount} records of ${header.recordDuration}s)`,\n );\n const elapsedSpan = plan.range.recordingEndSeconds - plan.range.recordingStartSeconds;\n if (Math.abs(elapsedSpan - file.durationSeconds) > 1e-9) {\n lines.push(`Time span ${formatDuration(elapsedSpan)} (includes discontinuities)`);\n }\n lines.push(`Size ${formatBytes(file.fileSize)}`);\n if (header.patientId) lines.push(`Patient ${printable(header.patientId)}`);\n if (header.recordingId) lines.push(`Recording ${printable(header.recordingId)}`);\n\n const signals = file.dataSignals;\n lines.push('');\n // The signal count was pluralised but the annotation-channel count was not, so a file\n // carrying two of them read \"2 annotation channel\". EDF+ permits more than one.\n const annotationCount = file.annotationSignals.length;\n const annotationPart =\n annotationCount > 0\n ? ` + ${annotationCount} annotation channel${annotationCount === 1 ? '' : 's'}`\n : '';\n lines.push(\n `Channels ${signals.length} signal${signals.length === 1 ? '' : 's'}${annotationPart}`,\n );\n lines.push('');\n\n const rows: string[][] = [['#', 'COLUMN', 'LABEL', 'UNIT', 'RATE', 'RANGE', 'OUTPUT']];\n const fileFor = new Map<number, string>();\n for (const group of plan.groups) {\n for (const channel of group.channels) fileFor.set(channel.signal.index, group.fileName);\n }\n // Rendered as a group so that two channels recorded at different rates never show the\n // same figure in the RATE column, which is the one thing this table is asked to settle.\n const rateText = formatRates(signals.map((signal) => signal.samplingRate));\n for (const [row, signal] of signals.entries()) {\n rows.push([\n String(signal.index),\n printable(plan.columnNames.get(signal.index) ?? ''),\n printable(signal.label),\n printable(signal.physicalDimension),\n `${rateText[row]} Hz`,\n `${signal.physicalMin} to ${signal.physicalMax}`,\n /*\n A channel with no samples was reported as \"(not selected)\", which is a different\n thing and not true when it was named on --channels. `edf2csv rec.edf --info\n --channels unused` said the channel the command asked for had not been chosen, when\n what is actually the case is that the file gives it nothing to convert. The\n NO_SAMPLES warning below the table says so; the table contradicted it.\n */\n fileFor.get(signal.index) ??\n (signal.samplesPerRecord === 0 ? '(no samples)' : '(not selected)'),\n ]);\n }\n lines.push(table(rows, new Set([0])));\n\n lines.push('');\n if (plan.groups.length > 1) {\n lines.push(\n plan.layout === 'long'\n ? `Sampling rates differ, and the long layout puts them in one table anyway: each row ` +\n `carries its own time, so nothing has to line up. No channel is resampled.`\n : `Sampling rates differ, so channels are written to ${plan.groups.length} files, one per rate. ` +\n `No channel is resampled.`,\n );\n }\n /*\n The estimate describes the signal tables, and says so when that is not what will be\n written.\n\n Under --annotations-only there are no signal tables, and the line read \"Would write 0\n rows, roughly 0 B.\" for a conversion that goes on to write annotations.csv with three\n events in it. --info exists to say what a conversion will do; asserting it will write\n nothing, when it will write a file, is the one thing it must not do.\n\n How many events there are cannot be answered from the header — the annotation channel has\n to be read record by record, which is the scan --info is for avoiding. So it says which\n file, and that the count is not knowable this cheaply, rather than inventing a zero.\n */\n /*\n No signal table to describe, whichever way that came about.\n\n This asked only whether `--annotations-only` had been given. A recording that has no\n signal channels — one holding nothing but EDF+ annotations — has none either, and fell\n through to the estimate line: \"Would write 0 rows, roughly 0 B.\" for a conversion that\n goes on to write an annotations.csv with events in it, beside channels.csv and\n metadata.json. That is the sentence 0.4.51 removed, arriving by the other route.\n */\n if (!plan.writeSignals || plan.groups.length === 0) {\n // Named as they will be written. --info is read to find out what a run leaves behind,\n // and a script that opens the name it was given must find a file there.\n const suffix = plan.gzip ? '.csv.gz' : '.csv';\n lines.push(\n file.annotationSignals.length > 0\n ? `Would write annotations${suffix} and channels${suffix}, and no signal data. How ` +\n 'many events there are cannot be told from the header.'\n : `Would write channels${suffix} and no signal data — and no annotations${suffix} ` +\n 'either, since this recording has no annotation channel.',\n );\n return lines.join('\\n');\n }\n\n // The estimate counts the characters of the CSV, which is what --gzip then compresses.\n // Reporting it as the size on disk would overstate a compressed conversion several-fold.\n const compressing = plan.gzip;\n lines.push(\n `Would write ${plan.estimate.rows.toLocaleString('en-US')} rows, roughly ` +\n `${formatBytes(plan.estimate.bytes)}${compressing ? ' before compression' : ''}.`,\n );\n\n return lines.join('\\n');\n}\n\n/**\n * The `--info` view as JSON, for surveying files from a script.\n *\n * `indent` is 2 for a single recording, matching what this has always printed, and null for\n * a batch — several pretty-printed documents run together are readable by a streaming parser\n * but not by anything that expects one record per line, and a batch is exactly where\n * line-oriented reading is wanted. null rather than undefined because a default parameter\n * takes effect when undefined is passed, which quietly restored the indentation this was\n * meant to drop; JSON.stringify itself wants undefined, so it is translated at the call.\n *\n * `--info` answers \"what is in this recording and what would converting it cost\", which\n * is exactly the question you want to ask across a directory of hundreds of recordings —\n * and the text table is the wrong shape for that. `--json` previously applied only to\n * conversions, so scripts had to parse the aligned columns or convert files just to learn\n * what was in them.\n *\n * Field names match `metadata.json` where the two describe the same thing, so a survey and\n * a conversion can be read by the same code.\n */\nexport function infoJson(file: EdfFile, plan: ConversionPlan, indent: number | null = 2): string {\n const { header } = file;\n const fileFor = new Map<number, string>();\n for (const group of plan.groups) {\n for (const channel of group.channels) fileFor.set(channel.signal.index, group.fileName);\n }\n\n return JSON.stringify(\n {\n path: file.path,\n bytes: file.fileSize,\n format: describeFormat(header),\n start_datetime_local: formatWallClock(header.startDateTime),\n start_date_raw: header.startDateRaw,\n start_time_raw: header.startTimeRaw,\n patient_id: header.patientId,\n recording_id: header.recordingId,\n data_records: file.recordCount,\n data_records_declared: header.declaredRecordCount,\n record_duration_seconds: header.recordDuration,\n duration_seconds: file.durationSeconds,\n // For a discontinuous file this exceeds duration_seconds by the length of the gaps.\n time_span_seconds: plan.range.recordingEndSeconds - plan.range.recordingStartSeconds,\n annotation_channels: file.annotationSignals.length,\n channels: file.dataSignals.map((signal) => ({\n signal_index: signal.index,\n column: plan.columnNames.get(signal.index) ?? '',\n label: signal.label,\n unit: signal.physicalDimension,\n sampling_rate_hz: signal.samplingRate,\n samples_per_record: signal.samplesPerRecord,\n physical_min: signal.physicalMin,\n physical_max: signal.physicalMax,\n digital_min: signal.digitalMin,\n digital_max: signal.digitalMax,\n transducer: signal.transducer,\n prefiltering: signal.prefiltering,\n output_file: fileFor.get(signal.index) ?? null,\n })),\n estimate: {\n rows: plan.estimate.rows,\n // Character count of the CSV. With --gzip the file on disk is smaller than this.\n bytes: plan.estimate.bytes,\n exceeds_spreadsheet_limit: plan.estimate.exceedsSpreadsheetLimit,\n },\n // The plan's mixed-rate warning replaces the header parser's, as it does everywhere\n // else. This was the one consumer left out of that when 0.3.2 made the warning follow\n // --channels, so `--info --json` carried it twice: once counting the rates being\n // converted and once counting every rate in the file, with the same code and severity.\n warnings: plan.diagnostics\n .concat(withoutFileRateWarning(file.diagnostics))\n .map((d) => ({ code: d.code, severity: d.severity, message: d.message })),\n },\n null,\n indent ?? undefined,\n );\n}\n\n/** One line per diagnostic, prefixed so warnings are greppable. */\nexport function formatDiagnostics(diagnostics: readonly Diagnostic[]): string {\n return diagnostics\n .map((d) => {\n // Diagnostics quote channel labels, which come from the file, so they need the\n // same treatment as the --info table.\n const head = `${d.severity === 'warning' ? 'warning' : 'note'}: ${printable(d.message)}`;\n return d.hint ? `${head}\\n ${printable(d.hint)}` : head;\n })\n .join('\\n');\n}\n\nexport function formatSummary(result: ConvertResult): string {\n const lines: string[] = [];\n const rows: string[][] = [];\n for (const file of result.files) {\n // `.csv.gz` is still a CSV, and its rows are still rows. The suffix test dropped the\n // unit from every line of a --gzip summary, so the numbers stood on their own.\n rows.push([\n ` ${file.name}`,\n file.rows.toLocaleString('en-US'),\n /\\.csv(\\.gz)?$/u.test(file.name) ? 'rows' : '',\n ]);\n }\n lines.push(`Wrote ${result.outputDir}`);\n lines.push(table(rows, new Set([1])));\n lines.push(`Done in ${(result.elapsedMs / 1000).toFixed(1)}s.`);\n return lines.join('\\n');\n}\n\nexport function summaryJson(result: ConvertResult, indent: number | null = 2): string {\n return JSON.stringify(\n {\n output_dir: result.outputDir,\n files: result.files,\n annotations: result.annotationCount,\n duration_seconds: result.file.durationSeconds,\n records: result.file.recordCount,\n elapsed_ms: result.elapsedMs,\n warnings: result.diagnostics.map((d) => ({ code: d.code, severity: d.severity, message: d.message })),\n },\n null,\n indent ?? undefined,\n );\n}\n"]}
@@ -91,10 +91,25 @@ export class BufferedLineWriter {
91
91
  };
92
92
  this.#stream.on('error', this.#onError);
93
93
  }
94
- /** Take the 'error' listener off a stream that outlives this writer. */
94
+ /**
95
+ * Take the 'error' listener off a stream that outlives this writer.
96
+ *
97
+ * Only those streams. 0.5.36 released it from every stream once `end()`'s callback had
98
+ * settled, and an `fs.WriteStream` whose write failed emits 'error' again during its own
99
+ * auto-destroy — after that callback. With the listener already gone that reached Node as
100
+ * an unhandled 'error' event: a raw stack trace, the process down, `convert()` never
101
+ * rejecting, and no `WRITE_FAILED` message. Which is the failure this listener exists to
102
+ * prevent, and the one the constructor's comment describes.
103
+ *
104
+ * A stream this writer opened is finished with and about to be collected, so a listener
105
+ * left on it leaks nothing. The leak was only ever about `process.stdout`, which outlives
106
+ * every writer in the process.
107
+ */
95
108
  #release() {
96
109
  if (!this.#onError)
97
110
  return;
111
+ if (this.#stream !== process.stdout && this.#stream !== process.stderr)
112
+ return;
98
113
  this.#stream.off('error', this.#onError);
99
114
  this.#onError = null;
100
115
  }
@@ -1 +1 @@
1
- {"version":3,"file":"csv.js","sourceRoot":"","sources":["../../src/format/csv.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAEnC;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,QAAQ;AAExD,MAAM,aAAa,GAAG,WAAW,CAAC;AAElC;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,QAAQ,CAAC;AAEjC,6EAA6E;AAC7E,MAAM,UAAU,cAAc,CAAC,KAAa;IAC1C,IAAI,KAAK,KAAK,EAAE;QAAE,OAAO,EAAE,CAAC;IAC5B,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC7C,OAAO,IAAI,KAAK,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC;AAC5C,CAAC;AAED,MAAM,UAAU,MAAM,CAAC,KAAwB;IAC7C,OAAO,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC7C,CAAC;AAED;;;;;GAKG;AACH,MAAM,OAAO,kBAAkB;IAC7B,OAAO,CAAW;IAClB,MAAM,GAAa,EAAE,CAAC;IACtB,QAAQ,GAAG,CAAC,CAAC;IACb,UAAU,CAAS;IACnB,aAAa,GAAG,CAAC,CAAC;IAClB,iFAAiF;IACjF,SAAS,GAAG,CAAC,CAAC;IACd,MAAM,GAAG,KAAK,CAAC;IACf,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IAAI,CAAC,QAAQ,EAAE,CAAC;QAChB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;IACzB,CAAC;CACF","sourcesContent":["/**\n * CSV escaping and a buffered, backpressure-aware line writer.\n *\n * Rows are accumulated in memory and flushed in large blocks. Writing row by row\n * would issue millions of small stream writes, and ignoring the return value of\n * `write()` would let Node buffer the entire output in RAM — which for an hour of\n * 23-channel EEG is several hundred megabytes.\n */\n\nimport type { Writable } from 'node:stream';\nimport { once } from 'node:events';\n\n/**\n * Flush once this many characters have accumulated.\n *\n * Exported because it is a budget for the whole conversion rather than a per-writer\n * constant: a mixed-rate recording opens one writer per rate, and each taking a megabyte\n * meant memory followed the number of tables. See writeSignalFiles.\n */\nexport const DEFAULT_FLUSH_THRESHOLD = 1 << 20; // 1 MiB\n\nconst NEEDS_QUOTING = /[\",\\r\\n]/u;\n\n/**\n * U+FEFF, written as EF BB BF, which is what `--bom` prepends to each CSV.\n *\n * Excel on Windows reads a CSV with no byte order mark in the system code page rather than\n * UTF-8, so `µV` — two bytes of UTF-8 for one character — shows up as `µ`. The mark tells\n * it the file is UTF-8.\n *\n * Opt-in because it is not free. pandas strips it either engine (checked against 3.0.5),\n * but Python's own `csv.reader` over a plain `open()` does not, and neither does\n * `fs.readFileSync(path, 'utf8')`: the first column name comes back as `\\ufefftime_s`, and\n * a lookup of `time_s` misses. Readers that want it gone ask for `utf-8-sig`.\n */\nexport const UTF8_BOM = '\\ufeff';\n\n/** Quote a field only when CSV requires it, doubling any embedded quotes. */\nexport function escapeCsvField(value: string): string {\n if (value === '') return '';\n if (!NEEDS_QUOTING.test(value)) return value;\n return `\"${value.replaceAll('\"', '\"\"')}\"`;\n}\n\nexport function csvRow(cells: readonly string[]): string {\n return cells.map(escapeCsvField).join(',');\n}\n\n/**\n * Accumulates text and flushes it to a stream, respecting backpressure.\n *\n * Call `push()` freely, then `await maybeFlush()` at a row boundary. Memory stays\n * bounded by the flush threshold plus whatever the stream has not yet drained.\n */\nexport class BufferedLineWriter {\n #stream: Writable;\n #parts: string[] = [];\n #pending = 0;\n #threshold: number;\n #bytesWritten = 0;\n /** Real bytes handed to the stream, as opposed to characters. See `bytesOut`. */\n #bytesOut = 0;\n #ended = false;\n /** The reader closed the pipe; there is nowhere left to write, but this is not a failure. */\n #hungUp = false;\n #failure: Error | null = null;\n\n /** Kept so the listener can come off again; see the constructor. */\n #onError: ((error: NodeJS.ErrnoException) => void) | null = null;\n\n constructor(stream: Writable, threshold: number = DEFAULT_FLUSH_THRESHOLD) {\n this.#stream = stream;\n this.#threshold = threshold;\n /*\n A stream with no 'error' listener throws asynchronously and takes the whole process\n down with a raw stack trace. Capturing the error here lets the next flush surface it as\n a normal failure with a usable message.\n\n Removed again when the writer is finished with, because one of these streams outlives\n the writer: `process.stdout`. A library caller converting twelve recordings with\n `toStdout` left twelve listeners on it and got Node's MaxListenersExceededWarning on\n the eleventh — a leak warning that was, for once, describing a real leak.\n */\n this.#onError = (error: NodeJS.ErrnoException) => {\n /*\n EPIPE is the reader hanging up, not a write failure.\n\n `edf2csv recording.edf --stdout | head -1` closes the pipe while the conversion is\n still writing, and treating that as an error produced exit 1 and a message about\n files that do not exist and disk space that is not the problem. A file stream\n cannot raise EPIPE, so this only ever means \"the consumer stopped reading\", which\n is what a shell pipeline does routinely and on purpose.\n */\n if (error.code === 'EPIPE') {\n this.#hungUp = true;\n return;\n }\n this.#failure ??= error;\n };\n this.#stream.on('error', this.#onError);\n }\n\n /** Take the 'error' listener off a stream that outlives this writer. */\n #release(): void {\n if (!this.#onError) return;\n this.#stream.off('error', this.#onError);\n this.#onError = null;\n }\n\n /** True once the reader closed the pipe. Nothing more can reach the consumer. */\n get hungUp(): boolean {\n return this.#hungUp;\n }\n\n /** Characters written to the stream so far, before any encoding expansion. */\n get charsWritten(): number {\n return this.#bytesWritten;\n }\n\n /**\n * Bytes handed to the stream, counting a multi-byte character once per byte.\n *\n * `charsWritten` drives the progress meter, where the difference does not matter. This is\n * for checking that what was handed over actually arrived, which is a byte question: a\n * channel labelled in Cyrillic makes the two differ by hundreds of bytes on the header\n * line alone.\n */\n get bytesOut(): number {\n return this.#bytesOut;\n }\n\n push(text: string): void {\n this.#parts.push(text);\n this.#pending += text.length;\n }\n\n pushLine(text: string): void {\n this.push(text);\n this.push('\\n');\n }\n\n /**\n * Whether enough has accumulated to be worth writing out.\n *\n * A synchronous question, so a row loop can ask it every row without paying for a\n * microtask on the twenty million that answer no.\n */\n get full(): boolean {\n return this.#pending >= this.#threshold;\n }\n\n /** Flush if enough has accumulated. Await this at row boundaries. */\n async maybeFlush(): Promise<void> {\n if (this.full) await this.flush();\n }\n\n async flush(): Promise<void> {\n if (this.#failure) throw this.#failure;\n /*\n The reader hung up (see the EPIPE note above); there is nowhere left to write.\n\n The buffer is DISCARDED rather than left in place. Returning without clearing it let\n push() keep appending for the rest of the conversion with nothing ever draining it,\n so `--stdout | head -1` on a 165 MB conversion grew to a 1.3 GB working set and died\n with a heap out-of-memory under a 256 MB limit — worse than the error this replaced.\n Bounded memory is the invariant this class exists to hold, and a hung-up reader is no\n reason to abandon it.\n\n Deliberately not `#ended`, which end() sets before its own final flush.\n */\n if (this.#hungUp) {\n this.#parts = [];\n this.#pending = 0;\n return;\n }\n if (this.#parts.length === 0) return;\n\n const chunk = this.#parts.join('');\n this.#parts = [];\n this.#pending = 0;\n this.#bytesWritten += chunk.length;\n this.#bytesOut += Buffer.byteLength(chunk);\n\n if (!this.#stream.write(chunk)) {\n // The consumer is behind; wait rather than letting Node buffer without bound.\n // Waiting only on 'drain' would hang forever if the stream fails instead.\n await this.#drain();\n }\n }\n\n /** Resolve on 'drain', reject if the stream fails first. */\n async #drain(): Promise<void> {\n if (this.#failure) throw this.#failure;\n await new Promise<void>((resolve, reject) => {\n const cleanup = (): void => {\n this.#stream.off('drain', onDrain);\n this.#stream.off('error', onError);\n this.#stream.off('close', onClose);\n };\n const onDrain = (): void => {\n cleanup();\n resolve();\n };\n const onError = (error: NodeJS.ErrnoException): void => {\n cleanup();\n // A pipe closing while we wait for drain is the same benign hang-up as one\n // closing during a write, and has to be handled here too: this listener is\n // registered for the duration of the wait and sees the error first.\n if (error.code === 'EPIPE') {\n this.#hungUp = true;\n resolve();\n return;\n }\n reject(error);\n };\n const onClose = (): void => {\n cleanup();\n reject(this.#failure ?? new Error('The output stream closed before the data was written.'));\n };\n this.#stream.once('drain', onDrain);\n this.#stream.once('error', onError);\n this.#stream.once('close', onClose);\n });\n }\n\n /** Flush anything left and close the stream. */\n async end(): Promise<void> {\n if (this.#ended) return;\n this.#ended = true;\n await this.flush();\n /*\n The reader is gone, so there is nothing to close and possibly nothing left to close it\n on. Under --gzip this stream is the compressor, and the EPIPE forwarded from stdout\n destroyed it — end() on a destroyed stream fails with ERR_STREAM_DESTROYED, which is\n not EPIPE, so it escaped the hang-up guard and came back as a write failure:\n\n edf2csv big.edf --stdout --gzip | head\n error: Writing to stdout failed: Cannot call end after a stream was destroyed\n\n Exactly the three symptoms 0.2.30 removed from the uncompressed path — exit 1 for a\n routine shell idiom, a claim about files that were never written, and advice about disk\n space — reappearing on the one path 0.3.1 said would behave identically.\n */\n if (this.#hungUp) {\n this.#release();\n return;\n }\n // stdout must not be closed; ending it would break piping for the rest of the process.\n // The failure still has to be reported: returning here without looking meant an error\n // recorded on the stream, but not yet surfaced by a later flush, was simply dropped.\n if (this.#stream === process.stdout || this.#stream === process.stderr) {\n const failure = this.#failure;\n this.#release();\n if (failure) throw failure;\n return;\n }\n /*\n Released after the stream has finished ending, not before.\n\n Releasing first meant an EACCES arriving during that final end had no listener left and\n went out as an unhandled 'error' event — a raw stack trace, which is the one thing this\n listener exists to prevent. The leak it was added to fix is about streams this writer\n does not own; the window it must stay attached for runs to the last byte either way.\n */\n try {\n await new Promise<void>((resolve, reject) => {\n this.#stream.end((error?: Error | null) => {\n const failure = error ?? this.#failure;\n if (failure) reject(failure);\n else resolve();\n });\n });\n } finally {\n this.#release();\n }\n }\n\n /** Close the stream without caring whether the data made it out. */\n destroy(): void {\n if (this.#ended) return;\n this.#ended = true;\n this.#parts = [];\n this.#pending = 0;\n this.#release();\n this.#stream.destroy();\n }\n}\n"]}
1
+ {"version":3,"file":"csv.js","sourceRoot":"","sources":["../../src/format/csv.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAEnC;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,QAAQ;AAExD,MAAM,aAAa,GAAG,WAAW,CAAC;AAElC;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,QAAQ,CAAC;AAEjC,6EAA6E;AAC7E,MAAM,UAAU,cAAc,CAAC,KAAa;IAC1C,IAAI,KAAK,KAAK,EAAE;QAAE,OAAO,EAAE,CAAC;IAC5B,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC7C,OAAO,IAAI,KAAK,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC;AAC5C,CAAC;AAED,MAAM,UAAU,MAAM,CAAC,KAAwB;IAC7C,OAAO,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC7C,CAAC;AAED;;;;;GAKG;AACH,MAAM,OAAO,kBAAkB;IAC7B,OAAO,CAAW;IAClB,MAAM,GAAa,EAAE,CAAC;IACtB,QAAQ,GAAG,CAAC,CAAC;IACb,UAAU,CAAS;IACnB,aAAa,GAAG,CAAC,CAAC;IAClB,iFAAiF;IACjF,SAAS,GAAG,CAAC,CAAC;IACd,MAAM,GAAG,KAAK,CAAC;IACf,6FAA6F;IAC7F,OAAO,GAAG,KAAK,CAAC;IAChB,QAAQ,GAAiB,IAAI,CAAC;IAE9B,oEAAoE;IACpE,QAAQ,GAAoD,IAAI,CAAC;IAEjE,YAAY,MAA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,QAAQ,EAAE,CAAC;QAChB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;IACzB,CAAC;CACF","sourcesContent":["/**\n * CSV escaping and a buffered, backpressure-aware line writer.\n *\n * Rows are accumulated in memory and flushed in large blocks. Writing row by row\n * would issue millions of small stream writes, and ignoring the return value of\n * `write()` would let Node buffer the entire output in RAM — which for an hour of\n * 23-channel EEG is several hundred megabytes.\n */\n\nimport type { Writable } from 'node:stream';\nimport { once } from 'node:events';\n\n/**\n * Flush once this many characters have accumulated.\n *\n * Exported because it is a budget for the whole conversion rather than a per-writer\n * constant: a mixed-rate recording opens one writer per rate, and each taking a megabyte\n * meant memory followed the number of tables. See writeSignalFiles.\n */\nexport const DEFAULT_FLUSH_THRESHOLD = 1 << 20; // 1 MiB\n\nconst NEEDS_QUOTING = /[\",\\r\\n]/u;\n\n/**\n * U+FEFF, written as EF BB BF, which is what `--bom` prepends to each CSV.\n *\n * Excel on Windows reads a CSV with no byte order mark in the system code page rather than\n * UTF-8, so `µV` — two bytes of UTF-8 for one character — shows up as `µ`. The mark tells\n * it the file is UTF-8.\n *\n * Opt-in because it is not free. pandas strips it either engine (checked against 3.0.5),\n * but Python's own `csv.reader` over a plain `open()` does not, and neither does\n * `fs.readFileSync(path, 'utf8')`: the first column name comes back as `\\ufefftime_s`, and\n * a lookup of `time_s` misses. Readers that want it gone ask for `utf-8-sig`.\n */\nexport const UTF8_BOM = '\\ufeff';\n\n/** Quote a field only when CSV requires it, doubling any embedded quotes. */\nexport function escapeCsvField(value: string): string {\n if (value === '') return '';\n if (!NEEDS_QUOTING.test(value)) return value;\n return `\"${value.replaceAll('\"', '\"\"')}\"`;\n}\n\nexport function csvRow(cells: readonly string[]): string {\n return cells.map(escapeCsvField).join(',');\n}\n\n/**\n * Accumulates text and flushes it to a stream, respecting backpressure.\n *\n * Call `push()` freely, then `await maybeFlush()` at a row boundary. Memory stays\n * bounded by the flush threshold plus whatever the stream has not yet drained.\n */\nexport class BufferedLineWriter {\n #stream: Writable;\n #parts: string[] = [];\n #pending = 0;\n #threshold: number;\n #bytesWritten = 0;\n /** Real bytes handed to the stream, as opposed to characters. See `bytesOut`. */\n #bytesOut = 0;\n #ended = false;\n /** The reader closed the pipe; there is nowhere left to write, but this is not a failure. */\n #hungUp = false;\n #failure: Error | null = null;\n\n /** Kept so the listener can come off again; see the constructor. */\n #onError: ((error: NodeJS.ErrnoException) => void) | null = null;\n\n constructor(stream: Writable, threshold: number = DEFAULT_FLUSH_THRESHOLD) {\n this.#stream = stream;\n this.#threshold = threshold;\n /*\n A stream with no 'error' listener throws asynchronously and takes the whole process\n down with a raw stack trace. Capturing the error here lets the next flush surface it as\n a normal failure with a usable message.\n\n Removed again when the writer is finished with, because one of these streams outlives\n the writer: `process.stdout`. A library caller converting twelve recordings with\n `toStdout` left twelve listeners on it and got Node's MaxListenersExceededWarning on\n the eleventh — a leak warning that was, for once, describing a real leak.\n */\n this.#onError = (error: NodeJS.ErrnoException) => {\n /*\n EPIPE is the reader hanging up, not a write failure.\n\n `edf2csv recording.edf --stdout | head -1` closes the pipe while the conversion is\n still writing, and treating that as an error produced exit 1 and a message about\n files that do not exist and disk space that is not the problem. A file stream\n cannot raise EPIPE, so this only ever means \"the consumer stopped reading\", which\n is what a shell pipeline does routinely and on purpose.\n */\n if (error.code === 'EPIPE') {\n this.#hungUp = true;\n return;\n }\n this.#failure ??= error;\n };\n this.#stream.on('error', this.#onError);\n }\n\n /**\n * Take the 'error' listener off a stream that outlives this writer.\n *\n * Only those streams. 0.5.36 released it from every stream once `end()`'s callback had\n * settled, and an `fs.WriteStream` whose write failed emits 'error' again during its own\n * auto-destroy — after that callback. With the listener already gone that reached Node as\n * an unhandled 'error' event: a raw stack trace, the process down, `convert()` never\n * rejecting, and no `WRITE_FAILED` message. Which is the failure this listener exists to\n * prevent, and the one the constructor's comment describes.\n *\n * A stream this writer opened is finished with and about to be collected, so a listener\n * left on it leaks nothing. The leak was only ever about `process.stdout`, which outlives\n * every writer in the process.\n */\n #release(): void {\n if (!this.#onError) return;\n if (this.#stream !== process.stdout && this.#stream !== process.stderr) return;\n this.#stream.off('error', this.#onError);\n this.#onError = null;\n }\n\n /** True once the reader closed the pipe. Nothing more can reach the consumer. */\n get hungUp(): boolean {\n return this.#hungUp;\n }\n\n /** Characters written to the stream so far, before any encoding expansion. */\n get charsWritten(): number {\n return this.#bytesWritten;\n }\n\n /**\n * Bytes handed to the stream, counting a multi-byte character once per byte.\n *\n * `charsWritten` drives the progress meter, where the difference does not matter. This is\n * for checking that what was handed over actually arrived, which is a byte question: a\n * channel labelled in Cyrillic makes the two differ by hundreds of bytes on the header\n * line alone.\n */\n get bytesOut(): number {\n return this.#bytesOut;\n }\n\n push(text: string): void {\n this.#parts.push(text);\n this.#pending += text.length;\n }\n\n pushLine(text: string): void {\n this.push(text);\n this.push('\\n');\n }\n\n /**\n * Whether enough has accumulated to be worth writing out.\n *\n * A synchronous question, so a row loop can ask it every row without paying for a\n * microtask on the twenty million that answer no.\n */\n get full(): boolean {\n return this.#pending >= this.#threshold;\n }\n\n /** Flush if enough has accumulated. Await this at row boundaries. */\n async maybeFlush(): Promise<void> {\n if (this.full) await this.flush();\n }\n\n async flush(): Promise<void> {\n if (this.#failure) throw this.#failure;\n /*\n The reader hung up (see the EPIPE note above); there is nowhere left to write.\n\n The buffer is DISCARDED rather than left in place. Returning without clearing it let\n push() keep appending for the rest of the conversion with nothing ever draining it,\n so `--stdout | head -1` on a 165 MB conversion grew to a 1.3 GB working set and died\n with a heap out-of-memory under a 256 MB limit — worse than the error this replaced.\n Bounded memory is the invariant this class exists to hold, and a hung-up reader is no\n reason to abandon it.\n\n Deliberately not `#ended`, which end() sets before its own final flush.\n */\n if (this.#hungUp) {\n this.#parts = [];\n this.#pending = 0;\n return;\n }\n if (this.#parts.length === 0) return;\n\n const chunk = this.#parts.join('');\n this.#parts = [];\n this.#pending = 0;\n this.#bytesWritten += chunk.length;\n this.#bytesOut += Buffer.byteLength(chunk);\n\n if (!this.#stream.write(chunk)) {\n // The consumer is behind; wait rather than letting Node buffer without bound.\n // Waiting only on 'drain' would hang forever if the stream fails instead.\n await this.#drain();\n }\n }\n\n /** Resolve on 'drain', reject if the stream fails first. */\n async #drain(): Promise<void> {\n if (this.#failure) throw this.#failure;\n await new Promise<void>((resolve, reject) => {\n const cleanup = (): void => {\n this.#stream.off('drain', onDrain);\n this.#stream.off('error', onError);\n this.#stream.off('close', onClose);\n };\n const onDrain = (): void => {\n cleanup();\n resolve();\n };\n const onError = (error: NodeJS.ErrnoException): void => {\n cleanup();\n // A pipe closing while we wait for drain is the same benign hang-up as one\n // closing during a write, and has to be handled here too: this listener is\n // registered for the duration of the wait and sees the error first.\n if (error.code === 'EPIPE') {\n this.#hungUp = true;\n resolve();\n return;\n }\n reject(error);\n };\n const onClose = (): void => {\n cleanup();\n reject(this.#failure ?? new Error('The output stream closed before the data was written.'));\n };\n this.#stream.once('drain', onDrain);\n this.#stream.once('error', onError);\n this.#stream.once('close', onClose);\n });\n }\n\n /** Flush anything left and close the stream. */\n async end(): Promise<void> {\n if (this.#ended) return;\n this.#ended = true;\n await this.flush();\n /*\n The reader is gone, so there is nothing to close and possibly nothing left to close it\n on. Under --gzip this stream is the compressor, and the EPIPE forwarded from stdout\n destroyed it — end() on a destroyed stream fails with ERR_STREAM_DESTROYED, which is\n not EPIPE, so it escaped the hang-up guard and came back as a write failure:\n\n edf2csv big.edf --stdout --gzip | head\n error: Writing to stdout failed: Cannot call end after a stream was destroyed\n\n Exactly the three symptoms 0.2.30 removed from the uncompressed path — exit 1 for a\n routine shell idiom, a claim about files that were never written, and advice about disk\n space — reappearing on the one path 0.3.1 said would behave identically.\n */\n if (this.#hungUp) {\n this.#release();\n return;\n }\n // stdout must not be closed; ending it would break piping for the rest of the process.\n // The failure still has to be reported: returning here without looking meant an error\n // recorded on the stream, but not yet surfaced by a later flush, was simply dropped.\n if (this.#stream === process.stdout || this.#stream === process.stderr) {\n const failure = this.#failure;\n this.#release();\n if (failure) throw failure;\n return;\n }\n /*\n Released after the stream has finished ending, not before.\n\n Releasing first meant an EACCES arriving during that final end had no listener left and\n went out as an unhandled 'error' event — a raw stack trace, which is the one thing this\n listener exists to prevent. The leak it was added to fix is about streams this writer\n does not own; the window it must stay attached for runs to the last byte either way.\n */\n try {\n await new Promise<void>((resolve, reject) => {\n this.#stream.end((error?: Error | null) => {\n const failure = error ?? this.#failure;\n if (failure) reject(failure);\n else resolve();\n });\n });\n } finally {\n this.#release();\n }\n }\n\n /** Close the stream without caring whether the data made it out. */\n destroy(): void {\n if (this.#ended) return;\n this.#ended = true;\n this.#parts = [];\n this.#pending = 0;\n this.#release();\n this.#stream.destroy();\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "edf2csv",
3
- "version": "0.5.43",
3
+ "version": "0.5.45",
4
4
  "description": "Convert EDF, EDF+ and BDF biosignal recordings (European Data Format) to CSV from the command line. Local, streaming, and never resamples or alters units.",
5
5
  "keywords": [
6
6
  "edf",