@graphty/graph-io 0.3.18 → 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 (118) hide show
  1. package/README.md +37 -2
  2. package/dist/chunks/{escape-D-gZWO26.js → escape-CWExcecC.js} +3 -3
  3. package/dist/chunks/{escape-D-gZWO26.js.map → escape-CWExcecC.js.map} +1 -1
  4. package/dist/chunks/exporter-CbMZyVt-.js +735 -0
  5. package/dist/chunks/exporter-CbMZyVt-.js.map +1 -0
  6. package/dist/chunks/importer-BAP4PrxR.js +2194 -0
  7. package/dist/chunks/importer-BAP4PrxR.js.map +1 -0
  8. package/dist/chunks/{importer-Br_QeAeE.js → importer-BNFuV1-K.js} +5 -4
  9. package/dist/chunks/{importer-Br_QeAeE.js.map → importer-BNFuV1-K.js.map} +1 -1
  10. package/dist/chunks/{importer-d0uQxFp6.js → importer-BVGtU1NA.js} +5 -4
  11. package/dist/chunks/{importer-d0uQxFp6.js.map → importer-BVGtU1NA.js.map} +1 -1
  12. package/dist/chunks/{importer-DHagxvDD.js → importer-BW-Ft2ps.js} +5 -4
  13. package/dist/chunks/{importer-DHagxvDD.js.map → importer-BW-Ft2ps.js.map} +1 -1
  14. package/dist/chunks/{importer-Du5crN9l.js → importer-Bm1_5vPS.js} +275 -82
  15. package/dist/chunks/importer-Bm1_5vPS.js.map +1 -0
  16. package/dist/chunks/{importer-aNJfe0qu.js → importer-ByPGO-09.js} +2 -2
  17. package/dist/chunks/{importer-aNJfe0qu.js.map → importer-ByPGO-09.js.map} +1 -1
  18. package/dist/chunks/importer-DOepkgnG.js +1713 -0
  19. package/dist/chunks/importer-DOepkgnG.js.map +1 -0
  20. package/dist/chunks/json-elements-CZY1wiZh.js +779 -0
  21. package/dist/chunks/json-elements-CZY1wiZh.js.map +1 -0
  22. package/dist/chunks/{records-Bk9jgodz.js → records-BzNicMsf.js} +2 -2
  23. package/dist/chunks/{records-Bk9jgodz.js.map → records-BzNicMsf.js.map} +1 -1
  24. package/dist/chunks/{report-BOk0p5y8.js → report-BcWboivV.js} +95 -95
  25. package/dist/chunks/{report-BOk0p5y8.js.map → report-BcWboivV.js.map} +1 -1
  26. package/dist/chunks/weights-CwISIpCP.js +176 -0
  27. package/dist/chunks/weights-CwISIpCP.js.map +1 -0
  28. package/dist/chunks/{writer-GAdltGmC.js → writer-DQiKgQJc.js} +8 -179
  29. package/dist/chunks/writer-DQiKgQJc.js.map +1 -0
  30. package/dist/csv.js +5 -4
  31. package/dist/csv.js.map +1 -1
  32. package/dist/cx.d.ts +1 -0
  33. package/dist/cx.js +6 -0
  34. package/dist/cx.js.map +1 -0
  35. package/dist/cx2.d.ts +1 -0
  36. package/dist/cx2.js +10 -0
  37. package/dist/cx2.js.map +1 -0
  38. package/dist/dot.js +1 -1
  39. package/dist/gexf.js +15 -4
  40. package/dist/gexf.js.map +1 -1
  41. package/dist/gml.js +5 -4
  42. package/dist/gml.js.map +1 -1
  43. package/dist/graph-io.js +145 -389
  44. package/dist/graph-io.js.map +1 -1
  45. package/dist/graphml.js +1 -1
  46. package/dist/json.js +1 -1
  47. package/dist/neo4j.js +5 -4
  48. package/dist/neo4j.js.map +1 -1
  49. package/dist/obo.js +1 -1
  50. package/dist/pajek.js +1 -1
  51. package/dist/src/common/json-elements.d.ts +286 -0
  52. package/dist/src/common/json-elements.d.ts.map +1 -0
  53. package/dist/src/common/json-elements.js +926 -0
  54. package/dist/src/common/json-elements.js.map +1 -0
  55. package/dist/src/formats/cx/importer.d.ts +133 -0
  56. package/dist/src/formats/cx/importer.d.ts.map +1 -0
  57. package/dist/src/formats/cx/importer.js +2220 -0
  58. package/dist/src/formats/cx/importer.js.map +1 -0
  59. package/dist/src/formats/cx/index.d.ts +7 -0
  60. package/dist/src/formats/cx/index.d.ts.map +1 -0
  61. package/dist/src/formats/cx/index.js +7 -0
  62. package/dist/src/formats/cx/index.js.map +1 -0
  63. package/dist/src/formats/cx2/exporter.d.ts +59 -0
  64. package/dist/src/formats/cx2/exporter.d.ts.map +1 -0
  65. package/dist/src/formats/cx2/exporter.js +864 -0
  66. package/dist/src/formats/cx2/exporter.js.map +1 -0
  67. package/dist/src/formats/cx2/importer.d.ts +169 -0
  68. package/dist/src/formats/cx2/importer.d.ts.map +1 -0
  69. package/dist/src/formats/cx2/importer.js +1652 -0
  70. package/dist/src/formats/cx2/importer.js.map +1 -0
  71. package/dist/src/formats/cx2/index.d.ts +7 -0
  72. package/dist/src/formats/cx2/index.d.ts.map +1 -0
  73. package/dist/src/formats/cx2/index.js +7 -0
  74. package/dist/src/formats/cx2/index.js.map +1 -0
  75. package/dist/src/formats/gexf/exporter.d.ts +2 -0
  76. package/dist/src/formats/gexf/exporter.d.ts.map +1 -1
  77. package/dist/src/formats/gexf/exporter.js +6 -0
  78. package/dist/src/formats/gexf/exporter.js.map +1 -1
  79. package/dist/src/formats/gexf/importer.d.ts +2 -4
  80. package/dist/src/formats/gexf/importer.d.ts.map +1 -1
  81. package/dist/src/formats/gexf/importer.js +2 -4
  82. package/dist/src/formats/gexf/importer.js.map +1 -1
  83. package/dist/src/formats/gexf/index.d.ts +1 -1
  84. package/dist/src/formats/gexf/index.js +2 -2
  85. package/dist/src/formats/gexf/index.js.map +1 -1
  86. package/dist/src/formats/gml/exporter.js +1 -1
  87. package/dist/src/formats/gml/exporter.js.map +1 -1
  88. package/dist/src/formats/json/importer.d.ts.map +1 -1
  89. package/dist/src/formats/json/importer.js +6 -104
  90. package/dist/src/formats/json/importer.js.map +1 -1
  91. package/dist/src/index.d.ts +2 -0
  92. package/dist/src/index.d.ts.map +1 -1
  93. package/dist/src/index.js +2 -0
  94. package/dist/src/index.js.map +1 -1
  95. package/dist/src/registry.d.ts.map +1 -1
  96. package/dist/src/registry.js +5 -0
  97. package/dist/src/registry.js.map +1 -1
  98. package/dist/src/sniff.d.ts +1 -1
  99. package/dist/src/sniff.d.ts.map +1 -1
  100. package/dist/src/sniff.js +2 -0
  101. package/dist/src/sniff.js.map +1 -1
  102. package/package.json +11 -1
  103. package/src/common/json-elements.ts +1147 -0
  104. package/src/formats/cx/importer.ts +2733 -0
  105. package/src/formats/cx/index.ts +7 -0
  106. package/src/formats/cx2/exporter.ts +1036 -0
  107. package/src/formats/cx2/importer.ts +2187 -0
  108. package/src/formats/cx2/index.ts +7 -0
  109. package/src/formats/gexf/exporter.ts +11 -0
  110. package/src/formats/gexf/importer.ts +2 -2
  111. package/src/formats/gexf/index.ts +1 -1
  112. package/src/formats/gml/exporter.ts +1 -1
  113. package/src/formats/json/importer.ts +6 -105
  114. package/src/index.ts +10 -0
  115. package/src/registry.ts +5 -0
  116. package/src/sniff.ts +14 -1
  117. package/dist/chunks/importer-Du5crN9l.js.map +0 -1
  118. package/dist/chunks/writer-GAdltGmC.js.map +0 -1
@@ -0,0 +1,864 @@
1
+ /**
2
+ * The CX2 exporter (design/graph-io/cytoscape-and-obo/design.md section 1.3; graphty issue #307):
3
+ * writes a snapshot as one CX2 document -- the descriptor, the pre-metadata, one
4
+ * `attributeDeclarations` block (aliases from `origin.id`, defaults from `meta.default`),
5
+ * `networkAttributes`, `nodes` (x / y from the position with y flipped back to screen coordinates,
6
+ * `z` from the `z` column), `edges`, the `cx2.bypass` columns as `nodeBypasses` / `edgeBypasses`,
7
+ * the opaque aspects a CX2 import kept (which returns its own style rules) and `status`.
8
+ *
9
+ * What CX2 cannot hold is announced by check() before anything is written: every edge is
10
+ * directed (W_CX2_UNDIRECTED_AS_DIRECTED, W_MUTUAL_EXPANDED), node ids are integers (E_ID_CHARSET
11
+ * unless `sanitizeIds: "mangle"`, which keeps the original in the `graphty:originalId` attribute
12
+ * the importer restores), nested values are written as JSON text (W_CX2_JSON_AS_STRING), NaN and
13
+ * the infinities as null (W_CX2_NONFINITE_AS_NULL), and the generic notes of checkCapabilities().
14
+ */
15
+ import { GraphFormatError } from "@graphty/graph-format";
16
+ import { pairFolding } from "../../common/direction.js";
17
+ import { capabilities, checkCapabilities, LOSS } from "../../common/export.js";
18
+ import { isRecord, POSITION_COLUMN } from "../../common/json-elements.js";
19
+ import { resolveExportOptions } from "../../common/options.js";
20
+ import { explicitWeights } from "../../common/weights.js";
21
+ import { encodeChunks, joinText } from "../../common/writer.js";
22
+ import { BYPASS_NAMESPACE, CX2_FORMAT, cx2Type, ORIGINAL_ID_ATTRIBUTE } from "./importer.js";
23
+ /**
24
+ * The loss notes the CX2 exporter's check() returns (design section 1.3), by name. A key is the
25
+ * code without its severity and format prefixes.
26
+ */
27
+ export const CX2_LOSS = Object.freeze({
28
+ /** Every edge is written directed: an undirected snapshot, or the undirected pairs of a mixed one. */
29
+ UNDIRECTED_AS_DIRECTED: "W_CX2_UNDIRECTED_AS_DIRECTED",
30
+ /** A nested (json) column is written as a string attribute holding its JSON text. */
31
+ JSON_AS_STRING: "W_CX2_JSON_AS_STRING",
32
+ /** NaN and the infinities cannot be written; they are written as null and read back unset. */
33
+ NONFINITE_AS_NULL: "W_CX2_NONFINITE_AS_NULL",
34
+ /** A mutual pair is written as two directed edges without its mark. */
35
+ MUTUAL_EXPANDED: LOSS.MUTUAL_EXPANDED,
36
+ /** A plain edge column named like the weight key reads back as THE weight (or is skipped when weights are written). */
37
+ WEIGHT_KEY_CLASH: LOSS.WEIGHT_KEY_CLASH,
38
+ /** A parent / parents column: CX2 has no containment. */
39
+ HIERARCHY_DROPPED: LOSS.HIERARCHY,
40
+ /** A start / end / timestamp column: CX2 has no time. */
41
+ TEMPORAL_DROPPED: LOSS.TEMPORAL,
42
+ /** A role column written as a plain attribute. */
43
+ ROLE_DROPPED: LOSS.ROLE,
44
+ /** A dtype CX2 declares as another (f32 as double, u32 as long, dict as string, ...). */
45
+ DTYPE_UNSUPPORTED: LOSS.DTYPE,
46
+ /** Node ids that are not integers under the default sanitizeIds "error": export() throws E_INVALID_ID. */
47
+ ID_CHARSET: LOSS.ID_CHARSET,
48
+ /** Node ids that are not integers under sanitizeIds "mangle": renumbered, originals kept. */
49
+ ID_MANGLED: LOSS.ID_MANGLED,
50
+ /** Edges without a usable id get generated integer ids. */
51
+ EDGE_IDS_GENERATED: LOSS.EDGE_IDS_GENERATED,
52
+ });
53
+ /**
54
+ * What CX2 keeps (design section 1.3): directed multigraphs with self-loops, integer node ids,
55
+ * required integer edge ids, declared string / double / integer / boolean columns and lists of
56
+ * them, declared defaults, network attributes and the position role. f32, u32, u8 and dict columns
57
+ * are written as the nearest declared type and read back as it.
58
+ */
59
+ export const CX2_CAPABILITIES = capabilities({
60
+ mixedDirection: false,
61
+ multiEdges: true,
62
+ selfLoops: true,
63
+ edgeIds: "required",
64
+ idCharset: "integer",
65
+ dtypes: ["string", "f64", "i32", "bool"],
66
+ components: false,
67
+ lists: true,
68
+ json: false,
69
+ defaults: true,
70
+ options: false,
71
+ hierarchy: false,
72
+ temporal: "none",
73
+ graphAttributes: true,
74
+ positions: true,
75
+ viz: false,
76
+ });
77
+ /** The roles CX2 has a slot for, and the column names its importer gives them. */
78
+ const SLOT_ROLES = new Set(["label", "position", "id"]);
79
+ const ROLE_NAMES = Object.freeze({
80
+ label: "name",
81
+ position: POSITION_COLUMN,
82
+ });
83
+ /** Roles whose columns are never written as attributes. */
84
+ const SKIPPED_ROLES = new Set([
85
+ "directed",
86
+ "pair",
87
+ "mutual",
88
+ "weight",
89
+ "timeText",
90
+ "originalId",
91
+ "parent",
92
+ "parents",
93
+ "start",
94
+ "end",
95
+ "timestamp",
96
+ "timestamps",
97
+ "spells",
98
+ "open",
99
+ "spellsOpen",
100
+ "position",
101
+ "color",
102
+ "size",
103
+ "shape",
104
+ "thickness",
105
+ ]);
106
+ /** The aspects the exporter writes itself; an opaque aspect of the same name is not written again. */
107
+ const CORE_ASPECTS = new Set([
108
+ "nodes",
109
+ "edges",
110
+ "attributeDeclarations",
111
+ "networkAttributes",
112
+ "nodeBypasses",
113
+ "edgeBypasses",
114
+ "metaData",
115
+ "status",
116
+ ]);
117
+ /** The weight attribute name. */
118
+ const WEIGHT_ATTRIBUTE = "weight";
119
+ /**
120
+ * The prefix of a string that stands for a raw number literal in the output: -0 (which
121
+ * JSON.stringify writes as 0) and an integer id beyond 2^53 (kept as its digits).
122
+ */
123
+ const RAW = `${String.fromCharCode(0)}cx2:`;
124
+ /** A raw literal as JSON.stringify writes it, to be unquoted. */
125
+ const RAW_JSON = /"\\u0000cx2:(-?[0-9]+)"/g;
126
+ /** An integer literal beyond 2^53 as text: a CX2 id graph-io keeps as its digits. */
127
+ const BIG_INTEGER_TEXT = /^-?[1-9][0-9]{15,}$/;
128
+ /**
129
+ * Whether an id can be written as a CX2 id unchanged: a safe integer, or the digits of an integer
130
+ * beyond 2^53 (the CX2 importer reads those back as the same digits).
131
+ * @param id - the id
132
+ * @returns true when writable
133
+ */
134
+ function writableId(id) {
135
+ return typeof id === "number"
136
+ ? Number.isSafeInteger(id)
137
+ : BIG_INTEGER_TEXT.test(id) && !Number.isSafeInteger(Number(id));
138
+ }
139
+ /**
140
+ * The written node ids; under "error" an id that is not writable throws E_INVALID_ID, under
141
+ * "mangle" it gets the next unused integer.
142
+ * @param snapshot - the snapshot
143
+ * @param mode - the sanitizeIds option
144
+ * @returns the ids
145
+ */
146
+ function writtenIds(snapshot, mode) {
147
+ const { ids } = snapshot;
148
+ const bad = [];
149
+ const used = new Set();
150
+ for (let i = 0; i < ids.size; i++) {
151
+ const id = ids.idOf(i);
152
+ if (!writableId(id)) {
153
+ bad.push(i);
154
+ }
155
+ else if (typeof id === "number") {
156
+ used.add(id);
157
+ }
158
+ }
159
+ if (bad.length > 0 && mode === "error") {
160
+ const first = ids.idOf(bad[0]);
161
+ throw new GraphFormatError("E_INVALID_ID", `${bad.length} node id(s) cannot be written as CX2 integers (first: ${JSON.stringify(first)} at index ${bad[0]}); pass sanitizeIds: "mangle" to rewrite them`, { reason: "charset", charset: "integer", count: bad.length, index: bad[0] });
162
+ }
163
+ const renumbered = new Map();
164
+ let next = 0;
165
+ for (const i of bad) {
166
+ while (used.has(next)) {
167
+ next++;
168
+ }
169
+ used.add(next);
170
+ renumbered.set(i, next);
171
+ }
172
+ return {
173
+ changed: bad.length,
174
+ idAt: (i) => {
175
+ const id = renumbered.get(i) ?? ids.idOf(i);
176
+ return typeof id === "string" ? `${RAW}${id}` : id;
177
+ },
178
+ isChanged: (i) => renumbered.has(i),
179
+ originalAt: (i) => ids.idOf(i),
180
+ };
181
+ }
182
+ /**
183
+ * How many node ids are not writable unchanged.
184
+ * @param snapshot - the snapshot
185
+ * @returns the count
186
+ */
187
+ function unwritableIds(snapshot) {
188
+ let count = 0;
189
+ for (let i = 0; i < snapshot.ids.size; i++) {
190
+ if (!writableId(snapshot.ids.idOf(i))) {
191
+ count++;
192
+ }
193
+ }
194
+ return count;
195
+ }
196
+ /**
197
+ * Whether a column is a bypass column of a CX2 import.
198
+ * @param column - the column
199
+ * @returns true for the cx2.bypass namespace
200
+ */
201
+ function isBypass(column) {
202
+ return column.meta.origin?.namespace === BYPASS_NAMESPACE;
203
+ }
204
+ /**
205
+ * Whether a column is the z (stacking order) column.
206
+ * @param column - the column
207
+ * @returns true for the column marked by a Cytoscape-family importer
208
+ */
209
+ function isZ(column) {
210
+ return column.meta.extra.cytoscape === "z";
211
+ }
212
+ /**
213
+ * The CX2 type of a scalar dtype.
214
+ * @param dtype - the dtype
215
+ * @param longOrigin - whether the source declared the column long
216
+ * @returns the type text
217
+ */
218
+ function scalarType(dtype, longOrigin) {
219
+ switch (dtype) {
220
+ case "f64":
221
+ return longOrigin ? "long" : "double";
222
+ case "f32":
223
+ return "double";
224
+ case "i32":
225
+ case "u8":
226
+ return "integer";
227
+ case "u32":
228
+ return "long";
229
+ case "bool":
230
+ return "boolean";
231
+ default:
232
+ return "string";
233
+ }
234
+ }
235
+ /**
236
+ * Whether every set value of an f64 column is integral (so a declared long stays long).
237
+ * @param column - the column
238
+ * @returns true when every set value is a safe integer
239
+ */
240
+ function allIntegral(column) {
241
+ for (let i = 0; i < column.length; i++) {
242
+ if (column.isSet(i) && !Number.isSafeInteger(column.value(i))) {
243
+ return false;
244
+ }
245
+ }
246
+ return true;
247
+ }
248
+ /**
249
+ * The declared type of a column.
250
+ * @param column - the column
251
+ * @returns the CX2 type text
252
+ */
253
+ function declaredType(column) {
254
+ const { meta } = column;
255
+ const origin = meta.origin?.type ?? null;
256
+ const longOrigin = origin !== null && /long$/.test(origin) && (meta.dtype !== "f64" || allIntegral(column));
257
+ if (meta.dtype === "list") {
258
+ return meta.itemDtype === null || meta.itemDtype === "json"
259
+ ? "string"
260
+ : `list_of_${scalarType(meta.itemDtype, longOrigin)}`;
261
+ }
262
+ // a multi-component column (a color, a 3D vector) is written as a list of its components
263
+ return meta.components > 1 ? `list_of_${scalarType(meta.dtype, false)}` : scalarType(meta.dtype, longOrigin);
264
+ }
265
+ /**
266
+ * Count the non-finite numbers of a column.
267
+ * @param column - the column
268
+ * @returns how many set cells (or list items) are NaN or infinite
269
+ */
270
+ function nonFiniteCount(column) {
271
+ const { dtype, itemDtype } = column.meta;
272
+ const numeric = dtype === "f32" || dtype === "f64" || (dtype === "list" && (itemDtype === "f32" || itemDtype === "f64"));
273
+ if (!numeric) {
274
+ return 0;
275
+ }
276
+ let count = 0;
277
+ for (let i = 0; i < column.length; i++) {
278
+ if (!column.isSet(i)) {
279
+ continue;
280
+ }
281
+ const value = column.value(i);
282
+ if (dtype === "list") {
283
+ if (value.some((v) => !Number.isFinite(v))) {
284
+ count++;
285
+ }
286
+ }
287
+ else if (!Number.isFinite(value)) {
288
+ count++;
289
+ }
290
+ }
291
+ return count;
292
+ }
293
+ /**
294
+ * Plan the attribute columns of one table.
295
+ * @param table - the table
296
+ * @param skip - columns not written as attributes
297
+ * @param rename - the written name of a column, when it differs (the label as `name`)
298
+ * @param reserved - keys already used in v
299
+ * @returns the plans
300
+ */
301
+ function planAttributes(table, skip, rename, reserved = new Set()) {
302
+ const plans = [];
303
+ const used = new Set(reserved);
304
+ const candidates = [...table].filter((c) => !skip(c));
305
+ for (const column of candidates) {
306
+ used.add(rename(column));
307
+ }
308
+ for (const column of candidates) {
309
+ const name = rename(column);
310
+ const { origin } = column.meta;
311
+ let key = name;
312
+ const alias = origin?.format === CX2_FORMAT && typeof origin.id === "string" ? origin.id : null;
313
+ if (alias !== null && alias.length > 0 && alias !== name && !used.has(alias)) {
314
+ key = alias;
315
+ used.add(alias);
316
+ }
317
+ plans.push({ column, name, key, d: declaredType(column), jsonText: column.meta.dtype === "json" });
318
+ }
319
+ return plans;
320
+ }
321
+ /**
322
+ * Plan an export: the notes, the fatal condition and what is written.
323
+ * @param snapshot - the snapshot
324
+ * @param common - the resolved common options
325
+ * @returns the plan
326
+ */
327
+ function plan(snapshot, common) {
328
+ const notes = [];
329
+ let fatal = null;
330
+ const note = (code, message, column = null, count = null) => {
331
+ notes.push(Object.freeze({ code, message, column, count }));
332
+ };
333
+ // bypass columns are written as bypasses, which hold any JSON value
334
+ const bypassNames = new Set([...snapshot.nodes, ...snapshot.edges].filter((c) => isBypass(c) || isZ(c)).map((c) => c.meta.name));
335
+ for (const gen of checkCapabilities(snapshot, CX2_CAPABILITIES, common, {
336
+ roles: SLOT_ROLES,
337
+ roleNames: ROLE_NAMES,
338
+ })) {
339
+ if (gen.column !== null && bypassNames.has(gen.column) && (gen.code === LOSS.JSON || gen.code === LOSS.DTYPE)) {
340
+ continue;
341
+ }
342
+ if (gen.code === LOSS.ID_CHARSET || gen.code === LOSS.ID_MANGLED) {
343
+ // counted below: CX2 also keeps integer ids beyond 2^53, which the generic rule refuses
344
+ continue;
345
+ }
346
+ if (gen.code === LOSS.JSON) {
347
+ note(CX2_LOSS.JSON_AS_STRING, `${gen.column === null ? "a column" : `column "${gen.column}"`} holds nested values; written as a string attribute holding their JSON text`, gen.column, gen.count);
348
+ continue;
349
+ }
350
+ if (gen.code === LOSS.MIXED_DIRECTION_ERROR && fatal === null) {
351
+ fatal = new GraphFormatError("E_DIRECTED", gen.message, { reason: "mixed direction" });
352
+ }
353
+ notes.push(gen);
354
+ }
355
+ const folding = pairFolding(snapshot);
356
+ directionNotes(snapshot, folding, common, note);
357
+ const unwritable = unwritableIds(snapshot);
358
+ if (unwritable > 0) {
359
+ note(common.sanitizeIds === "mangle" ? LOSS.ID_MANGLED : LOSS.ID_CHARSET, common.sanitizeIds === "mangle"
360
+ ? `${unwritable} node id(s) that are not integers are renumbered; the originals are kept in the ${ORIGINAL_ID_ATTRIBUTE} attribute (restored by restoreMangledIds)`
361
+ : `${unwritable} node id(s) that are not integers; export() will throw unless sanitizeIds is "mangle"`, null, unwritable);
362
+ }
363
+ let ids = null;
364
+ try {
365
+ ids = writtenIds(snapshot, common.sanitizeIds);
366
+ }
367
+ catch (err) {
368
+ if (!(err instanceof GraphFormatError)) {
369
+ throw err;
370
+ }
371
+ fatal ?? (fatal = err);
372
+ }
373
+ const weights = explicitWeights(snapshot);
374
+ const label = snapshot.nodes.byRole("label");
375
+ const nodeAttrs = planAttributes(snapshot.nodes, (c) => (c.meta.role !== null && SKIPPED_ROLES.has(c.meta.role)) || isBypass(c) || isZ(c), (c) => (c === label && !snapshot.nodes.has("name") ? "name" : c.meta.name), ids !== null && ids.changed > 0 ? new Set([ORIGINAL_ID_ATTRIBUTE]) : new Set());
376
+ const plainWeight = snapshot.edges.get(WEIGHT_ATTRIBUTE);
377
+ const weightColumnClash = plainWeight !== null && plainWeight.meta.role === null;
378
+ if (weightColumnClash) {
379
+ note(LOSS.WEIGHT_KEY_CLASH, weights.weighted
380
+ ? `edge column "${WEIGHT_ATTRIBUTE}" is not written: the explicit weights are written under that name`
381
+ : `edge column "${WEIGHT_ATTRIBUTE}" reads back as the edge weight`, WEIGHT_ATTRIBUTE, null);
382
+ }
383
+ const edgeAttrs = planAttributes(snapshot.edges, (c) => (c.meta.role !== null && (SKIPPED_ROLES.has(c.meta.role) || c.meta.role === "id")) ||
384
+ isBypass(c) ||
385
+ (weights.weighted && c === plainWeight), (c) => c.meta.name, weights.weighted ? new Set([WEIGHT_ATTRIBUTE]) : new Set());
386
+ const graphAttrs = planAttributes(snapshot.graph, () => false, (c) => c.meta.name).map((p) => ({ ...p, key: p.name }));
387
+ let nonfinite = 0;
388
+ for (const p of [...nodeAttrs, ...edgeAttrs, ...graphAttrs]) {
389
+ nonfinite += nonFiniteCount(p.column);
390
+ }
391
+ for (let e = 0; e < snapshot.edgeCount; e++) {
392
+ if (weights.isExplicit(e) && !Number.isFinite(weights.value(e))) {
393
+ nonfinite++;
394
+ }
395
+ }
396
+ const position = snapshot.nodes.byRole("position");
397
+ if (position !== null) {
398
+ nonfinite += nonFinitePositions(position);
399
+ }
400
+ if (nonfinite > 0) {
401
+ note(CX2_LOSS.NONFINITE_AS_NULL, `${nonfinite} NaN or infinite value(s) cannot be written in CX2; written as null, they read back unset`, null, nonfinite);
402
+ }
403
+ const edgeIds = planEdgeIds(snapshot, note);
404
+ const idColumn = snapshot.edges.byRole("id");
405
+ if (idColumn !== null && idColumn.dtype !== "f64") {
406
+ note(LOSS.DTYPE, `edge id column "${idColumn.meta.name}" is ${idColumn.dtype}; CX2 edge ids are integers and read back as f64`, idColumn.meta.name, snapshot.edgeCount - idColumn.nullCount);
407
+ }
408
+ const z = [...snapshot.nodes].find(isZ) ?? null;
409
+ const positionZ = position !== null && z === null && position.meta.extra.sourceDims === 3;
410
+ return {
411
+ notes,
412
+ fatal,
413
+ ids,
414
+ folding,
415
+ weights,
416
+ nodeAttrs,
417
+ edgeAttrs,
418
+ graphAttrs,
419
+ nodeBypasses: [...snapshot.nodes].filter(isBypass),
420
+ edgeBypasses: [...snapshot.edges].filter(isBypass),
421
+ position,
422
+ positionZ,
423
+ z,
424
+ edgeIds,
425
+ originalIds: ids !== null && ids.changed > 0,
426
+ };
427
+ }
428
+ /**
429
+ * The direction notes: every CX2 edge is directed, so an undirected snapshot (or the undirected
430
+ * pairs of a mixed one, folded under onMixedDirection) is written directed, and a mutual pair as
431
+ * two edges without its mark.
432
+ * @param snapshot - the snapshot
433
+ * @param folding - the pair folding
434
+ * @param common - the resolved common options
435
+ * @param note - records a note
436
+ */
437
+ function directionNotes(snapshot, folding, common, note) {
438
+ if (!snapshot.directed) {
439
+ note(CX2_LOSS.UNDIRECTED_AS_DIRECTED, `the snapshot is undirected; every edge is written as a directed CX2 edge (${snapshot.edgeCount} edge(s))`, null, snapshot.edgeCount);
440
+ }
441
+ else if (common.onMixedDirection !== "error") {
442
+ let undirected = 0;
443
+ for (let e = 0; e < snapshot.edgeCount; e++) {
444
+ if (!folding.folded(e) && !folding.sourceDirected(e)) {
445
+ undirected++;
446
+ }
447
+ }
448
+ if (undirected > 0) {
449
+ note(CX2_LOSS.UNDIRECTED_AS_DIRECTED, `${undirected} undirected edge(s) are written as one directed edge each (a pair folded to its primary); CX2 has no undirected edge`, null, undirected);
450
+ }
451
+ }
452
+ if (folding.mutualCount > 0) {
453
+ note(LOSS.MUTUAL_EXPANDED, `${folding.mutualCount} mutual pair(s) are written as two directed edges; the mutual mark is lost`, null, folding.mutualCount);
454
+ }
455
+ }
456
+ /**
457
+ * Count the positions with a non-finite x or y.
458
+ * @param position - the position column
459
+ * @returns the count
460
+ */
461
+ function nonFinitePositions(position) {
462
+ let count = 0;
463
+ for (let i = 0; i < position.length; i++) {
464
+ if (position.isSet(i)) {
465
+ const p = position.value(i);
466
+ if (!Number.isFinite(p[0]) || !Number.isFinite(p[1])) {
467
+ count++;
468
+ }
469
+ }
470
+ }
471
+ return count;
472
+ }
473
+ /**
474
+ * The edge ids to write: the id role column's values when they are distinct safe integers,
475
+ * next unused integers for edges without one.
476
+ * @param snapshot - the snapshot
477
+ * @param note - records a note
478
+ * @returns one id per edge
479
+ */
480
+ function planEdgeIds(snapshot, note) {
481
+ const column = snapshot.edges.byRole("id");
482
+ const ids = new Array(snapshot.edgeCount).fill(null);
483
+ const used = new Set();
484
+ let generated = 0;
485
+ if (column !== null) {
486
+ for (let e = 0; e < snapshot.edgeCount; e++) {
487
+ const value = column.isSet(e) ? column.value(e) : undefined;
488
+ let n = NaN;
489
+ if (typeof value === "number") {
490
+ n = value;
491
+ }
492
+ else if (typeof value === "string") {
493
+ n = Number(value);
494
+ }
495
+ if (Number.isSafeInteger(n) && !used.has(n)) {
496
+ ids[e] = n === 0 ? 0 : n;
497
+ used.add(n);
498
+ }
499
+ }
500
+ }
501
+ let next = 0;
502
+ const out = [];
503
+ for (let e = 0; e < snapshot.edgeCount; e++) {
504
+ let id = ids[e];
505
+ if (id === null) {
506
+ while (used.has(next)) {
507
+ next++;
508
+ }
509
+ id = next;
510
+ used.add(next);
511
+ generated++;
512
+ }
513
+ out.push(id);
514
+ }
515
+ if (column !== null && generated > 0) {
516
+ note(LOSS.EDGE_IDS_GENERATED, `${generated} edge(s) have no distinct integer id in "${column.meta.name}"; they are written with generated ids`, column.meta.name, generated);
517
+ }
518
+ return out;
519
+ }
520
+ // ============================================================ writing
521
+ /**
522
+ * The JSON text of a value, keeping -0.
523
+ * @param value - the value
524
+ * @returns the text
525
+ */
526
+ function stringify(value) {
527
+ const text = JSON.stringify(value, (_key, v) => (Object.is(v, -0) ? `${RAW}-0` : v));
528
+ return text.includes("\\u0000cx2:") ? text.replace(RAW_JSON, "$1") : text;
529
+ }
530
+ /**
531
+ * The value written for one cell.
532
+ * @param p - the attribute plan
533
+ * @param row - the row
534
+ * @returns the value, or undefined for an unset cell
535
+ */
536
+ function cellValue(p, row) {
537
+ const { column } = p;
538
+ if (!column.isSet(row)) {
539
+ return undefined;
540
+ }
541
+ const value = column.value(row);
542
+ if (p.jsonText) {
543
+ return JSON.stringify(value);
544
+ }
545
+ if (column.meta.dtype === "list" || column.meta.components > 1) {
546
+ const items = Array.from(value);
547
+ if (p.d === "string") {
548
+ return JSON.stringify(items);
549
+ }
550
+ return items.some((v) => typeof v === "number" && !Number.isFinite(v)) ? null : items;
551
+ }
552
+ if (typeof value === "number" && !Number.isFinite(value)) {
553
+ return null;
554
+ }
555
+ return value;
556
+ }
557
+ /**
558
+ * The declarations of one table.
559
+ * @param plans - the attribute plans
560
+ * @param defaults - whether defaults and aliases may be written (not for network attributes)
561
+ * @returns the declaration object
562
+ */
563
+ function declarations(plans, defaults) {
564
+ const out = {};
565
+ for (const p of plans) {
566
+ const decl = { d: p.d };
567
+ if (defaults && p.key !== p.name) {
568
+ decl.a = p.key;
569
+ }
570
+ const fallback = p.column.meta.default;
571
+ if (defaults && fallback !== undefined && fallback !== null) {
572
+ if (defaultFits(cx2Type(p.d), fallback)) {
573
+ decl.v = fallback;
574
+ }
575
+ }
576
+ out[p.name] = decl;
577
+ }
578
+ return out;
579
+ }
580
+ /**
581
+ * Whether a declared default can be written as the value of a declared type.
582
+ * @param type - the type
583
+ * @param fallback - the default
584
+ * @returns true when it matches
585
+ */
586
+ function defaultFits(type, fallback) {
587
+ if (type === null) {
588
+ return false;
589
+ }
590
+ if (type.list) {
591
+ return Array.isArray(fallback);
592
+ }
593
+ switch (type.scalar) {
594
+ case "string":
595
+ return typeof fallback === "string";
596
+ case "boolean":
597
+ return typeof fallback === "boolean";
598
+ default:
599
+ return typeof fallback === "number" && Number.isFinite(fallback);
600
+ }
601
+ }
602
+ /**
603
+ * The v object of one element.
604
+ * @param plans - the attribute plans
605
+ * @param row - the row
606
+ * @returns the object, or null when empty
607
+ */
608
+ function attributesOf(plans, row) {
609
+ let out = null;
610
+ for (const p of plans) {
611
+ const value = cellValue(p, row);
612
+ if (value !== undefined) {
613
+ out ?? (out = {});
614
+ out[p.key] = value;
615
+ }
616
+ }
617
+ return out;
618
+ }
619
+ /**
620
+ * Write the document as text parts.
621
+ * @param snapshot - the snapshot
622
+ * @param p - the plan
623
+ * @yields the document's text
624
+ * @returns nothing
625
+ */
626
+ function* write(snapshot, p) {
627
+ if (p.fatal !== null) {
628
+ throw p.fatal;
629
+ }
630
+ const { ids } = p;
631
+ if (ids === null) {
632
+ throw new GraphFormatError("E_INVALID_ID", "node ids cannot be written as CX2 integers", { reason: "charset" });
633
+ }
634
+ const { src, dst } = snapshot.edgeList();
635
+ const edges = [];
636
+ for (let e = 0; e < snapshot.edgeCount; e++) {
637
+ if (!p.folding.folded(e)) {
638
+ edges.push(e);
639
+ }
640
+ }
641
+ const nodeDecls = declarations(p.nodeAttrs, true);
642
+ if (p.originalIds) {
643
+ nodeDecls[ORIGINAL_ID_ATTRIBUTE] = { d: "string" };
644
+ }
645
+ const edgeDecls = declarations(p.edgeAttrs, true);
646
+ if (p.weights.weighted) {
647
+ edgeDecls[WEIGHT_ATTRIBUTE] = { d: "double" };
648
+ }
649
+ const networkDecls = declarations(p.graphAttrs, false);
650
+ const network = {};
651
+ for (const a of p.graphAttrs) {
652
+ const value = cellValue(a, 0);
653
+ if (value !== undefined) {
654
+ network[a.name] = value;
655
+ }
656
+ }
657
+ const { meta } = snapshot;
658
+ for (const [key, value] of [
659
+ ["name", meta.name],
660
+ ["description", meta.description],
661
+ ]) {
662
+ if (value !== null && !(key in network) && !(key in networkDecls)) {
663
+ network[key] = value;
664
+ networkDecls[key] = { d: "string" };
665
+ }
666
+ }
667
+ const kept = isRecord(meta.extra.cx2) ? meta.extra.cx2 : {};
668
+ const otherDecls = isRecord(kept.declarations) ? kept.declarations : {};
669
+ const opaque = meta.sourceFormat === CX2_FORMAT && isRecord(kept.opaque) ? kept.opaque : {};
670
+ const declarationsElement = { ...otherDecls };
671
+ for (const [key, table] of [
672
+ ["networkAttributes", networkDecls],
673
+ ["nodes", nodeDecls],
674
+ ["edges", edgeDecls],
675
+ ]) {
676
+ if (Object.keys(table).length > 0) {
677
+ declarationsElement[key] = table;
678
+ }
679
+ }
680
+ const nodeBypassRows = bypassRows(p.nodeBypasses, snapshot.nodeCount);
681
+ const edgeBypassRows = bypassRows(p.edgeBypasses, snapshot.edgeCount).filter((e) => !p.folding.folded(e));
682
+ const opaqueAspects = Object.entries(opaque).filter((entry) => !CORE_ASPECTS.has(entry[0]) && Array.isArray(entry[1]));
683
+ const counts = [];
684
+ const hasDeclarations = Object.keys(declarationsElement).length > 0;
685
+ if (hasDeclarations) {
686
+ counts.push(["attributeDeclarations", 1]);
687
+ }
688
+ if (Object.keys(network).length > 0) {
689
+ counts.push(["networkAttributes", 1]);
690
+ }
691
+ counts.push(["nodes", snapshot.nodeCount], ["edges", edges.length]);
692
+ if (nodeBypassRows.length > 0) {
693
+ counts.push(["nodeBypasses", nodeBypassRows.length]);
694
+ }
695
+ if (edgeBypassRows.length > 0) {
696
+ counts.push(["edgeBypasses", edgeBypassRows.length]);
697
+ }
698
+ for (const [name, elements] of opaqueAspects) {
699
+ counts.push([name, elements.length]);
700
+ }
701
+ yield '[{"CXVersion":"2.0","hasFragments":false},\n';
702
+ yield `{"metaData":${stringify(counts.map(([name, elementCount]) => ({ name, elementCount })))}},\n`;
703
+ if (hasDeclarations) {
704
+ yield `{"attributeDeclarations":[${stringify(declarationsElement)}]},\n`;
705
+ }
706
+ if (Object.keys(network).length > 0) {
707
+ yield `{"networkAttributes":[${stringify(network)}]},\n`;
708
+ }
709
+ yield* block("nodes", snapshot.nodeCount, (i) => stringify(nodeElement(p, ids, i)));
710
+ yield* block("edges", edges.length, (k) => {
711
+ const e = edges[k];
712
+ const element = {
713
+ id: p.edgeIds[e],
714
+ s: ids.idAt(src[e]),
715
+ t: ids.idAt(dst[e]),
716
+ };
717
+ let v = attributesOf(p.edgeAttrs, e);
718
+ if (p.weights.isExplicit(e)) {
719
+ const w = p.weights.value(e);
720
+ v ?? (v = {});
721
+ v[WEIGHT_ATTRIBUTE] = Number.isFinite(w) ? w : null;
722
+ }
723
+ if (v !== null) {
724
+ element.v = v;
725
+ }
726
+ return stringify(element);
727
+ });
728
+ if (nodeBypassRows.length > 0) {
729
+ yield* block("nodeBypasses", nodeBypassRows.length, (k) => {
730
+ const i = nodeBypassRows[k];
731
+ return stringify({ id: ids.idAt(i), v: bypassValues(p.nodeBypasses, i) });
732
+ });
733
+ }
734
+ if (edgeBypassRows.length > 0) {
735
+ yield* block("edgeBypasses", edgeBypassRows.length, (k) => {
736
+ const e = edgeBypassRows[k];
737
+ return stringify({ id: p.edgeIds[e], v: bypassValues(p.edgeBypasses, e) });
738
+ });
739
+ }
740
+ for (const [name, elements] of opaqueAspects) {
741
+ yield* block(name, elements.length, (k) => stringify(elements[k]));
742
+ }
743
+ yield '{"status":[{"error":"","success":true}]}]\n';
744
+ }
745
+ /**
746
+ * The text of one aspect block, element by element.
747
+ * @param aspect - the aspect name
748
+ * @param count - its element count
749
+ * @param element - the JSON text of element k
750
+ * @yields the block's text
751
+ * @returns nothing
752
+ */
753
+ function* block(aspect, count, element) {
754
+ yield `{${JSON.stringify(aspect)}:[`;
755
+ for (let k = 0; k < count; k++) {
756
+ yield k === 0 ? `\n${element(k)}` : `,\n${element(k)}`;
757
+ }
758
+ yield "]},\n";
759
+ }
760
+ /**
761
+ * The element of node i.
762
+ * @param p - the plan
763
+ * @param ids - the written ids
764
+ * @param i - the node index
765
+ * @returns the element
766
+ */
767
+ function nodeElement(p, ids, i) {
768
+ const element = { id: ids.idAt(i) };
769
+ if (p.position?.isSet(i) === true) {
770
+ const point = p.position.value(i);
771
+ if (Number.isFinite(point[0]) && Number.isFinite(point[1])) {
772
+ element.x = point[0];
773
+ element.y = point[1] === 0 ? 0 : -point[1];
774
+ if (p.positionZ && Number.isFinite(point[2])) {
775
+ element.z = point[2];
776
+ }
777
+ }
778
+ }
779
+ if (p.z?.isSet(i) === true) {
780
+ const z = p.z.value(i);
781
+ if (typeof z === "number" && Number.isFinite(z)) {
782
+ element.z = z;
783
+ }
784
+ }
785
+ let v = attributesOf(p.nodeAttrs, i);
786
+ if (p.originalIds && ids.isChanged(i)) {
787
+ v ?? (v = {});
788
+ v[ORIGINAL_ID_ATTRIBUTE] = String(ids.originalAt(i));
789
+ }
790
+ if (v !== null) {
791
+ element.v = v;
792
+ }
793
+ return element;
794
+ }
795
+ /**
796
+ * The rows with at least one bypass value.
797
+ * @param columns - the bypass columns
798
+ * @param rows - the row count
799
+ * @returns the rows, ascending
800
+ */
801
+ function bypassRows(columns, rows) {
802
+ const out = [];
803
+ if (columns.length === 0) {
804
+ return out;
805
+ }
806
+ for (let i = 0; i < rows; i++) {
807
+ if (columns.some((c) => c.isSet(i))) {
808
+ out.push(i);
809
+ }
810
+ }
811
+ return out;
812
+ }
813
+ /**
814
+ * The bypass values of one row.
815
+ * @param columns - the bypass columns
816
+ * @param row - the row
817
+ * @returns property -> value
818
+ */
819
+ function bypassValues(columns, row) {
820
+ const out = {};
821
+ for (const column of columns) {
822
+ if (column.isSet(row)) {
823
+ // the visual property's own name: a column renamed for a clash with an attribute keeps it in origin.id
824
+ const property = column.meta.origin?.id;
825
+ out[typeof property === "string" && property.length > 0 ? property : column.meta.name] = column.value(row);
826
+ }
827
+ }
828
+ return out;
829
+ }
830
+ /**
831
+ * The CX2 exporter plugin (design section 1.3).
832
+ */
833
+ export const cx2Exporter = Object.freeze({
834
+ format: CX2_FORMAT,
835
+ capabilities: CX2_CAPABILITIES,
836
+ /**
837
+ * Pre-flight: what export() would lose, without writing anything.
838
+ * @param snapshot - the snapshot
839
+ * @param options - the common options
840
+ * @returns the notes, empty when the export is exact
841
+ */
842
+ check(snapshot, options) {
843
+ return Object.freeze([...plan(snapshot, resolveExportOptions(options)).notes]);
844
+ },
845
+ /**
846
+ * Write the document as UTF-8 chunks.
847
+ * @param snapshot - the snapshot
848
+ * @param options - the common options
849
+ * @returns the chunks
850
+ */
851
+ export(snapshot, options) {
852
+ return encodeChunks(write(snapshot, plan(snapshot, resolveExportOptions(options))));
853
+ },
854
+ /**
855
+ * Write the document as one string.
856
+ * @param snapshot - the snapshot
857
+ * @param options - the common options
858
+ * @returns the document
859
+ */
860
+ exportToString(snapshot, options) {
861
+ return joinText(write(snapshot, plan(snapshot, resolveExportOptions(options))));
862
+ },
863
+ });
864
+ //# sourceMappingURL=exporter.js.map