@graphty/graph-io 0.3.17 → 0.3.19

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.
Files changed (154) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +64 -3
  3. package/dist/chunks/{escape-scjHxjpr.js → escape-CWExcecC.js} +3 -2
  4. package/dist/chunks/{escape-scjHxjpr.js.map → escape-CWExcecC.js.map} +1 -1
  5. package/dist/chunks/exporter-CbMZyVt-.js +735 -0
  6. package/dist/chunks/exporter-CbMZyVt-.js.map +1 -0
  7. package/dist/chunks/importer-BAP4PrxR.js +2194 -0
  8. package/dist/chunks/importer-BAP4PrxR.js.map +1 -0
  9. package/dist/chunks/{importer-Xg07gk7p.js → importer-BNFuV1-K.js} +5 -3
  10. package/dist/chunks/{importer-Xg07gk7p.js.map → importer-BNFuV1-K.js.map} +1 -1
  11. package/dist/chunks/{importer-BmOl9gLW.js → importer-BVGtU1NA.js} +5 -3
  12. package/dist/chunks/{importer-BmOl9gLW.js.map → importer-BVGtU1NA.js.map} +1 -1
  13. package/dist/chunks/{importer-ruMWWvVs.js → importer-BW-Ft2ps.js} +5 -3
  14. package/dist/chunks/{importer-ruMWWvVs.js.map → importer-BW-Ft2ps.js.map} +1 -1
  15. package/dist/chunks/{importer-B6rKRxzv.js → importer-Bm1_5vPS.js} +781 -104
  16. package/dist/chunks/importer-Bm1_5vPS.js.map +1 -0
  17. package/dist/chunks/importer-ByPGO-09.js +1614 -0
  18. package/dist/chunks/importer-ByPGO-09.js.map +1 -0
  19. package/dist/chunks/importer-DOepkgnG.js +1713 -0
  20. package/dist/chunks/importer-DOepkgnG.js.map +1 -0
  21. package/dist/chunks/json-elements-CZY1wiZh.js +779 -0
  22. package/dist/chunks/json-elements-CZY1wiZh.js.map +1 -0
  23. package/dist/chunks/ontology-BnrJ4I98.js +113 -0
  24. package/dist/chunks/ontology-BnrJ4I98.js.map +1 -0
  25. package/dist/chunks/{records-DSpbTE5s.js → records-BzNicMsf.js} +2 -2
  26. package/dist/chunks/{records-DSpbTE5s.js.map → records-BzNicMsf.js.map} +1 -1
  27. package/dist/chunks/{writer-DHHfHn11.js → report-BcWboivV.js} +106 -928
  28. package/dist/chunks/report-BcWboivV.js.map +1 -0
  29. package/dist/chunks/weights-CwISIpCP.js +176 -0
  30. package/dist/chunks/weights-CwISIpCP.js.map +1 -0
  31. package/dist/chunks/writer-DQiKgQJc.js +656 -0
  32. package/dist/chunks/writer-DQiKgQJc.js.map +1 -0
  33. package/dist/csv.js +5 -3
  34. package/dist/csv.js.map +1 -1
  35. package/dist/cx.d.ts +1 -0
  36. package/dist/cx.js +6 -0
  37. package/dist/cx.js.map +1 -0
  38. package/dist/cx2.d.ts +1 -0
  39. package/dist/cx2.js +10 -0
  40. package/dist/cx2.js.map +1 -0
  41. package/dist/dot.js +1 -1
  42. package/dist/gexf.js +15 -3
  43. package/dist/gexf.js.map +1 -1
  44. package/dist/gml.js +5 -3
  45. package/dist/gml.js.map +1 -1
  46. package/dist/graph-io.js +158 -383
  47. package/dist/graph-io.js.map +1 -1
  48. package/dist/graphml.js +1 -1
  49. package/dist/json.js +1 -1
  50. package/dist/neo4j.js +5 -3
  51. package/dist/neo4j.js.map +1 -1
  52. package/dist/obo.d.ts +1 -0
  53. package/dist/obo.js +6 -0
  54. package/dist/obo.js.map +1 -0
  55. package/dist/pajek.js +1 -1
  56. package/dist/src/common/json-elements.d.ts +286 -0
  57. package/dist/src/common/json-elements.d.ts.map +1 -0
  58. package/dist/src/common/json-elements.js +926 -0
  59. package/dist/src/common/json-elements.js.map +1 -0
  60. package/dist/src/common/ontology.d.ts +59 -0
  61. package/dist/src/common/ontology.d.ts.map +1 -0
  62. package/dist/src/common/ontology.js +147 -0
  63. package/dist/src/common/ontology.js.map +1 -0
  64. package/dist/src/formats/cx/importer.d.ts +133 -0
  65. package/dist/src/formats/cx/importer.d.ts.map +1 -0
  66. package/dist/src/formats/cx/importer.js +2220 -0
  67. package/dist/src/formats/cx/importer.js.map +1 -0
  68. package/dist/src/formats/cx/index.d.ts +7 -0
  69. package/dist/src/formats/cx/index.d.ts.map +1 -0
  70. package/dist/src/formats/cx/index.js +7 -0
  71. package/dist/src/formats/cx/index.js.map +1 -0
  72. package/dist/src/formats/cx2/exporter.d.ts +59 -0
  73. package/dist/src/formats/cx2/exporter.d.ts.map +1 -0
  74. package/dist/src/formats/cx2/exporter.js +864 -0
  75. package/dist/src/formats/cx2/exporter.js.map +1 -0
  76. package/dist/src/formats/cx2/importer.d.ts +169 -0
  77. package/dist/src/formats/cx2/importer.d.ts.map +1 -0
  78. package/dist/src/formats/cx2/importer.js +1652 -0
  79. package/dist/src/formats/cx2/importer.js.map +1 -0
  80. package/dist/src/formats/cx2/index.d.ts +7 -0
  81. package/dist/src/formats/cx2/index.d.ts.map +1 -0
  82. package/dist/src/formats/cx2/index.js +7 -0
  83. package/dist/src/formats/cx2/index.js.map +1 -0
  84. package/dist/src/formats/gexf/exporter.d.ts +2 -0
  85. package/dist/src/formats/gexf/exporter.d.ts.map +1 -1
  86. package/dist/src/formats/gexf/exporter.js +6 -0
  87. package/dist/src/formats/gexf/exporter.js.map +1 -1
  88. package/dist/src/formats/gexf/importer.d.ts +2 -4
  89. package/dist/src/formats/gexf/importer.d.ts.map +1 -1
  90. package/dist/src/formats/gexf/importer.js +2 -4
  91. package/dist/src/formats/gexf/importer.js.map +1 -1
  92. package/dist/src/formats/gexf/index.d.ts +1 -1
  93. package/dist/src/formats/gexf/index.js +2 -2
  94. package/dist/src/formats/gexf/index.js.map +1 -1
  95. package/dist/src/formats/gml/exporter.js +1 -1
  96. package/dist/src/formats/gml/exporter.js.map +1 -1
  97. package/dist/src/formats/json/dialect.d.ts +8 -6
  98. package/dist/src/formats/json/dialect.d.ts.map +1 -1
  99. package/dist/src/formats/json/dialect.js +26 -3
  100. package/dist/src/formats/json/dialect.js.map +1 -1
  101. package/dist/src/formats/json/importer.d.ts +324 -7
  102. package/dist/src/formats/json/importer.d.ts.map +1 -1
  103. package/dist/src/formats/json/importer.js +159 -126
  104. package/dist/src/formats/json/importer.js.map +1 -1
  105. package/dist/src/formats/json/obographs.d.ts +21 -0
  106. package/dist/src/formats/json/obographs.d.ts.map +1 -0
  107. package/dist/src/formats/json/obographs.js +476 -0
  108. package/dist/src/formats/json/obographs.js.map +1 -0
  109. package/dist/src/formats/obo/importer.d.ts +90 -0
  110. package/dist/src/formats/obo/importer.d.ts.map +1 -0
  111. package/dist/src/formats/obo/importer.js +1248 -0
  112. package/dist/src/formats/obo/importer.js.map +1 -0
  113. package/dist/src/formats/obo/index.d.ts +7 -0
  114. package/dist/src/formats/obo/index.d.ts.map +1 -0
  115. package/dist/src/formats/obo/index.js +7 -0
  116. package/dist/src/formats/obo/index.js.map +1 -0
  117. package/dist/src/formats/obo/syntax.d.ts +121 -0
  118. package/dist/src/formats/obo/syntax.d.ts.map +1 -0
  119. package/dist/src/formats/obo/syntax.js +424 -0
  120. package/dist/src/formats/obo/syntax.js.map +1 -0
  121. package/dist/src/index.d.ts +3 -0
  122. package/dist/src/index.d.ts.map +1 -1
  123. package/dist/src/index.js +3 -0
  124. package/dist/src/index.js.map +1 -1
  125. package/dist/src/registry.d.ts.map +1 -1
  126. package/dist/src/registry.js +8 -1
  127. package/dist/src/registry.js.map +1 -1
  128. package/dist/src/sniff.d.ts +1 -1
  129. package/dist/src/sniff.d.ts.map +1 -1
  130. package/dist/src/sniff.js +25 -3
  131. package/dist/src/sniff.js.map +1 -1
  132. package/package.json +16 -1
  133. package/src/common/json-elements.ts +1147 -0
  134. package/src/common/ontology.ts +169 -0
  135. package/src/formats/cx/importer.ts +2733 -0
  136. package/src/formats/cx/index.ts +7 -0
  137. package/src/formats/cx2/exporter.ts +1036 -0
  138. package/src/formats/cx2/importer.ts +2187 -0
  139. package/src/formats/cx2/index.ts +7 -0
  140. package/src/formats/gexf/exporter.ts +11 -0
  141. package/src/formats/gexf/importer.ts +2 -2
  142. package/src/formats/gexf/index.ts +1 -1
  143. package/src/formats/gml/exporter.ts +1 -1
  144. package/src/formats/json/dialect.ts +37 -7
  145. package/src/formats/json/importer.ts +210 -132
  146. package/src/formats/json/obographs.ts +563 -0
  147. package/src/formats/obo/importer.ts +1695 -0
  148. package/src/formats/obo/index.ts +7 -0
  149. package/src/formats/obo/syntax.ts +466 -0
  150. package/src/index.ts +11 -0
  151. package/src/registry.ts +8 -1
  152. package/src/sniff.ts +48 -5
  153. package/dist/chunks/importer-B6rKRxzv.js.map +0 -1
  154. package/dist/chunks/writer-DHHfHn11.js.map +0 -1
@@ -0,0 +1,1147 @@
1
+ /**
2
+ * The JSON reading the two CX formats share (design section 1.0 of
3
+ * design/graph-io/cytoscape-and-obo/design.md): the exact-integer rewrite (also used by the JSON
4
+ * importer), a streaming scanner that walks a CX document's top-level array and hands over each
5
+ * aspect element as soon as its closing brace arrives (section 1.2.5), and the CX id rule of
6
+ * section 1.0.2.
7
+ *
8
+ * The scanner never holds the document as one string, so a file larger than the longest string a
9
+ * JavaScript engine can hold is still read: it keeps the text of the element being read and
10
+ * nothing else. Each element is parsed with `JSON.parse`; an integer literal beyond 2^53 is kept as
11
+ * an ExactInteger (its digits) so an id never loses a digit.
12
+ */
13
+
14
+ import {
15
+ type ColumnDecl,
16
+ type ColumnHandle,
17
+ GraphFormatError,
18
+ type GraphSink,
19
+ INVALID_INDEX,
20
+ type NodeId,
21
+ } from "@graphty/graph-format";
22
+
23
+ import { declareResolved, uniqueColumnName } from "./attributes.js";
24
+ import {
25
+ ASPECT_ORDER_CODE,
26
+ BAD_ASPECT_BLOCK_CODE,
27
+ COLUMN_RENAMED_CODE,
28
+ COUNT_MISMATCH_CODE,
29
+ STATUS_FAILED_CODE,
30
+ STATUS_WARNING_CODE,
31
+ } from "./codes.js";
32
+ import { type ImportReportBuilder } from "./report.js";
33
+
34
+ // ============================================================ exact integers
35
+
36
+ /** A run of 16 digits not inside a fraction: the shortest integer literal that can exceed 2^53 (9007199254740992). */
37
+ export const MAYBE_UNSAFE_INTEGER = /(?<![0-9.])[0-9]{16}/;
38
+
39
+ /**
40
+ * The prefix of the string a non-standard token or an exact integer is rewritten to (a NUL
41
+ * character first, which no sensible attribute value starts with).
42
+ */
43
+ const SENTINEL = `${String.fromCharCode(0)}graph-io:`;
44
+
45
+ /** The sentinel prefix of an integer literal kept as its digits. */
46
+ const EXACT_SENTINEL = `${SENTINEL}exact:`;
47
+
48
+ /** The non-standard tokens Python's json module writes, longest first so -Infinity wins over a bare minus. */
49
+ const NONSTANDARD_TOKENS: readonly (readonly [string, number])[] = [
50
+ ["-Infinity", -Infinity],
51
+ ["Infinity", Infinity],
52
+ ["NaN", NaN],
53
+ ];
54
+
55
+ /** A JSON integer literal (no fraction, no exponent, no leading zero), as CANONICAL_INTEGER in common/ids.ts. */
56
+ const INTEGER_LITERAL = /^-?(0|[1-9][0-9]*)$/;
57
+
58
+ /** What rewriteNumbers() found. */
59
+ interface RewrittenNumbers {
60
+ /** The rewritten text. */
61
+ readonly text: string;
62
+ /** The non-standard tokens seen (only when they were allowed). */
63
+ readonly tokens: Set<string>;
64
+ /** The integer literals beyond 2^53 that were quoted. */
65
+ readonly bigIntegers: string[];
66
+ }
67
+
68
+ /**
69
+ * Rewrite the numbers JSON.parse cannot read exactly, outside strings and in value positions only:
70
+ * NaN / Infinity / -Infinity become sentinel strings (when `nonstandard` is true), an integer
71
+ * literal that is not a safe integer becomes a string of its digits (or, with `exactSentinel`, a
72
+ * sentinel string reviveExact() turns into an ExactInteger). A container stack tells a value
73
+ * position (after `:`, `[`, or `,` inside an array) from a key position, so `{NaN: 1}` stays invalid.
74
+ * @param text - the document text
75
+ * @param options - which rewrites apply
76
+ * @param options.nonstandard - rewrite NaN / Infinity / -Infinity (default true)
77
+ * @param options.exactSentinel - quote big integers as sentinels instead of bare digits (default false)
78
+ * @returns the rewritten text, the non-standard tokens seen and the integer literals quoted
79
+ */
80
+ export function rewriteNumbers(
81
+ text: string,
82
+ options: { readonly nonstandard?: boolean; readonly exactSentinel?: boolean } = {},
83
+ ): RewrittenNumbers {
84
+ const nonstandard = options.nonstandard ?? true;
85
+ const exactSentinel = options.exactSentinel ?? false;
86
+ const parts: string[] = [];
87
+ const tokens = new Set<string>();
88
+ const bigIntegers: string[] = [];
89
+ const arrays: boolean[] = [];
90
+ let expectValue = true;
91
+ let copied = 0;
92
+ let i = 0;
93
+ const n = text.length;
94
+ while (i < n) {
95
+ const ch = text[i];
96
+ if (ch === '"') {
97
+ i++;
98
+ while (i < n && text[i] !== '"') {
99
+ i += text[i] === "\\" ? 2 : 1;
100
+ }
101
+ i++;
102
+ expectValue = false;
103
+ continue;
104
+ }
105
+ if (ch === "{" || ch === "[") {
106
+ arrays.push(ch === "[");
107
+ expectValue = ch === "[";
108
+ } else if (ch === "}" || ch === "]") {
109
+ arrays.pop();
110
+ expectValue = false;
111
+ } else if (ch === ":") {
112
+ expectValue = true;
113
+ } else if (ch === ",") {
114
+ expectValue = arrays.length > 0 && arrays[arrays.length - 1];
115
+ } else if (expectValue && ch !== " " && ch !== "\t" && ch !== "\n" && ch !== "\r") {
116
+ expectValue = false;
117
+ const token = nonstandard ? NONSTANDARD_TOKENS.find(([word]) => text.startsWith(word, i)) : undefined;
118
+ let end = i;
119
+ let replacement: string | null = null;
120
+ if (token !== undefined) {
121
+ end = i + token[0].length;
122
+ tokens.add(token[0]);
123
+ replacement = JSON.stringify(`${SENTINEL}${token[0]}`);
124
+ } else if (ch === "-" || (ch >= "0" && ch <= "9")) {
125
+ end = i + 1;
126
+ while (end < n && "0123456789+-.eE".includes(text[end])) {
127
+ end++;
128
+ }
129
+ const literal = text.slice(i, end);
130
+ if (INTEGER_LITERAL.test(literal) && !Number.isSafeInteger(Number(literal))) {
131
+ bigIntegers.push(literal);
132
+ replacement = exactSentinel ? JSON.stringify(`${EXACT_SENTINEL}${literal}`) : `"${literal}"`;
133
+ }
134
+ }
135
+ if (replacement !== null) {
136
+ parts.push(text.slice(copied, i), replacement);
137
+ copied = end;
138
+ }
139
+ i = Math.max(end, i + 1);
140
+ continue;
141
+ }
142
+ i++;
143
+ }
144
+ parts.push(text.slice(copied));
145
+ return { text: parts.join(""), tokens, bigIntegers };
146
+ }
147
+
148
+ /**
149
+ * The JSON.parse reviver that turns the non-standard sentinel strings of rewriteNumbers() back into
150
+ * numbers.
151
+ * @param _key - the member key (unused)
152
+ * @param value - the parsed value
153
+ * @returns the number for a sentinel string, the value otherwise
154
+ */
155
+ export function reviveNonstandard(_key: string, value: unknown): unknown {
156
+ if (typeof value === "string" && value.startsWith(SENTINEL)) {
157
+ const found = NONSTANDARD_TOKENS.find(([word]) => word === value.slice(SENTINEL.length));
158
+ return found === undefined ? value : found[1];
159
+ }
160
+ return value;
161
+ }
162
+
163
+ /** An integer literal beyond 2^53, kept as its exact digits (a CX id must never lose a digit). */
164
+ export class ExactInteger {
165
+ /** The digits, with a leading minus for a negative value. */
166
+ readonly digits: string;
167
+
168
+ /**
169
+ * Wrap the digits of an integer literal.
170
+ * @param digits - the literal
171
+ */
172
+ constructor(digits: string) {
173
+ this.digits = digits;
174
+ }
175
+
176
+ /**
177
+ * The nearest number (JSON.stringify writes it as such).
178
+ * @returns the number
179
+ */
180
+ toJSON(): number {
181
+ return Number(this.digits);
182
+ }
183
+ }
184
+
185
+ /**
186
+ * The JSON.parse reviver of an element whose big integers were rewritten as exact sentinels.
187
+ * @param _key - the member key (unused)
188
+ * @param value - the parsed value
189
+ * @returns an ExactInteger for an exact sentinel, the value otherwise
190
+ */
191
+ function reviveExact(_key: string, value: unknown): unknown {
192
+ if (typeof value === "string" && value.startsWith(EXACT_SENTINEL)) {
193
+ return new ExactInteger(value.slice(EXACT_SENTINEL.length));
194
+ }
195
+ return value;
196
+ }
197
+
198
+ /**
199
+ * Parse one JSON value, keeping integer literals beyond 2^53 as ExactInteger.
200
+ * @param text - the JSON text
201
+ * @returns the value and whether it may hold an ExactInteger; SyntaxError when it is not JSON
202
+ */
203
+ export function parseExact(text: string): { readonly value: unknown; readonly exact: boolean } {
204
+ if (!MAYBE_UNSAFE_INTEGER.test(text)) {
205
+ return { value: JSON.parse(text) as unknown, exact: false };
206
+ }
207
+ const scan = rewriteNumbers(text, { nonstandard: false, exactSentinel: true });
208
+ if (scan.bigIntegers.length === 0) {
209
+ return { value: JSON.parse(text) as unknown, exact: false };
210
+ }
211
+ return { value: JSON.parse(scan.text, reviveExact) as unknown, exact: true };
212
+ }
213
+
214
+ /**
215
+ * A parsed value with every ExactInteger replaced by its nearest number, for metadata and for
216
+ * values that are not ids.
217
+ * @param value - the value
218
+ * @param onPrecision - called with the digits of each integer that lost precision
219
+ * @returns the plain JSON value
220
+ */
221
+ export function plainJson(value: unknown, onPrecision?: (digits: string) => void): unknown {
222
+ if (value instanceof ExactInteger) {
223
+ onPrecision?.(value.digits);
224
+ return Number(value.digits);
225
+ }
226
+ if (Array.isArray(value)) {
227
+ return value.map((item) => plainJson(item, onPrecision));
228
+ }
229
+ if (typeof value === "object" && value !== null) {
230
+ const out: Record<string, unknown> = {};
231
+ for (const [key, item] of Object.entries(value)) {
232
+ out[key] = plainJson(item, onPrecision);
233
+ }
234
+ return out;
235
+ }
236
+ return value;
237
+ }
238
+
239
+ // ============================================================ the streaming aspect scanner
240
+
241
+ /** A problem with the document's JSON; the importer turns it into a fatal E_SYNTAX or E_EMPTY_INPUT. */
242
+ export class JsonScanError extends Error {
243
+ /** The 1-based line of the problem. */
244
+ readonly line: number;
245
+
246
+ /** Whether the document holds nothing but whitespace. */
247
+ readonly empty: boolean;
248
+
249
+ /**
250
+ * Create the error.
251
+ * @param message - what is wrong
252
+ * @param line - the 1-based line
253
+ * @param empty - whether the input is empty
254
+ */
255
+ constructor(message: string, line: number, empty = false) {
256
+ super(message);
257
+ this.name = "JsonScanError";
258
+ this.line = line;
259
+ this.empty = empty;
260
+ }
261
+ }
262
+
263
+ /** One thing the scanner found in a CX document. */
264
+ export type AspectEvent =
265
+ | {
266
+ /** A top-level value that is not an array: the whole document, parsed. */
267
+ readonly kind: "root";
268
+ readonly value: unknown;
269
+ readonly line: number;
270
+ }
271
+ | {
272
+ /** A member `{"<aspect>": [` whose elements follow one by one. */
273
+ readonly kind: "block";
274
+ readonly aspect: string;
275
+ readonly block: number;
276
+ readonly line: number;
277
+ }
278
+ | {
279
+ /** One element of the current block, parsed. */
280
+ readonly kind: "element";
281
+ readonly aspect: string;
282
+ readonly block: number;
283
+ readonly value: unknown;
284
+ /** Whether the value may hold an ExactInteger. */
285
+ readonly exact: boolean;
286
+ /** The element's JSON text (for lexical checks of its ids). */
287
+ readonly text: string;
288
+ readonly line: number;
289
+ }
290
+ | {
291
+ /** Keys after the first one of a block member (`{"nodes": [...], "edges": [...]}`); their values were skipped. */
292
+ readonly kind: "extraKeys";
293
+ readonly aspect: string;
294
+ readonly block: number;
295
+ readonly keys: readonly string[];
296
+ readonly line: number;
297
+ }
298
+ | {
299
+ /**
300
+ * An element, or a member, nested deeper than MAX_ELEMENT_DEPTH: not parsed, so nothing
301
+ * downstream recurses into it (aspect: the block's aspect, null for a member).
302
+ */
303
+ readonly kind: "deep";
304
+ readonly aspect: string | null;
305
+ readonly block: number;
306
+ readonly depth: number;
307
+ readonly line: number;
308
+ }
309
+ | {
310
+ /** Any other member of the top-level array (a CX2 descriptor, `{"ndexStatus": {...}}`, `1`), parsed. */
311
+ readonly kind: "member";
312
+ readonly block: number;
313
+ readonly value: unknown;
314
+ readonly exact: boolean;
315
+ readonly line: number;
316
+ };
317
+
318
+ /**
319
+ * Whether a character code is whitespace to JSON.
320
+ * @param c - the character code
321
+ * @returns true for space, line feed, carriage return and tab
322
+ */
323
+ const isSpace = (c: number): boolean => c === 32 || c === 10 || c === 13 || c === 9;
324
+
325
+ /**
326
+ * Whether a character code ends a bare scalar (number, true, false, null).
327
+ * @param c - the character code
328
+ * @returns true for whitespace, a comma, a closing bracket or brace, or a colon
329
+ */
330
+ const endsScalar = (c: number): boolean => isSpace(c) || c === 44 || c === 93 || c === 125 || c === 58;
331
+
332
+ const QUOTE_OR_BACKSLASH = /["\\]/g;
333
+
334
+ /**
335
+ * The deepest nesting of an element the scanner parses. graph-format refuses JSON values (a json
336
+ * cell, meta.extra) nested deeper than 256 levels, and a kept element sits a few levels down
337
+ * meta.extra; a deeper element is reported instead, before anything recurses into it.
338
+ */
339
+ const MAX_ELEMENT_DEPTH = 200;
340
+
341
+ /**
342
+ * A cursor over text chunks with capture: the text of the value being read is kept across chunk
343
+ * boundaries as a list of parts, so a long element costs linear time.
344
+ */
345
+ class ChunkCursor {
346
+ private readonly iterator: AsyncIterator<string>;
347
+
348
+ private buf = "";
349
+
350
+ /** The read position in buf. */
351
+ pos = 0;
352
+
353
+ /** The line number of buf's first character. */
354
+ private linesBefore = 1;
355
+
356
+ private parts: string[] | null = null;
357
+
358
+ private captureStart = 0;
359
+
360
+ /** The deepest nesting the last skipValue() reached. */
361
+ deepest = 0;
362
+
363
+ /**
364
+ * Wrap text chunks.
365
+ * @param chunks - the decoded text
366
+ */
367
+ constructor(chunks: AsyncIterable<string>) {
368
+ this.iterator = chunks[Symbol.asyncIterator]();
369
+ }
370
+
371
+ /**
372
+ * Read the next chunk once the current one is consumed.
373
+ * @returns false at the end of the input
374
+ */
375
+ async fill(): Promise<boolean> {
376
+ if (this.parts !== null) {
377
+ this.parts.push(this.buf.slice(this.captureStart));
378
+ this.captureStart = 0;
379
+ }
380
+ this.linesBefore += countNewlines(this.buf, 0, this.buf.length);
381
+ for (;;) {
382
+ const next = await this.iterator.next();
383
+ if (next.done === true) {
384
+ this.buf = "";
385
+ this.pos = 0;
386
+ return false;
387
+ }
388
+ if (next.value.length > 0) {
389
+ this.buf = next.value;
390
+ this.pos = 0;
391
+ return true;
392
+ }
393
+ }
394
+ }
395
+
396
+ /**
397
+ * The 1-based line of the read position.
398
+ * @returns the line
399
+ */
400
+ line(): number {
401
+ return this.linesBefore + countNewlines(this.buf, 0, Math.min(this.pos, this.buf.length));
402
+ }
403
+
404
+ /**
405
+ * Skip whitespace and return the next character without consuming it.
406
+ * @returns the character, or "" at the end of the input
407
+ */
408
+ async peek(): Promise<string> {
409
+ for (;;) {
410
+ while (this.pos < this.buf.length && isSpace(this.buf.charCodeAt(this.pos))) {
411
+ this.pos++;
412
+ }
413
+ if (this.pos < this.buf.length) {
414
+ return this.buf[this.pos];
415
+ }
416
+ if (!(await this.fill())) {
417
+ return "";
418
+ }
419
+ }
420
+ }
421
+
422
+ /** Start keeping the text from the read position. */
423
+ beginCapture(): void {
424
+ this.parts = [];
425
+ this.captureStart = this.pos;
426
+ }
427
+
428
+ /**
429
+ * Stop keeping text.
430
+ * @returns the text kept since beginCapture()
431
+ */
432
+ endCapture(): string {
433
+ const parts = this.parts ?? [];
434
+ parts.push(this.buf.slice(this.captureStart, this.pos));
435
+ this.parts = null;
436
+ return parts.length === 1 ? parts[0] : parts.join("");
437
+ }
438
+
439
+ /** Drop the capture without building its text. */
440
+ dropCapture(): void {
441
+ this.parts = null;
442
+ }
443
+
444
+ /**
445
+ * Advance past one JSON value starting at the read position (which holds its first
446
+ * character), tracking strings and nesting only; the value is validated when it is parsed.
447
+ * @param startDepth - the nesting depth already entered (1 when the opening brace was consumed)
448
+ */
449
+ async skipValue(startDepth = 0): Promise<void> {
450
+ let depth = startDepth;
451
+ this.deepest = depth;
452
+ if (depth === 0) {
453
+ const c = this.buf.charCodeAt(this.pos);
454
+ if (c === 34) {
455
+ this.pos++;
456
+ await this.skipString();
457
+ return;
458
+ }
459
+ if (c !== 123 && c !== 91) {
460
+ await this.skipScalar();
461
+ return;
462
+ }
463
+ }
464
+ for (;;) {
465
+ if (this.pos >= this.buf.length && !(await this.fill())) {
466
+ throw new JsonScanError("the document ends inside a value", this.line());
467
+ }
468
+ const c = this.buf.charCodeAt(this.pos);
469
+ this.pos++;
470
+ if (c === 34) {
471
+ await this.skipString();
472
+ } else if (c === 123 || c === 91) {
473
+ depth++;
474
+ if (depth > this.deepest) {
475
+ this.deepest = depth;
476
+ }
477
+ } else if (c === 125 || c === 93) {
478
+ depth--;
479
+ if (depth === 0) {
480
+ return;
481
+ }
482
+ }
483
+ }
484
+ }
485
+
486
+ /** Advance past the rest of a string whose opening quote was consumed. */
487
+ private async skipString(): Promise<void> {
488
+ for (;;) {
489
+ QUOTE_OR_BACKSLASH.lastIndex = this.pos;
490
+ const found = QUOTE_OR_BACKSLASH.exec(this.buf);
491
+ if (found === null) {
492
+ this.pos = this.buf.length;
493
+ if (!(await this.fill())) {
494
+ throw new JsonScanError("the document ends inside a string", this.line());
495
+ }
496
+ continue;
497
+ }
498
+ this.pos = found.index + 1;
499
+ if (found[0] === '"') {
500
+ return;
501
+ }
502
+ // a backslash: skip the escaped character, which may be in the next chunk
503
+ if (this.pos >= this.buf.length && !(await this.fill())) {
504
+ throw new JsonScanError("the document ends inside a string", this.line());
505
+ }
506
+ this.pos++;
507
+ }
508
+ }
509
+
510
+ /** Advance past a bare scalar (a number, true, false, null or a stray word). */
511
+ private async skipScalar(): Promise<void> {
512
+ for (;;) {
513
+ while (this.pos < this.buf.length && !endsScalar(this.buf.charCodeAt(this.pos))) {
514
+ this.pos++;
515
+ }
516
+ if (this.pos < this.buf.length || !(await this.fill())) {
517
+ return;
518
+ }
519
+ }
520
+ }
521
+
522
+ /**
523
+ * Read one JSON string literal at the read position (its opening quote).
524
+ * @returns the decoded string
525
+ */
526
+ async readString(): Promise<string> {
527
+ this.beginCapture();
528
+ this.pos++;
529
+ await this.skipString();
530
+ const literal = this.endCapture();
531
+ try {
532
+ return JSON.parse(literal) as string;
533
+ } catch (err) {
534
+ throw new JsonScanError(`invalid string: ${messageOf(err)}`, this.line());
535
+ }
536
+ }
537
+ }
538
+
539
+ /**
540
+ * The number of line feeds in a slice of a string.
541
+ * @param text - the string
542
+ * @param from - the first index
543
+ * @param to - one past the last index
544
+ * @returns the count
545
+ */
546
+ function countNewlines(text: string, from: number, to: number): number {
547
+ let count = 0;
548
+ let i = text.indexOf("\n", from);
549
+ while (i >= 0 && i < to) {
550
+ count++;
551
+ i = text.indexOf("\n", i + 1);
552
+ }
553
+ return count;
554
+ }
555
+
556
+ /**
557
+ * The message of a caught value.
558
+ * @param err - the thrown value
559
+ * @returns the message
560
+ */
561
+ function messageOf(err: unknown): string {
562
+ return err instanceof Error ? err.message : String(err);
563
+ }
564
+
565
+ /**
566
+ * Parse a captured value, turning a parse failure into a JsonScanError at its line.
567
+ * @param text - the value text
568
+ * @param line - the line the value starts on
569
+ * @returns the value and whether it may hold an ExactInteger
570
+ */
571
+ function parseAt(text: string, line: number): { readonly value: unknown; readonly exact: boolean } {
572
+ try {
573
+ return parseExact(text);
574
+ } catch (err) {
575
+ throw new JsonScanError(`invalid JSON: ${messageOf(err)}`, line);
576
+ }
577
+ }
578
+
579
+ /**
580
+ * Walk a CX document (CX1 or CX2): a top-level array of members, each normally a one-key object
581
+ * `{"<aspect>": [elements]}`. The elements of such a block are parsed and yielded one at a time;
582
+ * any other member is parsed whole and yielded as a "member". A document that is not an array is
583
+ * yielded as one "root" event. Syntax errors throw JsonScanError.
584
+ * @param chunks - the decoded text
585
+ * @yields the events in document order
586
+ * @returns nothing
587
+ */
588
+ export async function* scanAspects(chunks: AsyncIterable<string>): AsyncGenerator<AspectEvent, void, undefined> {
589
+ const cur = new ChunkCursor(chunks);
590
+ const first = await cur.peek();
591
+ if (first === "") {
592
+ throw new JsonScanError("the input is empty", 1, true);
593
+ }
594
+ if (first !== "[") {
595
+ const line = cur.line();
596
+ cur.beginCapture();
597
+ await cur.skipValue();
598
+ const { value } = parseAt(cur.endCapture(), line);
599
+ if ((await cur.peek()) !== "") {
600
+ throw new JsonScanError("unexpected text after the document", cur.line());
601
+ }
602
+ yield { kind: "root", value, line };
603
+ return;
604
+ }
605
+ cur.pos++;
606
+ let block = 0;
607
+ if ((await cur.peek()) === "]") {
608
+ cur.pos++;
609
+ } else {
610
+ for (;;) {
611
+ yield* member(cur, block);
612
+ block++;
613
+ const next = await cur.peek();
614
+ if (next === ",") {
615
+ cur.pos++;
616
+ continue;
617
+ }
618
+ if (next === "]") {
619
+ cur.pos++;
620
+ break;
621
+ }
622
+ throw new JsonScanError(
623
+ next === "" ? "the document ends before its closing bracket" : `expected "," or "]", found "${next}"`,
624
+ cur.line(),
625
+ );
626
+ }
627
+ }
628
+ if ((await cur.peek()) !== "") {
629
+ throw new JsonScanError("unexpected text after the closing bracket", cur.line());
630
+ }
631
+ }
632
+
633
+ /**
634
+ * Read one member of the top-level array.
635
+ * @param cur - the cursor at the member's first character
636
+ * @param block - the member's position among the members
637
+ * @yields the member's events
638
+ * @returns nothing
639
+ */
640
+ async function* member(cur: ChunkCursor, block: number): AsyncGenerator<AspectEvent, void, undefined> {
641
+ const c = await cur.peek();
642
+ const line = cur.line();
643
+ if (c === "" || c === "]" || c === ",") {
644
+ throw new JsonScanError(c === "" ? "the document ends inside its array" : `unexpected "${c}"`, line);
645
+ }
646
+ if (c !== "{") {
647
+ cur.beginCapture();
648
+ await cur.skipValue();
649
+ if (cur.deepest > MAX_ELEMENT_DEPTH) {
650
+ cur.dropCapture();
651
+ yield { kind: "deep", aspect: null, block, depth: cur.deepest, line };
652
+ return;
653
+ }
654
+ const parsed = parseAt(cur.endCapture(), line);
655
+ yield { kind: "member", block, value: parsed.value, exact: parsed.exact, line };
656
+ return;
657
+ }
658
+ cur.beginCapture();
659
+ cur.pos++;
660
+ const k = await cur.peek();
661
+ if (k !== '"') {
662
+ // `{}` or not JSON: parse the whole member so a syntax error is reported as such
663
+ await cur.skipValue(1);
664
+ if (cur.deepest > MAX_ELEMENT_DEPTH) {
665
+ cur.dropCapture();
666
+ yield { kind: "deep", aspect: null, block, depth: cur.deepest, line };
667
+ return;
668
+ }
669
+ const parsed = parseAt(cur.endCapture(), line);
670
+ yield { kind: "member", block, value: parsed.value, exact: parsed.exact, line };
671
+ return;
672
+ }
673
+ // the outer capture keeps the member's text in case it is not a block; readString nests its own
674
+ const outer = cur.endCapture();
675
+ const keyLine = cur.line();
676
+ const aspect = await cur.readString();
677
+ if ((await cur.peek()) !== ":") {
678
+ throw new JsonScanError(`expected ":" after the key "${aspect}"`, cur.line());
679
+ }
680
+ cur.pos++;
681
+ const v = await cur.peek();
682
+ if (v !== "[") {
683
+ // not a block: read the rest of the object and parse the member whole
684
+ cur.beginCapture();
685
+ await cur.skipValue(1);
686
+ if (cur.deepest > MAX_ELEMENT_DEPTH) {
687
+ cur.dropCapture();
688
+ yield { kind: "deep", aspect, block, depth: cur.deepest, line };
689
+ return;
690
+ }
691
+ const rest = cur.endCapture();
692
+ const text = `${outer}${JSON.stringify(aspect)}:${rest}`;
693
+ const parsed = parseAt(text, keyLine);
694
+ yield { kind: "member", block, value: parsed.value, exact: parsed.exact, line };
695
+ return;
696
+ }
697
+ cur.pos++;
698
+ yield { kind: "block", aspect, block, line };
699
+ if ((await cur.peek()) === "]") {
700
+ cur.pos++;
701
+ } else {
702
+ for (;;) {
703
+ const e = await cur.peek();
704
+ if (e === "") {
705
+ throw new JsonScanError(`the document ends inside the "${aspect}" block`, cur.line());
706
+ }
707
+ const elementLine = cur.line();
708
+ cur.beginCapture();
709
+ await cur.skipValue();
710
+ if (cur.deepest > MAX_ELEMENT_DEPTH) {
711
+ cur.dropCapture();
712
+ yield { kind: "deep", aspect, block, depth: cur.deepest, line: elementLine };
713
+ } else {
714
+ const text = cur.endCapture();
715
+ const parsed = parseAt(text, elementLine);
716
+ yield {
717
+ kind: "element",
718
+ aspect,
719
+ block,
720
+ value: parsed.value,
721
+ exact: parsed.exact,
722
+ text,
723
+ line: elementLine,
724
+ };
725
+ }
726
+ const next = await cur.peek();
727
+ if (next === ",") {
728
+ cur.pos++;
729
+ continue;
730
+ }
731
+ if (next === "]") {
732
+ cur.pos++;
733
+ break;
734
+ }
735
+ throw new JsonScanError(
736
+ next === ""
737
+ ? `the document ends inside the "${aspect}" block`
738
+ : `expected "," or "]" in the "${aspect}" block, found "${next}"`,
739
+ cur.line(),
740
+ );
741
+ }
742
+ }
743
+ const end = await cur.peek();
744
+ if (end === "}") {
745
+ cur.pos++;
746
+ return;
747
+ }
748
+ if (end !== ",") {
749
+ throw new JsonScanError(
750
+ end === "" ? "the document ends inside a member" : `expected "}" after the "${aspect}" block`,
751
+ cur.line(),
752
+ );
753
+ }
754
+ // more keys: a malformed block; skip their values and name them
755
+ const keys: string[] = [];
756
+ const extraLine = cur.line();
757
+ while ((await cur.peek()) === ",") {
758
+ cur.pos++;
759
+ if ((await cur.peek()) !== '"') {
760
+ throw new JsonScanError("expected a key", cur.line());
761
+ }
762
+ keys.push(await cur.readString());
763
+ if ((await cur.peek()) !== ":") {
764
+ throw new JsonScanError('expected ":"', cur.line());
765
+ }
766
+ cur.pos++;
767
+ await cur.peek();
768
+ cur.beginCapture();
769
+ await cur.skipValue();
770
+ parseAt(cur.endCapture(), cur.line());
771
+ }
772
+ if ((await cur.peek()) !== "}") {
773
+ throw new JsonScanError('expected "}"', cur.line());
774
+ }
775
+ cur.pos++;
776
+ yield { kind: "extraKeys", aspect, block, keys, line: extraLine };
777
+ }
778
+
779
+ /**
780
+ * Report an element or member the scanner refused for its depth (E_BAD_ASPECT_BLOCK; skipped).
781
+ * @param report - the report
782
+ * @param event - the "deep" event
783
+ */
784
+ export function reportTooDeep(report: ImportReportBuilder, event: Extract<AspectEvent, { kind: "deep" }>): void {
785
+ report.error(
786
+ "parse-error",
787
+ BAD_ASPECT_BLOCK_CODE,
788
+ `${event.aspect === null ? "a member of the document" : `an element of "${event.aspect}"`} is nested ${event.depth} levels deep, more than the ${MAX_ELEMENT_DEPTH} a graph keeps; skipped`,
789
+ { line: event.line, element: event.aspect },
790
+ );
791
+ }
792
+
793
+ // ============================================================ the CX id rule (design section 1.0.2)
794
+
795
+ /** How an id was spelled, when it was not a plain safe integer. */
796
+ type CxIdNote = "text" | "precision" | null;
797
+
798
+ /** A CX id, decided per id: a safe integer is a number, a larger one its exact digits. */
799
+ interface CxId {
800
+ /** The node or edge id. */
801
+ readonly id: NodeId;
802
+ /** "text": spelled as a string or a non-integer literal (W_ID_TEXT_TYPE); "precision": beyond 2^53 (W_PRECISION). */
803
+ readonly note: CxIdNote;
804
+ }
805
+
806
+ const DECIMAL_INTEGER_TEXT = /^-?(0|[1-9][0-9]*)$/;
807
+
808
+ /**
809
+ * Apply the CX id rule (design section 1.0.2) to a parsed value: a safe integer is the id; an
810
+ * integer beyond 2^53 is its exact digit string; a string spelling a decimal integer is that
811
+ * integer (as Jackson coerces it); anything else is E_INVALID_ID.
812
+ * @param raw - the parsed value
813
+ * @param inexactLiteral - whether the number was written as a non-integer literal (`5.0`, `1e3`)
814
+ * @returns the id and how it was spelled
815
+ */
816
+ export function cxId(raw: unknown, inexactLiteral = false): CxId {
817
+ if (raw instanceof ExactInteger) {
818
+ return { id: raw.digits, note: "precision" };
819
+ }
820
+ if (typeof raw === "number") {
821
+ if (Number.isSafeInteger(raw)) {
822
+ return { id: raw === 0 ? 0 : raw, note: inexactLiteral ? "text" : null };
823
+ }
824
+ throw invalidCxId(raw, Number.isInteger(raw) ? "an integer beyond 2^53 written inexactly" : "not an integer");
825
+ }
826
+ if (typeof raw === "string" && raw !== "-0" && DECIMAL_INTEGER_TEXT.test(raw)) {
827
+ const n = Number(raw);
828
+ return Number.isSafeInteger(n) ? { id: n, note: "text" } : { id: raw, note: "precision" };
829
+ }
830
+ throw invalidCxId(raw, "a CX id is an integer");
831
+ }
832
+
833
+ /**
834
+ * The E_INVALID_ID error of a rejected CX id.
835
+ * @param raw - the value
836
+ * @param reason - why
837
+ * @returns the error
838
+ */
839
+ function invalidCxId(raw: unknown, reason: string): GraphFormatError {
840
+ const shown = typeof raw === "string" || typeof raw === "number" ? JSON.stringify(raw) : typeof raw;
841
+ return new GraphFormatError("E_INVALID_ID", `invalid id ${raw === null ? "null" : shown}: ${reason}`, {
842
+ reason,
843
+ });
844
+ }
845
+
846
+ /**
847
+ * Whether the element text writes a top-level key's number as a non-integer literal (`"id": 5.0`,
848
+ * `"@id": 1e3`). A lexical check, so the parsed value (5) cannot tell. Only a key of the element
849
+ * itself counts, not one nested in its `v` (where `s` and `id` are ordinary attribute names).
850
+ * @param text - the element's JSON text
851
+ * @param key - the key
852
+ * @returns true when the literal holds a fraction or an exponent
853
+ */
854
+ export function inexactLiteral(text: string, key: string): boolean {
855
+ const quoted = JSON.stringify(key);
856
+ let depth = 0;
857
+ for (let i = 0; i < text.length; i++) {
858
+ const c = text[i];
859
+ if (c === "{" || c === "[") {
860
+ depth++;
861
+ } else if (c === "}" || c === "]") {
862
+ depth--;
863
+ } else if (c === '"') {
864
+ const start = i;
865
+ for (i++; i < text.length && text[i] !== '"'; i++) {
866
+ if (text[i] === "\\") {
867
+ i++;
868
+ }
869
+ }
870
+ // the key itself (a string at depth 1 followed by a colon), not a value spelled like it
871
+ if (depth === 1 && text.startsWith(quoted, start) && /^\s*:/.test(text.slice(i + 1, i + 16))) {
872
+ const match = /^\s*:\s*(-?[0-9][0-9.eE+-]*)/.exec(text.slice(i + 1, i + 64));
873
+ return match !== null && /[.eE]/.test(match[1]);
874
+ }
875
+ }
876
+ }
877
+ return false;
878
+ }
879
+
880
+ // ============================================================ Cytoscape positions (design section 1.0.2)
881
+
882
+ /** The name of the position column of every Cytoscape-family importer. */
883
+ export const POSITION_COLUMN = "position";
884
+
885
+ /** The name of the stacking-order column (Cytoscape's NODE_Z_LOCATION). */
886
+ const Z_COLUMN = "z";
887
+
888
+ /**
889
+ * The position column of a Cytoscape-family importer: f32 x3, y-up, 2 source dimensions.
890
+ * @param format - the importer's format name
891
+ * @param sourceDims - 3 when z goes into the position (zAs "position")
892
+ * @returns the declaration
893
+ */
894
+ export function positionDecl(format: string, sourceDims = 2): ColumnDecl {
895
+ return {
896
+ name: POSITION_COLUMN,
897
+ dtype: "f32",
898
+ components: 3,
899
+ role: "position",
900
+ mutable: true,
901
+ nullable: true,
902
+ extra: { sourceDims, units: "file" },
903
+ origin: { format, namespace: "cytoscape" },
904
+ };
905
+ }
906
+
907
+ /**
908
+ * The stacking-order column `z` (f64, origin namespace "cytoscape").
909
+ * @param format - the importer's format name
910
+ * @returns the declaration
911
+ */
912
+ export function zDecl(format: string): ColumnDecl {
913
+ return {
914
+ name: Z_COLUMN,
915
+ dtype: "f64",
916
+ nullable: true,
917
+ origin: { format, id: null, namespace: "cytoscape" },
918
+ extra: { cytoscape: "z" },
919
+ };
920
+ }
921
+
922
+ /**
923
+ * Cytoscape's screen y (growing downward) as graph-io's y (growing upward), and back: a negation
924
+ * that never yields -0.
925
+ * @param y - the coordinate
926
+ * @returns the flipped coordinate
927
+ */
928
+ export function flipY(y: number): number {
929
+ return y === 0 ? 0 : -y;
930
+ }
931
+
932
+ // ============================================================ stream structure shared by CX1 and CX2
933
+
934
+ /** The aspect names of the stream structure, not of the network. */
935
+ const STRUCTURE_ASPECTS: ReadonlySet<string> = new Set(["metaData", "status", "numberVerification"]);
936
+
937
+ /**
938
+ * The order, metadata and status rules CX1 and CX2 share (design section 1.0.1): a third
939
+ * `metaData` or an aspect after the post-metadata or after `status` is W_ASPECT_ORDER; declared
940
+ * element counts are compared with what was read (W_COUNT_MISMATCH); `status.success: false` is
941
+ * fatal (E_STATUS_FAILED) and `success: true` with an error text a warning (W_STATUS_WARNING).
942
+ */
943
+ export class CxStructure {
944
+ private readonly report: ImportReportBuilder;
945
+
946
+ /** Elements read per aspect name. */
947
+ readonly counts = new Map<string, number>();
948
+
949
+ /** Blocks read per aspect name. */
950
+ readonly blocks = new Map<string, number>();
951
+
952
+ /** The element counts the metadata declares, by aspect name (a later declaration wins). */
953
+ private readonly declared = new Map<string, number>();
954
+
955
+ private metaDataBlocks = 0;
956
+
957
+ private networkBlocks = 0;
958
+
959
+ private postMetadata = false;
960
+
961
+ private statusSeen = false;
962
+
963
+ /** The status element, when one was read. */
964
+ status: unknown = undefined;
965
+
966
+ /**
967
+ * Whether a status block was read.
968
+ * @returns true once a status block began
969
+ */
970
+ get hasStatus(): boolean {
971
+ return this.statusSeen;
972
+ }
973
+
974
+ /**
975
+ * Create the checker.
976
+ * @param report - the report
977
+ */
978
+ constructor(report: ImportReportBuilder) {
979
+ this.report = report;
980
+ }
981
+
982
+ /**
983
+ * Record the start of a block (or a member holding one aspect).
984
+ * @param aspect - the aspect name
985
+ * @param line - its line
986
+ */
987
+ block(aspect: string, line: number): void {
988
+ this.blocks.set(aspect, (this.blocks.get(aspect) ?? 0) + 1);
989
+ if (this.statusSeen) {
990
+ this.report.warnOnce(
991
+ "validation-error",
992
+ ASPECT_ORDER_CODE,
993
+ `the "${aspect}" block comes after the status block, which must be last; it is read`,
994
+ { line, element: aspect },
995
+ `${ASPECT_ORDER_CODE}:status`,
996
+ );
997
+ }
998
+ if (aspect === "metaData") {
999
+ this.metaDataBlocks++;
1000
+ if (this.networkBlocks > 0) {
1001
+ this.postMetadata = true;
1002
+ }
1003
+ if (this.metaDataBlocks > 2) {
1004
+ this.report.warnOnce(
1005
+ "validation-error",
1006
+ ASPECT_ORDER_CODE,
1007
+ `${this.metaDataBlocks} metaData blocks; a document has at most two (pre and post)`,
1008
+ { line, element: aspect },
1009
+ `${ASPECT_ORDER_CODE}:metaData`,
1010
+ );
1011
+ }
1012
+ return;
1013
+ }
1014
+ if (aspect === "status") {
1015
+ this.statusSeen = true;
1016
+ return;
1017
+ }
1018
+ if (STRUCTURE_ASPECTS.has(aspect)) {
1019
+ return;
1020
+ }
1021
+ this.networkBlocks++;
1022
+ if (this.postMetadata) {
1023
+ this.report.warnOnce(
1024
+ "validation-error",
1025
+ ASPECT_ORDER_CODE,
1026
+ `the "${aspect}" block comes after the post-metadata, where only status is allowed; it is read`,
1027
+ { line, element: aspect },
1028
+ `${ASPECT_ORDER_CODE}:post`,
1029
+ );
1030
+ }
1031
+ }
1032
+
1033
+ /**
1034
+ * Record one element of a block; metaData and status elements are checked here.
1035
+ * @param aspect - the aspect name
1036
+ * @param value - the parsed element
1037
+ * @param line - its line
1038
+ */
1039
+ element(aspect: string, value: unknown, line: number): void {
1040
+ this.counts.set(aspect, (this.counts.get(aspect) ?? 0) + 1);
1041
+ if (aspect === "metaData") {
1042
+ if (isRecord(value) && typeof value.name === "string" && typeof value.elementCount === "number") {
1043
+ this.declared.set(value.name, value.elementCount);
1044
+ }
1045
+ return;
1046
+ }
1047
+ if (aspect === "status") {
1048
+ this.readStatus(value, line);
1049
+ }
1050
+ }
1051
+
1052
+ /**
1053
+ * Check a status element: success false is fatal, an error text with success true a warning.
1054
+ * @param value - the element
1055
+ * @param line - its line
1056
+ */
1057
+ private readStatus(value: unknown, line: number): void {
1058
+ if (this.status !== undefined) {
1059
+ this.report.warnOnce(
1060
+ "validation-error",
1061
+ ASPECT_ORDER_CODE,
1062
+ "more than one status element; the last is used",
1063
+ { line, element: "status" },
1064
+ `${ASPECT_ORDER_CODE}:status2`,
1065
+ );
1066
+ }
1067
+ this.status = value;
1068
+ if (!isRecord(value)) {
1069
+ return;
1070
+ }
1071
+ const error = typeof value.error === "string" ? value.error : "";
1072
+ if (value.success === false) {
1073
+ const message = `the producer marked the document as failed${error.length > 0 ? `: ${error}` : ""}`;
1074
+ this.report.error("validation-error", STATUS_FAILED_CODE, message, { line, element: "status" });
1075
+ throw this.report.abort(message, { code: STATUS_FAILED_CODE });
1076
+ }
1077
+ if (value.success === true && error.length > 0) {
1078
+ this.report.warning("validation-error", STATUS_WARNING_CODE, `the producer reports a warning: ${error}`, {
1079
+ line,
1080
+ element: "status",
1081
+ });
1082
+ }
1083
+ }
1084
+
1085
+ /**
1086
+ * Whether the status element is one object with a boolean success.
1087
+ * @returns true for a well-formed status
1088
+ */
1089
+ statusWellFormed(): boolean {
1090
+ return isRecord(this.status) && typeof this.status.success === "boolean";
1091
+ }
1092
+
1093
+ /** Compare the declared element counts with what was read (W_COUNT_MISMATCH per aspect). */
1094
+ checkCounts(): void {
1095
+ for (const [name, declared] of this.declared) {
1096
+ const read = this.counts.get(name) ?? 0;
1097
+ if (read !== declared) {
1098
+ this.report.warning(
1099
+ "validation-error",
1100
+ COUNT_MISMATCH_CODE,
1101
+ `metaData declares ${declared} "${name}" element(s); ${read} were read`,
1102
+ { element: name },
1103
+ );
1104
+ }
1105
+ }
1106
+ }
1107
+ }
1108
+
1109
+ /**
1110
+ * Whether a value is a plain JSON object.
1111
+ * @param value - any value
1112
+ * @returns true for a non-null, non-array object
1113
+ */
1114
+ export function isRecord(value: unknown): value is Record<string, unknown> {
1115
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof ExactInteger);
1116
+ }
1117
+
1118
+ /**
1119
+ * Declare a column under a name no column of the table holds yet: a per-element visual property
1120
+ * whose name an attribute already has gets `<name>#2` (W_COLUMN_RENAMED), even when the two share a
1121
+ * shape, so the visual value never overwrites the attribute.
1122
+ * @param sink - the sink
1123
+ * @param domain - node or edge
1124
+ * @param decl - the declaration
1125
+ * @param report - the report the rename is recorded in
1126
+ * @returns the handle
1127
+ */
1128
+ export function declareFresh(
1129
+ sink: GraphSink,
1130
+ domain: "node" | "edge",
1131
+ decl: ColumnDecl,
1132
+ report: ImportReportBuilder,
1133
+ ): ColumnHandle {
1134
+ const taken = (name: string): boolean =>
1135
+ (domain === "node" ? sink.nodeColumn(name) : sink.edgeColumn(name)) !== INVALID_INDEX;
1136
+ let fresh = decl;
1137
+ if (taken(decl.name)) {
1138
+ fresh = { ...decl, name: uniqueColumnName(decl.name, null, taken) };
1139
+ report.warning(
1140
+ "coercion",
1141
+ COLUMN_RENAMED_CODE,
1142
+ `${domain} column "${decl.name}" renamed to "${fresh.name}": an attribute holds that name`,
1143
+ { element: decl.name },
1144
+ );
1145
+ }
1146
+ return declareResolved(sink, domain, fresh, report).handle;
1147
+ }