@loaders.gl/graphs 5.0.0-alpha.9 → 5.0.0-beta.2

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 (84) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +123 -4
  3. package/THIRD-PARTY-NOTICES.md +17 -0
  4. package/dist/dot-loader-types.cjs +59 -0
  5. package/dist/dot-loader-types.cjs.map +7 -0
  6. package/dist/dot-loader-types.d.ts +25 -8
  7. package/dist/dot-loader-types.d.ts.map +1 -1
  8. package/dist/dot-loader-types.js +2 -2
  9. package/dist/dot-loader-types.js.map +1 -1
  10. package/dist/dot-loader.cjs +638 -47
  11. package/dist/dot-loader.cjs.map +3 -3
  12. package/dist/dot-loader.d.ts +10 -6
  13. package/dist/dot-loader.d.ts.map +1 -1
  14. package/dist/dot-loader.js +3 -3
  15. package/dist/dot-loader.js.map +1 -1
  16. package/dist/dot-types.d.ts +6 -1
  17. package/dist/dot-types.d.ts.map +1 -1
  18. package/dist/gexf-loader-types.cjs +59 -0
  19. package/dist/gexf-loader-types.cjs.map +7 -0
  20. package/dist/gexf-loader-types.d.ts +53 -0
  21. package/dist/gexf-loader-types.d.ts.map +1 -0
  22. package/dist/gexf-loader-types.js +26 -0
  23. package/dist/gexf-loader-types.js.map +1 -0
  24. package/dist/gexf-loader.cjs +2940 -0
  25. package/dist/gexf-loader.cjs.map +6 -0
  26. package/dist/gexf-loader.d.ts +24 -0
  27. package/dist/gexf-loader.d.ts.map +1 -0
  28. package/dist/gexf-loader.js +13 -0
  29. package/dist/gexf-loader.js.map +1 -0
  30. package/dist/gexf-types.d.ts +16 -0
  31. package/dist/gexf-types.d.ts.map +1 -0
  32. package/dist/gexf-types.js +5 -0
  33. package/dist/gexf-types.js.map +1 -0
  34. package/dist/graph-types.d.ts +28 -0
  35. package/dist/graph-types.d.ts.map +1 -1
  36. package/dist/graphml-loader-types.cjs +59 -0
  37. package/dist/graphml-loader-types.cjs.map +7 -0
  38. package/dist/graphml-loader-types.d.ts +24 -8
  39. package/dist/graphml-loader-types.d.ts.map +1 -1
  40. package/dist/graphml-loader-types.js +2 -2
  41. package/dist/graphml-loader-types.js.map +1 -1
  42. package/dist/graphml-loader.cjs +2303 -69
  43. package/dist/graphml-loader.cjs.map +3 -3
  44. package/dist/graphml-loader.d.ts +10 -6
  45. package/dist/graphml-loader.d.ts.map +1 -1
  46. package/dist/graphml-loader.js +3 -3
  47. package/dist/graphml-loader.js.map +1 -1
  48. package/dist/index.cjs +56 -1085
  49. package/dist/index.cjs.map +4 -3
  50. package/dist/index.d.ts +7 -0
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +1 -0
  53. package/dist/index.js.map +1 -1
  54. package/dist/lib/build-graph-tables.d.ts +4 -0
  55. package/dist/lib/build-graph-tables.d.ts.map +1 -0
  56. package/dist/lib/build-graph-tables.js +143 -0
  57. package/dist/lib/build-graph-tables.js.map +1 -0
  58. package/dist/lib/parse-dot.d.ts +3 -1
  59. package/dist/lib/parse-dot.d.ts.map +1 -1
  60. package/dist/lib/parse-dot.js +38 -21
  61. package/dist/lib/parse-dot.js.map +1 -1
  62. package/dist/lib/parse-gexf.d.ts +5 -0
  63. package/dist/lib/parse-gexf.d.ts.map +1 -0
  64. package/dist/lib/parse-gexf.js +382 -0
  65. package/dist/lib/parse-gexf.js.map +1 -0
  66. package/dist/lib/parse-graphml.d.ts +2 -1
  67. package/dist/lib/parse-graphml.d.ts.map +1 -1
  68. package/dist/lib/parse-graphml.js +54 -31
  69. package/dist/lib/parse-graphml.js.map +1 -1
  70. package/package.json +18 -8
  71. package/src/dot-loader-types.ts +15 -5
  72. package/src/dot-loader.ts +7 -4
  73. package/src/dot-types.ts +7 -1
  74. package/src/gexf-loader-types.ts +41 -0
  75. package/src/gexf-loader.ts +17 -0
  76. package/src/gexf-types.ts +21 -0
  77. package/src/graph-types.ts +35 -0
  78. package/src/graphml-loader-types.ts +14 -5
  79. package/src/graphml-loader.ts +7 -4
  80. package/src/index.ts +9 -0
  81. package/src/lib/build-graph-tables.ts +208 -0
  82. package/src/lib/parse-dot.ts +44 -21
  83. package/src/lib/parse-gexf.ts +390 -0
  84. package/src/lib/parse-graphml.ts +92 -40
@@ -0,0 +1,2940 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res, err) => function __init() {
9
+ if (err) throw err[0];
10
+ try {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ } catch (e) {
13
+ throw err = [e], e;
14
+ }
15
+ };
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
+ mod
35
+ ));
36
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
+
38
+ // src/gexf-loader-types.ts
39
+ async function preload() {
40
+ const { GEXFLoaderWithParser: GEXFLoaderWithParser3 } = await Promise.resolve().then(() => (init_gexf_loader(), gexf_loader_exports));
41
+ return GEXFLoaderWithParser3;
42
+ }
43
+ var VERSION, GEXFLoader;
44
+ var init_gexf_loader_types = __esm({
45
+ "src/gexf-loader-types.ts"() {
46
+ "use strict";
47
+ VERSION = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
48
+ GEXFLoader = {
49
+ name: "GEXF",
50
+ id: "gexf",
51
+ module: "graphs",
52
+ version: VERSION,
53
+ extensions: ["gexf"],
54
+ mimeTypes: ["application/gexf+xml"],
55
+ text: true,
56
+ worker: false,
57
+ dataType: null,
58
+ batchType: null,
59
+ options: { gexf: { shape: "arrow-table" } },
60
+ preload
61
+ };
62
+ }
63
+ });
64
+
65
+ // ../documents/src/lib/xml-utils/uncapitalize.ts
66
+ function uncapitalize(str) {
67
+ return typeof str === "string" ? str.charAt(0).toLowerCase() + str.slice(1) : str;
68
+ }
69
+ function uncapitalizeKeys(object) {
70
+ if (Array.isArray(object)) {
71
+ return object.map((element) => uncapitalizeKeys(element));
72
+ }
73
+ if (object && typeof object === "object") {
74
+ const newObject = {};
75
+ for (const [key, value] of Object.entries(object)) {
76
+ Object.defineProperty(newObject, uncapitalize(key), {
77
+ value: uncapitalizeKeys(value),
78
+ enumerable: true,
79
+ configurable: true,
80
+ writable: true
81
+ });
82
+ }
83
+ return newObject;
84
+ }
85
+ return object;
86
+ }
87
+ var init_uncapitalize = __esm({
88
+ "../documents/src/lib/xml-utils/uncapitalize.ts"() {
89
+ "use strict";
90
+ }
91
+ });
92
+
93
+ // ../documents/src/sax-ts/sax.ts
94
+ var DEFAULT_SAX_EVENTS, DEFAULT_SAX_PARSER_OPTIONS, EVENTS, BUFFERS, nameStart, nameBody, entityStart, entityBody, ENTITIES, SAX, SAXParser;
95
+ var init_sax = __esm({
96
+ "../documents/src/sax-ts/sax.ts"() {
97
+ "use strict";
98
+ DEFAULT_SAX_EVENTS = {
99
+ ontext: () => {
100
+ },
101
+ onprocessinginstruction: () => {
102
+ },
103
+ onsgmldeclaration: () => {
104
+ },
105
+ ondoctype: () => {
106
+ },
107
+ oncomment: () => {
108
+ },
109
+ onopentagstart: () => {
110
+ },
111
+ onattribute: () => {
112
+ },
113
+ onopentag: () => {
114
+ },
115
+ onclosetag: () => {
116
+ },
117
+ onopencdata: () => {
118
+ },
119
+ oncdata: () => {
120
+ },
121
+ onclosecdata: () => {
122
+ },
123
+ onerror: () => {
124
+ },
125
+ onend: () => {
126
+ },
127
+ onready: () => {
128
+ },
129
+ onscript: () => {
130
+ },
131
+ onopennamespace: () => {
132
+ },
133
+ onclosenamespace: () => {
134
+ }
135
+ };
136
+ DEFAULT_SAX_PARSER_OPTIONS = {
137
+ ...DEFAULT_SAX_EVENTS,
138
+ strict: false,
139
+ MAX_BUFFER_LENGTH: 64 * 1024,
140
+ lowercase: false,
141
+ lowercasetags: false,
142
+ noscript: false,
143
+ strictEntities: false,
144
+ preserveCase: false,
145
+ caseInsensitiveTags: false,
146
+ processEntities: true,
147
+ xmlns: void 0,
148
+ position: void 0,
149
+ trim: void 0,
150
+ normalize: void 0
151
+ };
152
+ EVENTS = [
153
+ "text",
154
+ "processinginstruction",
155
+ "sgmldeclaration",
156
+ "doctype",
157
+ "comment",
158
+ "opentagstart",
159
+ "attribute",
160
+ "opentag",
161
+ "closetag",
162
+ "opencdata",
163
+ "cdata",
164
+ "closecdata",
165
+ "error",
166
+ "end",
167
+ "ready",
168
+ "script",
169
+ "opennamespace",
170
+ "closenamespace"
171
+ ];
172
+ BUFFERS = [
173
+ "comment",
174
+ "sgmlDecl",
175
+ "textNode",
176
+ "tagName",
177
+ "doctype",
178
+ "procInstName",
179
+ "procInstBody",
180
+ "entity",
181
+ "attribName",
182
+ "attribValue",
183
+ "cdata",
184
+ "script"
185
+ ];
186
+ nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;
187
+ nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;
188
+ entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;
189
+ entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;
190
+ ENTITIES = {
191
+ amp: "&",
192
+ gt: ">",
193
+ lt: "<",
194
+ quot: '"',
195
+ apos: "'",
196
+ AElig: 198,
197
+ Aacute: 193,
198
+ Acirc: 194,
199
+ Agrave: 192,
200
+ Aring: 197,
201
+ Atilde: 195,
202
+ Auml: 196,
203
+ Ccedil: 199,
204
+ ETH: 208,
205
+ Eacute: 201,
206
+ Ecirc: 202,
207
+ Egrave: 200,
208
+ Euml: 203,
209
+ Iacute: 205,
210
+ Icirc: 206,
211
+ Igrave: 204,
212
+ Iuml: 207,
213
+ Ntilde: 209,
214
+ Oacute: 211,
215
+ Ocirc: 212,
216
+ Ograve: 210,
217
+ Oslash: 216,
218
+ Otilde: 213,
219
+ Ouml: 214,
220
+ THORN: 222,
221
+ Uacute: 218,
222
+ Ucirc: 219,
223
+ Ugrave: 217,
224
+ Uuml: 220,
225
+ Yacute: 221,
226
+ aacute: 225,
227
+ acirc: 226,
228
+ aelig: 230,
229
+ agrave: 224,
230
+ aring: 229,
231
+ atilde: 227,
232
+ auml: 228,
233
+ ccedil: 231,
234
+ eacute: 233,
235
+ ecirc: 234,
236
+ egrave: 232,
237
+ eth: 240,
238
+ euml: 235,
239
+ iacute: 237,
240
+ icirc: 238,
241
+ igrave: 236,
242
+ iuml: 239,
243
+ ntilde: 241,
244
+ oacute: 243,
245
+ ocirc: 244,
246
+ ograve: 242,
247
+ oslash: 248,
248
+ otilde: 245,
249
+ ouml: 246,
250
+ szlig: 223,
251
+ thorn: 254,
252
+ uacute: 250,
253
+ ucirc: 251,
254
+ ugrave: 249,
255
+ uuml: 252,
256
+ yacute: 253,
257
+ yuml: 255,
258
+ copy: 169,
259
+ reg: 174,
260
+ nbsp: 160,
261
+ iexcl: 161,
262
+ cent: 162,
263
+ pound: 163,
264
+ curren: 164,
265
+ yen: 165,
266
+ brvbar: 166,
267
+ sect: 167,
268
+ uml: 168,
269
+ ordf: 170,
270
+ laquo: 171,
271
+ not: 172,
272
+ shy: 173,
273
+ macr: 175,
274
+ deg: 176,
275
+ plusmn: 177,
276
+ sup1: 185,
277
+ sup2: 178,
278
+ sup3: 179,
279
+ acute: 180,
280
+ micro: 181,
281
+ para: 182,
282
+ middot: 183,
283
+ cedil: 184,
284
+ ordm: 186,
285
+ raquo: 187,
286
+ frac14: 188,
287
+ frac12: 189,
288
+ frac34: 190,
289
+ iquest: 191,
290
+ times: 215,
291
+ divide: 247,
292
+ OElig: 338,
293
+ oelig: 339,
294
+ Scaron: 352,
295
+ scaron: 353,
296
+ Yuml: 376,
297
+ fnof: 402,
298
+ circ: 710,
299
+ tilde: 732,
300
+ Alpha: 913,
301
+ Beta: 914,
302
+ Gamma: 915,
303
+ Delta: 916,
304
+ Epsilon: 917,
305
+ Zeta: 918,
306
+ Eta: 919,
307
+ Theta: 920,
308
+ Iota: 921,
309
+ Kappa: 922,
310
+ Lambda: 923,
311
+ Mu: 924,
312
+ Nu: 925,
313
+ Xi: 926,
314
+ Omicron: 927,
315
+ Pi: 928,
316
+ Rho: 929,
317
+ Sigma: 931,
318
+ Tau: 932,
319
+ Upsilon: 933,
320
+ Phi: 934,
321
+ Chi: 935,
322
+ Psi: 936,
323
+ Omega: 937,
324
+ alpha: 945,
325
+ beta: 946,
326
+ gamma: 947,
327
+ delta: 948,
328
+ epsilon: 949,
329
+ zeta: 950,
330
+ eta: 951,
331
+ theta: 952,
332
+ iota: 953,
333
+ kappa: 954,
334
+ lambda: 955,
335
+ mu: 956,
336
+ nu: 957,
337
+ xi: 958,
338
+ omicron: 959,
339
+ pi: 960,
340
+ rho: 961,
341
+ sigmaf: 962,
342
+ sigma: 963,
343
+ tau: 964,
344
+ upsilon: 965,
345
+ phi: 966,
346
+ chi: 967,
347
+ psi: 968,
348
+ omega: 969,
349
+ thetasym: 977,
350
+ upsih: 978,
351
+ piv: 982,
352
+ ensp: 8194,
353
+ emsp: 8195,
354
+ thinsp: 8201,
355
+ zwnj: 8204,
356
+ zwj: 8205,
357
+ lrm: 8206,
358
+ rlm: 8207,
359
+ ndash: 8211,
360
+ mdash: 8212,
361
+ lsquo: 8216,
362
+ rsquo: 8217,
363
+ sbquo: 8218,
364
+ ldquo: 8220,
365
+ rdquo: 8221,
366
+ bdquo: 8222,
367
+ dagger: 8224,
368
+ Dagger: 8225,
369
+ bull: 8226,
370
+ hellip: 8230,
371
+ permil: 8240,
372
+ prime: 8242,
373
+ Prime: 8243,
374
+ lsaquo: 8249,
375
+ rsaquo: 8250,
376
+ oline: 8254,
377
+ frasl: 8260,
378
+ euro: 8364,
379
+ image: 8465,
380
+ weierp: 8472,
381
+ real: 8476,
382
+ trade: 8482,
383
+ alefsym: 8501,
384
+ larr: 8592,
385
+ uarr: 8593,
386
+ rarr: 8594,
387
+ darr: 8595,
388
+ harr: 8596,
389
+ crarr: 8629,
390
+ lArr: 8656,
391
+ uArr: 8657,
392
+ rArr: 8658,
393
+ dArr: 8659,
394
+ hArr: 8660,
395
+ forall: 8704,
396
+ part: 8706,
397
+ exist: 8707,
398
+ empty: 8709,
399
+ nabla: 8711,
400
+ isin: 8712,
401
+ notin: 8713,
402
+ ni: 8715,
403
+ prod: 8719,
404
+ sum: 8721,
405
+ minus: 8722,
406
+ lowast: 8727,
407
+ radic: 8730,
408
+ prop: 8733,
409
+ infin: 8734,
410
+ ang: 8736,
411
+ and: 8743,
412
+ or: 8744,
413
+ cap: 8745,
414
+ cup: 8746,
415
+ int: 8747,
416
+ there4: 8756,
417
+ sim: 8764,
418
+ cong: 8773,
419
+ asymp: 8776,
420
+ ne: 8800,
421
+ equiv: 8801,
422
+ le: 8804,
423
+ ge: 8805,
424
+ sub: 8834,
425
+ sup: 8835,
426
+ nsub: 8836,
427
+ sube: 8838,
428
+ supe: 8839,
429
+ oplus: 8853,
430
+ otimes: 8855,
431
+ perp: 8869,
432
+ sdot: 8901,
433
+ lceil: 8968,
434
+ rceil: 8969,
435
+ lfloor: 8970,
436
+ rfloor: 8971,
437
+ lang: 9001,
438
+ rang: 9002,
439
+ loz: 9674,
440
+ spades: 9824,
441
+ clubs: 9827,
442
+ hearts: 9829,
443
+ diams: 9830
444
+ };
445
+ Object.keys(ENTITIES).forEach((key) => {
446
+ const e = ENTITIES[key];
447
+ ENTITIES[key] = typeof e === "number" ? String.fromCharCode(e) : e;
448
+ });
449
+ SAX = class _SAX {
450
+ EVENTS = EVENTS;
451
+ ENTITIES = {
452
+ // TODO: make it readonly, needed for entity-mega test
453
+ // amp, gt, lt, quot and apos are resolved to strings instead of numerical
454
+ // codes, IDK why
455
+ ...ENTITIES
456
+ };
457
+ XML_ENTITIES = {
458
+ amp: "&",
459
+ gt: ">",
460
+ lt: "<",
461
+ quot: '"',
462
+ apos: "'"
463
+ };
464
+ S = 0;
465
+ opt;
466
+ trackPosition = false;
467
+ column = 0;
468
+ line = 0;
469
+ c = "";
470
+ error;
471
+ q = "";
472
+ bufferCheckPosition;
473
+ closed = false;
474
+ tags = [];
475
+ looseCase = "";
476
+ closedRoot = false;
477
+ sawRoot = false;
478
+ strict = false;
479
+ tag;
480
+ strictEntities;
481
+ state;
482
+ noscript = false;
483
+ attribList = [];
484
+ ns;
485
+ position = 0;
486
+ STATE = {
487
+ BEGIN: this.S++,
488
+ // leading byte order mark or whitespace
489
+ BEGIN_WHITESPACE: this.S++,
490
+ // leading whitespace
491
+ TEXT: this.S++,
492
+ // general stuff
493
+ TEXT_ENTITY: this.S++,
494
+ // &amp and such.
495
+ OPEN_WAKA: this.S++,
496
+ // <
497
+ SGML_DECL: this.S++,
498
+ // <!BLARG
499
+ SGML_DECL_QUOTED: this.S++,
500
+ // <!BLARG foo "bar
501
+ DOCTYPE: this.S++,
502
+ // <!DOCTYPE
503
+ DOCTYPE_QUOTED: this.S++,
504
+ // <!DOCTYPE "//blah
505
+ DOCTYPE_DTD: this.S++,
506
+ // <!DOCTYPE "//blah" [ ...
507
+ DOCTYPE_DTD_QUOTED: this.S++,
508
+ // <!DOCTYPE "//blah" [ "foo
509
+ COMMENT_STARTING: this.S++,
510
+ // <!-
511
+ COMMENT: this.S++,
512
+ // <!--
513
+ COMMENT_ENDING: this.S++,
514
+ // <!-- blah -
515
+ COMMENT_ENDED: this.S++,
516
+ // <!-- blah --
517
+ CDATA: this.S++,
518
+ // <![CDATA[ something
519
+ CDATA_ENDING: this.S++,
520
+ // ]
521
+ CDATA_ENDING_2: this.S++,
522
+ // ]]
523
+ PROC_INST: this.S++,
524
+ // <?hi
525
+ PROC_INST_BODY: this.S++,
526
+ // <?hi there
527
+ PROC_INST_ENDING: this.S++,
528
+ // <?hi "there" ?
529
+ OPEN_TAG: this.S++,
530
+ // <strong
531
+ OPEN_TAG_SLASH: this.S++,
532
+ // <strong /
533
+ ATTRIB: this.S++,
534
+ // <a
535
+ ATTRIB_NAME: this.S++,
536
+ // <a foo
537
+ ATTRIB_NAME_SAW_WHITE: this.S++,
538
+ // <a foo _
539
+ ATTRIB_VALUE: this.S++,
540
+ // <a foo=
541
+ ATTRIB_VALUE_QUOTED: this.S++,
542
+ // <a foo="bar
543
+ ATTRIB_VALUE_CLOSED: this.S++,
544
+ // <a foo="bar"
545
+ ATTRIB_VALUE_UNQUOTED: this.S++,
546
+ // <a foo=bar
547
+ ATTRIB_VALUE_ENTITY_Q: this.S++,
548
+ // <foo bar="&quot;"
549
+ ATTRIB_VALUE_ENTITY_U: this.S++,
550
+ // <foo bar=&quot
551
+ CLOSE_TAG: this.S++,
552
+ // </a
553
+ CLOSE_TAG_SAW_WHITE: this.S++,
554
+ // </a >
555
+ SCRIPT: this.S++,
556
+ // <script> ...
557
+ SCRIPT_ENDING: this.S++
558
+ // <script> ... <
559
+ };
560
+ BUFFERS = BUFFERS;
561
+ // private parser: (strict: boolean, opt: any) => SAXParser;
562
+ CDATA = "[CDATA[";
563
+ DOCTYPE = "DOCTYPE";
564
+ XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace";
565
+ XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/";
566
+ rootNS = {
567
+ xml: this.XML_NAMESPACE,
568
+ xmlns: this.XMLNS_NAMESPACE
569
+ };
570
+ comment;
571
+ sgmlDecl;
572
+ textNode = "";
573
+ tagName;
574
+ doctype;
575
+ procInstName;
576
+ procInstBody;
577
+ entity = "";
578
+ attribName;
579
+ attribValue;
580
+ cdata = "";
581
+ script = "";
582
+ startTagPosition = 0;
583
+ constructor() {
584
+ this.S = 0;
585
+ for (const s in this.STATE) {
586
+ if (this.STATE.hasOwnProperty(s)) {
587
+ this.STATE[this.STATE[s]] = s;
588
+ }
589
+ }
590
+ this.S = this.STATE;
591
+ }
592
+ static charAt(chunk, i) {
593
+ let result = "";
594
+ if (i < chunk.length) {
595
+ result = chunk.charAt(i);
596
+ }
597
+ return result;
598
+ }
599
+ static isWhitespace(c) {
600
+ return c === " " || c === "\n" || c === "\r" || c === " ";
601
+ }
602
+ static isQuote(c) {
603
+ return c === '"' || c === "'";
604
+ }
605
+ static isAttribEnd(c) {
606
+ return c === ">" || _SAX.isWhitespace(c);
607
+ }
608
+ static isMatch(regex, c) {
609
+ return regex.test(c);
610
+ }
611
+ static notMatch(regex, c) {
612
+ return !_SAX.isMatch(regex, c);
613
+ }
614
+ static qname(name, attribute) {
615
+ const i = name.indexOf(":");
616
+ const qualName = i < 0 ? ["", name] : name.split(":");
617
+ let prefix = qualName[0];
618
+ let local = qualName[1];
619
+ if (attribute && name === "xmlns") {
620
+ prefix = "xmlns";
621
+ local = "";
622
+ }
623
+ return { prefix, local };
624
+ }
625
+ write(chunk) {
626
+ if (this.error) {
627
+ throw this.error;
628
+ }
629
+ if (this.closed) {
630
+ return this.errorFunction("Cannot write after close. Assign an onready handler.");
631
+ }
632
+ if (chunk === null) {
633
+ return this.end();
634
+ }
635
+ if (typeof chunk === "object") {
636
+ chunk = chunk.toString();
637
+ }
638
+ let i = 0;
639
+ let c;
640
+ while (true) {
641
+ c = _SAX.charAt(chunk, i++);
642
+ this.c = c;
643
+ if (!c) {
644
+ break;
645
+ }
646
+ if (this.trackPosition) {
647
+ this.position++;
648
+ if (c === "\n") {
649
+ this.line++;
650
+ this.column = 0;
651
+ } else {
652
+ this.column++;
653
+ }
654
+ }
655
+ switch (this.state) {
656
+ case this.S.BEGIN:
657
+ this.state = this.S.BEGIN_WHITESPACE;
658
+ if (c === "\uFEFF") {
659
+ continue;
660
+ }
661
+ this.beginWhiteSpace(c);
662
+ continue;
663
+ case this.S.BEGIN_WHITESPACE:
664
+ this.beginWhiteSpace(c);
665
+ continue;
666
+ case this.S.TEXT:
667
+ if (this.sawRoot && !this.closedRoot) {
668
+ const starti = i - 1;
669
+ while (c && c !== "<" && c !== "&") {
670
+ c = _SAX.charAt(chunk, i++);
671
+ if (c && this.trackPosition) {
672
+ this.position++;
673
+ if (c === "\n") {
674
+ this.line++;
675
+ this.column = 0;
676
+ } else {
677
+ this.column++;
678
+ }
679
+ }
680
+ }
681
+ this.textNode += chunk.substring(starti, i - 1);
682
+ }
683
+ if (c === "<" && !(this.sawRoot && this.closedRoot && !this.strict)) {
684
+ this.state = this.S.OPEN_WAKA;
685
+ this.startTagPosition = this.position;
686
+ } else {
687
+ if (!_SAX.isWhitespace(c) && (!this.sawRoot || this.closedRoot)) {
688
+ this.strictFail("Text data outside of root node.");
689
+ }
690
+ if (c === "&") {
691
+ this.state = this.S.TEXT_ENTITY;
692
+ } else {
693
+ this.textNode += c;
694
+ }
695
+ }
696
+ continue;
697
+ case this.S.SCRIPT:
698
+ if (c === "<") {
699
+ this.state = this.S.SCRIPT_ENDING;
700
+ } else {
701
+ this.script += c;
702
+ }
703
+ continue;
704
+ case this.S.SCRIPT_ENDING:
705
+ if (c === "/") {
706
+ this.state = this.S.CLOSE_TAG;
707
+ } else {
708
+ this.script += `<${c}`;
709
+ this.state = this.S.SCRIPT;
710
+ }
711
+ continue;
712
+ case this.S.OPEN_WAKA:
713
+ if (c === "!") {
714
+ this.state = this.S.SGML_DECL;
715
+ this.sgmlDecl = "";
716
+ } else if (_SAX.isWhitespace(c)) {
717
+ } else if (_SAX.isMatch(nameStart, c)) {
718
+ this.state = this.S.OPEN_TAG;
719
+ this.tagName = c;
720
+ } else if (c === "/") {
721
+ this.state = this.S.CLOSE_TAG;
722
+ this.tagName = "";
723
+ } else if (c === "?") {
724
+ this.state = this.S.PROC_INST;
725
+ this.procInstName = this.procInstBody = "";
726
+ } else {
727
+ this.strictFail("Unencoded <");
728
+ if (this.startTagPosition + 1 < this.position) {
729
+ const pad = this.position - this.startTagPosition;
730
+ c = new Array(pad).join(" ") + c;
731
+ }
732
+ this.textNode += `<${c}`;
733
+ this.state = this.S.TEXT;
734
+ }
735
+ continue;
736
+ case this.S.SGML_DECL:
737
+ if ((this.sgmlDecl + c).toUpperCase() === this.CDATA) {
738
+ this.emitNode("onopencdata");
739
+ this.state = this.S.CDATA;
740
+ this.sgmlDecl = "";
741
+ this.cdata = "";
742
+ } else if (this.sgmlDecl + c === "--") {
743
+ this.state = this.S.COMMENT;
744
+ this.comment = "";
745
+ this.sgmlDecl = "";
746
+ } else if ((this.sgmlDecl + c).toUpperCase() === this.DOCTYPE) {
747
+ this.state = this.S.DOCTYPE;
748
+ if (this.doctype || this.sawRoot) {
749
+ this.strictFail("Inappropriately located doctype declaration");
750
+ }
751
+ this.doctype = "";
752
+ this.sgmlDecl = "";
753
+ } else if (c === ">") {
754
+ this.emitNode("onsgmldeclaration", this.sgmlDecl);
755
+ this.sgmlDecl = "";
756
+ this.state = this.S.TEXT;
757
+ } else if (_SAX.isQuote(c)) {
758
+ this.state = this.S.SGML_DECL_QUOTED;
759
+ this.sgmlDecl += c;
760
+ } else {
761
+ this.sgmlDecl += c;
762
+ }
763
+ continue;
764
+ case this.S.SGML_DECL_QUOTED:
765
+ if (c === this.q) {
766
+ this.state = this.S.SGML_DECL;
767
+ this.q = "";
768
+ }
769
+ this.sgmlDecl += c;
770
+ continue;
771
+ case this.S.DOCTYPE:
772
+ if (c === ">") {
773
+ this.state = this.S.TEXT;
774
+ this.emitNode("ondoctype", this.doctype);
775
+ this.doctype = true;
776
+ } else {
777
+ this.doctype += c;
778
+ if (c === "[") {
779
+ this.state = this.S.DOCTYPE_DTD;
780
+ } else if (_SAX.isQuote(c)) {
781
+ this.state = this.S.DOCTYPE_QUOTED;
782
+ this.q = c;
783
+ }
784
+ }
785
+ continue;
786
+ case this.S.DOCTYPE_QUOTED:
787
+ this.doctype += c;
788
+ if (c === this.q) {
789
+ this.q = "";
790
+ this.state = this.S.DOCTYPE;
791
+ }
792
+ continue;
793
+ case this.S.DOCTYPE_DTD:
794
+ this.doctype += c;
795
+ if (c === "]") {
796
+ this.state = this.S.DOCTYPE;
797
+ } else if (_SAX.isQuote(c)) {
798
+ this.state = this.S.DOCTYPE_DTD_QUOTED;
799
+ this.q = c;
800
+ }
801
+ continue;
802
+ case this.S.DOCTYPE_DTD_QUOTED:
803
+ this.doctype += c;
804
+ if (c === this.q) {
805
+ this.state = this.S.DOCTYPE_DTD;
806
+ this.q = "";
807
+ }
808
+ continue;
809
+ case this.S.COMMENT:
810
+ if (c === "-") {
811
+ this.state = this.S.COMMENT_ENDING;
812
+ } else {
813
+ this.comment += c;
814
+ }
815
+ continue;
816
+ case this.S.COMMENT_ENDING:
817
+ if (c === "-") {
818
+ this.state = this.S.COMMENT_ENDED;
819
+ this.comment = this.textApplyOptions(this.comment);
820
+ if (this.comment) {
821
+ this.emitNode("oncomment", this.comment);
822
+ }
823
+ this.comment = "";
824
+ } else {
825
+ this.comment += `-${c}`;
826
+ this.state = this.S.COMMENT;
827
+ }
828
+ continue;
829
+ case this.S.COMMENT_ENDED:
830
+ if (c !== ">") {
831
+ this.strictFail("Malformed comment");
832
+ this.comment += `--${c}`;
833
+ this.state = this.S.COMMENT;
834
+ } else {
835
+ this.state = this.S.TEXT;
836
+ }
837
+ continue;
838
+ case this.S.CDATA:
839
+ if (c === "]") {
840
+ this.state = this.S.CDATA_ENDING;
841
+ } else {
842
+ this.cdata += c;
843
+ }
844
+ continue;
845
+ case this.S.CDATA_ENDING:
846
+ if (c === "]") {
847
+ this.state = this.S.CDATA_ENDING_2;
848
+ } else {
849
+ this.cdata += `]${c}`;
850
+ this.state = this.S.CDATA;
851
+ }
852
+ continue;
853
+ case this.S.CDATA_ENDING_2:
854
+ if (c === ">") {
855
+ if (this.cdata) {
856
+ this.emitNode("oncdata", this.cdata);
857
+ }
858
+ this.emitNode("onclosecdata");
859
+ this.cdata = "";
860
+ this.state = this.S.TEXT;
861
+ } else if (c === "]") {
862
+ this.cdata += "]";
863
+ } else {
864
+ this.cdata += `]]${c}`;
865
+ this.state = this.S.CDATA;
866
+ }
867
+ continue;
868
+ case this.S.PROC_INST:
869
+ if (c === "?") {
870
+ this.state = this.S.PROC_INST_ENDING;
871
+ } else if (_SAX.isWhitespace(c)) {
872
+ this.state = this.S.PROC_INST_BODY;
873
+ } else {
874
+ this.procInstName += c;
875
+ }
876
+ continue;
877
+ case this.S.PROC_INST_BODY:
878
+ if (!this.procInstBody && _SAX.isWhitespace(c)) {
879
+ continue;
880
+ } else if (c === "?") {
881
+ this.state = this.S.PROC_INST_ENDING;
882
+ } else {
883
+ this.procInstBody += c;
884
+ }
885
+ continue;
886
+ case this.S.PROC_INST_ENDING:
887
+ if (c === ">") {
888
+ this.emitNode("onprocessinginstruction", {
889
+ name: this.procInstName,
890
+ body: this.procInstBody
891
+ });
892
+ this.procInstName = this.procInstBody = "";
893
+ this.state = this.S.TEXT;
894
+ } else {
895
+ this.procInstBody += `?${c}`;
896
+ this.state = this.S.PROC_INST_BODY;
897
+ }
898
+ continue;
899
+ case this.S.OPEN_TAG:
900
+ if (_SAX.isMatch(nameBody, c)) {
901
+ this.tagName += c;
902
+ } else {
903
+ this.newTag();
904
+ if (c === ">") {
905
+ this.openTag();
906
+ } else if (c === "/") {
907
+ this.state = this.S.OPEN_TAG_SLASH;
908
+ } else {
909
+ if (!_SAX.isWhitespace(c)) {
910
+ this.strictFail("Invalid character in tag name");
911
+ }
912
+ this.state = this.S.ATTRIB;
913
+ }
914
+ }
915
+ continue;
916
+ case this.S.OPEN_TAG_SLASH:
917
+ if (c === ">") {
918
+ this.openTag(true);
919
+ this.closeTag();
920
+ } else {
921
+ this.strictFail("Forward-slash in opening tag not followed by >");
922
+ this.state = this.S.ATTRIB;
923
+ }
924
+ continue;
925
+ case this.S.ATTRIB:
926
+ if (_SAX.isWhitespace(c)) {
927
+ continue;
928
+ } else if (c === ">") {
929
+ this.openTag();
930
+ } else if (c === "/") {
931
+ this.state = this.S.OPEN_TAG_SLASH;
932
+ } else if (_SAX.isMatch(nameStart, c)) {
933
+ this.attribName = c;
934
+ this.attribValue = "";
935
+ this.state = this.S.ATTRIB_NAME;
936
+ } else {
937
+ this.strictFail("Invalid attribute name");
938
+ }
939
+ continue;
940
+ case this.S.ATTRIB_NAME:
941
+ if (c === "=") {
942
+ this.state = this.S.ATTRIB_VALUE;
943
+ } else if (c === ">") {
944
+ this.strictFail("Attribute without value");
945
+ this.attribValue = this.attribName;
946
+ this.attrib();
947
+ this.openTag();
948
+ } else if (_SAX.isWhitespace(c)) {
949
+ this.state = this.S.ATTRIB_NAME_SAW_WHITE;
950
+ } else if (_SAX.isMatch(nameBody, c)) {
951
+ this.attribName += c;
952
+ } else {
953
+ this.strictFail("Invalid attribute name");
954
+ }
955
+ continue;
956
+ case this.S.ATTRIB_NAME_SAW_WHITE:
957
+ if (c === "=") {
958
+ this.state = this.S.ATTRIB_VALUE;
959
+ } else if (_SAX.isWhitespace(c)) {
960
+ continue;
961
+ } else {
962
+ this.strictFail("Attribute without value");
963
+ Object.defineProperty(this.tag.attributes, this.attribName, {
964
+ value: "",
965
+ enumerable: true,
966
+ configurable: true,
967
+ writable: true
968
+ });
969
+ this.attribValue = "";
970
+ this.emitNode("onattribute", {
971
+ name: this.attribName,
972
+ value: ""
973
+ });
974
+ this.attribName = "";
975
+ if (c === ">") {
976
+ this.openTag();
977
+ } else if (_SAX.isMatch(nameStart, c)) {
978
+ this.attribName = c;
979
+ this.state = this.S.ATTRIB_NAME;
980
+ } else {
981
+ this.strictFail("Invalid attribute name");
982
+ this.state = this.S.ATTRIB;
983
+ }
984
+ }
985
+ continue;
986
+ case this.S.ATTRIB_VALUE:
987
+ if (_SAX.isWhitespace(c)) {
988
+ continue;
989
+ } else if (_SAX.isQuote(c)) {
990
+ this.q = c;
991
+ this.state = this.S.ATTRIB_VALUE_QUOTED;
992
+ } else {
993
+ this.strictFail("Unquoted attribute value");
994
+ this.state = this.S.ATTRIB_VALUE_UNQUOTED;
995
+ this.attribValue = c;
996
+ }
997
+ continue;
998
+ case this.S.ATTRIB_VALUE_QUOTED:
999
+ if (c !== this.q) {
1000
+ if (c === "&") {
1001
+ this.state = this.S.ATTRIB_VALUE_ENTITY_Q;
1002
+ } else {
1003
+ this.attribValue += c;
1004
+ }
1005
+ continue;
1006
+ }
1007
+ this.attrib();
1008
+ this.q = "";
1009
+ this.state = this.S.ATTRIB_VALUE_CLOSED;
1010
+ continue;
1011
+ case this.S.ATTRIB_VALUE_CLOSED:
1012
+ if (_SAX.isWhitespace(c)) {
1013
+ this.state = this.S.ATTRIB;
1014
+ } else if (c === ">") {
1015
+ this.openTag();
1016
+ } else if (c === "/") {
1017
+ this.state = this.S.OPEN_TAG_SLASH;
1018
+ } else if (_SAX.isMatch(nameStart, c)) {
1019
+ this.strictFail("No whitespace between attributes");
1020
+ this.attribName = c;
1021
+ this.attribValue = "";
1022
+ this.state = this.S.ATTRIB_NAME;
1023
+ } else {
1024
+ this.strictFail("Invalid attribute name");
1025
+ }
1026
+ continue;
1027
+ case this.S.ATTRIB_VALUE_UNQUOTED:
1028
+ if (!_SAX.isAttribEnd(c)) {
1029
+ if (c === "&") {
1030
+ this.state = this.S.ATTRIB_VALUE_ENTITY_U;
1031
+ } else {
1032
+ this.attribValue += c;
1033
+ }
1034
+ continue;
1035
+ }
1036
+ this.attrib();
1037
+ if (c === ">") {
1038
+ this.openTag();
1039
+ } else {
1040
+ this.state = this.S.ATTRIB;
1041
+ }
1042
+ continue;
1043
+ case this.S.CLOSE_TAG:
1044
+ if (!this.tagName) {
1045
+ if (_SAX.isWhitespace(c)) {
1046
+ continue;
1047
+ } else if (_SAX.notMatch(nameStart, c)) {
1048
+ if (this.script) {
1049
+ this.script += `</${c}`;
1050
+ this.state = this.S.SCRIPT;
1051
+ } else {
1052
+ this.strictFail("Invalid tagname in closing tag.");
1053
+ }
1054
+ } else {
1055
+ this.tagName = c;
1056
+ }
1057
+ } else if (c === ">") {
1058
+ this.closeTag();
1059
+ } else if (_SAX.isMatch(nameBody, c)) {
1060
+ this.tagName += c;
1061
+ } else if (this.script) {
1062
+ this.script += `</${this.tagName}`;
1063
+ this.tagName = "";
1064
+ this.state = this.S.SCRIPT;
1065
+ } else {
1066
+ if (!_SAX.isWhitespace(c)) {
1067
+ this.strictFail("Invalid tagname in closing tag");
1068
+ }
1069
+ this.state = this.S.CLOSE_TAG_SAW_WHITE;
1070
+ }
1071
+ continue;
1072
+ case this.S.CLOSE_TAG_SAW_WHITE:
1073
+ if (_SAX.isWhitespace(c)) {
1074
+ continue;
1075
+ }
1076
+ if (c === ">") {
1077
+ this.closeTag();
1078
+ } else {
1079
+ this.strictFail("Invalid characters in closing tag");
1080
+ }
1081
+ continue;
1082
+ case this.S.TEXT_ENTITY:
1083
+ case this.S.ATTRIB_VALUE_ENTITY_Q:
1084
+ case this.S.ATTRIB_VALUE_ENTITY_U:
1085
+ let returnState;
1086
+ let buffer;
1087
+ switch (this.state) {
1088
+ case this.S.TEXT_ENTITY:
1089
+ returnState = this.S.TEXT;
1090
+ buffer = "textNode";
1091
+ break;
1092
+ case this.S.ATTRIB_VALUE_ENTITY_Q:
1093
+ returnState = this.S.ATTRIB_VALUE_QUOTED;
1094
+ buffer = "attribValue";
1095
+ break;
1096
+ case this.S.ATTRIB_VALUE_ENTITY_U:
1097
+ returnState = this.S.ATTRIB_VALUE_UNQUOTED;
1098
+ buffer = "attribValue";
1099
+ break;
1100
+ default:
1101
+ throw new Error(`Unknown state: ${this.state}`);
1102
+ }
1103
+ if (c === ";") {
1104
+ this[buffer] += this.parseEntity();
1105
+ this.entity = "";
1106
+ this.state = returnState;
1107
+ } else if (_SAX.isMatch(this.entity.length ? entityBody : entityStart, c)) {
1108
+ this.entity += c;
1109
+ } else {
1110
+ this.strictFail("Invalid character in entity name");
1111
+ this[buffer] += `&${this.entity}${c}`;
1112
+ this.entity = "";
1113
+ this.state = returnState;
1114
+ }
1115
+ continue;
1116
+ default:
1117
+ throw new Error(`Unknown state: ${this.state}`);
1118
+ }
1119
+ }
1120
+ if (this.position >= this.bufferCheckPosition) {
1121
+ this.checkBufferLength();
1122
+ }
1123
+ return this;
1124
+ }
1125
+ emit(event, data) {
1126
+ if (this.events.hasOwnProperty(event)) {
1127
+ const eventName = event.replace(/^on/, "");
1128
+ this.events[event](data, eventName, this);
1129
+ }
1130
+ }
1131
+ clearBuffers() {
1132
+ for (let i = 0, l = this.BUFFERS.length; i < l; i++) {
1133
+ this[this[i]] = "";
1134
+ }
1135
+ }
1136
+ flushBuffers() {
1137
+ this.closeText();
1138
+ if (this.cdata !== "") {
1139
+ this.emitNode("oncdata", this.cdata);
1140
+ this.cdata = "";
1141
+ }
1142
+ if (this.script !== "") {
1143
+ this.emitNode("onscript", this.script);
1144
+ this.script = "";
1145
+ }
1146
+ }
1147
+ end() {
1148
+ if (this.sawRoot && !this.closedRoot) this.strictFail("Unclosed root tag");
1149
+ if (this.strict && this.state !== this.S.BEGIN && this.state !== this.S.BEGIN_WHITESPACE && this.state !== this.S.TEXT) {
1150
+ this.errorFunction("Unexpected end");
1151
+ }
1152
+ this.closeText();
1153
+ this.c = "";
1154
+ this.closed = true;
1155
+ this.emit("onend");
1156
+ return new SAXParser(this.opt);
1157
+ }
1158
+ errorFunction(er) {
1159
+ this.closeText();
1160
+ if (this.trackPosition) {
1161
+ er += `
1162
+ Line: ${this.line}
1163
+ Column: ${this.column}
1164
+ Char: ${this.c}`;
1165
+ }
1166
+ const error = new Error(er);
1167
+ this.error = error;
1168
+ this.emit("onerror", error);
1169
+ return this;
1170
+ }
1171
+ attrib() {
1172
+ if (!this.strict && !this.opt.preserveCase) {
1173
+ this.attribName = this.attribName[this.looseCase]();
1174
+ }
1175
+ if (this.attribList.indexOf(this.attribName) !== -1 || Object.hasOwn(this.tag.attributes, this.attribName)) {
1176
+ this.strictFail("Duplicate attribute");
1177
+ this.attribName = this.attribValue = "";
1178
+ return;
1179
+ }
1180
+ if (this.opt.xmlns) {
1181
+ const qn = _SAX.qname(this.attribName, true);
1182
+ const prefix = qn.prefix;
1183
+ const local = qn.local;
1184
+ if (prefix === "xmlns") {
1185
+ if (local === "xml" && this.attribValue !== this.XML_NAMESPACE) {
1186
+ this.strictFail(
1187
+ `xml: prefix must be bound to ${this.XML_NAMESPACE}
1188
+ Actual: ${this.attribValue}`
1189
+ );
1190
+ } else if (local === "xmlns" && this.attribValue !== this.XMLNS_NAMESPACE) {
1191
+ this.strictFail(
1192
+ `xmlns: prefix must be bound to ${this.XMLNS_NAMESPACE}
1193
+ Actual: ${this.attribValue}`
1194
+ );
1195
+ } else {
1196
+ const tag = this.tag;
1197
+ const parent = this.tags[this.tags.length - 1] || this;
1198
+ if (tag.ns === parent.ns) {
1199
+ tag.ns = Object.create(parent.ns);
1200
+ }
1201
+ tag.ns[local] = this.attribValue;
1202
+ }
1203
+ }
1204
+ this.attribList.push([this.attribName, this.attribValue]);
1205
+ } else {
1206
+ Object.defineProperty(this.tag.attributes, this.attribName, {
1207
+ value: this.attribValue,
1208
+ enumerable: true,
1209
+ configurable: true,
1210
+ writable: true
1211
+ });
1212
+ this.emitNode("onattribute", {
1213
+ name: this.attribName,
1214
+ value: this.attribValue
1215
+ });
1216
+ }
1217
+ this.attribName = this.attribValue = "";
1218
+ }
1219
+ newTag() {
1220
+ if (!this.strict && !this.opt.preserveCase) this.tagName = this.tagName[this.looseCase]();
1221
+ const parent = this.tags[this.tags.length - 1] || this;
1222
+ const tag = { name: this.tagName, attributes: {} };
1223
+ this.tag = tag;
1224
+ if (this.opt.xmlns) {
1225
+ tag.ns = parent.ns;
1226
+ }
1227
+ this.attribList.length = 0;
1228
+ this.emitNode("onopentagstart", tag);
1229
+ }
1230
+ /** Validates an entity before optionally preserving its authored spelling. */
1231
+ parseEntity() {
1232
+ const decoded = this.decodeEntity();
1233
+ return this.opt.processEntities === false ? `&${this.entity};` : decoded;
1234
+ }
1235
+ /** Decodes predefined, configured, or numeric entities without resolving document types. */
1236
+ decodeEntity() {
1237
+ let entity = this.entity;
1238
+ const entityLC = entity.toLowerCase();
1239
+ let num = NaN;
1240
+ let numStr = "";
1241
+ if (typeof this.ENTITIES[entity] === "string" || typeof this.ENTITIES[entity] === "number") {
1242
+ return this.ENTITIES[entity];
1243
+ }
1244
+ if (typeof this.ENTITIES[entityLC] === "string" || typeof this.ENTITIES[entityLC] === "number") {
1245
+ return this.ENTITIES[entityLC];
1246
+ }
1247
+ entity = entityLC;
1248
+ if (entity.charAt(0) === "#") {
1249
+ if (entity.charAt(1) === "x") {
1250
+ entity = entity.slice(2);
1251
+ num = parseInt(entity, 16);
1252
+ numStr = num.toString(16);
1253
+ } else {
1254
+ entity = entity.slice(1);
1255
+ num = parseInt(entity, 10);
1256
+ numStr = num.toString(10);
1257
+ }
1258
+ }
1259
+ entity = entity.replace(/^0+/, "");
1260
+ if (Number.isNaN(num) || numStr.toLowerCase() !== entity) {
1261
+ this.strictFail("Invalid character entity");
1262
+ return `&${this.entity};`;
1263
+ }
1264
+ if (num < 0 || num > 1114111 || num >= 55296 && num <= 57343 || num < 32 && ![9, 10, 13].includes(num) || num === 65534 || num === 65535) {
1265
+ this.strictFail("Invalid character entity");
1266
+ return `&${this.entity};`;
1267
+ }
1268
+ return String.fromCodePoint(num);
1269
+ }
1270
+ beginWhiteSpace(c) {
1271
+ if (c === "<") {
1272
+ this.state = this.S.OPEN_WAKA;
1273
+ this.startTagPosition = this.position;
1274
+ } else if (!_SAX.isWhitespace(c)) {
1275
+ this.strictFail("Non-whitespace before first tag.");
1276
+ this.textNode = c;
1277
+ this.state = this.S.TEXT;
1278
+ } else {
1279
+ }
1280
+ }
1281
+ strictFail(message) {
1282
+ if (typeof this !== "object" || !(this instanceof SAXParser)) {
1283
+ throw new Error("bad call to strictFail");
1284
+ }
1285
+ if (this.strict) {
1286
+ this.errorFunction(message);
1287
+ }
1288
+ }
1289
+ textApplyOptions(text) {
1290
+ if (this.opt.trim) text = text.trim();
1291
+ if (this.opt.normalize) text = text.replace(/\s+/g, " ");
1292
+ return text;
1293
+ }
1294
+ emitNode(nodeType, data) {
1295
+ if (this.textNode) this.closeText();
1296
+ this.emit(nodeType, data);
1297
+ }
1298
+ closeText() {
1299
+ this.textNode = this.textApplyOptions(this.textNode);
1300
+ if (this.textNode !== void 0 && this.textNode !== "" && this.textNode !== "undefined") {
1301
+ this.emit("ontext", this.textNode);
1302
+ }
1303
+ this.textNode = "";
1304
+ }
1305
+ checkBufferLength() {
1306
+ var _a;
1307
+ const maxAllowed = Math.max(this.opt.MAX_BUFFER_LENGTH, 10);
1308
+ let maxActual = 0;
1309
+ for (let i = 0, l = this.BUFFERS.length; i < l; i++) {
1310
+ const len = ((_a = this[this.BUFFERS[i]]) == null ? void 0 : _a.length) || 0;
1311
+ if (len > maxAllowed) {
1312
+ switch (this.BUFFERS[i]) {
1313
+ case "textNode":
1314
+ this.closeText();
1315
+ break;
1316
+ case "cdata":
1317
+ this.emitNode("oncdata", this.cdata);
1318
+ this.cdata = "";
1319
+ break;
1320
+ case "script":
1321
+ this.emitNode("onscript", this.script);
1322
+ this.script = "";
1323
+ break;
1324
+ default:
1325
+ this.errorFunction(`Max buffer length exceeded: ${this.BUFFERS[i]}`);
1326
+ }
1327
+ }
1328
+ maxActual = Math.max(maxActual, len);
1329
+ }
1330
+ const m = this.opt.MAX_BUFFER_LENGTH - maxActual;
1331
+ this.bufferCheckPosition = m + this.position;
1332
+ }
1333
+ openTag(selfClosing) {
1334
+ if (this.opt.xmlns) {
1335
+ const tag = this.tag;
1336
+ const qn = _SAX.qname(this.tagName);
1337
+ tag.prefix = qn.prefix;
1338
+ tag.local = qn.local;
1339
+ tag.uri = tag.ns[qn.prefix] || "";
1340
+ if (tag.prefix && !tag.uri) {
1341
+ this.strictFail(`Unbound namespace prefix: ${JSON.stringify(this.tagName)}`);
1342
+ tag.uri = qn.prefix;
1343
+ }
1344
+ const parent = this.tags[this.tags.length - 1] || this;
1345
+ if (tag.ns && parent.ns !== tag.ns) {
1346
+ const that = this;
1347
+ Object.keys(tag.ns).forEach((p) => {
1348
+ that.emitNode("onopennamespace", {
1349
+ prefix: p,
1350
+ uri: tag.ns[p]
1351
+ });
1352
+ });
1353
+ }
1354
+ for (let i = 0, l = this.attribList.length; i < l; i++) {
1355
+ const nv = this.attribList[i];
1356
+ const name = nv[0];
1357
+ const value = nv[1];
1358
+ const qualName = _SAX.qname(name, true);
1359
+ const prefix = qualName.prefix;
1360
+ const local = qualName.local;
1361
+ const uri = prefix === "" ? "" : tag.ns[prefix] || "";
1362
+ const a = {
1363
+ name,
1364
+ value,
1365
+ prefix,
1366
+ local,
1367
+ uri
1368
+ };
1369
+ if (prefix && prefix !== "xmlns" && !uri) {
1370
+ this.strictFail(`Unbound namespace prefix: ${JSON.stringify(prefix)}`);
1371
+ a.uri = prefix;
1372
+ }
1373
+ Object.defineProperty(this.tag.attributes, name, {
1374
+ value: a,
1375
+ enumerable: true,
1376
+ configurable: true,
1377
+ writable: true
1378
+ });
1379
+ this.emitNode("onattribute", a);
1380
+ }
1381
+ this.attribList.length = 0;
1382
+ }
1383
+ this.tag.isSelfClosing = Boolean(selfClosing);
1384
+ this.sawRoot = true;
1385
+ this.tags.push(this.tag);
1386
+ this.emitNode("onopentag", this.tag);
1387
+ if (!selfClosing) {
1388
+ if (!this.noscript && this.tagName.toLowerCase() === "script") {
1389
+ this.state = this.S.SCRIPT;
1390
+ } else {
1391
+ this.state = this.S.TEXT;
1392
+ }
1393
+ this.tag = null;
1394
+ this.tagName = "";
1395
+ }
1396
+ this.attribName = this.attribValue = "";
1397
+ this.attribList.length = 0;
1398
+ }
1399
+ closeTag() {
1400
+ if (!this.tagName) {
1401
+ this.strictFail("Weird empty close tag.");
1402
+ this.textNode += "</>";
1403
+ this.state = this.S.TEXT;
1404
+ return;
1405
+ }
1406
+ const caseInsensitiveTags = !this.strict && (this.opt.caseInsensitiveTags || !this.opt.preserveCase);
1407
+ if (this.script) {
1408
+ const normalizedScriptCloseTag = caseInsensitiveTags ? this.tagName.toLowerCase() : this.tagName;
1409
+ if (normalizedScriptCloseTag !== "script") {
1410
+ this.script += `</${this.tagName}>`;
1411
+ this.tagName = "";
1412
+ this.state = this.S.SCRIPT;
1413
+ return;
1414
+ }
1415
+ this.emitNode("onscript", this.script);
1416
+ this.script = "";
1417
+ }
1418
+ let t = this.tags.length;
1419
+ let tagName = this.tagName;
1420
+ const normalizedTagName = caseInsensitiveTags ? tagName.toLowerCase() : tagName;
1421
+ while (t--) {
1422
+ const close = this.tags[t];
1423
+ const normalizedOpenTagName = caseInsensitiveTags ? close.name.toLowerCase() : close.name;
1424
+ if (normalizedOpenTagName !== normalizedTagName) {
1425
+ this.strictFail("Unexpected close tag");
1426
+ } else {
1427
+ break;
1428
+ }
1429
+ }
1430
+ if (t < 0) {
1431
+ this.strictFail(`Unmatched closing tag: ${this.tagName}`);
1432
+ this.textNode += `</${this.tagName}>`;
1433
+ this.state = this.S.TEXT;
1434
+ return;
1435
+ }
1436
+ this.tagName = tagName;
1437
+ let s = this.tags.length;
1438
+ while (s-- > t) {
1439
+ const tag = this.tags.pop();
1440
+ this.tag = tag;
1441
+ this.tagName = this.tag.name;
1442
+ this.emitNode("onclosetag", this.tagName);
1443
+ const x = {};
1444
+ for (const i in tag.ns) {
1445
+ if (tag.ns.hasOwnProperty(i)) {
1446
+ x[i] = tag.ns[i];
1447
+ }
1448
+ }
1449
+ const parent = this.tags[this.tags.length - 1] || this;
1450
+ if (this.opt.xmlns && tag.ns !== parent.ns) {
1451
+ const that = this;
1452
+ Object.keys(tag.ns).forEach((p) => {
1453
+ const n = tag.ns[p];
1454
+ that.emitNode("onclosenamespace", { prefix: p, uri: n });
1455
+ });
1456
+ }
1457
+ }
1458
+ if (t === 0) this.closedRoot = true;
1459
+ this.tagName = this.attribValue = this.attribName = "";
1460
+ this.attribList.length = 0;
1461
+ this.state = this.S.TEXT;
1462
+ }
1463
+ };
1464
+ SAXParser = class extends SAX {
1465
+ static ENTITIES = ENTITIES;
1466
+ opt = DEFAULT_SAX_PARSER_OPTIONS;
1467
+ events = DEFAULT_SAX_EVENTS;
1468
+ constructor(opt) {
1469
+ super();
1470
+ this.clearBuffers();
1471
+ this.opt = opt = { ...this.opt, ...opt };
1472
+ this.events = { ...this.events, ...opt };
1473
+ this.q = this.c = "";
1474
+ this.opt.lowercase = this.opt.lowercase || this.opt.lowercasetags;
1475
+ this.bufferCheckPosition = this.opt.MAX_BUFFER_LENGTH;
1476
+ this.looseCase = this.opt.lowercase ? "toLowerCase" : "toUpperCase";
1477
+ this.tags = [];
1478
+ this.closed = this.closedRoot = this.sawRoot = false;
1479
+ this.tag = this.error = null;
1480
+ this.strict = Boolean(this.opt.strict);
1481
+ this.noscript = Boolean(this.opt.strict || this.opt.noscript);
1482
+ this.state = this.S.BEGIN;
1483
+ this.strictEntities = this.opt.strictEntities;
1484
+ this.ENTITIES = this.strictEntities ? Object.create(this.XML_ENTITIES) : Object.create(this.ENTITIES);
1485
+ this.attribList = [];
1486
+ if (this.opt.xmlns) {
1487
+ this.ns = Object.create(this.rootNS);
1488
+ }
1489
+ this.trackPosition = this.opt.position !== false;
1490
+ if (this.trackPosition) {
1491
+ this.position = this.line = this.column = 0;
1492
+ }
1493
+ this.emit("onready");
1494
+ }
1495
+ resume() {
1496
+ this.error = null;
1497
+ return this;
1498
+ }
1499
+ close() {
1500
+ return this.write(null);
1501
+ }
1502
+ flush() {
1503
+ this.flushBuffers();
1504
+ }
1505
+ };
1506
+ }
1507
+ });
1508
+
1509
+ // ../documents/src/lib/parsers/parse-xml-internal.ts
1510
+ function setXMLField(object, name, value) {
1511
+ Object.defineProperty(object, name, {
1512
+ value,
1513
+ enumerable: true,
1514
+ configurable: true,
1515
+ writable: true
1516
+ });
1517
+ }
1518
+ function parseXMLInternal(text, options = {}) {
1519
+ if (options.strict !== false && /[^\u0009\u000a\u000d\u0020-\ud7ff\ue000-\ufffd\u{10000}-\u{10ffff}]/u.test(text)) {
1520
+ throw new Error("XML: invalid XML character");
1521
+ }
1522
+ const maximumDepth = options.maxDepth ?? 256;
1523
+ if (!Number.isSafeInteger(maximumDepth) || maximumDepth < 1 || maximumDepth > 4096) {
1524
+ throw new Error("XML: maxDepth must be an integer between 1 and 4096");
1525
+ }
1526
+ const state = new InternalXMLParserState(options, maximumDepth);
1527
+ const parser = new SAXParser({
1528
+ strict: options.strict !== false,
1529
+ strictEntities: !options.htmlEntities,
1530
+ preserveCase: true,
1531
+ caseInsensitiveTags: options.strict === false,
1532
+ processEntities: options.processEntities !== false,
1533
+ onopentag: (tag) => state.openElement(tag.name, tag.attributes || {}),
1534
+ ontext: (value) => state.addText(value),
1535
+ oncdata: (value) => state.addText(value),
1536
+ onscript: (value) => state.addText(value),
1537
+ onclosetag: () => state.closeElement(),
1538
+ onerror: (error) => {
1539
+ throw error;
1540
+ }
1541
+ });
1542
+ parser.write(text).close();
1543
+ if (options.strict === false) {
1544
+ while (state.stack.length) state.closeElement();
1545
+ }
1546
+ if (state.result === void 0) throw new Error("XML: document requires a root element");
1547
+ return state.result;
1548
+ }
1549
+ var InternalXMLParserState;
1550
+ var init_parse_xml_internal = __esm({
1551
+ "../documents/src/lib/parsers/parse-xml-internal.ts"() {
1552
+ "use strict";
1553
+ init_sax();
1554
+ InternalXMLParserState = class {
1555
+ /** Initializes conversion options and the element nesting budget. */
1556
+ constructor(options, maximumDepth) {
1557
+ this.options = options;
1558
+ this.maximumDepth = maximumDepth;
1559
+ }
1560
+ options;
1561
+ maximumDepth;
1562
+ /** Open element stack. */
1563
+ stack = [];
1564
+ /** Parsed root document. */
1565
+ result;
1566
+ /** Starts an element, rejecting multiple roots and excessive nesting. */
1567
+ openElement(name, attributes) {
1568
+ if (this.stack.length >= this.maximumDepth)
1569
+ throw new Error("XML: maximum nesting depth exceeded");
1570
+ if (!this.stack.length && this.result !== void 0 && this.options.strict !== false) {
1571
+ throw new Error("XML: document requires a single root element");
1572
+ }
1573
+ const elementName = this.normalizeName(name);
1574
+ const parent = this.stack[this.stack.length - 1];
1575
+ this.stack.push({
1576
+ name: elementName,
1577
+ path: parent ? `${parent.path}.${elementName}` : elementName,
1578
+ attributes: this.normalizeAttributes(attributes),
1579
+ children: {},
1580
+ text: ""
1581
+ });
1582
+ }
1583
+ /** Accumulates text without losing whitespace between text and CDATA chunks. */
1584
+ addText(text) {
1585
+ const current = this.stack[this.stack.length - 1];
1586
+ if (current) current.text += text;
1587
+ }
1588
+ /** Finishes an element and attaches it to its parent or the document root. */
1589
+ closeElement() {
1590
+ const node = this.stack.pop();
1591
+ if (!node) return;
1592
+ const value = this.finalizeElement(node);
1593
+ const parent = this.stack[this.stack.length - 1];
1594
+ if (parent) this.addChild(parent.children, node.name, node.path, value);
1595
+ else {
1596
+ if (this.result === void 0) this.result = {};
1597
+ this.addChild(this.result, node.name, node.path, value);
1598
+ }
1599
+ }
1600
+ /** Converts a completed element, keeping grouping and coercion independent. */
1601
+ finalizeElement(node) {
1602
+ const text = this.options.trimValues === false ? node.text : node.text.trim();
1603
+ const hasAttributes = Object.keys(node.attributes).length > 0;
1604
+ if (!hasAttributes && !Object.keys(node.children).length) {
1605
+ return this.parseValue(text, this.options.parseTagValue !== false);
1606
+ }
1607
+ const object = node.children;
1608
+ if (text)
1609
+ setXMLField(
1610
+ object,
1611
+ this.options.textNodeName ?? "value",
1612
+ this.parseValue(text, this.options.parseTagValue !== false)
1613
+ );
1614
+ if (hasAttributes && this.options.attributesGroupName) {
1615
+ setXMLField(object, this.options.attributesGroupName, node.attributes);
1616
+ } else {
1617
+ for (const [name, value] of Object.entries(node.attributes)) setXMLField(object, name, value);
1618
+ }
1619
+ return object;
1620
+ }
1621
+ /** Appends an element while preserving repeated and explicitly array-valued fields. */
1622
+ addChild(object, name, path, value) {
1623
+ var _a;
1624
+ if (!Object.hasOwn(object, name)) {
1625
+ setXMLField(object, name, ((_a = this.options.arrayPaths) == null ? void 0 : _a.includes(path)) ? [value] : value);
1626
+ } else {
1627
+ const existing = object[name];
1628
+ if (Array.isArray(existing)) existing.push(value);
1629
+ else setXMLField(object, name, [existing, value]);
1630
+ }
1631
+ }
1632
+ /** Applies namespace, prefix, grouping and scalar options to attributes. */
1633
+ normalizeAttributes(attributes) {
1634
+ const normalized = {};
1635
+ if (this.options.ignoreAttributes) return normalized;
1636
+ for (const [name, value] of Object.entries(attributes)) {
1637
+ if (this.options.removeNSPrefix && (name === "xmlns" || name.startsWith("xmlns:"))) continue;
1638
+ const text = this.options.trimValues === false ? value : value.trim();
1639
+ setXMLField(
1640
+ normalized,
1641
+ (this.options.attributeNamePrefix ?? "") + this.normalizeName(name),
1642
+ this.parseValue(text, this.options.parseAttributeValue === true)
1643
+ );
1644
+ }
1645
+ return normalized;
1646
+ }
1647
+ /** Removes a namespace prefix only when requested. */
1648
+ normalizeName(name) {
1649
+ return this.options.removeNSPrefix ? name.slice(name.indexOf(":") + 1) : name;
1650
+ }
1651
+ /** Coerces only finite numeric values and lowercase XML boolean literals. */
1652
+ parseValue(value, convert) {
1653
+ if (!convert) return value;
1654
+ if (value === "true" || value === "false") return value === "true";
1655
+ if (value !== "" && value.trim() !== "" && Number.isFinite(Number(value))) return Number(value);
1656
+ return value;
1657
+ }
1658
+ };
1659
+ }
1660
+ });
1661
+
1662
+ // ../documents/src/lib/parsers/parse-xml.ts
1663
+ function parseXMLSync(text, options = {}) {
1664
+ if (Object.hasOwn(options, "_fastXML") || Object.hasOwn(options, "_sax")) {
1665
+ throw new Error("XML: backend-specific options were removed; use native XML options");
1666
+ }
1667
+ if (options._parser && !["internal", "sax"].includes(options._parser)) {
1668
+ throw new Error("XML: unsupported parser backend; use the native documents parser");
1669
+ }
1670
+ const parsed = parseXMLInternal(text, options);
1671
+ return options.uncapitalizeKeys ? uncapitalizeKeys(parsed) : parsed;
1672
+ }
1673
+ function validateXML(text) {
1674
+ try {
1675
+ parseXMLInternal(text, {});
1676
+ return true;
1677
+ } catch (error) {
1678
+ return error instanceof Error ? error : new Error(String(error));
1679
+ }
1680
+ }
1681
+ var init_parse_xml = __esm({
1682
+ "../documents/src/lib/parsers/parse-xml.ts"() {
1683
+ "use strict";
1684
+ init_uncapitalize();
1685
+ init_parse_xml_internal();
1686
+ }
1687
+ });
1688
+
1689
+ // ../documents/src/xml-parser.ts
1690
+ var init_xml_parser = __esm({
1691
+ "../documents/src/xml-parser.ts"() {
1692
+ "use strict";
1693
+ init_parse_xml();
1694
+ }
1695
+ });
1696
+
1697
+ // ../core/src/schema-utils/lib/schema/convert-arrow-schema.ts
1698
+ function convertArrowToSchema(arrowSchema) {
1699
+ return serializeArrowSchema(arrowSchema);
1700
+ }
1701
+ function serializeArrowSchema(arrowSchema) {
1702
+ return {
1703
+ fields: arrowSchema.fields.map((arrowField) => serializeArrowField(arrowField)),
1704
+ metadata: serializeArrowMetadata(arrowSchema.metadata)
1705
+ };
1706
+ }
1707
+ function serializeArrowMetadata(arrowMetadata) {
1708
+ return Object.fromEntries(arrowMetadata);
1709
+ }
1710
+ function serializeArrowField(field) {
1711
+ return {
1712
+ name: field.name,
1713
+ type: serializeArrowType(field.type),
1714
+ nullable: field.nullable,
1715
+ metadata: serializeArrowMetadata(field.metadata)
1716
+ };
1717
+ }
1718
+ function serializeArrowType(arrowType) {
1719
+ if (isArrowViewType(arrowType, "BinaryView")) {
1720
+ return "binary-view";
1721
+ }
1722
+ if (isArrowViewType(arrowType, "Utf8View")) {
1723
+ return "utf8-view";
1724
+ }
1725
+ if (isOptionalArrowType(arrowType, "LargeList")) {
1726
+ const largeListType = arrowType;
1727
+ return {
1728
+ type: "large-list",
1729
+ children: [serializeArrowField(largeListType.valueField)]
1730
+ };
1731
+ }
1732
+ switch (arrowType.constructor) {
1733
+ case arrow.Null:
1734
+ return "null";
1735
+ case arrow.Binary:
1736
+ return "binary";
1737
+ case arrow.FixedSizeBinary:
1738
+ return {
1739
+ type: "fixed-size-binary",
1740
+ byteWidth: arrowType.byteWidth
1741
+ };
1742
+ case arrow.Bool:
1743
+ return "bool";
1744
+ case arrow.Int:
1745
+ const intType = arrowType;
1746
+ return `${intType.isSigned ? "" : "u"}int${intType.bitWidth}`;
1747
+ case arrow.Int8:
1748
+ return "int8";
1749
+ case arrow.Int16:
1750
+ return "int16";
1751
+ case arrow.Int32:
1752
+ return "int32";
1753
+ case arrow.Int64:
1754
+ return "int64";
1755
+ case arrow.Uint8:
1756
+ return "uint8";
1757
+ case arrow.Uint16:
1758
+ return "uint16";
1759
+ case arrow.Uint32:
1760
+ return "uint32";
1761
+ case arrow.Uint64:
1762
+ return "uint64";
1763
+ case arrow.Float:
1764
+ const precision = arrowType.precision;
1765
+ switch (precision) {
1766
+ case arrow.Precision.HALF:
1767
+ return "float16";
1768
+ case arrow.Precision.SINGLE:
1769
+ return "float32";
1770
+ case arrow.Precision.DOUBLE:
1771
+ return "float64";
1772
+ default:
1773
+ return "float16";
1774
+ }
1775
+ case arrow.Float16:
1776
+ return "float16";
1777
+ case arrow.Float32:
1778
+ return "float32";
1779
+ case arrow.Float64:
1780
+ return "float64";
1781
+ case arrow.Utf8:
1782
+ return "utf8";
1783
+ case arrow.Decimal:
1784
+ const decimal = arrowType;
1785
+ return {
1786
+ type: "decimal",
1787
+ bitWidth: decimal.bitWidth,
1788
+ precision: decimal.precision,
1789
+ scale: decimal.scale
1790
+ };
1791
+ case arrow.Date_:
1792
+ const dateUnit = arrowType.unit;
1793
+ return dateUnit === arrow.DateUnit.DAY ? "date-day" : "date-millisecond";
1794
+ case arrow.DateDay:
1795
+ return "date-day";
1796
+ case arrow.DateMillisecond:
1797
+ return "date-millisecond";
1798
+ case arrow.Time:
1799
+ const timeUnit = arrowType.unit;
1800
+ switch (timeUnit) {
1801
+ case arrow.TimeUnit.SECOND:
1802
+ return "time-second";
1803
+ case arrow.TimeUnit.MILLISECOND:
1804
+ return "time-millisecond";
1805
+ case arrow.TimeUnit.MICROSECOND:
1806
+ return "time-microsecond";
1807
+ case arrow.TimeUnit.NANOSECOND:
1808
+ return "time-nanosecond";
1809
+ default:
1810
+ return "time-second";
1811
+ }
1812
+ case arrow.TimeMillisecond:
1813
+ return "time-millisecond";
1814
+ case arrow.TimeSecond:
1815
+ return "time-second";
1816
+ case arrow.TimeMicrosecond:
1817
+ return "time-microsecond";
1818
+ case arrow.TimeNanosecond:
1819
+ return "time-nanosecond";
1820
+ case arrow.Timestamp:
1821
+ const timeStampUnit = arrowType.unit;
1822
+ switch (timeStampUnit) {
1823
+ case arrow.TimeUnit.SECOND:
1824
+ return "timestamp-second";
1825
+ case arrow.TimeUnit.MILLISECOND:
1826
+ return "timestamp-millisecond";
1827
+ case arrow.TimeUnit.MICROSECOND:
1828
+ return "timestamp-microsecond";
1829
+ case arrow.TimeUnit.NANOSECOND:
1830
+ return "timestamp-nanosecond";
1831
+ default:
1832
+ return "timestamp-second";
1833
+ }
1834
+ case arrow.TimestampSecond:
1835
+ return "timestamp-second";
1836
+ case arrow.TimestampMillisecond:
1837
+ return "timestamp-millisecond";
1838
+ case arrow.TimestampMicrosecond:
1839
+ return "timestamp-microsecond";
1840
+ case arrow.TimestampNanosecond:
1841
+ return "timestamp-nanosecond";
1842
+ case arrow.Interval:
1843
+ const intervalUnit = arrowType.unit;
1844
+ switch (intervalUnit) {
1845
+ case arrow.IntervalUnit.DAY_TIME:
1846
+ return "interval-daytime";
1847
+ case arrow.IntervalUnit.YEAR_MONTH:
1848
+ return "interval-yearmonth";
1849
+ default:
1850
+ return "interval-daytime";
1851
+ }
1852
+ case arrow.IntervalDayTime:
1853
+ return "interval-daytime";
1854
+ case arrow.IntervalYearMonth:
1855
+ return "interval-yearmonth";
1856
+ case arrow.Map_:
1857
+ const mapType = arrowType;
1858
+ return {
1859
+ type: "map",
1860
+ keysSorted: mapType.keysSorted,
1861
+ children: mapType.children.map((arrowField) => serializeArrowField(arrowField))
1862
+ };
1863
+ case arrow.List:
1864
+ const listType = arrowType;
1865
+ const listField = listType.valueField;
1866
+ return {
1867
+ type: "list",
1868
+ children: [serializeArrowField(listField)]
1869
+ };
1870
+ case arrow.FixedSizeList:
1871
+ const fixedSizeList = arrowType;
1872
+ return {
1873
+ type: "fixed-size-list",
1874
+ listSize: fixedSizeList.listSize,
1875
+ children: [serializeArrowField(fixedSizeList.children[0])]
1876
+ };
1877
+ case arrow.Struct:
1878
+ const structType = arrowType;
1879
+ return {
1880
+ type: "struct",
1881
+ children: structType.children.map((arrowField) => serializeArrowField(arrowField))
1882
+ };
1883
+ case arrow.SparseUnion:
1884
+ case arrow.DenseUnion:
1885
+ const unionType = arrowType;
1886
+ return {
1887
+ type: unionType instanceof arrow.DenseUnion ? "dense-union" : "sparse-union",
1888
+ typeIds: unionType.typeIds,
1889
+ children: unionType.children.map((arrowField) => serializeArrowField(arrowField)),
1890
+ typeIdToChildIndex: { ...unionType.typeIdToChildIndex }
1891
+ };
1892
+ case arrow.Dictionary:
1893
+ const dictionaryType = arrowType;
1894
+ return {
1895
+ type: "dictionary",
1896
+ id: dictionaryType.id,
1897
+ indices: serializeArrowDictionaryKeyType(dictionaryType.indices),
1898
+ dictionary: serializeArrowType(dictionaryType.dictionary),
1899
+ isOrdered: dictionaryType.isOrdered
1900
+ };
1901
+ default:
1902
+ throw new Error(`arrow type not supported: ${arrowType.constructor.name}`);
1903
+ }
1904
+ }
1905
+ function getOptionalArrowConstructor(typeName) {
1906
+ return arrow[typeName];
1907
+ }
1908
+ function isArrowViewType(arrowType, viewTypeName) {
1909
+ const constructor = getOptionalArrowConstructor(viewTypeName);
1910
+ if (constructor && arrowType instanceof constructor) {
1911
+ return true;
1912
+ }
1913
+ const guards = arrow.DataType;
1914
+ const guard = viewTypeName === "BinaryView" ? guards.isBinaryView : guards.isUtf8View;
1915
+ return Boolean(guard == null ? void 0 : guard(arrowType));
1916
+ }
1917
+ function isOptionalArrowType(arrowType, typeName) {
1918
+ const constructor = getOptionalArrowConstructor(typeName);
1919
+ return Boolean(constructor && arrowType instanceof constructor);
1920
+ }
1921
+ function serializeArrowDictionaryKeyType(arrowType) {
1922
+ if (arrowType instanceof arrow.Int) {
1923
+ const prefix = arrowType.isSigned ? "int" : "uint";
1924
+ const keyType = `${prefix}${arrowType.bitWidth}`;
1925
+ if (isSchemaDictionaryKeyType(keyType)) {
1926
+ return keyType;
1927
+ }
1928
+ }
1929
+ switch (arrowType.constructor) {
1930
+ case arrow.Int8:
1931
+ return "int8";
1932
+ case arrow.Int16:
1933
+ return "int16";
1934
+ case arrow.Int32:
1935
+ return "int32";
1936
+ case arrow.Uint8:
1937
+ return "uint8";
1938
+ case arrow.Uint16:
1939
+ return "uint16";
1940
+ case arrow.Uint32:
1941
+ return "uint32";
1942
+ default:
1943
+ throw new Error(`arrow dictionary index type not supported: ${arrowType.constructor.name}`);
1944
+ }
1945
+ }
1946
+ function isSchemaDictionaryKeyType(keyType) {
1947
+ return ["int8", "int16", "int32", "uint8", "uint16", "uint32"].includes(keyType);
1948
+ }
1949
+ var arrow;
1950
+ var init_convert_arrow_schema = __esm({
1951
+ "../core/src/schema-utils/lib/schema/convert-arrow-schema.ts"() {
1952
+ "use strict";
1953
+ arrow = __toESM(require("apache-arrow"), 1);
1954
+ }
1955
+ });
1956
+
1957
+ // ../core/src/schema-utils/index.ts
1958
+ var init_schema_utils = __esm({
1959
+ "../core/src/schema-utils/index.ts"() {
1960
+ "use strict";
1961
+ init_convert_arrow_schema();
1962
+ }
1963
+ });
1964
+
1965
+ // src/lib/build-graph-tables.ts
1966
+ function buildGraphTables(nodes, edges, shape, declarations) {
1967
+ if (shape === "plain-graph-data") {
1968
+ return { shape, nodes: Array.from(nodes), edges: Array.from(edges) };
1969
+ }
1970
+ if (shape !== "arrow-table" && shape !== "object-row-table") {
1971
+ throw new Error(`Unsupported graph shape: ${shape}`);
1972
+ }
1973
+ const nodeTable = buildGraphTable(nodes, false, shape, declarations == null ? void 0 : declarations.nodes);
1974
+ const edgeTable = buildGraphTable(edges, true, shape, declarations == null ? void 0 : declarations.edges);
1975
+ return {
1976
+ shape: "tables",
1977
+ tables: [
1978
+ { name: "nodes", table: nodeTable },
1979
+ { name: "edges", table: edgeTable }
1980
+ ]
1981
+ };
1982
+ }
1983
+ function buildGraphTable(records, isEdge, shape, declarations) {
1984
+ const columnNames = isEdge ? ["id", "sourceId", "targetId", "directed", "label", "attributes"] : ["id", "label", "attributes"];
1985
+ const columns = new Map(columnNames.map((name) => [name, []]));
1986
+ for (const record of records) {
1987
+ for (const name of columnNames) {
1988
+ const value = record[name];
1989
+ columns.get(name).push(
1990
+ name === "id" || name === "sourceId" || name === "targetId" ? String(value) : value ?? null
1991
+ );
1992
+ }
1993
+ }
1994
+ if (shape === "object-row-table") {
1995
+ return {
1996
+ shape,
1997
+ data: columns.get("id").map(
1998
+ (_, index) => Object.fromEntries(columnNames.map((name) => [name, columns.get(name)[index]]))
1999
+ )
2000
+ };
2001
+ }
2002
+ const vectors = /* @__PURE__ */ Object.create(null);
2003
+ for (const [name, values] of columns) {
2004
+ const type = name === "attributes" ? inferAttributeType(values, declarations) : name === "directed" ? new import_apache_arrow.Bool() : new import_apache_arrow.Utf8();
2005
+ vectors[name] = (0, import_apache_arrow.vectorFromArray)(
2006
+ values.map((value) => normalizeValue(value, type)),
2007
+ type
2008
+ );
2009
+ }
2010
+ const data = new import_apache_arrow.Table(vectors);
2011
+ return { shape, schema: convertArrowToSchema(data.schema), data };
2012
+ }
2013
+ function inferAttributeType(values, declarations) {
2014
+ const names = new Set(declarations == null ? void 0 : declarations.keys());
2015
+ for (const value of values) {
2016
+ if (value && typeof value === "object") {
2017
+ for (const name of Object.keys(value)) {
2018
+ names.add(name);
2019
+ }
2020
+ }
2021
+ }
2022
+ return new import_apache_arrow.Struct(
2023
+ Array.from(names, (name) => {
2024
+ const fieldValues = values.map(
2025
+ (value) => (value == null ? void 0 : value[name]) ?? null
2026
+ );
2027
+ return new import_apache_arrow.Field(name, inferValueType(fieldValues, declarations == null ? void 0 : declarations.get(name)), true);
2028
+ })
2029
+ );
2030
+ }
2031
+ function inferValueType(values, declaration) {
2032
+ const present = values.filter((value) => value !== null && value !== void 0);
2033
+ if (declaration && typeof declaration === "object") {
2034
+ if (!present.every((value) => Array.isArray(value))) return new import_apache_arrow.Utf8();
2035
+ return new import_apache_arrow.List(
2036
+ new import_apache_arrow.Field(
2037
+ "item",
2038
+ inferValueType(
2039
+ present.flatMap((value) => value),
2040
+ declaration.list
2041
+ ),
2042
+ true
2043
+ )
2044
+ );
2045
+ }
2046
+ if (declaration) {
2047
+ const declaredTypes = {
2048
+ boolean: new import_apache_arrow.Bool(),
2049
+ int: new import_apache_arrow.Int32(),
2050
+ long: new import_apache_arrow.Int64(),
2051
+ float: new import_apache_arrow.Float32(),
2052
+ double: new import_apache_arrow.Float64(),
2053
+ string: new import_apache_arrow.Utf8()
2054
+ };
2055
+ const valid = present.every((value) => {
2056
+ switch (declaration) {
2057
+ case "boolean":
2058
+ return typeof value === "boolean";
2059
+ case "int":
2060
+ return typeof value === "number" && Number.isInteger(value) && value >= -2147483648 && value <= 2147483647;
2061
+ case "long":
2062
+ return typeof value === "bigint" && value >= -(2n ** 63n) && value < 2n ** 63n;
2063
+ case "float":
2064
+ case "double":
2065
+ return typeof value === "number";
2066
+ case "string":
2067
+ return typeof value === "string";
2068
+ }
2069
+ });
2070
+ return valid ? declaredTypes[declaration] : new import_apache_arrow.Utf8();
2071
+ }
2072
+ if (present.length && present.every((value) => typeof value === "boolean")) return new import_apache_arrow.Bool();
2073
+ if (present.length && present.every((value) => typeof value === "number")) return new import_apache_arrow.Float64();
2074
+ if (present.length && present.every((value) => Array.isArray(value))) {
2075
+ return new import_apache_arrow.List(
2076
+ new import_apache_arrow.Field("item", inferValueType(present.flatMap((value) => value)), true)
2077
+ );
2078
+ }
2079
+ if (present.length && present.every((value) => typeof value === "object" && !Array.isArray(value))) {
2080
+ return inferAttributeType(present);
2081
+ }
2082
+ return new import_apache_arrow.Utf8();
2083
+ }
2084
+ function normalizeValue(value, type) {
2085
+ if (value === null || value === void 0) return null;
2086
+ if (type instanceof import_apache_arrow.Struct) {
2087
+ return Object.fromEntries(
2088
+ type.children.map((field) => [
2089
+ field.name,
2090
+ normalizeValue(value[field.name], field.type)
2091
+ ])
2092
+ );
2093
+ }
2094
+ if (type instanceof import_apache_arrow.List)
2095
+ return value.map((item) => normalizeValue(item, type.valueType));
2096
+ if (type instanceof import_apache_arrow.Utf8 && typeof value !== "string") {
2097
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
2098
+ }
2099
+ return value;
2100
+ }
2101
+ var import_apache_arrow;
2102
+ var init_build_graph_tables = __esm({
2103
+ "src/lib/build-graph-tables.ts"() {
2104
+ "use strict";
2105
+ import_apache_arrow = require("apache-arrow");
2106
+ init_schema_utils();
2107
+ }
2108
+ });
2109
+
2110
+ // src/lib/parse-gexf.ts
2111
+ function parseGEXF(input, shape = "arrow-table") {
2112
+ const text = typeof input === "string" ? input : new TextDecoder().decode(input);
2113
+ const validation = validateXML(text);
2114
+ if (validation !== true) throw new Error(`Invalid GEXF XML: ${validation.message}`);
2115
+ if (/<!DOCTYPE\s/i.test(text)) throw new Error("GEXF document types are unsupported.");
2116
+ const document = normalizeNamespaces(parseXMLSync(text, XML_OPTIONS), {});
2117
+ const root = getElement(document.gexf, "gexf");
2118
+ const version = root["@_version"];
2119
+ if (version && !["1.2", "1.2draft", "1.3"].includes(version)) {
2120
+ throw new Error(`Unsupported GEXF version: ${version}`);
2121
+ }
2122
+ const graph = getElement(root.graph, "graph");
2123
+ const directed = parseDirection(graph["@_defaultedgetype"] ?? "undirected");
2124
+ const definitions = {
2125
+ nodes: /* @__PURE__ */ new Map(),
2126
+ edges: /* @__PURE__ */ new Map()
2127
+ };
2128
+ for (const attributes of getElements(graph.attributes)) {
2129
+ const domain = attributes["@_class"];
2130
+ if (domain !== "node" && domain !== "edge")
2131
+ throw new Error("GEXF attributes require a node or edge class.");
2132
+ const scoped = domain === "node" ? definitions.nodes : definitions.edges;
2133
+ const names = new Set(Array.from(scoped.values(), (definition) => definition.name));
2134
+ for (const attribute of getElements(attributes.attribute)) {
2135
+ const identifier = requireAttribute(attribute, "id");
2136
+ const name = requireAttribute(attribute, "title");
2137
+ if (name === "gexf" || names.has(name) || scoped.has(identifier)) {
2138
+ throw new Error(`Duplicate or reserved GEXF attribute: ${name}`);
2139
+ }
2140
+ names.add(name);
2141
+ const type = parseAttributeType(requireAttribute(attribute, "type"));
2142
+ scoped.set(identifier, {
2143
+ name,
2144
+ type,
2145
+ defaultValue: attribute.default === void 0 ? void 0 : castValue(readTextContent(attribute.default), type)
2146
+ });
2147
+ }
2148
+ }
2149
+ const nodeElements = getElements(getContainer(graph.nodes).node);
2150
+ const edgeElements = getElements(getContainer(graph.edges).edge);
2151
+ const nodeIdentifiers = /* @__PURE__ */ new Set();
2152
+ for (const node of nodeElements) {
2153
+ const identifier = requireAttribute(node, "id");
2154
+ if (nodeIdentifiers.has(identifier)) throw new Error(`Duplicate GEXF node ID: ${identifier}`);
2155
+ nodeIdentifiers.add(identifier);
2156
+ }
2157
+ const edgeIdentifiers = new Set(
2158
+ edgeElements.map((edge) => edge["@_id"]).filter((identifier) => typeof identifier === "string")
2159
+ );
2160
+ const seenEdges = /* @__PURE__ */ new Set();
2161
+ function* iterateNodes() {
2162
+ for (const node of nodeElements) yield parseRecord(node, definitions.nodes);
2163
+ }
2164
+ function* iterateEdges() {
2165
+ for (const [index, edge] of edgeElements.entries()) {
2166
+ const sourceId = requireAttribute(edge, "source");
2167
+ const targetId = requireAttribute(edge, "target");
2168
+ if (!nodeIdentifiers.has(sourceId) || !nodeIdentifiers.has(targetId)) {
2169
+ throw new Error("GEXF edge references an undeclared node.");
2170
+ }
2171
+ let identifier = edge["@_id"] === void 0 ? void 0 : requireAttribute(edge, "id");
2172
+ if (identifier === void 0) {
2173
+ identifier = `edge-${index}`;
2174
+ while (edgeIdentifiers.has(identifier)) identifier = `_${identifier}`;
2175
+ edgeIdentifiers.add(identifier);
2176
+ }
2177
+ if (seenEdges.has(identifier)) throw new Error(`Duplicate GEXF edge ID: ${identifier}`);
2178
+ seenEdges.add(identifier);
2179
+ yield {
2180
+ ...parseRecord(edge, definitions.edges, identifier),
2181
+ sourceId,
2182
+ targetId,
2183
+ directed: edge["@_type"] === void 0 ? directed : parseDirection(edge["@_type"])
2184
+ };
2185
+ }
2186
+ }
2187
+ const metadataAttributes = /* @__PURE__ */ Object.create(null);
2188
+ const meta = getContainer(root.meta);
2189
+ for (const name of ["creator", "description", "keywords"]) {
2190
+ if (meta[name] !== void 0) metadataAttributes[name] = readTextContent(meta[name]);
2191
+ }
2192
+ if (typeof meta["@_lastmodifieddate"] === "string")
2193
+ metadataAttributes.lastmodifieddate = meta["@_lastmodifieddate"];
2194
+ const declarations = {
2195
+ nodes: new Map(
2196
+ Array.from(definitions.nodes.values(), (definition) => [definition.name, definition.type])
2197
+ ),
2198
+ edges: new Map(
2199
+ Array.from(definitions.edges.values(), (definition) => [definition.name, definition.type])
2200
+ )
2201
+ };
2202
+ return {
2203
+ ...buildGraphTables(iterateNodes(), iterateEdges(), shape, declarations),
2204
+ metadata: { version, directed, attributes: metadataAttributes }
2205
+ };
2206
+ }
2207
+ function normalizeNamespaces(element, inherited) {
2208
+ const namespaces = Object.assign(/* @__PURE__ */ Object.create(null), inherited);
2209
+ for (const [name, value] of Object.entries(element)) {
2210
+ if (name === "@_xmlns") namespaces[""] = String(value);
2211
+ else if (name.startsWith("@_xmlns:")) namespaces[name.slice(8)] = String(value);
2212
+ }
2213
+ const normalized = /* @__PURE__ */ Object.create(null);
2214
+ for (const [name, value] of Object.entries(element)) {
2215
+ if (name.startsWith("@_") || name === "#text" || name.startsWith("?")) {
2216
+ normalized[name] = value;
2217
+ continue;
2218
+ }
2219
+ const separator = name.indexOf(":");
2220
+ const prefix = separator < 0 ? "" : name.slice(0, separator);
2221
+ const localName = name.slice(separator + 1);
2222
+ const children = Array.isArray(value) ? value : [value];
2223
+ for (const child of children) {
2224
+ const object = typeof child === "object" && child !== null ? child : {};
2225
+ const namespace = object[prefix ? `@_xmlns:${prefix}` : "@_xmlns"] ?? namespaces[prefix];
2226
+ const match = typeof namespace === "string" ? GEXF_NAMESPACE.exec(namespace) : null;
2227
+ const key = match ? `${match[1] ? "viz:" : ""}${localName}` : namespace || prefix ? `foreign:${name}` : localName;
2228
+ const childValue = typeof child === "object" && child !== null ? match || !namespace && !prefix ? normalizeNamespaces(object, namespaces) : object : child;
2229
+ if (normalized[key] === void 0) normalized[key] = childValue;
2230
+ else
2231
+ normalized[key] = [
2232
+ ...Array.isArray(normalized[key]) ? normalized[key] : [normalized[key]],
2233
+ childValue
2234
+ ];
2235
+ }
2236
+ }
2237
+ assertStaticElement(normalized);
2238
+ return normalized;
2239
+ }
2240
+ function assertStaticElement(element) {
2241
+ if (element["@_mode"] !== void 0 && element["@_mode"] !== "static" || TEMPORAL_ATTRIBUTES.some((name) => element[`@_${name}`] !== void 0) || element.spells !== void 0) {
2242
+ throw new Error("Dynamic GEXF graphs and temporal values are unsupported.");
2243
+ }
2244
+ if (element["@_pid"] !== void 0 || element.parents !== void 0 || element["@_id"] !== void 0 && (element.nodes !== void 0 || element.edges !== void 0)) {
2245
+ throw new Error("Hierarchical GEXF graphs are unsupported.");
2246
+ }
2247
+ }
2248
+ function getElement(value, name) {
2249
+ if (value === "") return {};
2250
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
2251
+ throw new Error(`GEXF requires one <${name}> element.`);
2252
+ }
2253
+ function readTextContent(value) {
2254
+ if (typeof value === "string") return value;
2255
+ const text = getElement(value, "text")["#text"];
2256
+ return typeof text === "string" ? text : "";
2257
+ }
2258
+ function getContainer(value) {
2259
+ return value === void 0 ? {} : getElement(value, "container");
2260
+ }
2261
+ function getElements(value) {
2262
+ if (value === void 0) return [];
2263
+ return (Array.isArray(value) ? value : [value]).map((entry) => getElement(entry, "record"));
2264
+ }
2265
+ function requireAttribute(element, name) {
2266
+ const value = element[`@_${name}`];
2267
+ if (typeof value !== "string" || value === "")
2268
+ throw new Error(`GEXF requires a ${name} attribute.`);
2269
+ return value;
2270
+ }
2271
+ function parseDirection(value) {
2272
+ if (value !== "directed" && value !== "undirected")
2273
+ throw new Error(`Unsupported GEXF edge type: ${String(value)}`);
2274
+ return value === "directed";
2275
+ }
2276
+ function parseAttributeType(value) {
2277
+ if (value.startsWith("list") && !value.slice(4).startsWith("list")) {
2278
+ return { list: parseAttributeType(value.slice(4)) };
2279
+ }
2280
+ if (value === "integer" || value === "byte" || value === "short") return "int";
2281
+ if (value === "boolean" || value === "long" || value === "float" || value === "double")
2282
+ return value;
2283
+ if (["string", "anyURI", "date", "char", "bigdecimal", "biginteger"].includes(value))
2284
+ return "string";
2285
+ throw new Error(`Unsupported GEXF attribute type: ${value}`);
2286
+ }
2287
+ function castValue(text, type) {
2288
+ if (typeof type === "object") {
2289
+ return parseListValues(text).map((value) => castValue(value, type.list));
2290
+ }
2291
+ if (type === "string") return text;
2292
+ const trimmed = text.trim();
2293
+ if (type === "boolean") {
2294
+ if (trimmed === "true" || trimmed === "1") return true;
2295
+ if (trimmed === "false" || trimmed === "0") return false;
2296
+ return text;
2297
+ }
2298
+ if (type === "int" || type === "long") {
2299
+ if (!/^[+-]?\d+$/.test(trimmed)) return text;
2300
+ return type === "long" ? BigInt(trimmed) : Number.isSafeInteger(Number(trimmed)) ? Number(trimmed) : text;
2301
+ }
2302
+ if (trimmed === "INF") return Infinity;
2303
+ if (trimmed === "-INF") return -Infinity;
2304
+ if (trimmed === "NaN") return NaN;
2305
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(trimmed)) return text;
2306
+ const number = Number(trimmed);
2307
+ const represented = type === "float" ? Math.fround(number) : number;
2308
+ const nonzero = /[1-9]/.test(trimmed.split(/[eE]/)[0]);
2309
+ return Number.isFinite(represented) && (represented !== 0 || !nonzero) ? number : text;
2310
+ }
2311
+ function parseListValues(text) {
2312
+ const trimmed = text.trim();
2313
+ const bracketed = trimmed.startsWith("[");
2314
+ if (bracketed !== trimmed.endsWith("]")) throw new Error("Invalid GEXF list brackets.");
2315
+ const contents = bracketed ? trimmed.slice(1, -1) : trimmed;
2316
+ if (!contents.trim()) return [];
2317
+ const values = [];
2318
+ let value = "";
2319
+ let quote = "";
2320
+ let quoted = false;
2321
+ let closed = false;
2322
+ for (let index = 0; index < contents.length; index++) {
2323
+ const character = contents[index];
2324
+ if (quote) {
2325
+ if (character === "\\" && (contents[index + 1] === quote || contents[index + 1] === "\\")) {
2326
+ value += contents[++index];
2327
+ } else if (character === quote) {
2328
+ quote = "";
2329
+ closed = true;
2330
+ } else value += character;
2331
+ } else if (character === "," || !bracketed && (character === "|" || character === ";")) {
2332
+ values.push(quoted ? value : value.trim());
2333
+ value = "";
2334
+ quoted = false;
2335
+ closed = false;
2336
+ } else if (closed) {
2337
+ if (character.trim()) throw new Error("Invalid GEXF list text after a quote.");
2338
+ } else if ((character === "'" || character === '"') && !value.trim()) {
2339
+ quote = character;
2340
+ quoted = true;
2341
+ value = "";
2342
+ } else value += character;
2343
+ }
2344
+ if (quote) throw new Error("Unterminated GEXF list quote.");
2345
+ values.push(quoted ? value : value.trim());
2346
+ return values;
2347
+ }
2348
+ function parseRecord(element, definitions, identifier) {
2349
+ const attributes = /* @__PURE__ */ Object.create(null);
2350
+ for (const definition of definitions.values()) {
2351
+ if (definition.defaultValue !== void 0)
2352
+ attributes[definition.name] = Array.isArray(definition.defaultValue) ? [...definition.defaultValue] : definition.defaultValue;
2353
+ }
2354
+ for (const attvalue of getElements(getContainer(element.attvalues).attvalue)) {
2355
+ const key = requireAttribute(attvalue, "for");
2356
+ const definition = definitions.get(key);
2357
+ if (!definition) throw new Error(`Undeclared GEXF attribute: ${key}`);
2358
+ attributes[definition.name] = castValue(requireValue(attvalue), definition.type);
2359
+ }
2360
+ const native = /* @__PURE__ */ Object.create(null);
2361
+ if (element["@_weight"] !== void 0)
2362
+ native.weight = castValue(String(element["@_weight"]), "double");
2363
+ if (element["@_kind"] !== void 0) native.kind = element["@_kind"];
2364
+ const visualization = /* @__PURE__ */ Object.create(null);
2365
+ for (const name of ["color", "position", "size", "shape", "thickness"]) {
2366
+ const value = element[`viz:${name}`];
2367
+ if (value === void 0) continue;
2368
+ const properties = /* @__PURE__ */ Object.create(null);
2369
+ for (const [key, property] of Object.entries(getElement(value, `viz:${name}`))) {
2370
+ if (key.startsWith("@_") && !key.startsWith("@_xmlns")) {
2371
+ const propertyName = key.slice(2);
2372
+ properties[propertyName] = ["r", "g", "b", "a", "x", "y", "z"].includes(propertyName) || propertyName === "value" && (name === "size" || name === "thickness") ? castValue(String(property), "double") : property;
2373
+ }
2374
+ }
2375
+ visualization[name] = properties;
2376
+ }
2377
+ if (Object.keys(visualization).length) native.viz = visualization;
2378
+ if (Object.keys(native).length) attributes.gexf = native;
2379
+ return {
2380
+ id: identifier ?? requireAttribute(element, "id"),
2381
+ label: element["@_label"],
2382
+ attributes
2383
+ };
2384
+ }
2385
+ function requireValue(element) {
2386
+ const value = element["@_value"];
2387
+ if (typeof value !== "string") throw new Error("GEXF attvalue requires a value attribute.");
2388
+ return value;
2389
+ }
2390
+ var XML_OPTIONS, GEXF_NAMESPACE, TEMPORAL_ATTRIBUTES;
2391
+ var init_parse_gexf = __esm({
2392
+ "src/lib/parse-gexf.ts"() {
2393
+ "use strict";
2394
+ init_xml_parser();
2395
+ init_build_graph_tables();
2396
+ XML_OPTIONS = {
2397
+ ignoreAttributes: false,
2398
+ parseAttributeValue: false,
2399
+ parseTagValue: false,
2400
+ trimValues: false,
2401
+ attributeNamePrefix: "@_",
2402
+ textNodeName: "#text"
2403
+ };
2404
+ GEXF_NAMESPACE = /^https?:\/\/(?:www\.)?gexf.net\/1\.(?:2(?:draft)?|3)(\/viz)?$/;
2405
+ TEMPORAL_ATTRIBUTES = [
2406
+ "start",
2407
+ "end",
2408
+ "startopen",
2409
+ "endopen",
2410
+ "timestamp",
2411
+ "timestamps",
2412
+ "intervals"
2413
+ ];
2414
+ }
2415
+ });
2416
+
2417
+ // src/gexf-loader.ts
2418
+ var gexf_loader_exports = {};
2419
+ __export(gexf_loader_exports, {
2420
+ GEXFLoaderWithParser: () => GEXFLoaderWithParser
2421
+ });
2422
+ var GEXFLoaderWithParser;
2423
+ var init_gexf_loader = __esm({
2424
+ "src/gexf-loader.ts"() {
2425
+ "use strict";
2426
+ init_gexf_loader_types();
2427
+ init_parse_gexf();
2428
+ GEXFLoaderWithParser = {
2429
+ ...GEXFLoader,
2430
+ parse: async (data, options) => {
2431
+ var _a;
2432
+ return parseGEXF(data, ((_a = options == null ? void 0 : options.gexf) == null ? void 0 : _a.shape) ?? "arrow-table");
2433
+ },
2434
+ parseSync: (data, options) => {
2435
+ var _a;
2436
+ return parseGEXF(data, ((_a = options == null ? void 0 : options.gexf) == null ? void 0 : _a.shape) ?? "arrow-table");
2437
+ },
2438
+ parseTextSync: (data, options) => {
2439
+ var _a;
2440
+ return parseGEXF(data, ((_a = options == null ? void 0 : options.gexf) == null ? void 0 : _a.shape) ?? "arrow-table");
2441
+ }
2442
+ };
2443
+ }
2444
+ });
2445
+
2446
+ // dist/gexf-loader.js
2447
+ var gexf_loader_exports2 = {};
2448
+ __export(gexf_loader_exports2, {
2449
+ GEXFLoaderWithParser: () => GEXFLoaderWithParser2
2450
+ });
2451
+ module.exports = __toCommonJS(gexf_loader_exports2);
2452
+
2453
+ // dist/gexf-loader-types.js
2454
+ var VERSION2 = true ? "5.0.0-beta.2" : "latest";
2455
+ async function preload2() {
2456
+ const { GEXFLoaderWithParser: GEXFLoaderWithParser3 } = await Promise.resolve().then(() => (init_gexf_loader(), gexf_loader_exports));
2457
+ return GEXFLoaderWithParser3;
2458
+ }
2459
+ var GEXFLoader2 = {
2460
+ name: "GEXF",
2461
+ id: "gexf",
2462
+ module: "graphs",
2463
+ version: VERSION2,
2464
+ extensions: ["gexf"],
2465
+ mimeTypes: ["application/gexf+xml"],
2466
+ text: true,
2467
+ worker: false,
2468
+ dataType: null,
2469
+ batchType: null,
2470
+ options: { gexf: { shape: "arrow-table" } },
2471
+ preload: preload2
2472
+ };
2473
+
2474
+ // dist/lib/parse-gexf.js
2475
+ init_xml_parser();
2476
+
2477
+ // dist/lib/build-graph-tables.js
2478
+ var import_apache_arrow2 = require("apache-arrow");
2479
+ init_schema_utils();
2480
+ function buildGraphTables2(nodes, edges, shape, declarations) {
2481
+ if (shape === "plain-graph-data") {
2482
+ return { shape, nodes: Array.from(nodes), edges: Array.from(edges) };
2483
+ }
2484
+ if (shape !== "arrow-table" && shape !== "object-row-table") {
2485
+ throw new Error(`Unsupported graph shape: ${shape}`);
2486
+ }
2487
+ const nodeTable = buildGraphTable2(nodes, false, shape, declarations == null ? void 0 : declarations.nodes);
2488
+ const edgeTable = buildGraphTable2(edges, true, shape, declarations == null ? void 0 : declarations.edges);
2489
+ return {
2490
+ shape: "tables",
2491
+ tables: [
2492
+ { name: "nodes", table: nodeTable },
2493
+ { name: "edges", table: edgeTable }
2494
+ ]
2495
+ };
2496
+ }
2497
+ function buildGraphTable2(records, isEdge, shape, declarations) {
2498
+ const columnNames = isEdge ? ["id", "sourceId", "targetId", "directed", "label", "attributes"] : ["id", "label", "attributes"];
2499
+ const columns = new Map(columnNames.map((name) => [name, []]));
2500
+ for (const record of records) {
2501
+ for (const name of columnNames) {
2502
+ const value = record[name];
2503
+ columns.get(name).push(name === "id" || name === "sourceId" || name === "targetId" ? String(value) : value ?? null);
2504
+ }
2505
+ }
2506
+ if (shape === "object-row-table") {
2507
+ return {
2508
+ shape,
2509
+ data: columns.get("id").map((_, index) => Object.fromEntries(columnNames.map((name) => [name, columns.get(name)[index]])))
2510
+ };
2511
+ }
2512
+ const vectors = /* @__PURE__ */ Object.create(null);
2513
+ for (const [name, values] of columns) {
2514
+ const type = name === "attributes" ? inferAttributeType2(values, declarations) : name === "directed" ? new import_apache_arrow2.Bool() : new import_apache_arrow2.Utf8();
2515
+ vectors[name] = (0, import_apache_arrow2.vectorFromArray)(values.map((value) => normalizeValue2(value, type)), type);
2516
+ }
2517
+ const data = new import_apache_arrow2.Table(vectors);
2518
+ return { shape, schema: convertArrowToSchema(data.schema), data };
2519
+ }
2520
+ function inferAttributeType2(values, declarations) {
2521
+ const names = new Set(declarations == null ? void 0 : declarations.keys());
2522
+ for (const value of values) {
2523
+ if (value && typeof value === "object") {
2524
+ for (const name of Object.keys(value)) {
2525
+ names.add(name);
2526
+ }
2527
+ }
2528
+ }
2529
+ return new import_apache_arrow2.Struct(Array.from(names, (name) => {
2530
+ const fieldValues = values.map((value) => (value == null ? void 0 : value[name]) ?? null);
2531
+ return new import_apache_arrow2.Field(name, inferValueType2(fieldValues, declarations == null ? void 0 : declarations.get(name)), true);
2532
+ }));
2533
+ }
2534
+ function inferValueType2(values, declaration) {
2535
+ const present = values.filter((value) => value !== null && value !== void 0);
2536
+ if (declaration && typeof declaration === "object") {
2537
+ if (!present.every((value) => Array.isArray(value)))
2538
+ return new import_apache_arrow2.Utf8();
2539
+ return new import_apache_arrow2.List(new import_apache_arrow2.Field("item", inferValueType2(present.flatMap((value) => value), declaration.list), true));
2540
+ }
2541
+ if (declaration) {
2542
+ const declaredTypes = {
2543
+ boolean: new import_apache_arrow2.Bool(),
2544
+ int: new import_apache_arrow2.Int32(),
2545
+ long: new import_apache_arrow2.Int64(),
2546
+ float: new import_apache_arrow2.Float32(),
2547
+ double: new import_apache_arrow2.Float64(),
2548
+ string: new import_apache_arrow2.Utf8()
2549
+ };
2550
+ const valid = present.every((value) => {
2551
+ switch (declaration) {
2552
+ case "boolean":
2553
+ return typeof value === "boolean";
2554
+ case "int":
2555
+ return typeof value === "number" && Number.isInteger(value) && value >= -2147483648 && value <= 2147483647;
2556
+ case "long":
2557
+ return typeof value === "bigint" && value >= -(2n ** 63n) && value < 2n ** 63n;
2558
+ case "float":
2559
+ case "double":
2560
+ return typeof value === "number";
2561
+ case "string":
2562
+ return typeof value === "string";
2563
+ }
2564
+ });
2565
+ return valid ? declaredTypes[declaration] : new import_apache_arrow2.Utf8();
2566
+ }
2567
+ if (present.length && present.every((value) => typeof value === "boolean"))
2568
+ return new import_apache_arrow2.Bool();
2569
+ if (present.length && present.every((value) => typeof value === "number"))
2570
+ return new import_apache_arrow2.Float64();
2571
+ if (present.length && present.every((value) => Array.isArray(value))) {
2572
+ return new import_apache_arrow2.List(new import_apache_arrow2.Field("item", inferValueType2(present.flatMap((value) => value)), true));
2573
+ }
2574
+ if (present.length && present.every((value) => typeof value === "object" && !Array.isArray(value))) {
2575
+ return inferAttributeType2(present);
2576
+ }
2577
+ return new import_apache_arrow2.Utf8();
2578
+ }
2579
+ function normalizeValue2(value, type) {
2580
+ if (value === null || value === void 0)
2581
+ return null;
2582
+ if (type instanceof import_apache_arrow2.Struct) {
2583
+ return Object.fromEntries(type.children.map((field) => [
2584
+ field.name,
2585
+ normalizeValue2(value[field.name], field.type)
2586
+ ]));
2587
+ }
2588
+ if (type instanceof import_apache_arrow2.List)
2589
+ return value.map((item) => normalizeValue2(item, type.valueType));
2590
+ if (type instanceof import_apache_arrow2.Utf8 && typeof value !== "string") {
2591
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
2592
+ }
2593
+ return value;
2594
+ }
2595
+
2596
+ // dist/lib/parse-gexf.js
2597
+ var XML_OPTIONS2 = {
2598
+ ignoreAttributes: false,
2599
+ parseAttributeValue: false,
2600
+ parseTagValue: false,
2601
+ trimValues: false,
2602
+ attributeNamePrefix: "@_",
2603
+ textNodeName: "#text"
2604
+ };
2605
+ var GEXF_NAMESPACE2 = /^https?:\/\/(?:www\.)?gexf.net\/1\.(?:2(?:draft)?|3)(\/viz)?$/;
2606
+ var TEMPORAL_ATTRIBUTES2 = [
2607
+ "start",
2608
+ "end",
2609
+ "startopen",
2610
+ "endopen",
2611
+ "timestamp",
2612
+ "timestamps",
2613
+ "intervals"
2614
+ ];
2615
+ function parseGEXF2(input, shape = "arrow-table") {
2616
+ const text = typeof input === "string" ? input : new TextDecoder().decode(input);
2617
+ const validation = validateXML(text);
2618
+ if (validation !== true)
2619
+ throw new Error(`Invalid GEXF XML: ${validation.message}`);
2620
+ if (/<!DOCTYPE\s/i.test(text))
2621
+ throw new Error("GEXF document types are unsupported.");
2622
+ const document = normalizeNamespaces2(parseXMLSync(text, XML_OPTIONS2), {});
2623
+ const root = getElement2(document.gexf, "gexf");
2624
+ const version = root["@_version"];
2625
+ if (version && !["1.2", "1.2draft", "1.3"].includes(version)) {
2626
+ throw new Error(`Unsupported GEXF version: ${version}`);
2627
+ }
2628
+ const graph = getElement2(root.graph, "graph");
2629
+ const directed = parseDirection2(graph["@_defaultedgetype"] ?? "undirected");
2630
+ const definitions = {
2631
+ nodes: /* @__PURE__ */ new Map(),
2632
+ edges: /* @__PURE__ */ new Map()
2633
+ };
2634
+ for (const attributes of getElements2(graph.attributes)) {
2635
+ const domain = attributes["@_class"];
2636
+ if (domain !== "node" && domain !== "edge")
2637
+ throw new Error("GEXF attributes require a node or edge class.");
2638
+ const scoped = domain === "node" ? definitions.nodes : definitions.edges;
2639
+ const names = new Set(Array.from(scoped.values(), (definition) => definition.name));
2640
+ for (const attribute of getElements2(attributes.attribute)) {
2641
+ const identifier = requireAttribute2(attribute, "id");
2642
+ const name = requireAttribute2(attribute, "title");
2643
+ if (name === "gexf" || names.has(name) || scoped.has(identifier)) {
2644
+ throw new Error(`Duplicate or reserved GEXF attribute: ${name}`);
2645
+ }
2646
+ names.add(name);
2647
+ const type = parseAttributeType2(requireAttribute2(attribute, "type"));
2648
+ scoped.set(identifier, {
2649
+ name,
2650
+ type,
2651
+ defaultValue: attribute.default === void 0 ? void 0 : castValue2(readTextContent2(attribute.default), type)
2652
+ });
2653
+ }
2654
+ }
2655
+ const nodeElements = getElements2(getContainer2(graph.nodes).node);
2656
+ const edgeElements = getElements2(getContainer2(graph.edges).edge);
2657
+ const nodeIdentifiers = /* @__PURE__ */ new Set();
2658
+ for (const node of nodeElements) {
2659
+ const identifier = requireAttribute2(node, "id");
2660
+ if (nodeIdentifiers.has(identifier))
2661
+ throw new Error(`Duplicate GEXF node ID: ${identifier}`);
2662
+ nodeIdentifiers.add(identifier);
2663
+ }
2664
+ const edgeIdentifiers = new Set(edgeElements.map((edge) => edge["@_id"]).filter((identifier) => typeof identifier === "string"));
2665
+ const seenEdges = /* @__PURE__ */ new Set();
2666
+ function* iterateNodes() {
2667
+ for (const node of nodeElements)
2668
+ yield parseRecord2(node, definitions.nodes);
2669
+ }
2670
+ function* iterateEdges() {
2671
+ for (const [index, edge] of edgeElements.entries()) {
2672
+ const sourceId = requireAttribute2(edge, "source");
2673
+ const targetId = requireAttribute2(edge, "target");
2674
+ if (!nodeIdentifiers.has(sourceId) || !nodeIdentifiers.has(targetId)) {
2675
+ throw new Error("GEXF edge references an undeclared node.");
2676
+ }
2677
+ let identifier = edge["@_id"] === void 0 ? void 0 : requireAttribute2(edge, "id");
2678
+ if (identifier === void 0) {
2679
+ identifier = `edge-${index}`;
2680
+ while (edgeIdentifiers.has(identifier))
2681
+ identifier = `_${identifier}`;
2682
+ edgeIdentifiers.add(identifier);
2683
+ }
2684
+ if (seenEdges.has(identifier))
2685
+ throw new Error(`Duplicate GEXF edge ID: ${identifier}`);
2686
+ seenEdges.add(identifier);
2687
+ yield {
2688
+ ...parseRecord2(edge, definitions.edges, identifier),
2689
+ sourceId,
2690
+ targetId,
2691
+ directed: edge["@_type"] === void 0 ? directed : parseDirection2(edge["@_type"])
2692
+ };
2693
+ }
2694
+ }
2695
+ const metadataAttributes = /* @__PURE__ */ Object.create(null);
2696
+ const meta = getContainer2(root.meta);
2697
+ for (const name of ["creator", "description", "keywords"]) {
2698
+ if (meta[name] !== void 0)
2699
+ metadataAttributes[name] = readTextContent2(meta[name]);
2700
+ }
2701
+ if (typeof meta["@_lastmodifieddate"] === "string")
2702
+ metadataAttributes.lastmodifieddate = meta["@_lastmodifieddate"];
2703
+ const declarations = {
2704
+ nodes: new Map(Array.from(definitions.nodes.values(), (definition) => [definition.name, definition.type])),
2705
+ edges: new Map(Array.from(definitions.edges.values(), (definition) => [definition.name, definition.type]))
2706
+ };
2707
+ return {
2708
+ ...buildGraphTables2(iterateNodes(), iterateEdges(), shape, declarations),
2709
+ metadata: { version, directed, attributes: metadataAttributes }
2710
+ };
2711
+ }
2712
+ function normalizeNamespaces2(element, inherited) {
2713
+ const namespaces = Object.assign(/* @__PURE__ */ Object.create(null), inherited);
2714
+ for (const [name, value] of Object.entries(element)) {
2715
+ if (name === "@_xmlns")
2716
+ namespaces[""] = String(value);
2717
+ else if (name.startsWith("@_xmlns:"))
2718
+ namespaces[name.slice(8)] = String(value);
2719
+ }
2720
+ const normalized = /* @__PURE__ */ Object.create(null);
2721
+ for (const [name, value] of Object.entries(element)) {
2722
+ if (name.startsWith("@_") || name === "#text" || name.startsWith("?")) {
2723
+ normalized[name] = value;
2724
+ continue;
2725
+ }
2726
+ const separator = name.indexOf(":");
2727
+ const prefix = separator < 0 ? "" : name.slice(0, separator);
2728
+ const localName = name.slice(separator + 1);
2729
+ const children = Array.isArray(value) ? value : [value];
2730
+ for (const child of children) {
2731
+ const object = typeof child === "object" && child !== null ? child : {};
2732
+ const namespace = object[prefix ? `@_xmlns:${prefix}` : "@_xmlns"] ?? namespaces[prefix];
2733
+ const match = typeof namespace === "string" ? GEXF_NAMESPACE2.exec(namespace) : null;
2734
+ const key = match ? `${match[1] ? "viz:" : ""}${localName}` : namespace || prefix ? `foreign:${name}` : localName;
2735
+ const childValue = typeof child === "object" && child !== null ? match || !namespace && !prefix ? normalizeNamespaces2(object, namespaces) : object : child;
2736
+ if (normalized[key] === void 0)
2737
+ normalized[key] = childValue;
2738
+ else
2739
+ normalized[key] = [
2740
+ ...Array.isArray(normalized[key]) ? normalized[key] : [normalized[key]],
2741
+ childValue
2742
+ ];
2743
+ }
2744
+ }
2745
+ assertStaticElement2(normalized);
2746
+ return normalized;
2747
+ }
2748
+ function assertStaticElement2(element) {
2749
+ if (element["@_mode"] !== void 0 && element["@_mode"] !== "static" || TEMPORAL_ATTRIBUTES2.some((name) => element[`@_${name}`] !== void 0) || element.spells !== void 0) {
2750
+ throw new Error("Dynamic GEXF graphs and temporal values are unsupported.");
2751
+ }
2752
+ if (element["@_pid"] !== void 0 || element.parents !== void 0 || element["@_id"] !== void 0 && (element.nodes !== void 0 || element.edges !== void 0)) {
2753
+ throw new Error("Hierarchical GEXF graphs are unsupported.");
2754
+ }
2755
+ }
2756
+ function getElement2(value, name) {
2757
+ if (value === "")
2758
+ return {};
2759
+ if (value && typeof value === "object" && !Array.isArray(value))
2760
+ return value;
2761
+ throw new Error(`GEXF requires one <${name}> element.`);
2762
+ }
2763
+ function readTextContent2(value) {
2764
+ if (typeof value === "string")
2765
+ return value;
2766
+ const text = getElement2(value, "text")["#text"];
2767
+ return typeof text === "string" ? text : "";
2768
+ }
2769
+ function getContainer2(value) {
2770
+ return value === void 0 ? {} : getElement2(value, "container");
2771
+ }
2772
+ function getElements2(value) {
2773
+ if (value === void 0)
2774
+ return [];
2775
+ return (Array.isArray(value) ? value : [value]).map((entry) => getElement2(entry, "record"));
2776
+ }
2777
+ function requireAttribute2(element, name) {
2778
+ const value = element[`@_${name}`];
2779
+ if (typeof value !== "string" || value === "")
2780
+ throw new Error(`GEXF requires a ${name} attribute.`);
2781
+ return value;
2782
+ }
2783
+ function parseDirection2(value) {
2784
+ if (value !== "directed" && value !== "undirected")
2785
+ throw new Error(`Unsupported GEXF edge type: ${String(value)}`);
2786
+ return value === "directed";
2787
+ }
2788
+ function parseAttributeType2(value) {
2789
+ if (value.startsWith("list") && !value.slice(4).startsWith("list")) {
2790
+ return { list: parseAttributeType2(value.slice(4)) };
2791
+ }
2792
+ if (value === "integer" || value === "byte" || value === "short")
2793
+ return "int";
2794
+ if (value === "boolean" || value === "long" || value === "float" || value === "double")
2795
+ return value;
2796
+ if (["string", "anyURI", "date", "char", "bigdecimal", "biginteger"].includes(value))
2797
+ return "string";
2798
+ throw new Error(`Unsupported GEXF attribute type: ${value}`);
2799
+ }
2800
+ function castValue2(text, type) {
2801
+ if (typeof type === "object") {
2802
+ return parseListValues2(text).map((value) => castValue2(value, type.list));
2803
+ }
2804
+ if (type === "string")
2805
+ return text;
2806
+ const trimmed = text.trim();
2807
+ if (type === "boolean") {
2808
+ if (trimmed === "true" || trimmed === "1")
2809
+ return true;
2810
+ if (trimmed === "false" || trimmed === "0")
2811
+ return false;
2812
+ return text;
2813
+ }
2814
+ if (type === "int" || type === "long") {
2815
+ if (!/^[+-]?\d+$/.test(trimmed))
2816
+ return text;
2817
+ return type === "long" ? BigInt(trimmed) : Number.isSafeInteger(Number(trimmed)) ? Number(trimmed) : text;
2818
+ }
2819
+ if (trimmed === "INF")
2820
+ return Infinity;
2821
+ if (trimmed === "-INF")
2822
+ return -Infinity;
2823
+ if (trimmed === "NaN")
2824
+ return NaN;
2825
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(trimmed))
2826
+ return text;
2827
+ const number = Number(trimmed);
2828
+ const represented = type === "float" ? Math.fround(number) : number;
2829
+ const nonzero = /[1-9]/.test(trimmed.split(/[eE]/)[0]);
2830
+ return Number.isFinite(represented) && (represented !== 0 || !nonzero) ? number : text;
2831
+ }
2832
+ function parseListValues2(text) {
2833
+ const trimmed = text.trim();
2834
+ const bracketed = trimmed.startsWith("[");
2835
+ if (bracketed !== trimmed.endsWith("]"))
2836
+ throw new Error("Invalid GEXF list brackets.");
2837
+ const contents = bracketed ? trimmed.slice(1, -1) : trimmed;
2838
+ if (!contents.trim())
2839
+ return [];
2840
+ const values = [];
2841
+ let value = "";
2842
+ let quote = "";
2843
+ let quoted = false;
2844
+ let closed = false;
2845
+ for (let index = 0; index < contents.length; index++) {
2846
+ const character = contents[index];
2847
+ if (quote) {
2848
+ if (character === "\\" && (contents[index + 1] === quote || contents[index + 1] === "\\")) {
2849
+ value += contents[++index];
2850
+ } else if (character === quote) {
2851
+ quote = "";
2852
+ closed = true;
2853
+ } else
2854
+ value += character;
2855
+ } else if (character === "," || !bracketed && (character === "|" || character === ";")) {
2856
+ values.push(quoted ? value : value.trim());
2857
+ value = "";
2858
+ quoted = false;
2859
+ closed = false;
2860
+ } else if (closed) {
2861
+ if (character.trim())
2862
+ throw new Error("Invalid GEXF list text after a quote.");
2863
+ } else if ((character === "'" || character === '"') && !value.trim()) {
2864
+ quote = character;
2865
+ quoted = true;
2866
+ value = "";
2867
+ } else
2868
+ value += character;
2869
+ }
2870
+ if (quote)
2871
+ throw new Error("Unterminated GEXF list quote.");
2872
+ values.push(quoted ? value : value.trim());
2873
+ return values;
2874
+ }
2875
+ function parseRecord2(element, definitions, identifier) {
2876
+ const attributes = /* @__PURE__ */ Object.create(null);
2877
+ for (const definition of definitions.values()) {
2878
+ if (definition.defaultValue !== void 0)
2879
+ attributes[definition.name] = Array.isArray(definition.defaultValue) ? [...definition.defaultValue] : definition.defaultValue;
2880
+ }
2881
+ for (const attvalue of getElements2(getContainer2(element.attvalues).attvalue)) {
2882
+ const key = requireAttribute2(attvalue, "for");
2883
+ const definition = definitions.get(key);
2884
+ if (!definition)
2885
+ throw new Error(`Undeclared GEXF attribute: ${key}`);
2886
+ attributes[definition.name] = castValue2(requireValue2(attvalue), definition.type);
2887
+ }
2888
+ const native = /* @__PURE__ */ Object.create(null);
2889
+ if (element["@_weight"] !== void 0)
2890
+ native.weight = castValue2(String(element["@_weight"]), "double");
2891
+ if (element["@_kind"] !== void 0)
2892
+ native.kind = element["@_kind"];
2893
+ const visualization = /* @__PURE__ */ Object.create(null);
2894
+ for (const name of ["color", "position", "size", "shape", "thickness"]) {
2895
+ const value = element[`viz:${name}`];
2896
+ if (value === void 0)
2897
+ continue;
2898
+ const properties = /* @__PURE__ */ Object.create(null);
2899
+ for (const [key, property] of Object.entries(getElement2(value, `viz:${name}`))) {
2900
+ if (key.startsWith("@_") && !key.startsWith("@_xmlns")) {
2901
+ const propertyName = key.slice(2);
2902
+ properties[propertyName] = ["r", "g", "b", "a", "x", "y", "z"].includes(propertyName) || propertyName === "value" && (name === "size" || name === "thickness") ? castValue2(String(property), "double") : property;
2903
+ }
2904
+ }
2905
+ visualization[name] = properties;
2906
+ }
2907
+ if (Object.keys(visualization).length)
2908
+ native.viz = visualization;
2909
+ if (Object.keys(native).length)
2910
+ attributes.gexf = native;
2911
+ return {
2912
+ id: identifier ?? requireAttribute2(element, "id"),
2913
+ label: element["@_label"],
2914
+ attributes
2915
+ };
2916
+ }
2917
+ function requireValue2(element) {
2918
+ const value = element["@_value"];
2919
+ if (typeof value !== "string")
2920
+ throw new Error("GEXF attvalue requires a value attribute.");
2921
+ return value;
2922
+ }
2923
+
2924
+ // dist/gexf-loader.js
2925
+ var GEXFLoaderWithParser2 = {
2926
+ ...GEXFLoader2,
2927
+ parse: async (data, options) => {
2928
+ var _a;
2929
+ return parseGEXF2(data, ((_a = options == null ? void 0 : options.gexf) == null ? void 0 : _a.shape) ?? "arrow-table");
2930
+ },
2931
+ parseSync: (data, options) => {
2932
+ var _a;
2933
+ return parseGEXF2(data, ((_a = options == null ? void 0 : options.gexf) == null ? void 0 : _a.shape) ?? "arrow-table");
2934
+ },
2935
+ parseTextSync: (data, options) => {
2936
+ var _a;
2937
+ return parseGEXF2(data, ((_a = options == null ? void 0 : options.gexf) == null ? void 0 : _a.shape) ?? "arrow-table");
2938
+ }
2939
+ };
2940
+ //# sourceMappingURL=gexf-loader.cjs.map