@graphty/graph-io 0.3.18 → 0.3.20

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 (235) hide show
  1. package/README.md +80 -2
  2. package/dist/chunks/{escape-D-gZWO26.js → escape-B-tkk_Cl.js} +74 -16
  3. package/dist/chunks/escape-B-tkk_Cl.js.map +1 -0
  4. package/dist/chunks/{writer-GAdltGmC.js → export-Bh60Dv-n.js} +7 -252
  5. package/dist/chunks/export-Bh60Dv-n.js.map +1 -0
  6. package/dist/chunks/exporter-BGrsWamJ.js +736 -0
  7. package/dist/chunks/exporter-BGrsWamJ.js.map +1 -0
  8. package/dist/chunks/exporter-DIeGJXAZ.js +834 -0
  9. package/dist/chunks/exporter-DIeGJXAZ.js.map +1 -0
  10. package/dist/chunks/{importer-Br_QeAeE.js → importer-BWY2FFc5.js} +28 -6
  11. package/dist/chunks/importer-BWY2FFc5.js.map +1 -0
  12. package/dist/chunks/importer-BaQpCEcJ.js +2194 -0
  13. package/dist/chunks/importer-BaQpCEcJ.js.map +1 -0
  14. package/dist/chunks/importer-DD-xv9_Y.js +1471 -0
  15. package/dist/chunks/importer-DD-xv9_Y.js.map +1 -0
  16. package/dist/chunks/{importer-aNJfe0qu.js → importer-DEcKhsmQ.js} +2 -2
  17. package/dist/chunks/{importer-aNJfe0qu.js.map → importer-DEcKhsmQ.js.map} +1 -1
  18. package/dist/chunks/{importer-DHagxvDD.js → importer-DIrbbnAf.js} +6 -4
  19. package/dist/chunks/{importer-DHagxvDD.js.map → importer-DIrbbnAf.js.map} +1 -1
  20. package/dist/chunks/importer-D_e7e7LX.js +3055 -0
  21. package/dist/chunks/importer-D_e7e7LX.js.map +1 -0
  22. package/dist/chunks/{importer-Du5crN9l.js → importer-Wv4C4gaF.js} +278 -82
  23. package/dist/chunks/importer-Wv4C4gaF.js.map +1 -0
  24. package/dist/chunks/importer-vi3bSdtw.js +1713 -0
  25. package/dist/chunks/importer-vi3bSdtw.js.map +1 -0
  26. package/dist/chunks/{importer-d0uQxFp6.js → importer-zGLo8Dg_.js} +6 -4
  27. package/dist/chunks/{importer-d0uQxFp6.js.map → importer-zGLo8Dg_.js.map} +1 -1
  28. package/dist/chunks/json-elements-DDS8N2Dd.js +779 -0
  29. package/dist/chunks/json-elements-DDS8N2Dd.js.map +1 -0
  30. package/dist/chunks/{records-Bk9jgodz.js → records-dbRkxwaq.js} +2 -2
  31. package/dist/chunks/{records-Bk9jgodz.js.map → records-dbRkxwaq.js.map} +1 -1
  32. package/dist/chunks/{report-BOk0p5y8.js → report-B1z4WT9e.js} +143 -111
  33. package/dist/chunks/{report-BOk0p5y8.js.map → report-B1z4WT9e.js.map} +1 -1
  34. package/dist/chunks/weights-Dzba96G3.js +176 -0
  35. package/dist/chunks/weights-Dzba96G3.js.map +1 -0
  36. package/dist/chunks/writer-C7flM-Ih.js +77 -0
  37. package/dist/chunks/writer-C7flM-Ih.js.map +1 -0
  38. package/dist/csv.js +6 -4
  39. package/dist/csv.js.map +1 -1
  40. package/dist/cx.d.ts +1 -0
  41. package/dist/cx.js +6 -0
  42. package/dist/cx.js.map +1 -0
  43. package/dist/cx2.d.ts +1 -0
  44. package/dist/cx2.js +10 -0
  45. package/dist/cx2.js.map +1 -0
  46. package/dist/cys.d.ts +1 -0
  47. package/dist/cys.js +6 -0
  48. package/dist/cys.js.map +1 -0
  49. package/dist/dot.js +1 -1
  50. package/dist/gexf.js +16 -4
  51. package/dist/gexf.js.map +1 -1
  52. package/dist/gml.js +13 -14
  53. package/dist/gml.js.map +1 -1
  54. package/dist/graph-io.js +302 -399
  55. package/dist/graph-io.js.map +1 -1
  56. package/dist/graphml.js +1 -1
  57. package/dist/json.js +1 -1
  58. package/dist/neo4j.js +6 -4
  59. package/dist/neo4j.js.map +1 -1
  60. package/dist/obo.js +1 -1
  61. package/dist/pajek.js +1 -1
  62. package/dist/src/common/cell-budget.d.ts +84 -0
  63. package/dist/src/common/cell-budget.d.ts.map +1 -0
  64. package/dist/src/common/cell-budget.js +138 -0
  65. package/dist/src/common/cell-budget.js.map +1 -0
  66. package/dist/src/common/input.d.ts +10 -0
  67. package/dist/src/common/input.d.ts.map +1 -1
  68. package/dist/src/common/input.js +39 -0
  69. package/dist/src/common/input.js.map +1 -1
  70. package/dist/src/common/json-elements.d.ts +286 -0
  71. package/dist/src/common/json-elements.d.ts.map +1 -0
  72. package/dist/src/common/json-elements.js +926 -0
  73. package/dist/src/common/json-elements.js.map +1 -0
  74. package/dist/src/common/options.d.ts +6 -0
  75. package/dist/src/common/options.d.ts.map +1 -1
  76. package/dist/src/common/options.js +1 -1
  77. package/dist/src/common/options.js.map +1 -1
  78. package/dist/src/common/xml.d.ts +37 -3
  79. package/dist/src/common/xml.d.ts.map +1 -1
  80. package/dist/src/common/xml.js +86 -6
  81. package/dist/src/common/xml.js.map +1 -1
  82. package/dist/src/common/zip.d.ts +92 -0
  83. package/dist/src/common/zip.d.ts.map +1 -0
  84. package/dist/src/common/zip.js +399 -0
  85. package/dist/src/common/zip.js.map +1 -0
  86. package/dist/src/formats/cx/importer.d.ts +133 -0
  87. package/dist/src/formats/cx/importer.d.ts.map +1 -0
  88. package/dist/src/formats/cx/importer.js +2220 -0
  89. package/dist/src/formats/cx/importer.js.map +1 -0
  90. package/dist/src/formats/cx/index.d.ts +7 -0
  91. package/dist/src/formats/cx/index.d.ts.map +1 -0
  92. package/dist/src/formats/cx/index.js +7 -0
  93. package/dist/src/formats/cx/index.js.map +1 -0
  94. package/dist/src/formats/cx2/exporter.d.ts +59 -0
  95. package/dist/src/formats/cx2/exporter.d.ts.map +1 -0
  96. package/dist/src/formats/cx2/exporter.js +864 -0
  97. package/dist/src/formats/cx2/exporter.js.map +1 -0
  98. package/dist/src/formats/cx2/importer.d.ts +169 -0
  99. package/dist/src/formats/cx2/importer.d.ts.map +1 -0
  100. package/dist/src/formats/cx2/importer.js +1652 -0
  101. package/dist/src/formats/cx2/importer.js.map +1 -0
  102. package/dist/src/formats/cx2/index.d.ts +7 -0
  103. package/dist/src/formats/cx2/index.d.ts.map +1 -0
  104. package/dist/src/formats/cx2/index.js +7 -0
  105. package/dist/src/formats/cx2/index.js.map +1 -0
  106. package/dist/src/formats/cys/constants.d.ts +68 -0
  107. package/dist/src/formats/cys/constants.d.ts.map +1 -0
  108. package/dist/src/formats/cys/constants.js +76 -0
  109. package/dist/src/formats/cys/constants.js.map +1 -0
  110. package/dist/src/formats/cys/importer.d.ts +38 -0
  111. package/dist/src/formats/cys/importer.d.ts.map +1 -0
  112. package/dist/src/formats/cys/importer.js +830 -0
  113. package/dist/src/formats/cys/importer.js.map +1 -0
  114. package/dist/src/formats/cys/index.d.ts +7 -0
  115. package/dist/src/formats/cys/index.d.ts.map +1 -0
  116. package/dist/src/formats/cys/index.js +7 -0
  117. package/dist/src/formats/cys/index.js.map +1 -0
  118. package/dist/src/formats/cys/session.d.ts +132 -0
  119. package/dist/src/formats/cys/session.d.ts.map +1 -0
  120. package/dist/src/formats/cys/session.js +315 -0
  121. package/dist/src/formats/cys/session.js.map +1 -0
  122. package/dist/src/formats/cys/tables.d.ts +90 -0
  123. package/dist/src/formats/cys/tables.d.ts.map +1 -0
  124. package/dist/src/formats/cys/tables.js +293 -0
  125. package/dist/src/formats/cys/tables.js.map +1 -0
  126. package/dist/src/formats/dot/exporter.d.ts +2 -0
  127. package/dist/src/formats/dot/exporter.d.ts.map +1 -1
  128. package/dist/src/formats/dot/exporter.js +12 -0
  129. package/dist/src/formats/dot/exporter.js.map +1 -1
  130. package/dist/src/formats/dot/importer.js +6 -2
  131. package/dist/src/formats/dot/importer.js.map +1 -1
  132. package/dist/src/formats/gexf/exporter.d.ts +2 -0
  133. package/dist/src/formats/gexf/exporter.d.ts.map +1 -1
  134. package/dist/src/formats/gexf/exporter.js +6 -0
  135. package/dist/src/formats/gexf/exporter.js.map +1 -1
  136. package/dist/src/formats/gexf/importer.d.ts +0 -2
  137. package/dist/src/formats/gexf/importer.d.ts.map +1 -1
  138. package/dist/src/formats/gexf/importer.js +1 -3
  139. package/dist/src/formats/gexf/importer.js.map +1 -1
  140. package/dist/src/formats/gexf/index.d.ts +1 -1
  141. package/dist/src/formats/gexf/index.js +2 -2
  142. package/dist/src/formats/gexf/index.js.map +1 -1
  143. package/dist/src/formats/gml/exporter.d.ts +0 -8
  144. package/dist/src/formats/gml/exporter.d.ts.map +1 -1
  145. package/dist/src/formats/gml/exporter.js +8 -18
  146. package/dist/src/formats/gml/exporter.js.map +1 -1
  147. package/dist/src/formats/json/importer.d.ts.map +1 -1
  148. package/dist/src/formats/json/importer.js +6 -104
  149. package/dist/src/formats/json/importer.js.map +1 -1
  150. package/dist/src/formats/xgmml/columns.d.ts +152 -0
  151. package/dist/src/formats/xgmml/columns.d.ts.map +1 -0
  152. package/dist/src/formats/xgmml/columns.js +593 -0
  153. package/dist/src/formats/xgmml/columns.js.map +1 -0
  154. package/dist/src/formats/xgmml/constants.d.ts +196 -0
  155. package/dist/src/formats/xgmml/constants.d.ts.map +1 -0
  156. package/dist/src/formats/xgmml/constants.js +197 -0
  157. package/dist/src/formats/xgmml/constants.js.map +1 -0
  158. package/dist/src/formats/xgmml/document.d.ts +361 -0
  159. package/dist/src/formats/xgmml/document.d.ts.map +1 -0
  160. package/dist/src/formats/xgmml/document.js +695 -0
  161. package/dist/src/formats/xgmml/document.js.map +1 -0
  162. package/dist/src/formats/xgmml/emit.d.ts +341 -0
  163. package/dist/src/formats/xgmml/emit.d.ts.map +1 -0
  164. package/dist/src/formats/xgmml/emit.js +1275 -0
  165. package/dist/src/formats/xgmml/emit.js.map +1 -0
  166. package/dist/src/formats/xgmml/exporter.d.ts +24 -0
  167. package/dist/src/formats/xgmml/exporter.d.ts.map +1 -0
  168. package/dist/src/formats/xgmml/exporter.js +999 -0
  169. package/dist/src/formats/xgmml/exporter.js.map +1 -0
  170. package/dist/src/formats/xgmml/importer.d.ts +58 -0
  171. package/dist/src/formats/xgmml/importer.d.ts.map +1 -0
  172. package/dist/src/formats/xgmml/importer.js +360 -0
  173. package/dist/src/formats/xgmml/importer.js.map +1 -0
  174. package/dist/src/formats/xgmml/index.d.ts +8 -0
  175. package/dist/src/formats/xgmml/index.d.ts.map +1 -0
  176. package/dist/src/formats/xgmml/index.js +8 -0
  177. package/dist/src/formats/xgmml/index.js.map +1 -0
  178. package/dist/src/formats/xgmml/values.d.ts +60 -0
  179. package/dist/src/formats/xgmml/values.d.ts.map +1 -0
  180. package/dist/src/formats/xgmml/values.js +148 -0
  181. package/dist/src/formats/xgmml/values.js.map +1 -0
  182. package/dist/src/index.d.ts +4 -0
  183. package/dist/src/index.d.ts.map +1 -1
  184. package/dist/src/index.js +4 -0
  185. package/dist/src/index.js.map +1 -1
  186. package/dist/src/registry.d.ts +7 -0
  187. package/dist/src/registry.d.ts.map +1 -1
  188. package/dist/src/registry.js +30 -10
  189. package/dist/src/registry.js.map +1 -1
  190. package/dist/src/sniff.d.ts +1 -1
  191. package/dist/src/sniff.d.ts.map +1 -1
  192. package/dist/src/sniff.js +4 -0
  193. package/dist/src/sniff.js.map +1 -1
  194. package/dist/xgmml.d.ts +1 -0
  195. package/dist/xgmml.js +9 -0
  196. package/dist/xgmml.js.map +1 -0
  197. package/package.json +25 -2
  198. package/src/common/cell-budget.ts +170 -0
  199. package/src/common/input.ts +40 -0
  200. package/src/common/json-elements.ts +1147 -0
  201. package/src/common/options.ts +1 -1
  202. package/src/common/xml.ts +127 -6
  203. package/src/common/zip.ts +472 -0
  204. package/src/formats/cx/importer.ts +2733 -0
  205. package/src/formats/cx/index.ts +7 -0
  206. package/src/formats/cx2/exporter.ts +1036 -0
  207. package/src/formats/cx2/importer.ts +2187 -0
  208. package/src/formats/cx2/index.ts +7 -0
  209. package/src/formats/cys/constants.ts +99 -0
  210. package/src/formats/cys/importer.ts +1100 -0
  211. package/src/formats/cys/index.ts +7 -0
  212. package/src/formats/cys/session.ts +428 -0
  213. package/src/formats/cys/tables.ts +400 -0
  214. package/src/formats/dot/exporter.ts +17 -0
  215. package/src/formats/dot/importer.ts +6 -2
  216. package/src/formats/gexf/exporter.ts +11 -0
  217. package/src/formats/gexf/importer.ts +1 -2
  218. package/src/formats/gexf/index.ts +1 -1
  219. package/src/formats/gml/exporter.ts +8 -19
  220. package/src/formats/json/importer.ts +6 -105
  221. package/src/formats/xgmml/columns.ts +747 -0
  222. package/src/formats/xgmml/constants.ts +265 -0
  223. package/src/formats/xgmml/document.ts +975 -0
  224. package/src/formats/xgmml/emit.ts +1563 -0
  225. package/src/formats/xgmml/exporter.ts +1215 -0
  226. package/src/formats/xgmml/importer.ts +491 -0
  227. package/src/formats/xgmml/index.ts +8 -0
  228. package/src/formats/xgmml/values.ts +183 -0
  229. package/src/index.ts +19 -0
  230. package/src/registry.ts +46 -15
  231. package/src/sniff.ts +18 -1
  232. package/dist/chunks/escape-D-gZWO26.js.map +0 -1
  233. package/dist/chunks/importer-Br_QeAeE.js.map +0 -1
  234. package/dist/chunks/importer-Du5crN9l.js.map +0 -1
  235. package/dist/chunks/writer-GAdltGmC.js.map +0 -1
@@ -0,0 +1,1652 @@
1
+ /**
2
+ * The CX2 importer (design/graph-io/cytoscape-and-obo/design.md section 1.3; the feature and error
3
+ * inventory is research-cx2.md): the JSON exchange format of NDEx, Cytoscape 3.10+ and Cytoscape
4
+ * Web. A CX2 document is one array: a descriptor (`CXVersion`), aspect blocks (`nodes`, `edges`,
5
+ * `attributeDeclarations`, `networkAttributes`, `nodeBypasses`, `visualProperties`, opaque
6
+ * aspects) and a final `status`.
7
+ *
8
+ * The document is read through the streaming scanner of common/json-elements.ts, so its text is
9
+ * never held as one string; the parsed aspect elements are collected and the graph is built at the
10
+ * end, which makes every aspect order the format allows (declarations after the nodes, edges
11
+ * before their nodes) read the same.
12
+ *
13
+ * Mapping: every edge is directed (CX2 has no undirected edge); node ids follow the CX id rule
14
+ * (design section 1.0.2); declared attributes become typed columns named by their full name, with
15
+ * the alias in `origin.id` and the declared default in `meta.default`; `name` is the label; node
16
+ * `x` / `y` become the position column with y flipped to y-up, `z` the `z` column; per-element
17
+ * bypasses become one column per visual property (origin namespace "cx2.bypass"); style rules
18
+ * (`visualProperties`, `visualEditorProperties`) and every opaque aspect are kept verbatim in
19
+ * `meta.extra.cx2.opaque` and are not applied (W_STYLES_NOT_IMPORTED, issue #706).
20
+ */
21
+ import { GraphFormatError, INVALID_INDEX, } from "@graphty/graph-format";
22
+ import { declareResolved, uniqueColumnName } from "../../common/attributes.js";
23
+ import { ASPECT_ORDER_CODE, BAD_ASPECT_BLOCK_CODE, BAD_DEFAULT_CODE, BAD_VALUE_CODE, COLUMN_RENAMED_CODE, COUNT_MISMATCH_CODE, DANGLING_REFERENCE_CODE, DIRECTION_FORCED_CODE, DIRECTION_REFUSED_CODE, DUPLICATE_ATTRIBUTE_CODE, DUPLICATE_EDGE_ID_CODE, DUPLICATE_NODE_CODE, EMPTY_INPUT_CODE, ENCODING_FALLBACK_CODE, ID_MERGED_CODE, ID_TEXT_TYPE_CODE, INVALID_ENCODING_CODE, INVALID_UTF8_CODE, MISSING_ENDPOINT_CODE, MISSING_ID_CODE, OPTION_IGNORED_CODE, PRECISION_CODE, ROLE_TAKEN_CODE, SINK_OPTION_CODE, STATUS_FAILED_CODE, STATUS_WARNING_CODE, STYLES_NOT_IMPORTED_CODE, SYNTAX_CODE, TOO_LARGE_CODE, UNKNOWN_ATTR_TYPE_CODE, UNKNOWN_ELEMENT_CODE, UNKNOWN_ENCODING_CODE, } from "../../common/codes.js";
24
+ import { DirectionResolver } from "../../common/direction.js";
25
+ import { IdCoercer } from "../../common/ids.js";
26
+ import { textChunks, throwIfAborted } from "../../common/input.js";
27
+ import { cxId, CxStructure, declareFresh, ExactInteger, flipY, inexactLiteral, isRecord, JsonScanError, plainJson, positionDecl, reportTooDeep, scanAspects, zDecl, } from "../../common/json-elements.js";
28
+ import { reportSinkOptions, reportUnusedOptions, resolveImportOptions, } from "../../common/options.js";
29
+ import { ImportReportBuilder } from "../../common/report.js";
30
+ import { weightFromValue } from "../../common/weights.js";
31
+ /** The format name. */
32
+ export const CX2_FORMAT = "cx2";
33
+ /** The node attribute the exporter's `sanitizeIds: "mangle"` keeps an original id in. */
34
+ export const ORIGINAL_ID_ATTRIBUTE = "graphty:originalId";
35
+ /** The origin namespace of the per-element visual property columns. */
36
+ export const BYPASS_NAMESPACE = "cx2.bypass";
37
+ /**
38
+ * The issue codes the CX2 importer records (design section 1.3), by name: the codes shared with
39
+ * the other importers (src/common/codes.ts) and the CX2-specific ones. A key is the code without
40
+ * its severity and format prefixes.
41
+ */
42
+ export const CX2_ISSUE = Object.freeze({
43
+ /** The input is empty (fatal). */
44
+ EMPTY_INPUT: EMPTY_INPUT_CODE,
45
+ /** The text is not JSON (fatal). */
46
+ SYNTAX: SYNTAX_CODE,
47
+ /** Invalid UTF-8 (fatal). */
48
+ INVALID_UTF8: INVALID_UTF8_CODE,
49
+ /** Invalid bytes in the encoding a BOM or the encoding option chose (fatal). */
50
+ INVALID_ENCODING: INVALID_ENCODING_CODE,
51
+ /** Bytes that are not UTF-8 were read as windows-1252. */
52
+ ENCODING_FALLBACK: ENCODING_FALLBACK_CODE,
53
+ /** An encoding the platform cannot decode was ignored. */
54
+ UNKNOWN_ENCODING: UNKNOWN_ENCODING_CODE,
55
+ /** The document is not an array or does not start with a descriptor holding CXVersion (fatal). */
56
+ NO_DESCRIPTOR: "E_CX2_NO_DESCRIPTOR",
57
+ /** CXVersion names a major version other than 2 (fatal); "1.x" says the file is CX1. */
58
+ VERSION: "E_CX2_VERSION",
59
+ /** CXVersion is a 2.x other than "2.0" (or not a string); the document is read. */
60
+ MINOR_VERSION: "W_CX2_MINOR_VERSION",
61
+ /** The document has no status block, or a malformed one. */
62
+ NO_STATUS: "E_CX2_NO_STATUS",
63
+ /** The producer marked the document as failed (fatal). */
64
+ STATUS_FAILED: STATUS_FAILED_CODE,
65
+ /** The producer marked the document as successful with an error text. */
66
+ STATUS_WARNING: STATUS_WARNING_CODE,
67
+ /** An aspect appears in several blocks although the descriptor does not declare fragments. */
68
+ UNDECLARED_FRAGMENTS: "W_CX2_UNDECLARED_FRAGMENTS",
69
+ /** An attribute declared twice with two different types; the first declaration wins. */
70
+ DECLARATION_CONFLICT: "E_CX2_DECLARATION_CONFLICT",
71
+ /** An attribute value whose name no declaration covers; its column is inferred. */
72
+ UNDECLARED_ATTRIBUTE: "W_CX2_UNDECLARED_ATTRIBUTE",
73
+ /** A node or edge attribute named `id`, which the specification reserves. */
74
+ RESERVED_KEY: "W_CX2_RESERVED_KEY",
75
+ /** An alias that is another attribute's name or another attribute's alias; the alias is ignored. */
76
+ ALIAS_CONFLICT: "E_CX2_ALIAS_CONFLICT",
77
+ /** A network attribute declaration with an alias or a default, which CX2 forbids; both ignored. */
78
+ NETWORK_DECLARATION: "W_CX2_NETWORK_DECLARATION",
79
+ /** An aspect that holds one element holds several; the first is read. */
80
+ EXTRA_ELEMENTS: "W_CX2_EXTRA_ELEMENTS",
81
+ /** Some nodes have coordinates and others none, or a node has x without y. */
82
+ PARTIAL_LAYOUT: "W_CX2_PARTIAL_LAYOUT",
83
+ /** A full attribute name used where its alias is declared; read as the same attribute. */
84
+ ALIAS_BYPASSED: "W_CX2_ALIAS_BYPASSED",
85
+ /** A CX1 cartesianLayout aspect next to node coordinates; kept, not applied. */
86
+ LEGACY_LAYOUT: "W_CX2_LEGACY_LAYOUT",
87
+ /** The file's style rules are not applied (issue #706). */
88
+ STYLES_NOT_IMPORTED: STYLES_NOT_IMPORTED_CODE,
89
+ /** A member of the top-level array that is not a one-key aspect block, or an element that is not an object. */
90
+ BAD_ASPECT_BLOCK: BAD_ASPECT_BLOCK_CODE,
91
+ /** An aspect out of its place (after the post-metadata or the status, a third metaData, late declarations). */
92
+ ASPECT_ORDER: ASPECT_ORDER_CODE,
93
+ /** A metaData element count disagrees with what was read. */
94
+ COUNT_MISMATCH: COUNT_MISMATCH_CODE,
95
+ /** A value that does not match its declared type; the cell is unset. */
96
+ BAD_VALUE: BAD_VALUE_CODE,
97
+ /** A declared default that does not match its type. */
98
+ BAD_DEFAULT: BAD_DEFAULT_CODE,
99
+ /** A declared type CX2 does not define; the column is inferred from the values. */
100
+ UNKNOWN_ATTR_TYPE: UNKNOWN_ATTR_TYPE_CODE,
101
+ /** A bypass or a layout entry naming no node or edge. */
102
+ DANGLING_REFERENCE: DANGLING_REFERENCE_CODE,
103
+ /** The same attribute twice on one element (its alias and its full name). */
104
+ DUPLICATE_ATTRIBUTE: DUPLICATE_ATTRIBUTE_CODE,
105
+ /** A node without an id. */
106
+ MISSING_ID: MISSING_ID_CODE,
107
+ /** An edge without s or t. */
108
+ MISSING_ENDPOINT: MISSING_ENDPOINT_CODE,
109
+ /** A node id declared twice; the second merges into the first. */
110
+ DUPLICATE_NODE: DUPLICATE_NODE_CODE,
111
+ /** An edge id declared twice; the second edge is skipped. */
112
+ DUPLICATE_EDGE_ID: DUPLICATE_EDGE_ID_CODE,
113
+ /** An id that is not an integer. */
114
+ INVALID_ID: "E_INVALID_ID",
115
+ /** An edge endpoint naming no node (addMissingNodes false, the default). */
116
+ UNKNOWN_NODE: "E_UNKNOWN_NODE",
117
+ /** A weight that is not a number. */
118
+ INVALID_WEIGHT: "E_INVALID_WEIGHT",
119
+ /** An id spelled as a string or a non-integer literal; read as the integer. */
120
+ ID_TEXT_TYPE: ID_TEXT_TYPE_CODE,
121
+ /** An integer beyond 2^53: an id kept as its digits, a value stored as the nearest f64. */
122
+ PRECISION: PRECISION_CODE,
123
+ /** Two id texts merged under `ids: "number"`. */
124
+ ID_MERGED: ID_MERGED_CODE,
125
+ /** An element key CX2 does not define. */
126
+ UNKNOWN_ELEMENT: UNKNOWN_ELEMENT_CODE,
127
+ /** A column renamed because its name was taken. */
128
+ COLUMN_RENAMED: COLUMN_RENAMED_CODE,
129
+ /** A column that lost its role because another column holds it. */
130
+ ROLE_TAKEN: ROLE_TAKEN_CODE,
131
+ /** The sink refused the direction. */
132
+ DIRECTION_REFUSED: DIRECTION_REFUSED_CODE,
133
+ /** Edges forced to the policy's direction. */
134
+ DIRECTION_FORCED: DIRECTION_FORCED_CODE,
135
+ /** A common option CX2 has no use for. */
136
+ OPTION_IGNORED: OPTION_IGNORED_CODE,
137
+ /** A builder option the caller's sink does not honour. */
138
+ SINK_OPTION: SINK_OPTION_CODE,
139
+ /** The input is beyond a size limit (fatal). */
140
+ TOO_LARGE: TOO_LARGE_CODE,
141
+ });
142
+ const USED_OPTIONS = new Set([
143
+ "ids",
144
+ "addMissingNodes",
145
+ "duplicateEdges",
146
+ "selfLoops",
147
+ "onMixedDirection",
148
+ "weightFrom",
149
+ "weightDtype",
150
+ "long",
151
+ "restoreMangledIds",
152
+ "errorLimit",
153
+ "signal",
154
+ "onProgress",
155
+ ]);
156
+ /** CX2 has no undirected edge: defaultDirected never applies (reported W_OPTION_IGNORED). */
157
+ const FORMAT_DEFAULTS = {
158
+ ids: "keep",
159
+ defaultDirected: true,
160
+ weightFrom: "weight",
161
+ addMissingNodes: false,
162
+ };
163
+ const ABORT_CHECK_INTERVAL = 64;
164
+ /** The keys a node element defines. */
165
+ const NODE_KEYS = new Set(["id", "x", "y", "z", "v"]);
166
+ /** The keys an edge element defines. */
167
+ const EDGE_KEYS = new Set(["id", "s", "t", "v"]);
168
+ /** The aspects that hold one element. */
169
+ const SINGLE_ELEMENT_ASPECTS = ["networkAttributes", "visualProperties", "visualEditorProperties"];
170
+ /** The aspects whose content is a style rule (design section 2). */
171
+ const STYLE_ASPECTS = [
172
+ "visualProperties",
173
+ "visualEditorProperties",
174
+ "cyVisualProperties",
175
+ "tableVisualProperties",
176
+ "cyTableVisualProperties",
177
+ ];
178
+ /** The aspects the stream structure owns; never kept as opaque. */
179
+ const STRUCTURE_ASPECTS = new Set(["metaData", "status"]);
180
+ /** The type spellings CX2 defines, plus the Python spellings ndex2 writes. */
181
+ const SCALARS = {
182
+ string: "string",
183
+ long: "long",
184
+ integer: "integer",
185
+ double: "double",
186
+ boolean: "boolean",
187
+ str: "string",
188
+ int: "integer",
189
+ bool: "boolean",
190
+ float: "double",
191
+ };
192
+ /**
193
+ * Resolve a declared type text.
194
+ * @param d - the `d` value
195
+ * @returns the type, or null when CX2 does not define it
196
+ */
197
+ export function cx2Type(d) {
198
+ const list = d.startsWith("list_of_");
199
+ const scalar = SCALARS[list ? d.slice("list_of_".length) : d];
200
+ if (scalar === undefined) {
201
+ return null;
202
+ }
203
+ return { d: list ? `list_of_${scalar}` : scalar, scalar, list };
204
+ }
205
+ /**
206
+ * The column dtype of a scalar type.
207
+ * @param scalar - the type
208
+ * @param long - the importer's `long` option
209
+ * @returns the dtype
210
+ */
211
+ function scalarDtype(scalar, long) {
212
+ switch (scalar) {
213
+ case "string":
214
+ return "string";
215
+ case "long":
216
+ return long === "string" ? "string" : "f64";
217
+ case "integer":
218
+ return "i32";
219
+ case "double":
220
+ return "f64";
221
+ case "boolean":
222
+ return "bool";
223
+ default: {
224
+ const name = scalar;
225
+ return name;
226
+ }
227
+ }
228
+ }
229
+ /** What convertScalar() returns for a value of the wrong type. */
230
+ const BAD = Symbol("bad");
231
+ const I32_MIN = -2147483648;
232
+ const I32_MAX = 2147483647;
233
+ /**
234
+ * Convert one JSON value (or list item) by a declared scalar type.
235
+ * @param value - the value (never null)
236
+ * @param scalar - the type
237
+ * @param long - the importer's `long` option
238
+ * @param onPrecision - called for a long beyond 2^53
239
+ * @returns the value to store, or BAD
240
+ */
241
+ function convertScalar(value, scalar, long, onPrecision) {
242
+ switch (scalar) {
243
+ case "string":
244
+ return typeof value === "string" ? value : BAD;
245
+ case "boolean":
246
+ return typeof value === "boolean" ? value : BAD;
247
+ case "double":
248
+ if (value instanceof ExactInteger) {
249
+ return Number(value.digits);
250
+ }
251
+ return typeof value === "number" ? value : BAD;
252
+ case "integer":
253
+ return typeof value === "number" && Number.isInteger(value) && value >= I32_MIN && value <= I32_MAX
254
+ ? value
255
+ : BAD;
256
+ case "long":
257
+ if (value instanceof ExactInteger) {
258
+ if (long === "string") {
259
+ return value.digits;
260
+ }
261
+ onPrecision(value.digits);
262
+ return Number(value.digits);
263
+ }
264
+ if (typeof value === "number" && Number.isInteger(value)) {
265
+ return long === "string" ? String(value) : value;
266
+ }
267
+ return BAD;
268
+ default:
269
+ return BAD;
270
+ }
271
+ }
272
+ /**
273
+ * Convert one attribute value by its declared type.
274
+ * @param value - the value (never null)
275
+ * @param type - the declared type
276
+ * @param long - the importer's `long` option
277
+ * @param onPrecision - called for a long beyond 2^53
278
+ * @returns the value to store, or BAD
279
+ */
280
+ function convertValue(value, type, long, onPrecision) {
281
+ if (!type.list) {
282
+ return convertScalar(value, type.scalar, long, onPrecision);
283
+ }
284
+ if (!Array.isArray(value)) {
285
+ return BAD;
286
+ }
287
+ const out = [];
288
+ for (const item of value) {
289
+ const converted = item === null ? BAD : convertScalar(item, type.scalar, long, onPrecision);
290
+ if (converted === BAD) {
291
+ return BAD;
292
+ }
293
+ out.push(converted);
294
+ }
295
+ return out;
296
+ }
297
+ /**
298
+ * A short JSON rendering of a value for a message.
299
+ * @param value - the value
300
+ * @returns the text, at most 60 characters
301
+ */
302
+ function shown(value) {
303
+ if (value instanceof ExactInteger) {
304
+ return value.digits;
305
+ }
306
+ let text;
307
+ try {
308
+ text = JSON.stringify(value) ?? String(value);
309
+ }
310
+ catch {
311
+ text = String(value);
312
+ }
313
+ return text.length > 60 ? `${text.slice(0, 57)}...` : text;
314
+ }
315
+ /**
316
+ * The inexact-literal bits of an element.
317
+ * @param text - the element's JSON text
318
+ * @param keys - the id keys to check, bit 1, 2, 4 in order
319
+ * @returns the bits
320
+ */
321
+ function inexactBits(text, keys) {
322
+ if (!/[0-9][.eE]/.test(text)) {
323
+ return 0;
324
+ }
325
+ let bits = 0;
326
+ keys.forEach((key, i) => {
327
+ if (inexactLiteral(text, key)) {
328
+ bits |= 1 << i;
329
+ }
330
+ });
331
+ return bits;
332
+ }
333
+ /**
334
+ * Read the whole document through the streaming scanner, checking its structure.
335
+ * @param input - the input
336
+ * @param report - the report
337
+ * @param options - the resolved options
338
+ * @returns what was read
339
+ */
340
+ async function readDocument(input, report, options) {
341
+ const structure = new CxStructure(report);
342
+ const doc = {
343
+ version: "",
344
+ hasFragments: false,
345
+ nodes: [],
346
+ edges: [],
347
+ declarations: [],
348
+ networkAttributes: [],
349
+ nodeBypasses: [],
350
+ edgeBypasses: [],
351
+ cartesianLayout: [],
352
+ opaque: new Map(),
353
+ structure,
354
+ };
355
+ let descriptor = false;
356
+ let elementsSeen = false;
357
+ let sinceCheck = 0;
358
+ const collect = (aspect, value, text, line, exact) => {
359
+ structure.element(aspect, value, line);
360
+ switch (aspect) {
361
+ case "nodes":
362
+ elementsSeen = true;
363
+ doc.nodes.push({ value, line, inexact: inexactBits(text, ["id"]) });
364
+ return;
365
+ case "edges":
366
+ elementsSeen = true;
367
+ doc.edges.push({ value, line, inexact: inexactBits(text, ["id", "s", "t"]) });
368
+ return;
369
+ case "attributeDeclarations":
370
+ if (elementsSeen) {
371
+ report.warnOnce("validation-error", ASPECT_ORDER_CODE, "attributeDeclarations comes after the elements it types; the declarations are applied to them", { line, element: aspect }, `${ASPECT_ORDER_CODE}:declarations`);
372
+ }
373
+ doc.declarations.push({ value: plainJson(value), line, inexact: 0 });
374
+ return;
375
+ case "networkAttributes":
376
+ elementsSeen = true;
377
+ doc.networkAttributes.push({ value, line, inexact: 0 });
378
+ return;
379
+ case "nodeBypasses":
380
+ doc.nodeBypasses.push({ value, line, inexact: 0 });
381
+ return;
382
+ case "edgeBypasses":
383
+ doc.edgeBypasses.push({ value, line, inexact: 0 });
384
+ return;
385
+ case "cartesianLayout":
386
+ doc.cartesianLayout.push({ value, line, inexact: 0 });
387
+ return;
388
+ default:
389
+ if (STRUCTURE_ASPECTS.has(aspect)) {
390
+ return;
391
+ }
392
+ if (!doc.opaque.has(aspect)) {
393
+ doc.opaque.set(aspect, []);
394
+ }
395
+ doc.opaque.get(aspect)?.push(exact ? plainJson(value, () => undefined) : value);
396
+ }
397
+ };
398
+ try {
399
+ for await (const event of scanAspects(textChunks(input, report, options))) {
400
+ if (++sinceCheck >= ABORT_CHECK_INTERVAL) {
401
+ sinceCheck = 0;
402
+ throwIfAborted(options.signal);
403
+ }
404
+ switch (event.kind) {
405
+ case "root":
406
+ report.fail(CX2_ISSUE.NO_DESCRIPTOR, `a CX2 document is a JSON array; found ${isRecord(event.value) ? "an object" : shown(event.value)}`, { line: event.line });
407
+ break;
408
+ case "member":
409
+ if (!descriptor) {
410
+ readDescriptor(event.value, event.line, doc, report);
411
+ descriptor = true;
412
+ break;
413
+ }
414
+ memberAspect(event.value, event.line, structure, report, (aspect, value) => {
415
+ collect(aspect, value, JSON.stringify(value) ?? "", event.line, event.exact);
416
+ });
417
+ break;
418
+ case "block":
419
+ if (!descriptor) {
420
+ report.fail(CX2_ISSUE.NO_DESCRIPTOR, `the document starts with a "${event.aspect}" block, not a descriptor with CXVersion${event.aspect === "numberVerification" || event.aspect === "metaData" ? "; this looks like CX version 1 (read it with the cx importer)" : ""}`, { line: event.line });
421
+ }
422
+ structure.block(event.aspect, event.line);
423
+ break;
424
+ case "element":
425
+ collect(event.aspect, event.value, event.text, event.line, event.exact);
426
+ break;
427
+ case "deep":
428
+ reportTooDeep(report, event);
429
+ if (!descriptor) {
430
+ readDescriptor(null, event.line, doc, report);
431
+ }
432
+ break;
433
+ case "extraKeys":
434
+ report.error("parse-error", BAD_ASPECT_BLOCK_CODE, `the "${event.aspect}" block holds more keys (${event.keys.join(", ")}); an aspect block has one key, the others are skipped`, { line: event.line, element: event.aspect });
435
+ break;
436
+ default:
437
+ break;
438
+ }
439
+ }
440
+ }
441
+ catch (err) {
442
+ if (err instanceof JsonScanError) {
443
+ report.fail(err.empty ? EMPTY_INPUT_CODE : SYNTAX_CODE, err.message, { line: err.line });
444
+ }
445
+ throw err;
446
+ }
447
+ if (!descriptor) {
448
+ report.fail(CX2_ISSUE.NO_DESCRIPTOR, "the document is an empty array; a CX2 document starts with a descriptor");
449
+ }
450
+ return doc;
451
+ }
452
+ /**
453
+ * Check the descriptor, the first member of the array.
454
+ * @param value - the member
455
+ * @param line - its line
456
+ * @param doc - the document, which receives the version and the fragment flag
457
+ * @param report - the report
458
+ */
459
+ function readDescriptor(value, line, doc, report) {
460
+ if (!isRecord(value) || !("CXVersion" in value)) {
461
+ const keys = isRecord(value) ? Object.keys(value) : [];
462
+ report.fail(CX2_ISSUE.NO_DESCRIPTOR, `the first member of the array is not a descriptor with CXVersion${keys.length > 0 ? ` (keys: ${keys.join(", ")})` : ""}`, { line });
463
+ }
464
+ const raw = value.CXVersion;
465
+ const text = typeof raw === "string" || typeof raw === "number" ? String(raw) : "";
466
+ const match = /^([0-9]+)(?:\.([0-9]+))?$/.exec(text);
467
+ const major = match === null ? NaN : Number(match[1]);
468
+ if (major === 1) {
469
+ report.fail(CX2_ISSUE.VERSION, `CXVersion ${shown(raw)} is CX version 1, a different document shape; read it with the cx importer`, { line, element: "CXVersion" });
470
+ }
471
+ if (major !== 2) {
472
+ report.fail(CX2_ISSUE.VERSION, `CXVersion ${shown(raw)} is not a CX2 version`, { line, element: "CXVersion" });
473
+ }
474
+ doc.version = text;
475
+ if (raw !== "2.0") {
476
+ report.warning("validation-error", CX2_ISSUE.MINOR_VERSION, `CXVersion ${shown(raw)} is not "2.0"; the document is read as CX2 2.0`, { line, element: "CXVersion" });
477
+ }
478
+ for (const key of Object.keys(value)) {
479
+ if (key === "hasFragments") {
480
+ if (typeof value.hasFragments === "boolean") {
481
+ doc.hasFragments = value.hasFragments;
482
+ }
483
+ else {
484
+ report.error("validation-error", BAD_VALUE_CODE, `hasFragments is ${shown(value.hasFragments)}, not a boolean; read as false`, { line, element: "hasFragments" });
485
+ }
486
+ }
487
+ else if (key !== "CXVersion") {
488
+ report.warning("validation-error", UNKNOWN_ELEMENT_CODE, `the descriptor key "${key}" is not defined`, {
489
+ line,
490
+ element: key,
491
+ });
492
+ }
493
+ }
494
+ }
495
+ /**
496
+ * Read a member that is not a streamed block: a one-key object holding an object is a
497
+ * one-element aspect (`{"ndexStatus": {...}}`); anything else is E_BAD_ASPECT_BLOCK.
498
+ * @param value - the member
499
+ * @param line - its line
500
+ * @param structure - the structure checker
501
+ * @param report - the report
502
+ * @param collect - receives the aspect name and its one element
503
+ */
504
+ function memberAspect(value, line, structure, report, collect) {
505
+ const keys = isRecord(value) ? Object.keys(value) : [];
506
+ if (isRecord(value) && keys.length === 1 && isRecord(value[keys[0]])) {
507
+ structure.block(keys[0], line);
508
+ collect(keys[0], value[keys[0]]);
509
+ return;
510
+ }
511
+ report.error("parse-error", BAD_ASPECT_BLOCK_CODE, `a member of the document is ${keys.length > 1 ? `an object with ${keys.length} keys (${keys.join(", ")})` : shown(value)}, not a one-key aspect block; skipped`, { line, element: keys[0] ?? null });
512
+ }
513
+ /**
514
+ * The scalar kind of one value for inference.
515
+ * @param value - the value
516
+ * @returns a CX2 scalar, or null for anything else
517
+ */
518
+ function scalarKind(value) {
519
+ switch (typeof value) {
520
+ case "boolean":
521
+ return "boolean";
522
+ case "string":
523
+ return "string";
524
+ case "number":
525
+ return Number.isInteger(value) && value >= I32_MIN && value <= I32_MAX ? "integer" : "double";
526
+ default:
527
+ return value instanceof ExactInteger ? "double" : null;
528
+ }
529
+ }
530
+ /**
531
+ * Widen two scalar kinds: integer and double give double; anything else that differs has no
532
+ * CX2 type.
533
+ * @param a - the kind so far
534
+ * @param b - a new kind
535
+ * @returns the widened kind
536
+ */
537
+ function widenKind(a, b) {
538
+ if (a === undefined || a === b) {
539
+ return b;
540
+ }
541
+ if (a === null || b === null) {
542
+ return null;
543
+ }
544
+ return (a === "integer" && b === "double") || (a === "double" && b === "integer") ? "double" : null;
545
+ }
546
+ /**
547
+ * Observe one value of an undeclared attribute.
548
+ * @param seen - the state
549
+ * @param value - the value (never null)
550
+ */
551
+ function observe(seen, value) {
552
+ const list = Array.isArray(value);
553
+ if (seen.list !== undefined && seen.list !== list) {
554
+ seen.kind = null;
555
+ return;
556
+ }
557
+ seen.list = list;
558
+ if (!list) {
559
+ seen.kind = widenKind(seen.kind, scalarKind(value));
560
+ return;
561
+ }
562
+ for (const item of value) {
563
+ seen.kind = widenKind(seen.kind, item === null || Array.isArray(item) ? null : scalarKind(item));
564
+ }
565
+ }
566
+ /**
567
+ * The CX2 type inference settles on.
568
+ * @param seen - the state
569
+ * @returns the type, or null for a json column
570
+ */
571
+ function inferredType(seen) {
572
+ if (seen.kind === null) {
573
+ return null;
574
+ }
575
+ const scalar = seen.kind ?? "string";
576
+ return cx2Type(seen.list === true ? `list_of_${scalar}` : scalar);
577
+ }
578
+ /** The declarations of one table. */
579
+ class DeclarationTable {
580
+ constructor() {
581
+ this.byName = new Map();
582
+ this.byAlias = new Map();
583
+ }
584
+ /**
585
+ * The declaration a key of an element's `v` names.
586
+ * @param key - the key
587
+ * @returns the declaration and whether the key was its alias, or null
588
+ */
589
+ resolve(key) {
590
+ const viaAlias = this.byAlias.get(key);
591
+ if (viaAlias !== undefined) {
592
+ return { decl: viaAlias, viaAlias: true };
593
+ }
594
+ const decl = this.byName.get(key);
595
+ return decl === undefined ? null : { decl, viaAlias: false };
596
+ }
597
+ }
598
+ /** The domain key of attributeDeclarations for each table. */
599
+ const DECLARATION_KEYS = { nodes: "node", edges: "edge", networkAttributes: "network" };
600
+ // ============================================================ the build
601
+ /** Reads a collected document into a sink. */
602
+ class Cx2Reader {
603
+ /**
604
+ * Create the reader.
605
+ * @param sink - the sink
606
+ * @param report - the report
607
+ * @param options - the resolved options
608
+ * @param zAs - where z goes
609
+ * @param doc - the collected document
610
+ */
611
+ constructor(sink, report, options, zAs, doc) {
612
+ this.decls = {
613
+ node: new DeclarationTable(),
614
+ edge: new DeclarationTable(),
615
+ network: new DeclarationTable(),
616
+ other: {},
617
+ };
618
+ /** CX node id -> sink node index. */
619
+ this.nodeRows = new Map();
620
+ /** CX node id -> the id the sink holds it under (differs when a mangled id is restored). */
621
+ this.sinkIds = new Map();
622
+ /** CX edge id -> sink edge index. */
623
+ this.edgeRows = new Map();
624
+ this.positionHandle = INVALID_INDEX;
625
+ this.zHandle = INVALID_INDEX;
626
+ this.edgeIdHandle = INVALID_INDEX;
627
+ /** The rows that have a position (a set: a duplicate node may carry coordinates twice). */
628
+ this.positioned = new Set();
629
+ this.sinceCheck = 0;
630
+ this.idType = "integer";
631
+ this.weighted = false;
632
+ this.dangling = new Map();
633
+ this.point = [0, 0, 0];
634
+ this.sink = sink;
635
+ this.report = report;
636
+ this.options = options;
637
+ this.zAs = zAs;
638
+ this.doc = doc;
639
+ this.direction = new DirectionResolver(sink, report, options.onMixedDirection);
640
+ this.coercer = new IdCoercer(options.ids);
641
+ }
642
+ /** Build the graph. */
643
+ build() {
644
+ const { doc, report } = this;
645
+ this.direction.setHeader(true);
646
+ this.readDeclarations();
647
+ this.declareColumns();
648
+ this.sink.reserve(doc.nodes.length, doc.edges.length);
649
+ for (const held of doc.nodes) {
650
+ this.readNode(held);
651
+ }
652
+ this.readLegacyLayout();
653
+ if (this.positioned.size > 0 && this.positioned.size < this.nodeRows.size) {
654
+ report.warnOnce("missing-value", CX2_ISSUE.PARTIAL_LAYOUT, `${this.nodeRows.size - this.positioned.size} of ${this.nodeRows.size} node(s) have no coordinates; their positions are unset`, { element: "nodes" });
655
+ }
656
+ for (const held of doc.edges) {
657
+ this.readEdge(held);
658
+ }
659
+ this.readNetworkAttributes();
660
+ this.readBypasses("node", doc.nodeBypasses);
661
+ this.readBypasses("edge", doc.edgeBypasses);
662
+ for (const [kind, count] of this.dangling) {
663
+ report.warning("validation-error", DANGLING_REFERENCE_CODE, `${count} ${kind} name(s) no element; ignored`, { element: kind });
664
+ }
665
+ this.checkAspects();
666
+ this.setMeta();
667
+ }
668
+ // ------------------------------------------------------------ declarations
669
+ /** Merge every attributeDeclarations element (fragments in order) into the tables. */
670
+ readDeclarations() {
671
+ const { report } = this;
672
+ for (const held of this.doc.declarations) {
673
+ if (!isRecord(held.value)) {
674
+ report.error("parse-error", BAD_ASPECT_BLOCK_CODE, "an attributeDeclarations element is not an object", {
675
+ line: held.line,
676
+ element: "attributeDeclarations",
677
+ });
678
+ continue;
679
+ }
680
+ for (const [key, table] of Object.entries(held.value)) {
681
+ const domain = DECLARATION_KEYS[key];
682
+ if (domain === undefined) {
683
+ this.decls.other[key] = table;
684
+ continue;
685
+ }
686
+ if (!isRecord(table)) {
687
+ report.error("validation-error", BAD_VALUE_CODE, `the ${key} declarations are not an object; ignored`, { line: held.line, element: key });
688
+ continue;
689
+ }
690
+ for (const [name, decl] of Object.entries(table)) {
691
+ this.declare(domain, name, decl, held.line);
692
+ }
693
+ }
694
+ }
695
+ for (const domain of ["node", "edge"]) {
696
+ this.checkAliases(domain);
697
+ }
698
+ this.inferUndeclared("node", this.doc.nodes);
699
+ this.inferUndeclared("edge", this.doc.edges);
700
+ }
701
+ /**
702
+ * Type the attributes no declaration types (undeclared, or declared with a type CX2 does not
703
+ * define) from their values, so every attribute column is declared with its CX2 type.
704
+ * @param domain - node or edge
705
+ * @param elements - the elements
706
+ */
707
+ inferUndeclared(domain, elements) {
708
+ const table = this.decls[domain];
709
+ const seen = new Map();
710
+ for (const { value } of elements) {
711
+ if (!isRecord(value) || !isRecord(value.v)) {
712
+ continue;
713
+ }
714
+ for (const [key, raw] of Object.entries(value.v)) {
715
+ const resolved = table.resolve(key);
716
+ if ((resolved !== null && resolved.decl.type !== null) || raw === null || raw === undefined) {
717
+ continue;
718
+ }
719
+ const name = resolved?.decl.name ?? key;
720
+ let state = seen.get(name);
721
+ if (state === undefined) {
722
+ state = { kind: undefined, list: undefined };
723
+ seen.set(name, state);
724
+ }
725
+ observe(state, raw);
726
+ }
727
+ }
728
+ for (const [name, state] of seen) {
729
+ const type = inferredType(state);
730
+ const decl = table.byName.get(name);
731
+ if (decl !== undefined) {
732
+ decl.type = type;
733
+ if (decl.hasDefault && type !== null) {
734
+ // the default of a type CX2 does not define, converted now the values typed the column
735
+ decl.defaultValue = this.convertDefault(name, decl.rawDefault, type, { element: name });
736
+ decl.hasDefault = decl.defaultValue !== BAD;
737
+ }
738
+ continue;
739
+ }
740
+ table.byName.set(name, {
741
+ name,
742
+ type,
743
+ alias: null,
744
+ hasDefault: false,
745
+ defaultValue: undefined,
746
+ rawDefault: undefined,
747
+ handle: INVALID_INDEX,
748
+ undeclared: true,
749
+ });
750
+ }
751
+ }
752
+ /**
753
+ * Add one declaration to a table.
754
+ * @param domain - the table
755
+ * @param name - the attribute name
756
+ * @param raw - the declaration object
757
+ * @param line - its line
758
+ */
759
+ declare(domain, name, raw, line) {
760
+ const { report } = this;
761
+ const table = this.decls[domain];
762
+ const where = { line, element: name };
763
+ if (!isRecord(raw)) {
764
+ report.error("validation-error", BAD_VALUE_CODE, `the declaration of "${name}" is not an object; ignored`, where);
765
+ return;
766
+ }
767
+ let type;
768
+ if (raw.d === undefined) {
769
+ type = cx2Type("string");
770
+ report.warning("unsupported", UNKNOWN_ATTR_TYPE_CODE, `the declaration of "${name}" has no type; read as string (the Java reader's rule)`, where);
771
+ }
772
+ else {
773
+ type = typeof raw.d === "string" ? cx2Type(raw.d) : null;
774
+ if (type === null) {
775
+ report.warning("unsupported", UNKNOWN_ATTR_TYPE_CODE, `the type ${shown(raw.d)} of "${name}" is not a CX2 type; the column is inferred from its values`, where);
776
+ }
777
+ }
778
+ const existing = table.byName.get(name);
779
+ if (existing !== undefined) {
780
+ if (existing.type?.d !== type?.d) {
781
+ report.error("validation-error", CX2_ISSUE.DECLARATION_CONFLICT, `"${name}" is declared ${existing.type?.d ?? "untyped"} and again ${type?.d ?? "untyped"}; the first declaration wins`, where);
782
+ }
783
+ return;
784
+ }
785
+ let alias = typeof raw.a === "string" ? raw.a : null;
786
+ let hasDefault = raw.v !== undefined && raw.v !== null;
787
+ if (domain === "network" && (raw.a !== undefined || raw.v !== undefined)) {
788
+ report.warning("validation-error", CX2_ISSUE.NETWORK_DECLARATION, `the network attribute "${name}" declares an alias or a default, which CX2 forbids; ignored`, where);
789
+ alias = null;
790
+ hasDefault = false;
791
+ }
792
+ let defaultValue = undefined;
793
+ if (hasDefault && type !== null) {
794
+ defaultValue = this.convertDefault(name, raw.v, type, where);
795
+ hasDefault = defaultValue !== BAD;
796
+ }
797
+ table.byName.set(name, {
798
+ name,
799
+ type,
800
+ alias,
801
+ hasDefault,
802
+ defaultValue,
803
+ rawDefault: hasDefault && type === null ? plainJson(raw.v) : undefined,
804
+ handle: INVALID_INDEX,
805
+ undeclared: false,
806
+ });
807
+ }
808
+ /**
809
+ * Convert a declared default; a numeric string for a numeric type (the specification's own
810
+ * `"v": "0.0"`) is coerced, anything else that does not match drops the default.
811
+ * @param name - the attribute
812
+ * @param value - the default
813
+ * @param type - its type
814
+ * @param where - the location
815
+ * @param where.line - the line
816
+ * @param where.element - the attribute
817
+ * @returns the default, or BAD when dropped
818
+ */
819
+ convertDefault(name, value, type, where) {
820
+ const converted = convertValue(value, type, this.options.long, () => undefined);
821
+ if (converted !== BAD) {
822
+ return converted;
823
+ }
824
+ const numeric = type.scalar === "double" || type.scalar === "integer" || type.scalar === "long";
825
+ if (!type.list &&
826
+ numeric &&
827
+ typeof value === "string" &&
828
+ value.trim() !== "" &&
829
+ Number.isFinite(Number(value))) {
830
+ const coerced = convertValue(Number(value), type, this.options.long, () => undefined);
831
+ if (coerced !== BAD) {
832
+ this.report.warning("validation-error", BAD_DEFAULT_CODE, `the default ${shown(value)} of "${name}" is a string, not a ${type.d}; read as ${shown(coerced)}`, where);
833
+ return coerced;
834
+ }
835
+ }
836
+ this.report.warning("validation-error", BAD_DEFAULT_CODE, `the default ${shown(value)} of "${name}" is not a ${type.d}; the column has no default`, where);
837
+ return BAD;
838
+ }
839
+ /**
840
+ * Check the aliases of a table in declaration order: an alias that is another attribute's
841
+ * name or another attribute's alias is E_CX2_ALIAS_CONFLICT and ignored.
842
+ * @param domain - the table
843
+ */
844
+ checkAliases(domain) {
845
+ const table = this.decls[domain];
846
+ for (const decl of table.byName.values()) {
847
+ const { alias } = decl;
848
+ if (alias === null || alias === decl.name) {
849
+ if (alias !== null) {
850
+ table.byAlias.set(alias, decl);
851
+ }
852
+ continue;
853
+ }
854
+ const other = table.byName.get(alias) ?? table.byAlias.get(alias);
855
+ if (other !== undefined) {
856
+ this.report.error("validation-error", CX2_ISSUE.ALIAS_CONFLICT, `the alias "${alias}" of the ${domain} attribute "${decl.name}" is also ${other.name === alias ? "an attribute's name" : `the alias of "${other.name}"`}; the alias is ignored`, { element: decl.name });
857
+ decl.alias = null;
858
+ continue;
859
+ }
860
+ table.byAlias.set(alias, decl);
861
+ }
862
+ }
863
+ /** Declare the declared node and edge columns. */
864
+ declareColumns() {
865
+ const restore = this.options.restoreMangledIds;
866
+ for (const domain of ["node", "edge"]) {
867
+ for (const decl of this.decls[domain].byName.values()) {
868
+ if (domain === "node" && restore && decl.name === ORIGINAL_ID_ATTRIBUTE) {
869
+ continue;
870
+ }
871
+ if (domain === "edge" && decl.name === this.options.weightFrom) {
872
+ continue;
873
+ }
874
+ const column = decl.type === null
875
+ ? {
876
+ name: decl.name,
877
+ dtype: "json",
878
+ nullable: true,
879
+ origin: { format: CX2_FORMAT, id: decl.alias },
880
+ }
881
+ : {
882
+ ...this.columnDecl(decl.type),
883
+ name: decl.name,
884
+ origin: { format: CX2_FORMAT, id: decl.alias, type: decl.type.d },
885
+ };
886
+ if (decl.hasDefault) {
887
+ // a type nothing settled (no values) keeps its default as written, in the json column
888
+ column.default = decl.type === null ? decl.rawDefault : decl.defaultValue;
889
+ }
890
+ if (domain === "node" && decl.name === "name") {
891
+ column.role = "label";
892
+ }
893
+ decl.handle = declareResolved(this.sink, domain, column, this.report).handle;
894
+ }
895
+ }
896
+ }
897
+ /**
898
+ * The edge id column, declared with the first edge.
899
+ * @returns the handle
900
+ */
901
+ edgeIdColumn() {
902
+ if (this.edgeIdHandle === INVALID_INDEX) {
903
+ const taken = (name) => this.sink.edgeColumn(name) !== INVALID_INDEX;
904
+ this.edgeIdHandle = declareResolved(this.sink, "edge", { name: uniqueColumnName("id", "cx2", taken), dtype: "f64", role: "id", nullable: true }, this.report).handle;
905
+ }
906
+ return this.edgeIdHandle;
907
+ }
908
+ /**
909
+ * The dtype part of a declared column.
910
+ * @param type - the CX2 type
911
+ * @returns the dtype and item dtype
912
+ */
913
+ columnDecl(type) {
914
+ const scalar = scalarDtype(type.scalar, this.options.long);
915
+ return type.list
916
+ ? { name: "", dtype: "list", itemDtype: scalar, nullable: true }
917
+ : { name: "", dtype: scalar, nullable: true };
918
+ }
919
+ // ------------------------------------------------------------ ids
920
+ /**
921
+ * The id of an element, by the CX id rule and the `ids` option.
922
+ * @param raw - the parsed id
923
+ * @param inexact - whether the literal was not a plain integer
924
+ * @param element - the element name for issues
925
+ * @param edgeId - whether this is an edge's own id (stored in the f64 id column, not kept as digits)
926
+ * @returns the id, or null when it was reported
927
+ */
928
+ idOf(raw, inexact, element, edgeId = false) {
929
+ let id;
930
+ try {
931
+ const parsed = cxId(raw, inexact);
932
+ if (parsed.note === "text") {
933
+ this.report.warnOnce("coercion", ID_TEXT_TYPE_CODE, `${element}: the id ${shown(raw)} is not written as an integer; read as ${String(parsed.id)}`, { element });
934
+ }
935
+ else if (parsed.note === "precision" && edgeId) {
936
+ // the edge is told apart by its digits, but the id column is f64
937
+ this.report.warnOnce("precision", PRECISION_CODE, `${element}: the edge id ${String(parsed.id)} is beyond 2^53; the id column holds the nearest double`, { element }, `${PRECISION_CODE}:edge`);
938
+ }
939
+ else if (parsed.note === "precision") {
940
+ this.idType = "mixed";
941
+ this.report.warnOnce("precision", PRECISION_CODE, `${element}: the id ${String(parsed.id)} is beyond 2^53; kept as its digits (a string id)`, { element });
942
+ }
943
+ id = this.options.ids === "keep" ? parsed.id : this.coercer.value(parsed.id);
944
+ }
945
+ catch (err) {
946
+ this.report.recordError(err, { element });
947
+ return null;
948
+ }
949
+ return id;
950
+ }
951
+ /**
952
+ * Check the cancellation signal every ABORT_CHECK_INTERVAL elements.
953
+ */
954
+ checkAbort() {
955
+ if (++this.sinceCheck >= ABORT_CHECK_INTERVAL) {
956
+ this.sinceCheck = 0;
957
+ throwIfAborted(this.options.signal);
958
+ }
959
+ }
960
+ /**
961
+ * Report the keys of an element CX2 does not define, once per key.
962
+ * @param record - the element
963
+ * @param known - the keys it defines
964
+ * @param what - nodes or edges
965
+ * @param line - its line
966
+ */
967
+ unknownKeys(record, known, what, line) {
968
+ for (const key of Object.keys(record)) {
969
+ if (!known.has(key)) {
970
+ this.report.warnOnce("unsupported", UNKNOWN_ELEMENT_CODE, `the ${what} key "${key}" is not defined by CX2; its values are not read`, { line, element: key }, `${UNKNOWN_ELEMENT_CODE}:${what}:${key}`);
971
+ }
972
+ }
973
+ }
974
+ // ------------------------------------------------------------ nodes
975
+ /**
976
+ * Read one node element.
977
+ * @param held - the element
978
+ */
979
+ readNode(held) {
980
+ this.checkAbort();
981
+ const { report, sink } = this;
982
+ const { value, line } = held;
983
+ if (!isRecord(value)) {
984
+ report.error("parse-error", BAD_ASPECT_BLOCK_CODE, `a nodes element is ${shown(value)}, not an object`, {
985
+ line,
986
+ element: "nodes",
987
+ });
988
+ report.counts.skippedNodes++;
989
+ return;
990
+ }
991
+ this.unknownKeys(value, NODE_KEYS, "node", line);
992
+ if (value.id === undefined || value.id === null) {
993
+ report.error("missing-value", MISSING_ID_CODE, "a node has no id", { line, element: "nodes" });
994
+ report.counts.skippedNodes++;
995
+ return;
996
+ }
997
+ const element = `node ${shown(value.id)}`;
998
+ const cx = this.idOf(value.id, (held.inexact & 1) !== 0, element);
999
+ if (cx === null) {
1000
+ report.counts.skippedNodes++;
1001
+ return;
1002
+ }
1003
+ const attrs = isRecord(value.v) ? value.v : null;
1004
+ if (value.v !== undefined && value.v !== null && attrs === null) {
1005
+ report.error("validation-error", BAD_VALUE_CODE, `${element}: v is ${shown(value.v)}, not an object`, {
1006
+ line,
1007
+ element,
1008
+ });
1009
+ }
1010
+ let row = this.nodeRows.get(cx);
1011
+ if (row !== undefined) {
1012
+ report.warning("merged", DUPLICATE_NODE_CODE, `${element} is declared more than once; its attributes are merged (the later values win)`, { line, element });
1013
+ }
1014
+ else {
1015
+ const original = this.originalIdOf(attrs);
1016
+ this.idTypeOf(original ?? cx);
1017
+ try {
1018
+ row = sink.addNode(original ?? cx);
1019
+ }
1020
+ catch (err) {
1021
+ report.recordError(err, { line, element });
1022
+ report.counts.skippedNodes++;
1023
+ return;
1024
+ }
1025
+ this.nodeRows.set(cx, row);
1026
+ this.sinkIds.set(cx, original ?? cx);
1027
+ report.counts.nodes++;
1028
+ }
1029
+ this.readCoordinates(value, row, element, line);
1030
+ if (attrs !== null) {
1031
+ this.writeAttributes("node", row, attrs, element, line);
1032
+ }
1033
+ }
1034
+ /**
1035
+ * The original id the exporter's `sanitizeIds: "mangle"` kept, when it is to be restored.
1036
+ * @param attrs - the node's v
1037
+ * @returns the original id, or null
1038
+ */
1039
+ originalIdOf(attrs) {
1040
+ if (attrs === null || !this.options.restoreMangledIds) {
1041
+ return null;
1042
+ }
1043
+ const alias = this.decls.node.byName.get(ORIGINAL_ID_ATTRIBUTE)?.alias ?? null;
1044
+ const raw = attrs[ORIGINAL_ID_ATTRIBUTE] ?? (alias === null ? undefined : attrs[alias]);
1045
+ return typeof raw === "string" ? raw : null;
1046
+ }
1047
+ /**
1048
+ * Track the idType of the metadata.
1049
+ * @param id - a node id
1050
+ */
1051
+ idTypeOf(id) {
1052
+ if (typeof id === "string" && this.idType === "integer") {
1053
+ this.idType = "mixed";
1054
+ }
1055
+ }
1056
+ /**
1057
+ * Read a node's x / y / z.
1058
+ * @param value - the node element
1059
+ * @param row - the node
1060
+ * @param element - the element name
1061
+ * @param line - its line
1062
+ */
1063
+ readCoordinates(value, row, element, line) {
1064
+ const coordinate = (key) => {
1065
+ const raw = value[key];
1066
+ if (raw === undefined || raw === null) {
1067
+ return null;
1068
+ }
1069
+ if (typeof raw === "number") {
1070
+ return raw;
1071
+ }
1072
+ this.report.error("validation-error", BAD_VALUE_CODE, `${element}: ${key} is ${shown(raw)}, not a number`, {
1073
+ line,
1074
+ element,
1075
+ });
1076
+ return null;
1077
+ };
1078
+ const x = coordinate("x");
1079
+ const y = coordinate("y");
1080
+ const z = coordinate("z");
1081
+ if ((x === null) !== (y === null)) {
1082
+ this.report.warnOnce("missing-value", CX2_ISSUE.PARTIAL_LAYOUT, `${element} has ${x === null ? "y without x" : "x without y"}; its coordinates are dropped`, { line, element }, `${CX2_ISSUE.PARTIAL_LAYOUT}:half`);
1083
+ }
1084
+ if (z !== null && x === null && y === null) {
1085
+ // the specification requires x and y with z
1086
+ this.report.warnOnce("missing-value", CX2_ISSUE.PARTIAL_LAYOUT, `${element} has z without x and y; ${this.zAs === "column" ? "z is kept in the z column" : "with no position, z is dropped"}`, { line, element }, `${CX2_ISSUE.PARTIAL_LAYOUT}:z`);
1087
+ }
1088
+ if (x !== null && y !== null) {
1089
+ this.setPosition(row, x, y, z);
1090
+ }
1091
+ if (z !== null && this.zAs === "column") {
1092
+ if (this.zHandle === INVALID_INDEX) {
1093
+ this.zHandle = declareResolved(this.sink, "node", zDecl(CX2_FORMAT), this.report).handle;
1094
+ }
1095
+ this.sink.setNodeValue(this.zHandle, row, z);
1096
+ }
1097
+ }
1098
+ /**
1099
+ * Write a node's position, y flipped to y-up.
1100
+ * @param row - the node
1101
+ * @param x - screen x
1102
+ * @param y - screen y
1103
+ * @param z - z, used only under zAs "position"
1104
+ */
1105
+ setPosition(row, x, y, z) {
1106
+ if (this.positionHandle === INVALID_INDEX) {
1107
+ this.positionHandle = declareResolved(this.sink, "node", positionDecl(CX2_FORMAT, this.zAs === "position" ? 3 : 2), this.report).handle;
1108
+ }
1109
+ this.point[0] = x;
1110
+ this.point[1] = flipY(y);
1111
+ this.point[2] = this.zAs === "position" && z !== null ? z : 0;
1112
+ this.sink.setNodeValue(this.positionHandle, row, this.point);
1113
+ this.positioned.add(row);
1114
+ }
1115
+ /** Apply a CX1 cartesianLayout aspect when no node carries coordinates; keep and warn otherwise. */
1116
+ readLegacyLayout() {
1117
+ const { cartesianLayout } = this.doc;
1118
+ if (cartesianLayout.length === 0) {
1119
+ return;
1120
+ }
1121
+ if (this.positioned.size > 0) {
1122
+ this.doc.opaque.set("cartesianLayout", cartesianLayout.map((h) => plainJson(h.value)));
1123
+ this.report.warning("unsupported", CX2_ISSUE.LEGACY_LAYOUT, `a CX1 cartesianLayout aspect (${cartesianLayout.length} element(s)) next to node coordinates; the node coordinates are used, the aspect is kept in meta.extra.cx2`, { element: "cartesianLayout" });
1124
+ return;
1125
+ }
1126
+ for (const held of cartesianLayout) {
1127
+ const entry = held.value;
1128
+ if (!isRecord(entry) || typeof entry.x !== "number" || typeof entry.y !== "number") {
1129
+ this.report.error("validation-error", BAD_VALUE_CODE, "a cartesianLayout element has no numeric x and y; skipped", { line: held.line, element: "cartesianLayout" });
1130
+ continue;
1131
+ }
1132
+ const row = this.rowOf(this.nodeRows, entry.node);
1133
+ if (row === undefined) {
1134
+ this.dangle("cartesianLayout entry");
1135
+ continue;
1136
+ }
1137
+ const z = typeof entry.z === "number" ? entry.z : null;
1138
+ this.setPosition(row, entry.x, entry.y, z);
1139
+ if (z !== null && this.zAs === "column") {
1140
+ if (this.zHandle === INVALID_INDEX) {
1141
+ this.zHandle = declareResolved(this.sink, "node", zDecl(CX2_FORMAT), this.report).handle;
1142
+ }
1143
+ this.sink.setNodeValue(this.zHandle, row, z);
1144
+ }
1145
+ }
1146
+ }
1147
+ /**
1148
+ * The sink row of a referenced id.
1149
+ * @param rows - the id map
1150
+ * @param raw - the parsed reference
1151
+ * @returns the row, or undefined
1152
+ */
1153
+ rowOf(rows, raw) {
1154
+ try {
1155
+ const { id } = cxId(raw);
1156
+ return rows.get(this.options.ids === "keep" ? id : this.coercer.value(id));
1157
+ }
1158
+ catch {
1159
+ return undefined;
1160
+ }
1161
+ }
1162
+ /**
1163
+ * Count a reference that names nothing.
1164
+ * @param kind - what referred
1165
+ */
1166
+ dangle(kind) {
1167
+ this.dangling.set(kind, (this.dangling.get(kind) ?? 0) + 1);
1168
+ }
1169
+ // ------------------------------------------------------------ attributes
1170
+ /**
1171
+ * Write the attributes of an element's v.
1172
+ * @param domain - node or edge
1173
+ * @param row - the row
1174
+ * @param attrs - the v object
1175
+ * @param element - the element name
1176
+ * @param line - its line
1177
+ */
1178
+ writeAttributes(domain, row, attrs, element, line) {
1179
+ const { report } = this;
1180
+ const table = this.decls[domain];
1181
+ for (const key of Object.keys(attrs)) {
1182
+ const value = attrs[key];
1183
+ const resolved = table.resolve(key);
1184
+ const name = resolved?.decl.name ?? key;
1185
+ if (domain === "node" && this.options.restoreMangledIds && name === ORIGINAL_ID_ATTRIBUTE) {
1186
+ continue;
1187
+ }
1188
+ if (domain === "edge" && name === this.options.weightFrom) {
1189
+ continue;
1190
+ }
1191
+ if (key === "id") {
1192
+ report.warnOnce("validation-error", CX2_ISSUE.RESERVED_KEY, `${element}: the attribute name "id" is reserved in v; read as an ordinary attribute`, { line, element }, `${CX2_ISSUE.RESERVED_KEY}:${domain}`);
1193
+ }
1194
+ if (resolved !== null &&
1195
+ !resolved.viaAlias &&
1196
+ resolved.decl.alias !== null &&
1197
+ resolved.decl.alias !== key) {
1198
+ if (resolved.decl.alias in attrs) {
1199
+ report.warning("validation-error", DUPLICATE_ATTRIBUTE_CODE, `${element}: "${name}" is given under its alias and its full name; the alias wins`, { line, element });
1200
+ continue;
1201
+ }
1202
+ report.warnOnce("coercion", CX2_ISSUE.ALIAS_BYPASSED, `${element}: the full name "${name}" is used although its alias "${resolved.decl.alias}" is declared; read as the same attribute`, { line, element }, `${CX2_ISSUE.ALIAS_BYPASSED}:${domain}:${name}`);
1203
+ }
1204
+ if (value === null || value === undefined) {
1205
+ continue;
1206
+ }
1207
+ if (resolved === null) {
1208
+ continue;
1209
+ }
1210
+ const { decl } = resolved;
1211
+ if (decl.undeclared) {
1212
+ report.warnOnce("validation-error", CX2_ISSUE.UNDECLARED_ATTRIBUTE, `the ${domain} attribute "${key}" is not declared; its type is inferred from the values`, { line, element: key }, `${CX2_ISSUE.UNDECLARED_ATTRIBUTE}:${domain}:${key}`);
1213
+ }
1214
+ const converted = decl.type === null
1215
+ ? plainJson(value, (digits) => {
1216
+ this.precision(name, digits);
1217
+ })
1218
+ : convertValue(value, decl.type, this.options.long, (digits) => {
1219
+ this.precision(name, digits);
1220
+ });
1221
+ if (converted === BAD) {
1222
+ report.error("validation-error", BAD_VALUE_CODE, `${element}: "${name}" is ${shown(value)}, not a ${decl.type?.d ?? "value"}; the cell is unset`, { line, element });
1223
+ continue;
1224
+ }
1225
+ try {
1226
+ if (domain === "node") {
1227
+ this.sink.setNodeValue(decl.handle, row, converted);
1228
+ }
1229
+ else {
1230
+ this.sink.setEdgeValue(decl.handle, row, converted);
1231
+ }
1232
+ }
1233
+ catch (err) {
1234
+ report.recordError(err, { line, element });
1235
+ }
1236
+ }
1237
+ }
1238
+ /**
1239
+ * Record a long value beyond 2^53 (once).
1240
+ * @param name - the attribute
1241
+ * @param digits - the value
1242
+ */
1243
+ precision(name, digits) {
1244
+ this.report.warnOnce("precision", PRECISION_CODE, `"${name}": ${digits} is beyond 2^53; stored as the nearest double`, { element: name }, `${PRECISION_CODE}:value`);
1245
+ }
1246
+ // ------------------------------------------------------------ edges
1247
+ /**
1248
+ * Read one edge element.
1249
+ * @param held - the element
1250
+ */
1251
+ readEdge(held) {
1252
+ this.checkAbort();
1253
+ const { report, sink } = this;
1254
+ const { value, line } = held;
1255
+ if (!isRecord(value)) {
1256
+ report.error("parse-error", BAD_ASPECT_BLOCK_CODE, `an edges element is ${shown(value)}, not an object`, {
1257
+ line,
1258
+ element: "edges",
1259
+ });
1260
+ report.counts.skippedEdges++;
1261
+ return;
1262
+ }
1263
+ this.unknownKeys(value, EDGE_KEYS, "edge", line);
1264
+ if (value.id === undefined || value.id === null) {
1265
+ report.error("missing-value", MISSING_ID_CODE, "an edge has no id", { line, element: "edges" });
1266
+ report.counts.skippedEdges++;
1267
+ return;
1268
+ }
1269
+ const element = `edge ${shown(value.id)}`;
1270
+ for (const key of ["s", "t"]) {
1271
+ if (value[key] === undefined || value[key] === null) {
1272
+ report.error("missing-value", MISSING_ENDPOINT_CODE, `${element} has no ${key}`, { line, element });
1273
+ report.counts.skippedEdges++;
1274
+ return;
1275
+ }
1276
+ }
1277
+ const id = this.idOf(value.id, (held.inexact & 1) !== 0, element, true);
1278
+ const s = id === null ? null : this.idOf(value.s, (held.inexact & 2) !== 0, element);
1279
+ const t = s === null ? null : this.idOf(value.t, (held.inexact & 4) !== 0, element);
1280
+ if (id === null || s === null || t === null) {
1281
+ report.counts.skippedEdges++;
1282
+ return;
1283
+ }
1284
+ if (this.edgeRows.has(id)) {
1285
+ report.error("validation-error", DUPLICATE_EDGE_ID_CODE, `${element} is declared more than once; the later edge is skipped`, { line, element });
1286
+ report.counts.skippedEdges++;
1287
+ return;
1288
+ }
1289
+ const source = this.endpoint(s, element, line);
1290
+ const target = source === null ? null : this.endpoint(t, element, line);
1291
+ if (source === null || target === null) {
1292
+ report.counts.skippedEdges++;
1293
+ return;
1294
+ }
1295
+ const attrs = isRecord(value.v) ? value.v : null;
1296
+ let weight;
1297
+ const weightKey = this.weightKey(attrs);
1298
+ try {
1299
+ weight = weightKey === null || attrs === null ? undefined : weightFromValue(plainJson(attrs[weightKey]));
1300
+ }
1301
+ catch (err) {
1302
+ report.recordError(err, { line, element });
1303
+ report.counts.skippedEdges++;
1304
+ return;
1305
+ }
1306
+ if (weight !== undefined) {
1307
+ this.weighted = true;
1308
+ }
1309
+ const before = sink.edgeCount;
1310
+ let edge;
1311
+ try {
1312
+ edge = this.direction.addEdge(source, target, "directed", weight, { line, element });
1313
+ }
1314
+ catch (err) {
1315
+ report.recordError(err, { line, element });
1316
+ report.counts.skippedEdges++;
1317
+ return;
1318
+ }
1319
+ report.counts.edges += sink.edgeCount - before;
1320
+ this.edgeRows.set(id, edge);
1321
+ sink.setEdgeValue(this.edgeIdColumn(), edge, typeof id === "number" ? id : Number(id));
1322
+ if (attrs !== null) {
1323
+ this.writeAttributes("edge", edge, attrs, element, line);
1324
+ }
1325
+ }
1326
+ /**
1327
+ * The key of an edge's v that holds the weight: weightFrom, or its declared alias.
1328
+ * @param attrs - the edge's v
1329
+ * @returns the key present in attrs, or null
1330
+ */
1331
+ weightKey(attrs) {
1332
+ const { weightFrom } = this.options;
1333
+ if (weightFrom === null || attrs === null) {
1334
+ return null;
1335
+ }
1336
+ const alias = this.decls.edge.byName.get(weightFrom)?.alias ?? null;
1337
+ if (alias !== null && alias in attrs) {
1338
+ return alias;
1339
+ }
1340
+ return weightFrom in attrs ? weightFrom : null;
1341
+ }
1342
+ /**
1343
+ * The sink id of an edge endpoint: a known node, or a node created under addMissingNodes.
1344
+ * @param cx - the endpoint's CX id
1345
+ * @param element - the edge name
1346
+ * @param line - its line
1347
+ * @returns the sink id, or null when the endpoint was reported
1348
+ */
1349
+ endpoint(cx, element, line) {
1350
+ const known = this.sinkIds.get(cx);
1351
+ if (known !== undefined) {
1352
+ return known;
1353
+ }
1354
+ if (!this.options.addMissingNodes) {
1355
+ this.report.error("missing-value", CX2_ISSUE.UNKNOWN_NODE, `${element}: the endpoint ${String(cx)} is not a node; the edge is skipped`, { line, element });
1356
+ return null;
1357
+ }
1358
+ try {
1359
+ this.nodeRows.set(cx, this.sink.addNode(cx));
1360
+ }
1361
+ catch (err) {
1362
+ this.report.recordError(err, { line, element });
1363
+ return null;
1364
+ }
1365
+ this.sinkIds.set(cx, cx);
1366
+ this.report.counts.nodes++;
1367
+ return cx;
1368
+ }
1369
+ // ------------------------------------------------------------ network attributes, bypasses
1370
+ /** Write the network attributes (the first element; others are reported). */
1371
+ readNetworkAttributes() {
1372
+ const { networkAttributes } = this.doc;
1373
+ if (networkAttributes.length === 0) {
1374
+ return;
1375
+ }
1376
+ if (networkAttributes.length > 1) {
1377
+ this.report.warning("validation-error", CX2_ISSUE.EXTRA_ELEMENTS, `networkAttributes holds ${networkAttributes.length} elements; the first is read`, { line: networkAttributes[1].line, element: "networkAttributes" });
1378
+ }
1379
+ const { value, line } = networkAttributes[0];
1380
+ if (!isRecord(value)) {
1381
+ this.report.error("parse-error", BAD_ASPECT_BLOCK_CODE, "the networkAttributes element is not an object", {
1382
+ line,
1383
+ element: "networkAttributes",
1384
+ });
1385
+ return;
1386
+ }
1387
+ for (const [name, raw] of Object.entries(value)) {
1388
+ if (raw === null || raw === undefined) {
1389
+ continue;
1390
+ }
1391
+ const decl = this.decls.network.byName.get(name);
1392
+ const element = `networkAttributes.${name}`;
1393
+ if (decl === undefined) {
1394
+ this.report.warnOnce("validation-error", CX2_ISSUE.UNDECLARED_ATTRIBUTE, `the network attribute "${name}" is not declared; its column is inferred from the value`, { line, element: name }, `${CX2_ISSUE.UNDECLARED_ATTRIBUTE}:network:${name}`);
1395
+ }
1396
+ if ((name === "name" || name === "description") &&
1397
+ typeof raw === "string" &&
1398
+ decl?.type?.d !== "list_of_string") {
1399
+ // the graph's own name and description: GraphMeta, written back from there
1400
+ continue;
1401
+ }
1402
+ try {
1403
+ const seen = { kind: undefined, list: undefined };
1404
+ observe(seen, raw);
1405
+ const type = decl?.type ?? inferredType(seen);
1406
+ if (type === null) {
1407
+ this.sink.setGraphValue(name, plainJson(raw, (digits) => {
1408
+ this.precision(name, digits);
1409
+ }), {
1410
+ dtype: "json",
1411
+ origin: { format: CX2_FORMAT, id: null },
1412
+ });
1413
+ continue;
1414
+ }
1415
+ const converted = convertValue(raw, type, this.options.long, (digits) => {
1416
+ this.precision(name, digits);
1417
+ });
1418
+ if (converted === BAD) {
1419
+ this.report.error("validation-error", BAD_VALUE_CODE, `${element} is ${shown(raw)}, not a ${type.d}; unset`, { line, element });
1420
+ continue;
1421
+ }
1422
+ const scalar = scalarDtype(type.scalar, this.options.long);
1423
+ this.sink.setGraphValue(name, converted, {
1424
+ dtype: type.list ? "list" : scalar,
1425
+ ...(type.list ? { itemDtype: scalar } : {}),
1426
+ origin: { format: CX2_FORMAT, id: null, type: type.d },
1427
+ });
1428
+ }
1429
+ catch (err) {
1430
+ this.report.recordError(err, { line, element });
1431
+ }
1432
+ }
1433
+ }
1434
+ /**
1435
+ * Write the per-element visual property values: one column per property, typed by its values.
1436
+ * @param domain - node or edge
1437
+ * @param entries - the bypass elements
1438
+ */
1439
+ readBypasses(domain, entries) {
1440
+ const rows = domain === "node" ? this.nodeRows : this.edgeRows;
1441
+ const columns = new Map();
1442
+ for (const held of entries) {
1443
+ this.checkAbort();
1444
+ const { value, line } = held;
1445
+ if (!isRecord(value) || !isRecord(value.v)) {
1446
+ this.report.error("parse-error", BAD_ASPECT_BLOCK_CODE, `a ${domain}Bypasses element is not an object with an id and a v object; skipped`, { line, element: `${domain}Bypasses` });
1447
+ continue;
1448
+ }
1449
+ const row = this.rowOf(rows, value.id);
1450
+ if (row === undefined) {
1451
+ this.dangle(`${domain} bypass`);
1452
+ continue;
1453
+ }
1454
+ for (const [property, raw] of Object.entries(value.v)) {
1455
+ if (raw === null || raw === undefined) {
1456
+ continue;
1457
+ }
1458
+ let column = columns.get(property);
1459
+ if (column === undefined) {
1460
+ column = { rows: [], values: [] };
1461
+ columns.set(property, column);
1462
+ }
1463
+ column.rows.push(row);
1464
+ column.values.push(plainJson(raw));
1465
+ }
1466
+ }
1467
+ for (const [property, { rows: targets, values }] of columns) {
1468
+ const decl = {
1469
+ name: property,
1470
+ dtype: bypassDtype(values),
1471
+ nullable: true,
1472
+ // origin.id keeps the property's name: a column renamed for a clash is written back under it
1473
+ origin: { format: CX2_FORMAT, id: property, namespace: BYPASS_NAMESPACE },
1474
+ };
1475
+ const handle = declareFresh(this.sink, domain, decl, this.report);
1476
+ for (let i = 0; i < targets.length; i++) {
1477
+ if (domain === "node") {
1478
+ this.sink.setNodeValue(handle, targets[i], values[i]);
1479
+ }
1480
+ else {
1481
+ this.sink.setEdgeValue(handle, targets[i], values[i]);
1482
+ }
1483
+ }
1484
+ }
1485
+ }
1486
+ // ------------------------------------------------------------ aspects, status, metadata
1487
+ /** The style-rule loss, the single-element aspects, the status and the metadata counts. */
1488
+ checkAspects() {
1489
+ const { doc, report } = this;
1490
+ const { structure } = doc;
1491
+ const styles = [];
1492
+ for (const aspect of STYLE_ASPECTS) {
1493
+ const elements = doc.opaque.get(aspect);
1494
+ if (elements !== undefined) {
1495
+ styles.push(describeStyle(aspect, elements));
1496
+ }
1497
+ }
1498
+ if (styles.length > 0) {
1499
+ report.warning("unsupported", STYLES_NOT_IMPORTED_CODE, `the file's style rules are not applied (${styles.join("; ")}); they are kept in meta.extra.cx2.opaque (style import is issue #706)`, { element: STYLE_ASPECTS.filter((a) => doc.opaque.has(a)).join(",") });
1500
+ }
1501
+ for (const aspect of SINGLE_ELEMENT_ASPECTS.slice(1)) {
1502
+ const count = doc.opaque.get(aspect)?.length ?? 0;
1503
+ if (count > 1) {
1504
+ report.warning("validation-error", CX2_ISSUE.EXTRA_ELEMENTS, `${aspect} holds ${count} elements where CX2 allows one; all are kept, a reader uses the first`, { element: aspect });
1505
+ }
1506
+ }
1507
+ if (!doc.hasFragments) {
1508
+ for (const [aspect, blocks] of structure.blocks) {
1509
+ if (blocks > 1 && !STRUCTURE_ASPECTS.has(aspect)) {
1510
+ report.warnOnce("validation-error", CX2_ISSUE.UNDECLARED_FRAGMENTS, `"${aspect}" comes in ${blocks} blocks although the descriptor does not declare hasFragments; the blocks are joined in order`, { element: aspect });
1511
+ }
1512
+ }
1513
+ }
1514
+ if (!structure.hasStatus) {
1515
+ report.error("validation-error", CX2_ISSUE.NO_STATUS, "the document ends without a status block", {
1516
+ element: "status",
1517
+ });
1518
+ }
1519
+ else if (!structure.statusWellFormed() || structure.counts.get("status") !== 1) {
1520
+ // the specification: exactly one status aspect holding exactly one element
1521
+ const count = structure.counts.get("status") ?? 0;
1522
+ report.error("validation-error", CX2_ISSUE.NO_STATUS, `the status is malformed (${count === 1 ? shown(structure.status) : `${count} elements`}): a document ends with one status block holding one object with a boolean success`, { element: "status" });
1523
+ }
1524
+ structure.checkCounts();
1525
+ }
1526
+ /** Record the metadata: source format and version, name, description, id type, the kept aspects. */
1527
+ setMeta() {
1528
+ const { doc } = this;
1529
+ const attrs = doc.networkAttributes[0]?.value;
1530
+ const named = isRecord(attrs) ? attrs : {};
1531
+ const extra = {};
1532
+ if (doc.opaque.size > 0) {
1533
+ extra.opaque = Object.fromEntries(doc.opaque);
1534
+ }
1535
+ if (Object.keys(this.decls.other).length > 0) {
1536
+ extra.declarations = this.decls.other;
1537
+ }
1538
+ const { weightFrom } = this.options;
1539
+ const weightDecl = weightFrom === null ? undefined : this.decls.edge.byName.get(weightFrom);
1540
+ const patch = {
1541
+ sourceFormat: CX2_FORMAT,
1542
+ sourceVersion: doc.version,
1543
+ idType: this.idType,
1544
+ ...(typeof named.name === "string" ? { name: named.name } : {}),
1545
+ ...(typeof named.description === "string" ? { description: named.description } : {}),
1546
+ ...(this.weighted && weightFrom !== null
1547
+ ? {
1548
+ weightOrigin: {
1549
+ format: CX2_FORMAT,
1550
+ id: weightDecl?.alias ?? null,
1551
+ title: weightFrom,
1552
+ type: weightDecl?.type?.d ?? null,
1553
+ namespace: null,
1554
+ },
1555
+ }
1556
+ : {}),
1557
+ extra: { cx2: extra },
1558
+ };
1559
+ this.sink.setMeta(patch);
1560
+ }
1561
+ }
1562
+ /**
1563
+ * The dtype of a bypass column: f64 when every value is a number, bool when every one is a
1564
+ * boolean, string when every one is a string, json otherwise.
1565
+ * @param values - the values
1566
+ * @returns the dtype
1567
+ */
1568
+ function bypassDtype(values) {
1569
+ if (values.every((v) => typeof v === "number")) {
1570
+ return "f64";
1571
+ }
1572
+ if (values.every((v) => typeof v === "boolean")) {
1573
+ return "bool";
1574
+ }
1575
+ if (values.every((v) => typeof v === "string")) {
1576
+ return "string";
1577
+ }
1578
+ return "json";
1579
+ }
1580
+ /**
1581
+ * What a style aspect holds, for the W_STYLES_NOT_IMPORTED message.
1582
+ * @param aspect - the aspect name
1583
+ * @param elements - its elements
1584
+ * @returns a short description
1585
+ */
1586
+ function describeStyle(aspect, elements) {
1587
+ const first = elements[0];
1588
+ if (aspect === "visualProperties" && isRecord(first)) {
1589
+ const count = (key) => (isRecord(first[key]) ? Object.keys(first[key]).length : 0);
1590
+ const defaults = isRecord(first.default)
1591
+ ? Object.values(first.default).reduce((n, v) => n + (isRecord(v) ? Object.keys(v).length : 0), 0)
1592
+ : 0;
1593
+ return `visualProperties: ${defaults} default(s), ${count("nodeMapping")} node mapping(s), ${count("edgeMapping")} edge mapping(s)`;
1594
+ }
1595
+ return `${aspect}: ${elements.length} element(s)`;
1596
+ }
1597
+ /**
1598
+ * Resolve the zAs option.
1599
+ * @param value - the option
1600
+ * @returns the mode; E_UNSUPPORTED for any other value
1601
+ */
1602
+ export function zAsOption(value) {
1603
+ if (value === undefined) {
1604
+ return "column";
1605
+ }
1606
+ if (value === "column" || value === "position") {
1607
+ return value;
1608
+ }
1609
+ throw new GraphFormatError("E_UNSUPPORTED", `option zAs: ${shown(value)} is not one of "column", "position"`, {
1610
+ option: "zAs",
1611
+ found: typeof value === "string" ? value : typeof value,
1612
+ });
1613
+ }
1614
+ /**
1615
+ * The CX2 importer plugin (design section 1.3).
1616
+ */
1617
+ export const cx2Importer = Object.freeze({
1618
+ format: CX2_FORMAT,
1619
+ extensions: Object.freeze([".cx2"]),
1620
+ mimeTypes: Object.freeze(["application/json"]),
1621
+ /**
1622
+ * Confidence that the head is CX2: 0.97 when the first member of a top-level array is an
1623
+ * object with a CXVersion key, in any key order.
1624
+ * @param head - the first bytes
1625
+ * @returns the confidence
1626
+ */
1627
+ sniff(head) {
1628
+ const text = new TextDecoder("utf-8").decode(head.subarray(0, 1024)).replace(/^\uFEFF/, "");
1629
+ return /^\s*\[\s*\{(?:\s*"[^"]*"\s*:\s*(?:true|false|"[^"]*"|[0-9.]+)\s*,)*\s*"CXVersion"\s*:/.test(text)
1630
+ ? 0.97
1631
+ : 0;
1632
+ },
1633
+ /**
1634
+ * Read a CX2 document into the sink.
1635
+ * @param input - the text, bytes or stream
1636
+ * @param sink - the sink
1637
+ * @param options - format-specific and common options
1638
+ * @returns the import report; ImportError on a fatal error or beyond the error limit
1639
+ */
1640
+ async import(input, sink, options) {
1641
+ const resolved = resolveImportOptions(options, FORMAT_DEFAULTS);
1642
+ const zAs = zAsOption(options?.zAs);
1643
+ const report = new ImportReportBuilder(CX2_FORMAT, resolved.errorLimit);
1644
+ reportSinkOptions(sink, options, report, true);
1645
+ reportUnusedOptions(options, report, USED_OPTIONS);
1646
+ const doc = await readDocument(input, report, resolved);
1647
+ new Cx2Reader(sink, report, resolved, zAs, doc).build();
1648
+ throwIfAborted(resolved.signal);
1649
+ return report.finish();
1650
+ },
1651
+ });
1652
+ //# sourceMappingURL=importer.js.map