@graphty/graph-io 0.3.19 → 0.3.21

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 (201) hide show
  1. package/README.md +49 -4
  2. package/dist/chunks/{escape-CWExcecC.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-DQiKgQJc.js → export-Bh60Dv-n.js} +5 -79
  5. package/dist/chunks/export-Bh60Dv-n.js.map +1 -0
  6. package/dist/chunks/{exporter-CbMZyVt-.js → exporter-BGrsWamJ.js} +7 -6
  7. package/dist/chunks/{exporter-CbMZyVt-.js.map → exporter-BGrsWamJ.js.map} +1 -1
  8. package/dist/chunks/exporter-DIeGJXAZ.js +834 -0
  9. package/dist/chunks/exporter-DIeGJXAZ.js.map +1 -0
  10. package/dist/chunks/{importer-BNFuV1-K.js → importer-BWY2FFc5.js} +28 -7
  11. package/dist/chunks/importer-BWY2FFc5.js.map +1 -0
  12. package/dist/chunks/importer-DD-xv9_Y.js +1471 -0
  13. package/dist/chunks/importer-DD-xv9_Y.js.map +1 -0
  14. package/dist/chunks/{importer-BAP4PrxR.js → importer-DET1tg6s.js} +30 -20
  15. package/dist/chunks/importer-DET1tg6s.js.map +1 -0
  16. package/dist/chunks/{importer-ByPGO-09.js → importer-DEcKhsmQ.js} +2 -2
  17. package/dist/chunks/{importer-ByPGO-09.js.map → importer-DEcKhsmQ.js.map} +1 -1
  18. package/dist/chunks/{importer-BW-Ft2ps.js → importer-DIrbbnAf.js} +6 -5
  19. package/dist/chunks/{importer-BW-Ft2ps.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-Bm1_5vPS.js → importer-eUREhBGj.js} +11 -8
  23. package/dist/chunks/importer-eUREhBGj.js.map +1 -0
  24. package/dist/chunks/{importer-DOepkgnG.js → importer-vi3bSdtw.js} +4 -4
  25. package/dist/chunks/{importer-DOepkgnG.js.map → importer-vi3bSdtw.js.map} +1 -1
  26. package/dist/chunks/{importer-BVGtU1NA.js → importer-zGLo8Dg_.js} +6 -5
  27. package/dist/chunks/{importer-BVGtU1NA.js.map → importer-zGLo8Dg_.js.map} +1 -1
  28. package/dist/chunks/{json-elements-CZY1wiZh.js → json-elements-DDS8N2Dd.js} +2 -2
  29. package/dist/chunks/{json-elements-CZY1wiZh.js.map → json-elements-DDS8N2Dd.js.map} +1 -1
  30. package/dist/chunks/{records-BzNicMsf.js → records-dbRkxwaq.js} +2 -2
  31. package/dist/chunks/{records-BzNicMsf.js.map → records-dbRkxwaq.js.map} +1 -1
  32. package/dist/chunks/{report-BcWboivV.js → report-B1z4WT9e.js} +143 -111
  33. package/dist/chunks/{report-BcWboivV.js.map → report-B1z4WT9e.js.map} +1 -1
  34. package/dist/chunks/{weights-CwISIpCP.js → weights-Dzba96G3.js} +5 -5
  35. package/dist/chunks/{weights-CwISIpCP.js.map → weights-Dzba96G3.js.map} +1 -1
  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 -5
  39. package/dist/csv.js.map +1 -1
  40. package/dist/cx.js +1 -1
  41. package/dist/cx2.js +2 -2
  42. package/dist/cys.d.ts +1 -0
  43. package/dist/cys.js +6 -0
  44. package/dist/cys.js.map +1 -0
  45. package/dist/dot.js +1 -1
  46. package/dist/gexf.js +5 -4
  47. package/dist/gexf.js.map +1 -1
  48. package/dist/gml.js +12 -14
  49. package/dist/gml.js.map +1 -1
  50. package/dist/graph-io.js +288 -141
  51. package/dist/graph-io.js.map +1 -1
  52. package/dist/graphml.js +1 -1
  53. package/dist/json.js +1 -1
  54. package/dist/neo4j.js +6 -5
  55. package/dist/neo4j.js.map +1 -1
  56. package/dist/obo.js +1 -1
  57. package/dist/pajek.js +1 -1
  58. package/dist/src/common/cell-budget.d.ts +84 -0
  59. package/dist/src/common/cell-budget.d.ts.map +1 -0
  60. package/dist/src/common/cell-budget.js +138 -0
  61. package/dist/src/common/cell-budget.js.map +1 -0
  62. package/dist/src/common/input.d.ts +10 -0
  63. package/dist/src/common/input.d.ts.map +1 -1
  64. package/dist/src/common/input.js +39 -0
  65. package/dist/src/common/input.js.map +1 -1
  66. package/dist/src/common/options.d.ts +6 -0
  67. package/dist/src/common/options.d.ts.map +1 -1
  68. package/dist/src/common/options.js +1 -1
  69. package/dist/src/common/options.js.map +1 -1
  70. package/dist/src/common/xml.d.ts +37 -3
  71. package/dist/src/common/xml.d.ts.map +1 -1
  72. package/dist/src/common/xml.js +86 -6
  73. package/dist/src/common/xml.js.map +1 -1
  74. package/dist/src/common/zip.d.ts +92 -0
  75. package/dist/src/common/zip.d.ts.map +1 -0
  76. package/dist/src/common/zip.js +399 -0
  77. package/dist/src/common/zip.js.map +1 -0
  78. package/dist/src/formats/cx/importer.d.ts.map +1 -1
  79. package/dist/src/formats/cx/importer.js +26 -17
  80. package/dist/src/formats/cx/importer.js.map +1 -1
  81. package/dist/src/formats/cys/constants.d.ts +68 -0
  82. package/dist/src/formats/cys/constants.d.ts.map +1 -0
  83. package/dist/src/formats/cys/constants.js +76 -0
  84. package/dist/src/formats/cys/constants.js.map +1 -0
  85. package/dist/src/formats/cys/importer.d.ts +38 -0
  86. package/dist/src/formats/cys/importer.d.ts.map +1 -0
  87. package/dist/src/formats/cys/importer.js +830 -0
  88. package/dist/src/formats/cys/importer.js.map +1 -0
  89. package/dist/src/formats/cys/index.d.ts +7 -0
  90. package/dist/src/formats/cys/index.d.ts.map +1 -0
  91. package/dist/src/formats/cys/index.js +7 -0
  92. package/dist/src/formats/cys/index.js.map +1 -0
  93. package/dist/src/formats/cys/session.d.ts +132 -0
  94. package/dist/src/formats/cys/session.d.ts.map +1 -0
  95. package/dist/src/formats/cys/session.js +315 -0
  96. package/dist/src/formats/cys/session.js.map +1 -0
  97. package/dist/src/formats/cys/tables.d.ts +90 -0
  98. package/dist/src/formats/cys/tables.d.ts.map +1 -0
  99. package/dist/src/formats/cys/tables.js +293 -0
  100. package/dist/src/formats/cys/tables.js.map +1 -0
  101. package/dist/src/formats/dot/exporter.d.ts +2 -0
  102. package/dist/src/formats/dot/exporter.d.ts.map +1 -1
  103. package/dist/src/formats/dot/exporter.js +12 -0
  104. package/dist/src/formats/dot/exporter.js.map +1 -1
  105. package/dist/src/formats/dot/importer.js +6 -2
  106. package/dist/src/formats/dot/importer.js.map +1 -1
  107. package/dist/src/formats/gexf/importer.d.ts +2 -2
  108. package/dist/src/formats/gexf/importer.d.ts.map +1 -1
  109. package/dist/src/formats/gexf/importer.js +1 -1
  110. package/dist/src/formats/gexf/importer.js.map +1 -1
  111. package/dist/src/formats/gml/exporter.d.ts +0 -8
  112. package/dist/src/formats/gml/exporter.d.ts.map +1 -1
  113. package/dist/src/formats/gml/exporter.js +7 -17
  114. package/dist/src/formats/gml/exporter.js.map +1 -1
  115. package/dist/src/formats/json/exporter.d.ts.map +1 -1
  116. package/dist/src/formats/json/exporter.js +3 -1
  117. package/dist/src/formats/json/exporter.js.map +1 -1
  118. package/dist/src/formats/json/importer.d.ts.map +1 -1
  119. package/dist/src/formats/json/importer.js +3 -2
  120. package/dist/src/formats/json/importer.js.map +1 -1
  121. package/dist/src/formats/xgmml/columns.d.ts +152 -0
  122. package/dist/src/formats/xgmml/columns.d.ts.map +1 -0
  123. package/dist/src/formats/xgmml/columns.js +593 -0
  124. package/dist/src/formats/xgmml/columns.js.map +1 -0
  125. package/dist/src/formats/xgmml/constants.d.ts +196 -0
  126. package/dist/src/formats/xgmml/constants.d.ts.map +1 -0
  127. package/dist/src/formats/xgmml/constants.js +197 -0
  128. package/dist/src/formats/xgmml/constants.js.map +1 -0
  129. package/dist/src/formats/xgmml/document.d.ts +361 -0
  130. package/dist/src/formats/xgmml/document.d.ts.map +1 -0
  131. package/dist/src/formats/xgmml/document.js +695 -0
  132. package/dist/src/formats/xgmml/document.js.map +1 -0
  133. package/dist/src/formats/xgmml/emit.d.ts +341 -0
  134. package/dist/src/formats/xgmml/emit.d.ts.map +1 -0
  135. package/dist/src/formats/xgmml/emit.js +1275 -0
  136. package/dist/src/formats/xgmml/emit.js.map +1 -0
  137. package/dist/src/formats/xgmml/exporter.d.ts +24 -0
  138. package/dist/src/formats/xgmml/exporter.d.ts.map +1 -0
  139. package/dist/src/formats/xgmml/exporter.js +999 -0
  140. package/dist/src/formats/xgmml/exporter.js.map +1 -0
  141. package/dist/src/formats/xgmml/importer.d.ts +58 -0
  142. package/dist/src/formats/xgmml/importer.d.ts.map +1 -0
  143. package/dist/src/formats/xgmml/importer.js +360 -0
  144. package/dist/src/formats/xgmml/importer.js.map +1 -0
  145. package/dist/src/formats/xgmml/index.d.ts +8 -0
  146. package/dist/src/formats/xgmml/index.d.ts.map +1 -0
  147. package/dist/src/formats/xgmml/index.js +8 -0
  148. package/dist/src/formats/xgmml/index.js.map +1 -0
  149. package/dist/src/formats/xgmml/values.d.ts +60 -0
  150. package/dist/src/formats/xgmml/values.d.ts.map +1 -0
  151. package/dist/src/formats/xgmml/values.js +148 -0
  152. package/dist/src/formats/xgmml/values.js.map +1 -0
  153. package/dist/src/index.d.ts +2 -0
  154. package/dist/src/index.d.ts.map +1 -1
  155. package/dist/src/index.js +2 -0
  156. package/dist/src/index.js.map +1 -1
  157. package/dist/src/registry.d.ts +7 -0
  158. package/dist/src/registry.d.ts.map +1 -1
  159. package/dist/src/registry.js +25 -10
  160. package/dist/src/registry.js.map +1 -1
  161. package/dist/src/sniff.d.ts +1 -1
  162. package/dist/src/sniff.d.ts.map +1 -1
  163. package/dist/src/sniff.js +2 -0
  164. package/dist/src/sniff.js.map +1 -1
  165. package/dist/xgmml.d.ts +1 -0
  166. package/dist/xgmml.js +9 -0
  167. package/dist/xgmml.js.map +1 -0
  168. package/package.json +15 -2
  169. package/src/common/cell-budget.ts +170 -0
  170. package/src/common/input.ts +40 -0
  171. package/src/common/options.ts +1 -1
  172. package/src/common/xml.ts +127 -6
  173. package/src/common/zip.ts +472 -0
  174. package/src/formats/cx/importer.ts +27 -19
  175. package/src/formats/cys/constants.ts +99 -0
  176. package/src/formats/cys/importer.ts +1100 -0
  177. package/src/formats/cys/index.ts +7 -0
  178. package/src/formats/cys/session.ts +428 -0
  179. package/src/formats/cys/tables.ts +400 -0
  180. package/src/formats/dot/exporter.ts +17 -0
  181. package/src/formats/dot/importer.ts +6 -2
  182. package/src/formats/gexf/importer.ts +0 -1
  183. package/src/formats/gml/exporter.ts +7 -18
  184. package/src/formats/json/exporter.ts +3 -1
  185. package/src/formats/json/importer.ts +3 -2
  186. package/src/formats/xgmml/columns.ts +747 -0
  187. package/src/formats/xgmml/constants.ts +265 -0
  188. package/src/formats/xgmml/document.ts +975 -0
  189. package/src/formats/xgmml/emit.ts +1563 -0
  190. package/src/formats/xgmml/exporter.ts +1215 -0
  191. package/src/formats/xgmml/importer.ts +491 -0
  192. package/src/formats/xgmml/index.ts +8 -0
  193. package/src/formats/xgmml/values.ts +183 -0
  194. package/src/index.ts +9 -0
  195. package/src/registry.ts +41 -15
  196. package/src/sniff.ts +5 -1
  197. package/dist/chunks/escape-CWExcecC.js.map +0 -1
  198. package/dist/chunks/importer-BAP4PrxR.js.map +0 -1
  199. package/dist/chunks/importer-BNFuV1-K.js.map +0 -1
  200. package/dist/chunks/importer-Bm1_5vPS.js.map +0 -1
  201. package/dist/chunks/writer-DQiKgQJc.js.map +0 -1
@@ -0,0 +1,999 @@
1
+ /**
2
+ * The XGMML exporter (design `design/graph-io/cytoscape-and-obo/design.md` section 1.1;
3
+ * `research-xgmml.md` section 4.7): the Cytoscape 3.x dialect, which Cytoscape 3 opens with every
4
+ * attribute type intact. It writes `cy:documentVersion="3.0"`, the root `directed` from the
5
+ * snapshot and `cy:directed` on every edge (Cytoscape ignores the root attribute), `type` plus
6
+ * `cy:type` (and `cy:elementType`) on every att, positions as `graphics x y z` with y negated
7
+ * back to screen coordinates, the importer's `graphics` json columns back as graphics attributes
8
+ * and nested atts, containment as each group node's nested graph of `xlink:href` member
9
+ * references (every node is declared at the top level, so the node order survives), and newline
10
+ * and tab as character references unless `cytoscapeEscapes` asks for Cytoscape's two-character
11
+ * form. It writes the graph's structure and columns, never styles.
12
+ */
13
+ import { GraphFormatError } from "@graphty/graph-format";
14
+ import { childrenCsr } from "../../children.js";
15
+ import { DictHeuristic } from "../../common/attributes.js";
16
+ import { pairFolding } from "../../common/direction.js";
17
+ import { escapeXmlAttribute, escapeXmlText } from "../../common/escape.js";
18
+ import { capabilities, checkCapabilities, LOSS } from "../../common/export.js";
19
+ import { formatF32, formatF64 } from "../../common/format.js";
20
+ import { resolveExportOptions } from "../../common/options.js";
21
+ import { explicitWeights } from "../../common/weights.js";
22
+ import { encodeChunks, joinText } from "../../common/writer.js";
23
+ import { xmlIllegalTextNotes } from "../../common/xml.js";
24
+ import { CY_NAMESPACE, CYTOSCAPE_ORIGIN_NAMESPACE, EDGE_ID_COLUMN, FORMAT, GRAPHICS_COLUMN, INTERACTION_COLUMN, LABEL_COLUMN, META_KEY, NESTED_NETWORK_COLUMN, NETWORK_POINTER_COLUMN, NETWORKS_COLUMN, PARENT_COLUMN, PARENTS_COLUMN, POSITION_COLUMN, SUBGRAPH_COLUMN, XGMML_LOSS, XGMML_NAMESPACE, XGMML_ORIGIN_NAMESPACE, XLINK_NAMESPACE, Z_COLUMN, } from "./constants.js";
25
+ import { aliasesOf } from "./emit.js";
26
+ /** What XGMML keeps (design section 1.1, all 16 fields). */
27
+ const CAPABILITIES = capabilities({
28
+ mixedDirection: true,
29
+ multiEdges: true,
30
+ selfLoops: true,
31
+ edgeIds: "optional",
32
+ idCharset: "any",
33
+ dtypes: ["string", "dict", "f64", "f32", "i32", "u32", "u8", "bool", "list"],
34
+ components: false,
35
+ lists: true,
36
+ json: false,
37
+ defaults: false,
38
+ options: false,
39
+ hierarchy: true,
40
+ temporal: "none",
41
+ graphAttributes: true,
42
+ positions: true,
43
+ viz: false,
44
+ });
45
+ /** The roles with a slot: label (XML attribute), the edge id, containment and position. */
46
+ const SLOT_ROLES = new Set(["label", "id", "parent", "parents", "position"]);
47
+ /** The names the importer gives the slot columns. */
48
+ const ROLE_NAMES = Object.freeze({
49
+ label: LABEL_COLUMN,
50
+ id: EDGE_ID_COLUMN,
51
+ parent: PARENT_COLUMN,
52
+ position: POSITION_COLUMN,
53
+ });
54
+ /** Roles checkCapabilities() reports as not written (no slot in XGMML): the column is skipped. */
55
+ const DROPPED_ROLES = new Set([
56
+ "color",
57
+ "size",
58
+ "shape",
59
+ "thickness",
60
+ "start",
61
+ "end",
62
+ "timestamp",
63
+ "timestamps",
64
+ "spells",
65
+ "open",
66
+ "spellsOpen",
67
+ ]);
68
+ /** XML attributes of `<node>` and `<edge>` the importer reads itself; a column of such a name is an att. */
69
+ const READ_ATTRIBUTES = {
70
+ node: new Set(["id", "label", "name"]),
71
+ edge: new Set(["id", "label", "name", "source", "target", "weight"]),
72
+ };
73
+ /** Roles never written as atts. */
74
+ const STRUCTURAL_ROLES = new Set([
75
+ "directed",
76
+ "pair",
77
+ "mutual",
78
+ "weight",
79
+ "parent",
80
+ "parents",
81
+ "position",
82
+ ]);
83
+ /** Node column names the importer owns; a plain column of such a name reads back renamed. */
84
+ const RESERVED_NODE_NAMES = new Set([
85
+ LABEL_COLUMN,
86
+ POSITION_COLUMN,
87
+ Z_COLUMN,
88
+ GRAPHICS_COLUMN,
89
+ PARENT_COLUMN,
90
+ PARENTS_COLUMN,
91
+ SUBGRAPH_COLUMN,
92
+ NESTED_NETWORK_COLUMN,
93
+ NETWORK_POINTER_COLUMN,
94
+ NETWORKS_COLUMN,
95
+ ]);
96
+ /** Edge column names the importer owns. */
97
+ const RESERVED_EDGE_NAMES = new Set([EDGE_ID_COLUMN, LABEL_COLUMN, GRAPHICS_COLUMN]);
98
+ /** The importer-owned names of each table. */
99
+ const RESERVED_NAMES = {
100
+ graph: new Set([GRAPHICS_COLUMN]),
101
+ node: RESERVED_NODE_NAMES,
102
+ edge: RESERVED_EDGE_NAMES,
103
+ };
104
+ /** The XGMML and Cytoscape `<graphics>` XML attributes; every other graphics key is a nested att. */
105
+ const GRAPHICS_ATTRIBUTES = new Set([
106
+ "type",
107
+ "w",
108
+ "h",
109
+ "d",
110
+ "image",
111
+ "bitmap",
112
+ "width",
113
+ "arrow",
114
+ "capstyle",
115
+ "joinstyle",
116
+ "smooth",
117
+ "splinesteps",
118
+ "justify",
119
+ "font",
120
+ "background",
121
+ "foreground",
122
+ "extent",
123
+ "start",
124
+ "style",
125
+ "stipple",
126
+ "visible",
127
+ "fill",
128
+ "outline",
129
+ "anchor",
130
+ ]);
131
+ const I32_MAX = 2147483647;
132
+ /**
133
+ * The Cytoscape type of a scalar dtype and the XGMML type.
134
+ * @param column - the column
135
+ * @param dtype - the dtype (a list's item dtype)
136
+ * @returns [type, cy:type]
137
+ */
138
+ function typesOf(column, dtype) {
139
+ if (column.meta.components > 1) {
140
+ return ["string", "String"];
141
+ }
142
+ switch (dtype) {
143
+ case "bool":
144
+ return ["boolean", "Boolean"];
145
+ case "i32":
146
+ case "u8":
147
+ return ["integer", "Integer"];
148
+ case "u32":
149
+ return maxValue(column) > I32_MAX ? ["integer", "Long"] : ["integer", "Integer"];
150
+ case "f32":
151
+ case "f64":
152
+ return column.meta.origin?.type === "long" && allSafeIntegers(column)
153
+ ? ["integer", "Long"]
154
+ : ["real", "Double"];
155
+ default:
156
+ return ["string", "String"];
157
+ }
158
+ }
159
+ /**
160
+ * Whether every value of a numeric column (or of its list items) is a safe integer.
161
+ * @param column - the column
162
+ * @returns true when Long can carry every value
163
+ */
164
+ function allSafeIntegers(column) {
165
+ for (let r = 0; r < column.length; r++) {
166
+ if (!column.isSet(r)) {
167
+ continue;
168
+ }
169
+ const items = column.dtype === "list" ? [...column.sliceOf(r)] : [column.value(r)];
170
+ if (!items.every((item) => typeof item === "number" && Number.isSafeInteger(item))) {
171
+ return false;
172
+ }
173
+ }
174
+ return true;
175
+ }
176
+ /**
177
+ * The largest value of a u32 column (or of its list items).
178
+ * @param column - the column
179
+ * @returns the maximum, 0 when empty
180
+ */
181
+ function maxValue(column) {
182
+ let max = 0;
183
+ for (let r = 0; r < column.length; r++) {
184
+ if (!column.isSet(r)) {
185
+ continue;
186
+ }
187
+ const value = column.value(r);
188
+ const items = column.dtype === "list" ? [...column.sliceOf(r)] : [value];
189
+ for (const item of items) {
190
+ if (typeof item === "number" && item > max) {
191
+ max = item;
192
+ }
193
+ }
194
+ }
195
+ return max;
196
+ }
197
+ /**
198
+ * Whether a column came from the XGMML importer's own slot of that name.
199
+ * @param column - the column
200
+ * @param namespace - the origin namespace the importer gives it
201
+ * @returns true for an importer-owned column
202
+ */
203
+ function owned(column, namespace) {
204
+ const { origin } = column.meta;
205
+ return origin !== null && origin.namespace === namespace;
206
+ }
207
+ /**
208
+ * Plan the columns of one table.
209
+ * @param table - the columns
210
+ * @param domain - the table
211
+ * @param snapshot - the snapshot
212
+ * @param note - the recorder
213
+ * @returns the writes
214
+ */
215
+ function planTable(table, domain, snapshot, note) {
216
+ const writes = [];
217
+ const reserved = RESERVED_NAMES[domain];
218
+ const hasLabelRole = domain !== "graph" && (domain === "node" ? snapshot.nodes : snapshot.edges).byRole("label") !== null;
219
+ for (const column of table) {
220
+ const { meta } = column;
221
+ if (meta.role !== null &&
222
+ (STRUCTURAL_ROLES.has(meta.role) ||
223
+ DROPPED_ROLES.has(meta.role) ||
224
+ meta.role === "id" ||
225
+ meta.role === "timeText")) {
226
+ continue;
227
+ }
228
+ const kind = slotOf(column, domain, hasLabelRole);
229
+ const set = column.length - column.nullCount;
230
+ if (kind === "att" && reserved.has(meta.name)) {
231
+ note(LOSS.COLUMN_NAME_CHANGED, `${domain} column "${meta.name}" is named like a column the XGMML importer owns and reads back renamed`, meta.name, set);
232
+ }
233
+ else if (kind === "label" && meta.dtype !== "string" && meta.dtype !== "dict") {
234
+ note(LOSS.DTYPE, `${domain} label column "${meta.name}" (${meta.dtype}) is written as text and reads back as string`, meta.name, set);
235
+ }
236
+ else if (kind === "label" && meta.role === null) {
237
+ note(LOSS.ROLE_ASSUMED, `${domain} column "${meta.name}" is written as the label and reads back with the label role`, meta.name, set);
238
+ }
239
+ if (kind === "att") {
240
+ attNotes(column, domain, note);
241
+ }
242
+ const item = meta.dtype === "list" ? meta.itemDtype : meta.dtype;
243
+ const [type, cyType] = meta.dtype === "list" ? ["list", "List"] : declaredTypes(column, typesOf(column, item));
244
+ writes.push({
245
+ column,
246
+ name: meta.name,
247
+ kind,
248
+ type,
249
+ cyType,
250
+ elementType: meta.dtype === "list" ? typesOf(column, item)[1] : null,
251
+ });
252
+ }
253
+ return writes;
254
+ }
255
+ /**
256
+ * Where a column goes.
257
+ * @param column - the column
258
+ * @param domain - the table
259
+ * @param hasLabelRole - whether the table has a label role column
260
+ * @returns the slot
261
+ */
262
+ function slotOf(column, domain, hasLabelRole) {
263
+ const { meta } = column;
264
+ if (domain !== "graph" && untypedAttribute(column, domain)) {
265
+ return "xml";
266
+ }
267
+ if (meta.role === "label" ||
268
+ (!hasLabelRole &&
269
+ domain !== "graph" &&
270
+ meta.role === null &&
271
+ meta.name === LABEL_COLUMN &&
272
+ (meta.dtype === "string" || meta.dtype === "dict"))) {
273
+ return "label";
274
+ }
275
+ if (meta.dtype === "json" && meta.name === GRAPHICS_COLUMN && owned(column, XGMML_ORIGIN_NAMESPACE)) {
276
+ return "graphics";
277
+ }
278
+ if (domain !== "node") {
279
+ return "att";
280
+ }
281
+ if (meta.name === Z_COLUMN && meta.dtype === "f64" && meta.role === null) {
282
+ return "z";
283
+ }
284
+ if (meta.name === SUBGRAPH_COLUMN && meta.dtype === "json" && owned(column, XGMML_ORIGIN_NAMESPACE)) {
285
+ return "subgraph";
286
+ }
287
+ if (meta.name === NESTED_NETWORK_COLUMN && meta.dtype === "string" && owned(column, CYTOSCAPE_ORIGIN_NAMESPACE)) {
288
+ return "nested";
289
+ }
290
+ if (meta.name === NETWORK_POINTER_COLUMN && meta.dtype === "string" && owned(column, XGMML_ORIGIN_NAMESPACE)) {
291
+ return "pointer";
292
+ }
293
+ if (meta.name === NETWORKS_COLUMN && meta.dtype === "list" && owned(column, XGMML_ORIGIN_NAMESPACE)) {
294
+ return "networks";
295
+ }
296
+ return "att";
297
+ }
298
+ /**
299
+ * Whether a column came from an XML attribute of the element (the importer's 5.1 text grammar:
300
+ * xgmml origin, no declared type) and can be written back as one, so it reads back the same.
301
+ * @param column - the column
302
+ * @param domain - node or edge
303
+ * @returns true to write it as an XML attribute
304
+ */
305
+ function untypedAttribute(column, domain) {
306
+ const { meta } = column;
307
+ const { origin } = meta;
308
+ return (origin !== null &&
309
+ origin.format === FORMAT &&
310
+ origin.type === null &&
311
+ origin.namespace === null &&
312
+ meta.role === null &&
313
+ meta.components === 1 &&
314
+ (meta.dtype === "string" || meta.dtype === "bool" || meta.dtype === "i32" || meta.dtype === "f64") &&
315
+ /^[A-Za-z_][A-Za-z0-9_.-]*$/.test(meta.name) &&
316
+ !READ_ATTRIBUTES[domain].has(meta.name));
317
+ }
318
+ /**
319
+ * The type and cy:type of an att: the source's own declaration when the column came from an
320
+ * XGMML att that declared only `type` (a draft or 2.x file), else both.
321
+ * @param column - the column
322
+ * @param types - the type and cy:type of its dtype
323
+ * @returns the pair to write; a null member is not written
324
+ */
325
+ function declaredTypes(column, types) {
326
+ const { origin } = column.meta;
327
+ if (origin !== null && origin.format === FORMAT && origin.type === types[0] && column.meta.components === 1) {
328
+ return [types[0], null];
329
+ }
330
+ return types;
331
+ }
332
+ /**
333
+ * The notes of a column written as a typed att: dtypes Cytoscape widens, json written as text,
334
+ * literal backslash escapes, the string / dict heuristic.
335
+ * @param column - the column
336
+ * @param domain - the table
337
+ * @param note - the recorder
338
+ */
339
+ function attNotes(column, domain, note) {
340
+ const { meta } = column;
341
+ const set = column.length - column.nullCount;
342
+ const label = `${domain} column "${meta.name}"`;
343
+ const item = meta.dtype === "list" ? meta.itemDtype : meta.dtype;
344
+ if (meta.dtype === "json") {
345
+ note(XGMML_LOSS.JSON_AS_STRING, `${label} holds nested values; they are written as JSON text and read back as strings`, meta.name, set);
346
+ return;
347
+ }
348
+ if (item === "f32" || item === "u8" || item === "u32") {
349
+ note(XGMML_LOSS.WIDENED_TYPE, `${label} (${item}) is written as a wider Cytoscape type and reads back as ${readBackDtype(column, item)}`, meta.name, set);
350
+ }
351
+ if (item === "string" || item === "dict") {
352
+ let escapes = 0;
353
+ for (let r = 0; r < column.length; r++) {
354
+ if (column.isSet(r)) {
355
+ const values = column.dtype === "list" ? [...column.sliceOf(r)] : [column.value(r)];
356
+ if (values.some((v) => typeof v === "string" && /\\[nt]/.test(v))) {
357
+ escapes++;
358
+ }
359
+ }
360
+ }
361
+ if (escapes > 0) {
362
+ note(XGMML_LOSS.BACKSLASH_ESCAPE, `${label}: ${escapes} value(s) hold a literal \\n or \\t, which Cytoscape's escape convention reads back as a newline or tab`, meta.name, escapes);
363
+ }
364
+ }
365
+ if (meta.dtype === "string" || meta.dtype === "dict") {
366
+ const heuristic = new DictHeuristic();
367
+ for (let r = 0; r < column.length && !heuristic.decided; r++) {
368
+ if (column.isSet(r)) {
369
+ heuristic.observe(column.value(r));
370
+ }
371
+ }
372
+ const readsAs = heuristic.decide();
373
+ if (readsAs !== meta.dtype) {
374
+ note(XGMML_LOSS.STORAGE_CLASS_CHANGED, `${label} reads back as ${readsAs} (the cardinality heuristic)`, meta.name, null);
375
+ }
376
+ }
377
+ }
378
+ /**
379
+ * The dtype a widened column reads back as.
380
+ * @param column - the column
381
+ * @param item - its dtype (a list's item dtype)
382
+ * @returns the dtype the importer gives it
383
+ */
384
+ function readBackDtype(column, item) {
385
+ if (item === "u8" || (item === "u32" && maxValue(column) <= I32_MAX)) {
386
+ return "i32";
387
+ }
388
+ return "f64";
389
+ }
390
+ /**
391
+ * Build the plan and its loss notes.
392
+ * @param snapshot - the snapshot
393
+ * @param options - the common options
394
+ * @param escapes - the cytoscapeEscapes option
395
+ * @returns the plan
396
+ */
397
+ function planExport(snapshot, options, escapes) {
398
+ const notes = checkCapabilities(snapshot, CAPABILITIES, options, {
399
+ roles: SLOT_ROLES,
400
+ roleNames: ROLE_NAMES,
401
+ positionDtype: "f32",
402
+ }).filter((n) => n.code !== LOSS.JSON);
403
+ const note = (code, message, column = null, count = null) => {
404
+ notes.push(Object.freeze({ code, message, column, count }));
405
+ };
406
+ notes.push(...xmlIllegalTextNotes(snapshot));
407
+ const folding = pairFolding(snapshot);
408
+ if (folding.mutualCount > 0) {
409
+ note(XGMML_LOSS.MUTUAL_EXPANDED, `${folding.mutualCount} mutual pair(s) are written as two directed edges; the mutual mark is lost`, null, folding.mutualCount);
410
+ }
411
+ const numericIds = countNumericIds(snapshot);
412
+ if (numericIds > 0) {
413
+ note(XGMML_LOSS.ID_TEXT_TYPE, `${numericIds} numeric node id(s) are written as text and read back as strings`, null, numericIds);
414
+ }
415
+ const edgeId = snapshot.edges.byRole("id");
416
+ if (edgeId !== null && edgeId.dtype !== "string" && edgeId.dtype !== "dict") {
417
+ note(XGMML_LOSS.EDGE_ID_TEXT, `edge id column "${edgeId.meta.name}" (${edgeId.dtype}) is written as text and reads back as strings`, edgeId.meta.name, null);
418
+ }
419
+ const hierarchy = childrenCsr(snapshot);
420
+ if (hierarchy.unreachable > 0) {
421
+ note(XGMML_LOSS.PARENT_CYCLE, `${hierarchy.unreachable} node(s) whose parent chain never reaches a root are written at the top level and lose their parent`, null, hierarchy.unreachable);
422
+ }
423
+ const parents = snapshot.nodes.byRole("parents");
424
+ if (parents !== null && snapshot.nodes.byRole("parent") !== null) {
425
+ note(XGMML_LOSS.PARENTS_DROPPED, `parents column "${parents.meta.name}" is not written: the "parent" column is the containment written`, parents.meta.name, parents.length - parents.nullCount);
426
+ }
427
+ else if (parents !== null && !multiParent(parents)) {
428
+ note(LOSS.COLUMN_NAME_CHANGED, `parents column "${parents.meta.name}" holds one parent per node and reads back as the "parent" column`, parents.meta.name, null);
429
+ }
430
+ const position = snapshot.nodes.byRole("position");
431
+ if (position !== null) {
432
+ positionNotes(position, snapshot, note);
433
+ }
434
+ interactionNote(snapshot, note);
435
+ const weights = explicitWeights(snapshot);
436
+ for (const column of snapshot.edges) {
437
+ if (column.meta.name === "weight" && column.meta.role === null && !weights.weighted) {
438
+ note(LOSS.WEIGHT_KEY_CLASH, `edge column "weight" reads back as THE weight`, "weight", null);
439
+ }
440
+ }
441
+ return {
442
+ options,
443
+ escapes,
444
+ notes,
445
+ graph: planTable(snapshot.graph, "graph", snapshot, note),
446
+ nodes: planTable(snapshot.nodes, "node", snapshot, note),
447
+ edges: planTable(snapshot.edges, "edge", snapshot, note),
448
+ folding,
449
+ weights,
450
+ hierarchy,
451
+ reachable: reachableNodes(snapshot.nodeCount, hierarchy),
452
+ position,
453
+ edgeId,
454
+ };
455
+ }
456
+ /**
457
+ * The note for edge labels the importer reads as Cytoscape label aliases (`a (i) b`): without an
458
+ * `interaction` column they read back with one, as Cytoscape fills it.
459
+ * @param snapshot - the snapshot
460
+ * @param note - the recorder
461
+ */
462
+ function interactionNote(snapshot, note) {
463
+ const label = snapshot.edges.byRole("label") ?? snapshot.edges.get(LABEL_COLUMN);
464
+ if (label === null || snapshot.edges.get(INTERACTION_COLUMN) !== null) {
465
+ return;
466
+ }
467
+ let shaped = 0;
468
+ for (let e = 0; e < label.length; e++) {
469
+ if (label.isSet(e) && aliasesOf(scalarText(label.value(e))) !== null) {
470
+ shaped++;
471
+ }
472
+ }
473
+ if (shaped > 0) {
474
+ note(XGMML_LOSS.INTERACTION_FROM_LABEL, `${shaped} edge label(s) have Cytoscape's "a (i) b" shape and read back with an "${INTERACTION_COLUMN}" column`, INTERACTION_COLUMN, shaped);
475
+ }
476
+ }
477
+ /**
478
+ * The nodes a traversal of the containment from its roots reaches.
479
+ * @param nodeCount - the number of nodes
480
+ * @param hierarchy - the children CSR
481
+ * @returns 1 per reached node
482
+ */
483
+ function reachableNodes(nodeCount, hierarchy) {
484
+ const reached = new Uint8Array(nodeCount);
485
+ const stack = Array.from(hierarchy.roots);
486
+ for (const root of stack) {
487
+ reached[root] = 1;
488
+ }
489
+ while (stack.length > 0) {
490
+ for (const child of hierarchy.childrenOf(stack.pop())) {
491
+ if (reached[child] === 0) {
492
+ reached[child] = 1;
493
+ stack.push(child);
494
+ }
495
+ }
496
+ }
497
+ return reached;
498
+ }
499
+ /**
500
+ * Whether a parents column gives some node more than one parent.
501
+ * @param column - the parents column
502
+ * @returns true when a row holds two or more parents
503
+ */
504
+ function multiParent(column) {
505
+ for (let r = 0; r < column.length; r++) {
506
+ if (column.isSet(r) && column.dtype === "list" && column.sliceOf(r).length > 1) {
507
+ return true;
508
+ }
509
+ }
510
+ return false;
511
+ }
512
+ /**
513
+ * The notes of a position column: its shape, non-finite coordinates, and a z that reads back in
514
+ * the z column.
515
+ * @param position - the position column
516
+ * @param snapshot - the snapshot
517
+ * @param note - the recorder
518
+ */
519
+ function positionNotes(position, snapshot, note) {
520
+ const { meta } = position;
521
+ if (meta.components !== 3) {
522
+ note(XGMML_LOSS.POSITION, `position column "${meta.name}" has ${meta.components} component(s) and reads back with 3`, meta.name, null);
523
+ }
524
+ let nonFinite = 0;
525
+ let depth = 0;
526
+ for (let r = 0; r < position.length; r++) {
527
+ if (!position.isSet(r)) {
528
+ continue;
529
+ }
530
+ const xyz = Array.from(position.value(r));
531
+ if (xyz.slice(0, 2).some((v) => !Number.isFinite(v))) {
532
+ nonFinite++;
533
+ }
534
+ else if ((xyz[2] ?? 0) !== 0) {
535
+ depth++;
536
+ }
537
+ }
538
+ if (nonFinite > 0) {
539
+ note(XGMML_LOSS.POSITION, `${nonFinite} position(s) with a non-finite coordinate are not written`, meta.name, nonFinite);
540
+ }
541
+ const zColumn = snapshot.nodes.get(Z_COLUMN);
542
+ if (depth > 0) {
543
+ note(XGMML_LOSS.POSITION, zColumn === null
544
+ ? `${depth} position(s) have a z; it is written as graphics z and reads back in the z column (zAs: "position" reads it as a coordinate)`
545
+ : `${depth} position(s) have a z, but graphics z holds the z column; the position z is lost`, meta.name, depth);
546
+ }
547
+ }
548
+ /**
549
+ * Node ids that are numbers (written as text, read back as strings).
550
+ * @param snapshot - the snapshot
551
+ * @returns the count
552
+ */
553
+ function countNumericIds(snapshot) {
554
+ let n = 0;
555
+ for (let i = 0; i < snapshot.nodeCount; i++) {
556
+ if (typeof snapshot.ids.idOf(i) === "number") {
557
+ n++;
558
+ }
559
+ }
560
+ return n;
561
+ }
562
+ /**
563
+ * The text of a scalar for an att value.
564
+ * @param value - the value
565
+ * @param dtype - its dtype
566
+ * @param escapes - Cytoscape's two-character newline and tab
567
+ * @returns the attribute text, escaped
568
+ */
569
+ function valueText(value, dtype, escapes) {
570
+ let text;
571
+ if (typeof value === "boolean") {
572
+ text = value ? "1" : "0";
573
+ }
574
+ else if (typeof value === "number") {
575
+ text = dtype === "f32" ? formatF32(value) : formatF64(value);
576
+ }
577
+ else if (typeof value === "string") {
578
+ text = escapes ? value.replace(/\n/g, "\\n").replace(/\t/g, "\\t") : value;
579
+ }
580
+ else if (ArrayBuffer.isView(value)) {
581
+ text = JSON.stringify(Array.from(value));
582
+ }
583
+ else {
584
+ text = JSON.stringify(value) ?? "";
585
+ }
586
+ return escapeXmlAttribute(text);
587
+ }
588
+ /**
589
+ * The text of a scalar cell (a label, an edge id, a graphics value): numbers in their shortest
590
+ * form, anything that is not a scalar as JSON.
591
+ * @param value - the value
592
+ * @returns the text
593
+ */
594
+ function scalarText(value) {
595
+ if (typeof value === "string") {
596
+ return value;
597
+ }
598
+ if (typeof value === "number") {
599
+ return formatF64(value);
600
+ }
601
+ if (typeof value === "boolean") {
602
+ return value ? "true" : "false";
603
+ }
604
+ return JSON.stringify(value) ?? "";
605
+ }
606
+ /**
607
+ * The text of an id.
608
+ * @param id - the id
609
+ * @returns the text
610
+ */
611
+ function idText(id) {
612
+ return typeof id === "number" ? formatF64(id) : id;
613
+ }
614
+ /**
615
+ * The XML attributes of one row: the columns that came from XML attributes (`untypedAttribute`).
616
+ * @param writes - the column writes of the table
617
+ * @param row - the row
618
+ * @returns the attributes, each with a leading space
619
+ */
620
+ function xmlAttributesOf(writes, row) {
621
+ let out = "";
622
+ for (const w of writes) {
623
+ if (w.kind === "xml" && w.column.isSet(row)) {
624
+ out += ` ${w.name}="${escapeXmlAttribute(scalarText(w.column.value(row)))}"`;
625
+ }
626
+ }
627
+ return out;
628
+ }
629
+ /**
630
+ * The atts of one row of a table.
631
+ * @param writes - the column writes of the table
632
+ * @param row - the row
633
+ * @param first - whether this is the table's first row (an all-unset column is declared there)
634
+ * @param plan - the plan
635
+ * @param indent - the indentation
636
+ * @yields the att elements
637
+ * @returns nothing
638
+ */
639
+ function* attsOf(writes, row, first, plan, indent) {
640
+ for (const w of writes) {
641
+ if (w.kind !== "att") {
642
+ continue;
643
+ }
644
+ const { column } = w;
645
+ const isSet = column.isSet(row);
646
+ if (!isSet && !(first && column.nullCount === column.length)) {
647
+ continue;
648
+ }
649
+ const name = `${indent}<att name="${escapeXmlAttribute(w.name)}"`;
650
+ const types = `${w.type === null ? "" : ` type="${w.type}"`}${w.cyType === null ? "" : ` cy:type="${w.cyType}"`}`;
651
+ const extra = `${column.meta.extra.hidden === true ? ' cy:hidden="1"' : ""}${column.meta.extra.equation === true ? ' cy:equation="1"' : ""}`;
652
+ if (!isSet) {
653
+ yield `${name}${types}${w.elementType === null ? "" : ` cy:elementType="${w.elementType}"`}${extra}/>\n`;
654
+ continue;
655
+ }
656
+ if (column.dtype === "list") {
657
+ const items = [...column.sliceOf(row)];
658
+ const [itemType, itemCy] = typesOf(column, column.meta.itemDtype);
659
+ yield `${name}${types} cy:elementType="${w.elementType ?? "String"}"${extra}${items.length === 0 ? "/>" : ">"}\n`;
660
+ if (items.length > 0) {
661
+ for (const item of items) {
662
+ yield `${indent} <att name="${escapeXmlAttribute(w.name)}" value="${valueText(item, column.meta.itemDtype, plan.escapes)}" type="${itemType}" cy:type="${itemCy}"/>\n`;
663
+ }
664
+ yield `${indent}</att>\n`;
665
+ }
666
+ continue;
667
+ }
668
+ yield `${name} value="${valueText(column.value(row), column.dtype, plan.escapes)}"${types}${extra}/>\n`;
669
+ }
670
+ }
671
+ /**
672
+ * A graphics record as `<graphics>` XML attributes and nested atts.
673
+ * @param record - the record (the importer's graphics json value)
674
+ * @param coords - the x, y, z texts to write, or empty
675
+ * @param indent - the indentation
676
+ * @yields the graphics element
677
+ * @returns nothing
678
+ */
679
+ function* graphicsOf(record, coords, indent) {
680
+ const attrs = [...coords];
681
+ const nested = [];
682
+ for (const [key, value] of Object.entries(record ?? {})) {
683
+ if (key === "Line") {
684
+ nested.push([key, value]);
685
+ }
686
+ else if (typeof value === "string" && (GRAPHICS_ATTRIBUTES.has(key) || key.startsWith("cy:"))) {
687
+ attrs.push([key, value]);
688
+ }
689
+ else {
690
+ nested.push([key, value]);
691
+ }
692
+ }
693
+ if (attrs.length === 0 && nested.length === 0) {
694
+ return;
695
+ }
696
+ const head = `${indent}<graphics${attrs.map(([k, v]) => ` ${k}="${escapeXmlAttribute(v)}"`).join("")}`;
697
+ if (nested.length === 0) {
698
+ yield `${head}/>\n`;
699
+ return;
700
+ }
701
+ yield `${head}>\n`;
702
+ for (const [key, value] of nested) {
703
+ if (key === "Line" && Array.isArray(value)) {
704
+ yield `${indent} <Line>\n`;
705
+ for (const point of value) {
706
+ const entries = typeof point === "object" && point !== null ? Object.entries(point) : [];
707
+ yield `${indent} <point${entries.map(([k, v]) => ` ${k}="${escapeXmlAttribute(String(v))}"`).join("")}/>\n`;
708
+ }
709
+ yield `${indent} </Line>\n`;
710
+ }
711
+ else {
712
+ yield* jsonAtt(key, value, `${indent} `);
713
+ }
714
+ }
715
+ yield `${indent}</graphics>\n`;
716
+ }
717
+ /**
718
+ * A graphics value as an att: a string as its value, an array as a list of child atts, a record
719
+ * as named child atts (a record of strings with no further structure keeps its keys).
720
+ * @param name - the att name
721
+ * @param value - the value
722
+ * @param indent - the indentation
723
+ * @yields the att element
724
+ * @returns nothing
725
+ */
726
+ function* jsonAtt(name, value, indent) {
727
+ const nameAttr = name === null ? "" : ` name="${escapeXmlAttribute(name)}"`;
728
+ if (Array.isArray(value)) {
729
+ yield `${indent}<att${nameAttr} type="list">\n`;
730
+ for (const item of value) {
731
+ yield* jsonAtt(name, item, `${indent} `);
732
+ }
733
+ yield `${indent}</att>\n`;
734
+ }
735
+ else if (typeof value === "object" && value !== null) {
736
+ const entries = Object.entries(value);
737
+ if (name !== null &&
738
+ entries.every(([, v]) => typeof v === "string") &&
739
+ entries.length <= 3 &&
740
+ entries.every(([k]) => /^[a-z]$/.test(k))) {
741
+ yield `${indent}<att${nameAttr}${entries.map(([k, v]) => ` ${k}="${escapeXmlAttribute(v)}"`).join("")}/>\n`;
742
+ return;
743
+ }
744
+ yield `${indent}<att${nameAttr}>\n`;
745
+ for (const [key, item] of entries) {
746
+ yield* jsonAtt(key, item, `${indent} `);
747
+ }
748
+ yield `${indent}</att>\n`;
749
+ }
750
+ else if (value === null || value === undefined) {
751
+ yield `${indent}<att${nameAttr} type="string"/>\n`;
752
+ }
753
+ else {
754
+ yield `${indent}<att${nameAttr} value="${escapeXmlAttribute(scalarText(value))}" type="string"/>\n`;
755
+ }
756
+ }
757
+ /**
758
+ * The importer's slot column of a kind, if the table has it.
759
+ * @param writes - the writes
760
+ * @param kind - the slot
761
+ * @returns the column, or null
762
+ */
763
+ function slot(writes, kind) {
764
+ return writes.find((w) => w.kind === kind)?.column ?? null;
765
+ }
766
+ /**
767
+ * The value of a set cell, else null.
768
+ * @param column - the column, or null
769
+ * @param row - the row
770
+ * @returns the value
771
+ */
772
+ function cellOf(column, row) {
773
+ return column !== null && column.isSet(row) ? column.value(row) : null;
774
+ }
775
+ /**
776
+ * The graphics coordinates of a node: x, y negated back to screen coordinates, z.
777
+ * @param plan - the plan
778
+ * @param zColumn - the z column, or null
779
+ * @param node - the node
780
+ * @returns the coordinates as XML attributes
781
+ */
782
+ function coordsOf(plan, zColumn, node) {
783
+ const out = [];
784
+ const xyz = cellOf(plan.position, node);
785
+ if (xyz !== null) {
786
+ const [x, y, z] = Array.from(xyz);
787
+ if (Number.isFinite(x) && Number.isFinite(y)) {
788
+ out.push(["x", formatF32(x)], ["y", formatF32(y === 0 ? 0 : -y)]);
789
+ if (zColumn === null && z !== undefined && z !== 0 && Number.isFinite(z)) {
790
+ out.push(["z", formatF32(z)]);
791
+ }
792
+ }
793
+ }
794
+ const z = cellOf(zColumn, node);
795
+ if (typeof z === "number") {
796
+ out.push(["z", formatF64(z)]);
797
+ }
798
+ return out;
799
+ }
800
+ /**
801
+ * The XML of one node and its group graph, whose members are `xlink:href` references (every
802
+ * node is declared at the top level, in index order).
803
+ * @param snapshot - the snapshot
804
+ * @param plan - the plan
805
+ * @param node - the node
806
+ * @param indent - the indentation
807
+ * @yields the node element
808
+ * @returns nothing
809
+ */
810
+ function* nodeOf(snapshot, plan, node, indent) {
811
+ const labelCol = slot(plan.nodes, "label");
812
+ const label = cellOf(labelCol, node);
813
+ yield `${indent}<node id="${escapeXmlAttribute(idText(snapshot.ids.idOf(node)))}"${label === null ? "" : ` label="${escapeXmlAttribute(scalarText(label))}"`}${xmlAttributesOf(plan.nodes, node)}>\n`;
814
+ const inner = `${indent} `;
815
+ yield* attsOf(plan.nodes, node, node === 0, plan, inner);
816
+ const children = plan.reachable[node] === 1 ? plan.hierarchy.childrenOf(node) : [];
817
+ const nested = cellOf(slot(plan.nodes, "nested"), node);
818
+ const pointer = cellOf(slot(plan.nodes, "pointer"), node);
819
+ const subgraph = cellOf(slot(plan.nodes, "subgraph"), node);
820
+ if (children.length > 0 || subgraph !== null) {
821
+ const sub = (subgraph ?? {});
822
+ yield `${inner}<att name="__isGroup" value="1" type="boolean" cy:type="Boolean" cy:hidden="1"/>\n`;
823
+ const id = typeof sub.id === "string" ? ` id="${escapeXmlAttribute(sub.id)}"` : "";
824
+ const lbl = typeof sub.label === "string" ? ` label="${escapeXmlAttribute(sub.label)}"` : "";
825
+ yield `${inner}<att>\n${inner} <graph${id}${lbl}>\n`;
826
+ const atts = typeof sub.atts === "object" && sub.atts !== null
827
+ ? Object.entries(sub.atts)
828
+ : [];
829
+ for (const [key, value] of atts) {
830
+ yield* jsonAtt(key, value, `${inner} `);
831
+ }
832
+ for (const child of children) {
833
+ yield `${inner} <node xlink:href="#${escapeXmlAttribute(idText(snapshot.ids.idOf(child)))}"/>\n`;
834
+ }
835
+ yield `${inner} </graph>\n${inner}</att>\n`;
836
+ }
837
+ else if (typeof nested === "string") {
838
+ yield `${inner}<att>\n${inner} <graph label="${escapeXmlAttribute(nested)}"/>\n${inner}</att>\n`;
839
+ }
840
+ else if (typeof pointer === "string") {
841
+ yield `${inner}<att>\n${inner} <graph xlink:href="${escapeXmlAttribute(pointer)}"/>\n${inner}</att>\n`;
842
+ }
843
+ const graphics = cellOf(slot(plan.nodes, "graphics"), node);
844
+ yield* graphicsOf(graphics, coordsOf(plan, slot(plan.nodes, "z"), node), inner);
845
+ yield `${indent}</node>\n`;
846
+ }
847
+ /**
848
+ * The document, as string parts; the plan (and the E_ conditions it throws) is made when the
849
+ * first part is asked for.
850
+ * @param snapshot - the snapshot
851
+ * @param options - the options
852
+ * @yields the XML text
853
+ * @returns nothing
854
+ */
855
+ function* write(snapshot, options) {
856
+ const plan = planFor(snapshot, options);
857
+ const meta = snapshot.meta.extra[META_KEY];
858
+ const graphId = typeof meta?.graphId === "string" ? ` id="${escapeXmlAttribute(meta.graphId)}"` : "";
859
+ // Every edge carries cy:directed, so when they all agree the root attribute does not decide
860
+ // the direction and the source's own text is written back.
861
+ const keep = (meta?.directed === "0" || meta?.directed === "1") &&
862
+ snapshot.edgeCount > 0 &&
863
+ snapshot.edges.byRole("directed") === null;
864
+ let directed = snapshot.directed ? "1" : "0";
865
+ if (keep) {
866
+ directed = meta?.directed;
867
+ }
868
+ const name = snapshot.meta.name === null ? "" : ` label="${escapeXmlAttribute(snapshot.meta.name)}"`;
869
+ yield '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
870
+ yield `<graph${graphId}${name} directed="${directed}" cy:documentVersion="3.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xlink="${XLINK_NAMESPACE}" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cy="${CY_NAMESPACE}" xmlns="${XGMML_NAMESPACE}">\n`;
871
+ yield* metadataOf(snapshot);
872
+ yield* attsOf(plan.graph, 0, true, plan, " ");
873
+ yield* graphicsOf(cellOf(slot(plan.graph, "graphics"), 0), [], " ");
874
+ for (let u = 0; u < snapshot.nodeCount; u++) {
875
+ yield* nodeOf(snapshot, plan, u, " ");
876
+ }
877
+ yield* networksOf(snapshot, plan);
878
+ yield* edgesOf(snapshot, plan);
879
+ yield "</graph>\n";
880
+ }
881
+ /**
882
+ * The RDF network metadata, when the snapshot has a description or a creation date.
883
+ * @param snapshot - the snapshot
884
+ * @yields the networkMetadata att
885
+ * @returns nothing
886
+ */
887
+ function* metadataOf(snapshot) {
888
+ const { name, description, created } = snapshot.meta;
889
+ if (description === null && created === null) {
890
+ return;
891
+ }
892
+ yield ' <att name="networkMetadata">\n <rdf:RDF>\n <rdf:Description rdf:about="http://www.cytoscape.org/">\n';
893
+ if (name !== null) {
894
+ yield ` <dc:title>${escapeXmlText(name)}</dc:title>\n`;
895
+ }
896
+ if (description !== null) {
897
+ yield ` <dc:description>${escapeXmlText(description)}</dc:description>\n`;
898
+ }
899
+ if (created !== null) {
900
+ yield ` <dc:date>${escapeXmlText(created)}</dc:date>\n`;
901
+ }
902
+ yield " </rdf:Description>\n </rdf:RDF>\n </att>\n";
903
+ }
904
+ /**
905
+ * The root-level subgraphs of an `xgmml.networks` membership column.
906
+ * @param snapshot - the snapshot
907
+ * @param plan - the plan
908
+ * @yields the subgraph atts
909
+ * @returns nothing
910
+ */
911
+ function* networksOf(snapshot, plan) {
912
+ const column = slot(plan.nodes, "networks");
913
+ if (column?.dtype !== "list") {
914
+ return;
915
+ }
916
+ const members = new Map();
917
+ for (let u = 0; u < snapshot.nodeCount; u++) {
918
+ for (const id of column.isSet(u) ? column.sliceOf(u) : []) {
919
+ const list = members.get(String(id)) ?? [];
920
+ list.push(u);
921
+ members.set(String(id), list);
922
+ }
923
+ }
924
+ for (const [id, nodes] of members) {
925
+ yield ` <att>\n <graph id="${escapeXmlAttribute(id)}">\n`;
926
+ for (const u of nodes) {
927
+ yield ` <node xlink:href="#${escapeXmlAttribute(idText(snapshot.ids.idOf(u)))}"/>\n`;
928
+ }
929
+ yield " </graph>\n </att>\n";
930
+ }
931
+ }
932
+ /**
933
+ * The edges: one per logical edge, expanded pairs folded.
934
+ * @param snapshot - the snapshot
935
+ * @param plan - the plan
936
+ * @yields the edge elements
937
+ * @returns nothing
938
+ */
939
+ function* edgesOf(snapshot, plan) {
940
+ const { folding, weights } = plan;
941
+ const labelCol = slot(plan.edges, "label");
942
+ const graphicsCol = slot(plan.edges, "graphics");
943
+ const list = snapshot.edgeList();
944
+ let first = true;
945
+ for (let e = 0; e < snapshot.edgeCount; e++) {
946
+ if (folding.folded(e)) {
947
+ continue;
948
+ }
949
+ const u = list.src[e];
950
+ const v = list.dst[e];
951
+ const directed = snapshot.directed && folding.sourceDirected(e);
952
+ const id = cellOf(plan.edgeId, e);
953
+ const label = cellOf(labelCol, e);
954
+ const weight = weights.text(e);
955
+ yield ` <edge${id === null ? "" : ` id="${escapeXmlAttribute(scalarText(id))}"`}${label === null ? "" : ` label="${escapeXmlAttribute(scalarText(label))}"`} source="${escapeXmlAttribute(idText(snapshot.ids.idOf(u)))}" target="${escapeXmlAttribute(idText(snapshot.ids.idOf(v)))}" cy:directed="${directed ? "1" : "0"}"${weight === null ? "" : ` weight="${weight}"`}${xmlAttributesOf(plan.edges, e)}>\n`;
956
+ yield* attsOf(plan.edges, e, first, plan, " ");
957
+ yield* graphicsOf(cellOf(graphicsCol, e), [], " ");
958
+ yield " </edge>\n";
959
+ first = false;
960
+ }
961
+ }
962
+ /**
963
+ * Resolve the format-specific options.
964
+ * @param options - the caller's options
965
+ * @returns the cytoscapeEscapes flag
966
+ */
967
+ function resolveEscapes(options) {
968
+ const value = options?.cytoscapeEscapes ?? false;
969
+ if (typeof value !== "boolean") {
970
+ throw new GraphFormatError("E_UNSUPPORTED", "option cytoscapeEscapes must be a boolean", {
971
+ option: "cytoscapeEscapes",
972
+ found: typeof value,
973
+ });
974
+ }
975
+ return value;
976
+ }
977
+ /**
978
+ * The plan of one export call; throws the E_ conditions before anything is written.
979
+ * @param snapshot - the snapshot
980
+ * @param options - the options
981
+ * @returns the plan
982
+ */
983
+ function planFor(snapshot, options) {
984
+ const plan = planExport(snapshot, resolveExportOptions(options), resolveEscapes(options));
985
+ const illegal = plan.notes.find((n) => n.code === XGMML_LOSS.XML_ILLEGAL_CHAR);
986
+ if (illegal !== undefined) {
987
+ throw new GraphFormatError("E_COLUMN_TYPE", illegal.message, { code: illegal.code, column: illegal.column });
988
+ }
989
+ return plan;
990
+ }
991
+ /** The XGMML exporter. */
992
+ export const xgmmlExporter = Object.freeze({
993
+ format: FORMAT,
994
+ capabilities: CAPABILITIES,
995
+ check: (snapshot, options) => Object.freeze(planExport(snapshot, resolveExportOptions(options), resolveEscapes(options)).notes),
996
+ export: (snapshot, options) => encodeChunks(write(snapshot, options)),
997
+ exportToString: (snapshot, options) => joinText(write(snapshot, options)),
998
+ });
999
+ //# sourceMappingURL=exporter.js.map