@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
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __esm = (fn, res, err) => function __init() {
7
9
  if (err) throw err[0];
@@ -23,6 +25,14 @@ var __copyProps = (to, from, except, desc) => {
23
25
  }
24
26
  return to;
25
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
+ ));
26
36
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
37
 
28
38
  // src/graphml-loader-types.ts
@@ -46,16 +56,2053 @@ var init_graphml_loader_types = __esm({
46
56
  worker: false,
47
57
  dataType: null,
48
58
  batchType: null,
49
- options: {},
59
+ options: { graphml: { shape: "arrow-table" } },
50
60
  preload
51
61
  };
52
62
  }
53
63
  });
54
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
+ var init_parse_xml = __esm({
1674
+ "../documents/src/lib/parsers/parse-xml.ts"() {
1675
+ "use strict";
1676
+ init_uncapitalize();
1677
+ init_parse_xml_internal();
1678
+ }
1679
+ });
1680
+
1681
+ // ../documents/src/xml-parser.ts
1682
+ var init_xml_parser = __esm({
1683
+ "../documents/src/xml-parser.ts"() {
1684
+ "use strict";
1685
+ init_parse_xml();
1686
+ }
1687
+ });
1688
+
1689
+ // ../core/src/schema-utils/lib/schema/convert-arrow-schema.ts
1690
+ function convertArrowToSchema(arrowSchema) {
1691
+ return serializeArrowSchema(arrowSchema);
1692
+ }
1693
+ function serializeArrowSchema(arrowSchema) {
1694
+ return {
1695
+ fields: arrowSchema.fields.map((arrowField) => serializeArrowField(arrowField)),
1696
+ metadata: serializeArrowMetadata(arrowSchema.metadata)
1697
+ };
1698
+ }
1699
+ function serializeArrowMetadata(arrowMetadata) {
1700
+ return Object.fromEntries(arrowMetadata);
1701
+ }
1702
+ function serializeArrowField(field) {
1703
+ return {
1704
+ name: field.name,
1705
+ type: serializeArrowType(field.type),
1706
+ nullable: field.nullable,
1707
+ metadata: serializeArrowMetadata(field.metadata)
1708
+ };
1709
+ }
1710
+ function serializeArrowType(arrowType) {
1711
+ if (isArrowViewType(arrowType, "BinaryView")) {
1712
+ return "binary-view";
1713
+ }
1714
+ if (isArrowViewType(arrowType, "Utf8View")) {
1715
+ return "utf8-view";
1716
+ }
1717
+ if (isOptionalArrowType(arrowType, "LargeList")) {
1718
+ const largeListType = arrowType;
1719
+ return {
1720
+ type: "large-list",
1721
+ children: [serializeArrowField(largeListType.valueField)]
1722
+ };
1723
+ }
1724
+ switch (arrowType.constructor) {
1725
+ case arrow.Null:
1726
+ return "null";
1727
+ case arrow.Binary:
1728
+ return "binary";
1729
+ case arrow.FixedSizeBinary:
1730
+ return {
1731
+ type: "fixed-size-binary",
1732
+ byteWidth: arrowType.byteWidth
1733
+ };
1734
+ case arrow.Bool:
1735
+ return "bool";
1736
+ case arrow.Int:
1737
+ const intType = arrowType;
1738
+ return `${intType.isSigned ? "" : "u"}int${intType.bitWidth}`;
1739
+ case arrow.Int8:
1740
+ return "int8";
1741
+ case arrow.Int16:
1742
+ return "int16";
1743
+ case arrow.Int32:
1744
+ return "int32";
1745
+ case arrow.Int64:
1746
+ return "int64";
1747
+ case arrow.Uint8:
1748
+ return "uint8";
1749
+ case arrow.Uint16:
1750
+ return "uint16";
1751
+ case arrow.Uint32:
1752
+ return "uint32";
1753
+ case arrow.Uint64:
1754
+ return "uint64";
1755
+ case arrow.Float:
1756
+ const precision = arrowType.precision;
1757
+ switch (precision) {
1758
+ case arrow.Precision.HALF:
1759
+ return "float16";
1760
+ case arrow.Precision.SINGLE:
1761
+ return "float32";
1762
+ case arrow.Precision.DOUBLE:
1763
+ return "float64";
1764
+ default:
1765
+ return "float16";
1766
+ }
1767
+ case arrow.Float16:
1768
+ return "float16";
1769
+ case arrow.Float32:
1770
+ return "float32";
1771
+ case arrow.Float64:
1772
+ return "float64";
1773
+ case arrow.Utf8:
1774
+ return "utf8";
1775
+ case arrow.Decimal:
1776
+ const decimal = arrowType;
1777
+ return {
1778
+ type: "decimal",
1779
+ bitWidth: decimal.bitWidth,
1780
+ precision: decimal.precision,
1781
+ scale: decimal.scale
1782
+ };
1783
+ case arrow.Date_:
1784
+ const dateUnit = arrowType.unit;
1785
+ return dateUnit === arrow.DateUnit.DAY ? "date-day" : "date-millisecond";
1786
+ case arrow.DateDay:
1787
+ return "date-day";
1788
+ case arrow.DateMillisecond:
1789
+ return "date-millisecond";
1790
+ case arrow.Time:
1791
+ const timeUnit = arrowType.unit;
1792
+ switch (timeUnit) {
1793
+ case arrow.TimeUnit.SECOND:
1794
+ return "time-second";
1795
+ case arrow.TimeUnit.MILLISECOND:
1796
+ return "time-millisecond";
1797
+ case arrow.TimeUnit.MICROSECOND:
1798
+ return "time-microsecond";
1799
+ case arrow.TimeUnit.NANOSECOND:
1800
+ return "time-nanosecond";
1801
+ default:
1802
+ return "time-second";
1803
+ }
1804
+ case arrow.TimeMillisecond:
1805
+ return "time-millisecond";
1806
+ case arrow.TimeSecond:
1807
+ return "time-second";
1808
+ case arrow.TimeMicrosecond:
1809
+ return "time-microsecond";
1810
+ case arrow.TimeNanosecond:
1811
+ return "time-nanosecond";
1812
+ case arrow.Timestamp:
1813
+ const timeStampUnit = arrowType.unit;
1814
+ switch (timeStampUnit) {
1815
+ case arrow.TimeUnit.SECOND:
1816
+ return "timestamp-second";
1817
+ case arrow.TimeUnit.MILLISECOND:
1818
+ return "timestamp-millisecond";
1819
+ case arrow.TimeUnit.MICROSECOND:
1820
+ return "timestamp-microsecond";
1821
+ case arrow.TimeUnit.NANOSECOND:
1822
+ return "timestamp-nanosecond";
1823
+ default:
1824
+ return "timestamp-second";
1825
+ }
1826
+ case arrow.TimestampSecond:
1827
+ return "timestamp-second";
1828
+ case arrow.TimestampMillisecond:
1829
+ return "timestamp-millisecond";
1830
+ case arrow.TimestampMicrosecond:
1831
+ return "timestamp-microsecond";
1832
+ case arrow.TimestampNanosecond:
1833
+ return "timestamp-nanosecond";
1834
+ case arrow.Interval:
1835
+ const intervalUnit = arrowType.unit;
1836
+ switch (intervalUnit) {
1837
+ case arrow.IntervalUnit.DAY_TIME:
1838
+ return "interval-daytime";
1839
+ case arrow.IntervalUnit.YEAR_MONTH:
1840
+ return "interval-yearmonth";
1841
+ default:
1842
+ return "interval-daytime";
1843
+ }
1844
+ case arrow.IntervalDayTime:
1845
+ return "interval-daytime";
1846
+ case arrow.IntervalYearMonth:
1847
+ return "interval-yearmonth";
1848
+ case arrow.Map_:
1849
+ const mapType = arrowType;
1850
+ return {
1851
+ type: "map",
1852
+ keysSorted: mapType.keysSorted,
1853
+ children: mapType.children.map((arrowField) => serializeArrowField(arrowField))
1854
+ };
1855
+ case arrow.List:
1856
+ const listType = arrowType;
1857
+ const listField = listType.valueField;
1858
+ return {
1859
+ type: "list",
1860
+ children: [serializeArrowField(listField)]
1861
+ };
1862
+ case arrow.FixedSizeList:
1863
+ const fixedSizeList = arrowType;
1864
+ return {
1865
+ type: "fixed-size-list",
1866
+ listSize: fixedSizeList.listSize,
1867
+ children: [serializeArrowField(fixedSizeList.children[0])]
1868
+ };
1869
+ case arrow.Struct:
1870
+ const structType = arrowType;
1871
+ return {
1872
+ type: "struct",
1873
+ children: structType.children.map((arrowField) => serializeArrowField(arrowField))
1874
+ };
1875
+ case arrow.SparseUnion:
1876
+ case arrow.DenseUnion:
1877
+ const unionType = arrowType;
1878
+ return {
1879
+ type: unionType instanceof arrow.DenseUnion ? "dense-union" : "sparse-union",
1880
+ typeIds: unionType.typeIds,
1881
+ children: unionType.children.map((arrowField) => serializeArrowField(arrowField)),
1882
+ typeIdToChildIndex: { ...unionType.typeIdToChildIndex }
1883
+ };
1884
+ case arrow.Dictionary:
1885
+ const dictionaryType = arrowType;
1886
+ return {
1887
+ type: "dictionary",
1888
+ id: dictionaryType.id,
1889
+ indices: serializeArrowDictionaryKeyType(dictionaryType.indices),
1890
+ dictionary: serializeArrowType(dictionaryType.dictionary),
1891
+ isOrdered: dictionaryType.isOrdered
1892
+ };
1893
+ default:
1894
+ throw new Error(`arrow type not supported: ${arrowType.constructor.name}`);
1895
+ }
1896
+ }
1897
+ function getOptionalArrowConstructor(typeName) {
1898
+ return arrow[typeName];
1899
+ }
1900
+ function isArrowViewType(arrowType, viewTypeName) {
1901
+ const constructor = getOptionalArrowConstructor(viewTypeName);
1902
+ if (constructor && arrowType instanceof constructor) {
1903
+ return true;
1904
+ }
1905
+ const guards = arrow.DataType;
1906
+ const guard = viewTypeName === "BinaryView" ? guards.isBinaryView : guards.isUtf8View;
1907
+ return Boolean(guard == null ? void 0 : guard(arrowType));
1908
+ }
1909
+ function isOptionalArrowType(arrowType, typeName) {
1910
+ const constructor = getOptionalArrowConstructor(typeName);
1911
+ return Boolean(constructor && arrowType instanceof constructor);
1912
+ }
1913
+ function serializeArrowDictionaryKeyType(arrowType) {
1914
+ if (arrowType instanceof arrow.Int) {
1915
+ const prefix = arrowType.isSigned ? "int" : "uint";
1916
+ const keyType = `${prefix}${arrowType.bitWidth}`;
1917
+ if (isSchemaDictionaryKeyType(keyType)) {
1918
+ return keyType;
1919
+ }
1920
+ }
1921
+ switch (arrowType.constructor) {
1922
+ case arrow.Int8:
1923
+ return "int8";
1924
+ case arrow.Int16:
1925
+ return "int16";
1926
+ case arrow.Int32:
1927
+ return "int32";
1928
+ case arrow.Uint8:
1929
+ return "uint8";
1930
+ case arrow.Uint16:
1931
+ return "uint16";
1932
+ case arrow.Uint32:
1933
+ return "uint32";
1934
+ default:
1935
+ throw new Error(`arrow dictionary index type not supported: ${arrowType.constructor.name}`);
1936
+ }
1937
+ }
1938
+ function isSchemaDictionaryKeyType(keyType) {
1939
+ return ["int8", "int16", "int32", "uint8", "uint16", "uint32"].includes(keyType);
1940
+ }
1941
+ var arrow;
1942
+ var init_convert_arrow_schema = __esm({
1943
+ "../core/src/schema-utils/lib/schema/convert-arrow-schema.ts"() {
1944
+ "use strict";
1945
+ arrow = __toESM(require("apache-arrow"), 1);
1946
+ }
1947
+ });
1948
+
1949
+ // ../core/src/schema-utils/index.ts
1950
+ var init_schema_utils = __esm({
1951
+ "../core/src/schema-utils/index.ts"() {
1952
+ "use strict";
1953
+ init_convert_arrow_schema();
1954
+ }
1955
+ });
1956
+
1957
+ // src/lib/build-graph-tables.ts
1958
+ function buildGraphTables(nodes, edges, shape, declarations) {
1959
+ if (shape === "plain-graph-data") {
1960
+ return { shape, nodes: Array.from(nodes), edges: Array.from(edges) };
1961
+ }
1962
+ if (shape !== "arrow-table" && shape !== "object-row-table") {
1963
+ throw new Error(`Unsupported graph shape: ${shape}`);
1964
+ }
1965
+ const nodeTable = buildGraphTable(nodes, false, shape, declarations == null ? void 0 : declarations.nodes);
1966
+ const edgeTable = buildGraphTable(edges, true, shape, declarations == null ? void 0 : declarations.edges);
1967
+ return {
1968
+ shape: "tables",
1969
+ tables: [
1970
+ { name: "nodes", table: nodeTable },
1971
+ { name: "edges", table: edgeTable }
1972
+ ]
1973
+ };
1974
+ }
1975
+ function buildGraphTable(records, isEdge, shape, declarations) {
1976
+ const columnNames = isEdge ? ["id", "sourceId", "targetId", "directed", "label", "attributes"] : ["id", "label", "attributes"];
1977
+ const columns = new Map(columnNames.map((name) => [name, []]));
1978
+ for (const record of records) {
1979
+ for (const name of columnNames) {
1980
+ const value = record[name];
1981
+ columns.get(name).push(
1982
+ name === "id" || name === "sourceId" || name === "targetId" ? String(value) : value ?? null
1983
+ );
1984
+ }
1985
+ }
1986
+ if (shape === "object-row-table") {
1987
+ return {
1988
+ shape,
1989
+ data: columns.get("id").map(
1990
+ (_, index) => Object.fromEntries(columnNames.map((name) => [name, columns.get(name)[index]]))
1991
+ )
1992
+ };
1993
+ }
1994
+ const vectors = /* @__PURE__ */ Object.create(null);
1995
+ for (const [name, values] of columns) {
1996
+ const type = name === "attributes" ? inferAttributeType(values, declarations) : name === "directed" ? new import_apache_arrow.Bool() : new import_apache_arrow.Utf8();
1997
+ vectors[name] = (0, import_apache_arrow.vectorFromArray)(
1998
+ values.map((value) => normalizeValue(value, type)),
1999
+ type
2000
+ );
2001
+ }
2002
+ const data = new import_apache_arrow.Table(vectors);
2003
+ return { shape, schema: convertArrowToSchema(data.schema), data };
2004
+ }
2005
+ function inferAttributeType(values, declarations) {
2006
+ const names = new Set(declarations == null ? void 0 : declarations.keys());
2007
+ for (const value of values) {
2008
+ if (value && typeof value === "object") {
2009
+ for (const name of Object.keys(value)) {
2010
+ names.add(name);
2011
+ }
2012
+ }
2013
+ }
2014
+ return new import_apache_arrow.Struct(
2015
+ Array.from(names, (name) => {
2016
+ const fieldValues = values.map(
2017
+ (value) => (value == null ? void 0 : value[name]) ?? null
2018
+ );
2019
+ return new import_apache_arrow.Field(name, inferValueType(fieldValues, declarations == null ? void 0 : declarations.get(name)), true);
2020
+ })
2021
+ );
2022
+ }
2023
+ function inferValueType(values, declaration) {
2024
+ const present = values.filter((value) => value !== null && value !== void 0);
2025
+ if (declaration && typeof declaration === "object") {
2026
+ if (!present.every((value) => Array.isArray(value))) return new import_apache_arrow.Utf8();
2027
+ return new import_apache_arrow.List(
2028
+ new import_apache_arrow.Field(
2029
+ "item",
2030
+ inferValueType(
2031
+ present.flatMap((value) => value),
2032
+ declaration.list
2033
+ ),
2034
+ true
2035
+ )
2036
+ );
2037
+ }
2038
+ if (declaration) {
2039
+ const declaredTypes = {
2040
+ boolean: new import_apache_arrow.Bool(),
2041
+ int: new import_apache_arrow.Int32(),
2042
+ long: new import_apache_arrow.Int64(),
2043
+ float: new import_apache_arrow.Float32(),
2044
+ double: new import_apache_arrow.Float64(),
2045
+ string: new import_apache_arrow.Utf8()
2046
+ };
2047
+ const valid = present.every((value) => {
2048
+ switch (declaration) {
2049
+ case "boolean":
2050
+ return typeof value === "boolean";
2051
+ case "int":
2052
+ return typeof value === "number" && Number.isInteger(value) && value >= -2147483648 && value <= 2147483647;
2053
+ case "long":
2054
+ return typeof value === "bigint" && value >= -(2n ** 63n) && value < 2n ** 63n;
2055
+ case "float":
2056
+ case "double":
2057
+ return typeof value === "number";
2058
+ case "string":
2059
+ return typeof value === "string";
2060
+ }
2061
+ });
2062
+ return valid ? declaredTypes[declaration] : new import_apache_arrow.Utf8();
2063
+ }
2064
+ if (present.length && present.every((value) => typeof value === "boolean")) return new import_apache_arrow.Bool();
2065
+ if (present.length && present.every((value) => typeof value === "number")) return new import_apache_arrow.Float64();
2066
+ if (present.length && present.every((value) => Array.isArray(value))) {
2067
+ return new import_apache_arrow.List(
2068
+ new import_apache_arrow.Field("item", inferValueType(present.flatMap((value) => value)), true)
2069
+ );
2070
+ }
2071
+ if (present.length && present.every((value) => typeof value === "object" && !Array.isArray(value))) {
2072
+ return inferAttributeType(present);
2073
+ }
2074
+ return new import_apache_arrow.Utf8();
2075
+ }
2076
+ function normalizeValue(value, type) {
2077
+ if (value === null || value === void 0) return null;
2078
+ if (type instanceof import_apache_arrow.Struct) {
2079
+ return Object.fromEntries(
2080
+ type.children.map((field) => [
2081
+ field.name,
2082
+ normalizeValue(value[field.name], field.type)
2083
+ ])
2084
+ );
2085
+ }
2086
+ if (type instanceof import_apache_arrow.List)
2087
+ return value.map((item) => normalizeValue(item, type.valueType));
2088
+ if (type instanceof import_apache_arrow.Utf8 && typeof value !== "string") {
2089
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
2090
+ }
2091
+ return value;
2092
+ }
2093
+ var import_apache_arrow;
2094
+ var init_build_graph_tables = __esm({
2095
+ "src/lib/build-graph-tables.ts"() {
2096
+ "use strict";
2097
+ import_apache_arrow = require("apache-arrow");
2098
+ init_schema_utils();
2099
+ }
2100
+ });
2101
+
55
2102
  // src/lib/parse-graphml.ts
56
- function parseGraphML(graphml) {
2103
+ function parseGraphML(graphml, shape = "plain-graph-data") {
57
2104
  const xmlText = decodeGraphML(graphml);
58
- const document = graphmlParser.parse(xmlText);
2105
+ const document = parseXMLSync(xmlText, GRAPHML_XML_OPTIONS);
59
2106
  const graphmlRoot = getGraphMLRoot(document);
60
2107
  if (!graphmlRoot) {
61
2108
  throw new Error("GraphML document does not contain a <graphml> element.");
@@ -64,19 +2111,38 @@ function parseGraphML(graphml) {
64
2111
  if (!graphElement) {
65
2112
  throw new Error("GraphML document does not contain a <graph> element.");
66
2113
  }
67
- const keyDefinitions = collectKeyDefinitions(graphmlRoot, graphElement);
2114
+ const keyDefinitions = collectKeyDefinitions(
2115
+ graphmlRoot,
2116
+ graphElement,
2117
+ shape !== "plain-graph-data"
2118
+ );
68
2119
  const defaultDirected = parseEdgeDefault(graphElement[`${XML_ATTRIBUTE_PREFIX}edgedefault`]);
69
- const nodes = normalizeArray(graphElement.node).map((node) => parseNode(node, keyDefinitions));
70
- const edges = normalizeArray(graphElement.edge).map(
71
- (edge, index) => parseEdge(edge, index, keyDefinitions, defaultDirected)
2120
+ const declarations = { nodes: /* @__PURE__ */ new Map(), edges: /* @__PURE__ */ new Map() };
2121
+ for (const definition of keyDefinitions.values()) {
2122
+ if (definition.domain === "all" || definition.domain === "node")
2123
+ declarations.nodes.set(definition.name, definition.type);
2124
+ if (definition.domain === "all" || definition.domain === "edge")
2125
+ declarations.edges.set(definition.name, definition.type);
2126
+ }
2127
+ return buildGraphTables(
2128
+ iterateNodes(graphElement.node, keyDefinitions),
2129
+ iterateEdges(graphElement.edge, keyDefinitions, defaultDirected),
2130
+ shape,
2131
+ declarations
72
2132
  );
73
- const filteredNodes = nodes.filter((node) => Boolean(node));
74
- const filteredEdges = edges.filter((edge) => Boolean(edge));
75
- return {
76
- shape: "plain-graph-data",
77
- nodes: filteredNodes,
78
- edges: filteredEdges
79
- };
2133
+ }
2134
+ function* iterateNodes(nodes, definitions) {
2135
+ for (const node of normalizeArray(nodes)) {
2136
+ const record = parseNode(node, definitions);
2137
+ if (record) yield record;
2138
+ }
2139
+ }
2140
+ function* iterateEdges(edges, definitions, directed) {
2141
+ let index = 0;
2142
+ for (const edge of normalizeArray(edges)) {
2143
+ const record = parseEdge(edge, index++, definitions, directed);
2144
+ if (record) yield record;
2145
+ }
80
2146
  }
81
2147
  function decodeGraphML(graphml) {
82
2148
  if (typeof graphml === "string") {
@@ -99,16 +2165,21 @@ function getGraphMLRoot(document) {
99
2165
  }
100
2166
  function getGraphElement(graphmlRoot) {
101
2167
  const graph = graphmlRoot.graph;
2168
+ if (typeof graph === "string" && !graph.trim()) {
2169
+ return {};
2170
+ }
102
2171
  if (!graph) {
103
2172
  return null;
104
2173
  }
105
2174
  if (Array.isArray(graph)) {
106
- const firstGraph = graph.find((entry) => isObject(entry));
107
- return isObject(firstGraph) ? firstGraph : null;
2175
+ const firstGraph = graph.find(
2176
+ (entry) => isObject(entry) || typeof entry === "string" && !entry.trim()
2177
+ );
2178
+ return isObject(firstGraph) ? firstGraph : typeof firstGraph === "string" ? {} : null;
108
2179
  }
109
2180
  return isObject(graph) ? graph : null;
110
2181
  }
111
- function collectKeyDefinitions(graphmlRoot, graphElement) {
2182
+ function collectKeyDefinitions(graphmlRoot, graphElement, lossless) {
112
2183
  const keys = /* @__PURE__ */ new Map();
113
2184
  for (const candidate of [
114
2185
  ...normalizeArray(graphmlRoot.key),
@@ -121,8 +2192,8 @@ function collectKeyDefinitions(graphmlRoot, graphElement) {
121
2192
  const name = String(candidate[`${XML_ATTRIBUTE_PREFIX}attr.name`] ?? id).trim();
122
2193
  const type = normalizeType(candidate[`${XML_ATTRIBUTE_PREFIX}attr.type`]);
123
2194
  const defaultNode = candidate.default ?? null;
124
- const defaultValue = defaultNode !== null ? castDataValue(defaultNode, type) : void 0;
125
- keys.set(id, { id, domain, name, type, defaultValue });
2195
+ const defaultValue = defaultNode !== null ? castDataValue(defaultNode, type, lossless) : void 0;
2196
+ keys.set(id, { id, domain, name, type, defaultValue, lossless });
126
2197
  }
127
2198
  }
128
2199
  }
@@ -200,12 +2271,12 @@ function assignAttributeFromDataEntry(entry, keyDefinitions, attributes) {
200
2271
  }
201
2272
  const definition = keyDefinitions.get(keyId);
202
2273
  const attributeName = (definition == null ? void 0 : definition.name) ?? keyId;
203
- const value = castDataValue(entry, (definition == null ? void 0 : definition.type) ?? "string");
2274
+ const value = (definition == null ? void 0 : definition.type) === "boolean" && extractTextContent(entry) === void 0 ? false : castDataValue(entry, (definition == null ? void 0 : definition.type) ?? "string", definition == null ? void 0 : definition.lossless);
204
2275
  if (value !== void 0) {
205
2276
  attributes[attributeName] = value;
206
2277
  }
207
2278
  }
208
- function castDataValue(value, type) {
2279
+ function castDataValue(value, type, lossless = false) {
209
2280
  if (value === null || typeof value === "undefined") {
210
2281
  return void 0;
211
2282
  }
@@ -216,6 +2287,9 @@ function castDataValue(value, type) {
216
2287
  if (type === "boolean") {
217
2288
  return parseBoolean(text);
218
2289
  }
2290
+ if (type === "long" && lossless) {
2291
+ return /^[+-]?\d+$/.test(text.trim()) ? BigInt(text.trim()) : text;
2292
+ }
219
2293
  if (type === "int" || type === "long") {
220
2294
  const parsed = Number.parseInt(text, 10);
221
2295
  return Number.isNaN(parsed) ? text : parsed;
@@ -238,14 +2312,14 @@ function extractTextContent(value) {
238
2312
  }
239
2313
  if (isObject(value)) {
240
2314
  const text = value[XML_TEXT_KEY];
241
- if (typeof text === "string") {
242
- return text;
243
- }
244
2315
  const nonAttributeEntries = Object.entries(value).filter(
245
- ([key]) => !key.startsWith(XML_ATTRIBUTE_PREFIX)
2316
+ ([key]) => !key.startsWith(XML_ATTRIBUTE_PREFIX) && key !== XML_TEXT_KEY
246
2317
  );
247
2318
  if (nonAttributeEntries.length === 0) {
248
- return void 0;
2319
+ return typeof text === "string" ? text : void 0;
2320
+ }
2321
+ if (typeof text === "string" && text.trim()) {
2322
+ nonAttributeEntries.push([XML_TEXT_KEY, text]);
249
2323
  }
250
2324
  return JSON.stringify(Object.fromEntries(nonAttributeEntries));
251
2325
  }
@@ -306,24 +2380,25 @@ function parseBoolean(value) {
306
2380
  if (normalized === "false" || normalized === "0" || normalized === "no" || normalized === "n") {
307
2381
  return false;
308
2382
  }
309
- return Boolean(value);
2383
+ return Boolean(normalized);
310
2384
  }
311
- var import_fast_xml_parser, XML_ATTRIBUTE_PREFIX, XML_TEXT_KEY, graphmlParser;
2385
+ var XML_ATTRIBUTE_PREFIX, XML_TEXT_KEY, GRAPHML_XML_OPTIONS;
312
2386
  var init_parse_graphml = __esm({
313
2387
  "src/lib/parse-graphml.ts"() {
314
2388
  "use strict";
315
- import_fast_xml_parser = require("fast-xml-parser");
2389
+ init_xml_parser();
2390
+ init_build_graph_tables();
316
2391
  XML_ATTRIBUTE_PREFIX = "@_";
317
2392
  XML_TEXT_KEY = "#text";
318
- graphmlParser = new import_fast_xml_parser.XMLParser({
2393
+ GRAPHML_XML_OPTIONS = {
319
2394
  ignoreAttributes: false,
320
2395
  attributeNamePrefix: XML_ATTRIBUTE_PREFIX,
321
2396
  textNodeName: XML_TEXT_KEY,
322
- trimValues: true,
2397
+ trimValues: false,
323
2398
  parseAttributeValue: false,
324
2399
  parseTagValue: false,
325
2400
  removeNSPrefix: true
326
- });
2401
+ };
327
2402
  }
328
2403
  });
329
2404
 
@@ -340,9 +2415,18 @@ var init_graphml_loader = __esm({
340
2415
  init_parse_graphml();
341
2416
  GraphMLLoaderWithParser = {
342
2417
  ...GraphMLLoader,
343
- parse: async (data) => parseGraphML(data),
344
- parseSync: parseGraphML,
345
- parseTextSync: parseGraphML
2418
+ parse: async (data, options) => {
2419
+ var _a;
2420
+ return parseGraphML(data, ((_a = options == null ? void 0 : options.graphml) == null ? void 0 : _a.shape) ?? "arrow-table");
2421
+ },
2422
+ parseSync: (data, options) => {
2423
+ var _a;
2424
+ return parseGraphML(data, ((_a = options == null ? void 0 : options.graphml) == null ? void 0 : _a.shape) ?? "arrow-table");
2425
+ },
2426
+ parseTextSync: (data, options) => {
2427
+ var _a;
2428
+ return parseGraphML(data, ((_a = options == null ? void 0 : options.graphml) == null ? void 0 : _a.shape) ?? "arrow-table");
2429
+ }
346
2430
  };
347
2431
  }
348
2432
  });
@@ -355,7 +2439,7 @@ __export(graphml_loader_exports2, {
355
2439
  module.exports = __toCommonJS(graphml_loader_exports2);
356
2440
 
357
2441
  // dist/graphml-loader-types.js
358
- var VERSION2 = true ? "5.0.0-alpha.9" : "latest";
2442
+ var VERSION2 = true ? "5.0.0-beta.2" : "latest";
359
2443
  async function preload2() {
360
2444
  const { GraphMLLoaderWithParser: GraphMLLoaderWithParser3 } = await Promise.resolve().then(() => (init_graphml_loader(), graphml_loader_exports));
361
2445
  return GraphMLLoaderWithParser3;
@@ -371,26 +2455,147 @@ var GraphMLLoader2 = {
371
2455
  worker: false,
372
2456
  dataType: null,
373
2457
  batchType: null,
374
- options: {},
2458
+ options: { graphml: { shape: "arrow-table" } },
375
2459
  preload: preload2
376
2460
  };
377
2461
 
378
2462
  // dist/lib/parse-graphml.js
379
- var import_fast_xml_parser2 = require("fast-xml-parser");
2463
+ init_xml_parser();
2464
+
2465
+ // dist/lib/build-graph-tables.js
2466
+ var import_apache_arrow2 = require("apache-arrow");
2467
+ init_schema_utils();
2468
+ function buildGraphTables2(nodes, edges, shape, declarations) {
2469
+ if (shape === "plain-graph-data") {
2470
+ return { shape, nodes: Array.from(nodes), edges: Array.from(edges) };
2471
+ }
2472
+ if (shape !== "arrow-table" && shape !== "object-row-table") {
2473
+ throw new Error(`Unsupported graph shape: ${shape}`);
2474
+ }
2475
+ const nodeTable = buildGraphTable2(nodes, false, shape, declarations == null ? void 0 : declarations.nodes);
2476
+ const edgeTable = buildGraphTable2(edges, true, shape, declarations == null ? void 0 : declarations.edges);
2477
+ return {
2478
+ shape: "tables",
2479
+ tables: [
2480
+ { name: "nodes", table: nodeTable },
2481
+ { name: "edges", table: edgeTable }
2482
+ ]
2483
+ };
2484
+ }
2485
+ function buildGraphTable2(records, isEdge, shape, declarations) {
2486
+ const columnNames = isEdge ? ["id", "sourceId", "targetId", "directed", "label", "attributes"] : ["id", "label", "attributes"];
2487
+ const columns = new Map(columnNames.map((name) => [name, []]));
2488
+ for (const record of records) {
2489
+ for (const name of columnNames) {
2490
+ const value = record[name];
2491
+ columns.get(name).push(name === "id" || name === "sourceId" || name === "targetId" ? String(value) : value ?? null);
2492
+ }
2493
+ }
2494
+ if (shape === "object-row-table") {
2495
+ return {
2496
+ shape,
2497
+ data: columns.get("id").map((_, index) => Object.fromEntries(columnNames.map((name) => [name, columns.get(name)[index]])))
2498
+ };
2499
+ }
2500
+ const vectors = /* @__PURE__ */ Object.create(null);
2501
+ for (const [name, values] of columns) {
2502
+ const type = name === "attributes" ? inferAttributeType2(values, declarations) : name === "directed" ? new import_apache_arrow2.Bool() : new import_apache_arrow2.Utf8();
2503
+ vectors[name] = (0, import_apache_arrow2.vectorFromArray)(values.map((value) => normalizeValue2(value, type)), type);
2504
+ }
2505
+ const data = new import_apache_arrow2.Table(vectors);
2506
+ return { shape, schema: convertArrowToSchema(data.schema), data };
2507
+ }
2508
+ function inferAttributeType2(values, declarations) {
2509
+ const names = new Set(declarations == null ? void 0 : declarations.keys());
2510
+ for (const value of values) {
2511
+ if (value && typeof value === "object") {
2512
+ for (const name of Object.keys(value)) {
2513
+ names.add(name);
2514
+ }
2515
+ }
2516
+ }
2517
+ return new import_apache_arrow2.Struct(Array.from(names, (name) => {
2518
+ const fieldValues = values.map((value) => (value == null ? void 0 : value[name]) ?? null);
2519
+ return new import_apache_arrow2.Field(name, inferValueType2(fieldValues, declarations == null ? void 0 : declarations.get(name)), true);
2520
+ }));
2521
+ }
2522
+ function inferValueType2(values, declaration) {
2523
+ const present = values.filter((value) => value !== null && value !== void 0);
2524
+ if (declaration && typeof declaration === "object") {
2525
+ if (!present.every((value) => Array.isArray(value)))
2526
+ return new import_apache_arrow2.Utf8();
2527
+ return new import_apache_arrow2.List(new import_apache_arrow2.Field("item", inferValueType2(present.flatMap((value) => value), declaration.list), true));
2528
+ }
2529
+ if (declaration) {
2530
+ const declaredTypes = {
2531
+ boolean: new import_apache_arrow2.Bool(),
2532
+ int: new import_apache_arrow2.Int32(),
2533
+ long: new import_apache_arrow2.Int64(),
2534
+ float: new import_apache_arrow2.Float32(),
2535
+ double: new import_apache_arrow2.Float64(),
2536
+ string: new import_apache_arrow2.Utf8()
2537
+ };
2538
+ const valid = present.every((value) => {
2539
+ switch (declaration) {
2540
+ case "boolean":
2541
+ return typeof value === "boolean";
2542
+ case "int":
2543
+ return typeof value === "number" && Number.isInteger(value) && value >= -2147483648 && value <= 2147483647;
2544
+ case "long":
2545
+ return typeof value === "bigint" && value >= -(2n ** 63n) && value < 2n ** 63n;
2546
+ case "float":
2547
+ case "double":
2548
+ return typeof value === "number";
2549
+ case "string":
2550
+ return typeof value === "string";
2551
+ }
2552
+ });
2553
+ return valid ? declaredTypes[declaration] : new import_apache_arrow2.Utf8();
2554
+ }
2555
+ if (present.length && present.every((value) => typeof value === "boolean"))
2556
+ return new import_apache_arrow2.Bool();
2557
+ if (present.length && present.every((value) => typeof value === "number"))
2558
+ return new import_apache_arrow2.Float64();
2559
+ if (present.length && present.every((value) => Array.isArray(value))) {
2560
+ return new import_apache_arrow2.List(new import_apache_arrow2.Field("item", inferValueType2(present.flatMap((value) => value)), true));
2561
+ }
2562
+ if (present.length && present.every((value) => typeof value === "object" && !Array.isArray(value))) {
2563
+ return inferAttributeType2(present);
2564
+ }
2565
+ return new import_apache_arrow2.Utf8();
2566
+ }
2567
+ function normalizeValue2(value, type) {
2568
+ if (value === null || value === void 0)
2569
+ return null;
2570
+ if (type instanceof import_apache_arrow2.Struct) {
2571
+ return Object.fromEntries(type.children.map((field) => [
2572
+ field.name,
2573
+ normalizeValue2(value[field.name], field.type)
2574
+ ]));
2575
+ }
2576
+ if (type instanceof import_apache_arrow2.List)
2577
+ return value.map((item) => normalizeValue2(item, type.valueType));
2578
+ if (type instanceof import_apache_arrow2.Utf8 && typeof value !== "string") {
2579
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
2580
+ }
2581
+ return value;
2582
+ }
2583
+
2584
+ // dist/lib/parse-graphml.js
380
2585
  var XML_ATTRIBUTE_PREFIX2 = "@_";
381
2586
  var XML_TEXT_KEY2 = "#text";
382
- var graphmlParser2 = new import_fast_xml_parser2.XMLParser({
2587
+ var GRAPHML_XML_OPTIONS2 = {
383
2588
  ignoreAttributes: false,
384
2589
  attributeNamePrefix: XML_ATTRIBUTE_PREFIX2,
385
2590
  textNodeName: XML_TEXT_KEY2,
386
- trimValues: true,
2591
+ trimValues: false,
387
2592
  parseAttributeValue: false,
388
2593
  parseTagValue: false,
389
2594
  removeNSPrefix: true
390
- });
391
- function parseGraphML2(graphml) {
2595
+ };
2596
+ function parseGraphML2(graphml, shape = "plain-graph-data") {
392
2597
  const xmlText = decodeGraphML2(graphml);
393
- const document = graphmlParser2.parse(xmlText);
2598
+ const document = parseXMLSync(xmlText, GRAPHML_XML_OPTIONS2);
394
2599
  const graphmlRoot = getGraphMLRoot2(document);
395
2600
  if (!graphmlRoot) {
396
2601
  throw new Error("GraphML document does not contain a <graphml> element.");
@@ -399,17 +2604,31 @@ function parseGraphML2(graphml) {
399
2604
  if (!graphElement) {
400
2605
  throw new Error("GraphML document does not contain a <graph> element.");
401
2606
  }
402
- const keyDefinitions = collectKeyDefinitions2(graphmlRoot, graphElement);
2607
+ const keyDefinitions = collectKeyDefinitions2(graphmlRoot, graphElement, shape !== "plain-graph-data");
403
2608
  const defaultDirected = parseEdgeDefault2(graphElement[`${XML_ATTRIBUTE_PREFIX2}edgedefault`]);
404
- const nodes = normalizeArray2(graphElement.node).map((node) => parseNode2(node, keyDefinitions));
405
- const edges = normalizeArray2(graphElement.edge).map((edge, index) => parseEdge2(edge, index, keyDefinitions, defaultDirected));
406
- const filteredNodes = nodes.filter((node) => Boolean(node));
407
- const filteredEdges = edges.filter((edge) => Boolean(edge));
408
- return {
409
- shape: "plain-graph-data",
410
- nodes: filteredNodes,
411
- edges: filteredEdges
412
- };
2609
+ const declarations = { nodes: /* @__PURE__ */ new Map(), edges: /* @__PURE__ */ new Map() };
2610
+ for (const definition of keyDefinitions.values()) {
2611
+ if (definition.domain === "all" || definition.domain === "node")
2612
+ declarations.nodes.set(definition.name, definition.type);
2613
+ if (definition.domain === "all" || definition.domain === "edge")
2614
+ declarations.edges.set(definition.name, definition.type);
2615
+ }
2616
+ return buildGraphTables2(iterateNodes2(graphElement.node, keyDefinitions), iterateEdges2(graphElement.edge, keyDefinitions, defaultDirected), shape, declarations);
2617
+ }
2618
+ function* iterateNodes2(nodes, definitions) {
2619
+ for (const node of normalizeArray2(nodes)) {
2620
+ const record = parseNode2(node, definitions);
2621
+ if (record)
2622
+ yield record;
2623
+ }
2624
+ }
2625
+ function* iterateEdges2(edges, definitions, directed) {
2626
+ let index = 0;
2627
+ for (const edge of normalizeArray2(edges)) {
2628
+ const record = parseEdge2(edge, index++, definitions, directed);
2629
+ if (record)
2630
+ yield record;
2631
+ }
413
2632
  }
414
2633
  function decodeGraphML2(graphml) {
415
2634
  if (typeof graphml === "string") {
@@ -432,16 +2651,19 @@ function getGraphMLRoot2(document) {
432
2651
  }
433
2652
  function getGraphElement2(graphmlRoot) {
434
2653
  const graph = graphmlRoot.graph;
2654
+ if (typeof graph === "string" && !graph.trim()) {
2655
+ return {};
2656
+ }
435
2657
  if (!graph) {
436
2658
  return null;
437
2659
  }
438
2660
  if (Array.isArray(graph)) {
439
- const firstGraph = graph.find((entry) => isObject2(entry));
440
- return isObject2(firstGraph) ? firstGraph : null;
2661
+ const firstGraph = graph.find((entry) => isObject2(entry) || typeof entry === "string" && !entry.trim());
2662
+ return isObject2(firstGraph) ? firstGraph : typeof firstGraph === "string" ? {} : null;
441
2663
  }
442
2664
  return isObject2(graph) ? graph : null;
443
2665
  }
444
- function collectKeyDefinitions2(graphmlRoot, graphElement) {
2666
+ function collectKeyDefinitions2(graphmlRoot, graphElement, lossless) {
445
2667
  const keys = /* @__PURE__ */ new Map();
446
2668
  for (const candidate of [
447
2669
  ...normalizeArray2(graphmlRoot.key),
@@ -454,8 +2676,8 @@ function collectKeyDefinitions2(graphmlRoot, graphElement) {
454
2676
  const name = String(candidate[`${XML_ATTRIBUTE_PREFIX2}attr.name`] ?? id).trim();
455
2677
  const type = normalizeType2(candidate[`${XML_ATTRIBUTE_PREFIX2}attr.type`]);
456
2678
  const defaultNode = candidate.default ?? null;
457
- const defaultValue = defaultNode !== null ? castDataValue2(defaultNode, type) : void 0;
458
- keys.set(id, { id, domain, name, type, defaultValue });
2679
+ const defaultValue = defaultNode !== null ? castDataValue2(defaultNode, type, lossless) : void 0;
2680
+ keys.set(id, { id, domain, name, type, defaultValue, lossless });
459
2681
  }
460
2682
  }
461
2683
  }
@@ -533,12 +2755,12 @@ function assignAttributeFromDataEntry2(entry, keyDefinitions, attributes) {
533
2755
  }
534
2756
  const definition = keyDefinitions.get(keyId);
535
2757
  const attributeName = (definition == null ? void 0 : definition.name) ?? keyId;
536
- const value = castDataValue2(entry, (definition == null ? void 0 : definition.type) ?? "string");
2758
+ const value = (definition == null ? void 0 : definition.type) === "boolean" && extractTextContent2(entry) === void 0 ? false : castDataValue2(entry, (definition == null ? void 0 : definition.type) ?? "string", definition == null ? void 0 : definition.lossless);
537
2759
  if (value !== void 0) {
538
2760
  attributes[attributeName] = value;
539
2761
  }
540
2762
  }
541
- function castDataValue2(value, type) {
2763
+ function castDataValue2(value, type, lossless = false) {
542
2764
  if (value === null || typeof value === "undefined") {
543
2765
  return void 0;
544
2766
  }
@@ -549,6 +2771,9 @@ function castDataValue2(value, type) {
549
2771
  if (type === "boolean") {
550
2772
  return parseBoolean2(text);
551
2773
  }
2774
+ if (type === "long" && lossless) {
2775
+ return /^[+-]?\d+$/.test(text.trim()) ? BigInt(text.trim()) : text;
2776
+ }
552
2777
  if (type === "int" || type === "long") {
553
2778
  const parsed = Number.parseInt(text, 10);
554
2779
  return Number.isNaN(parsed) ? text : parsed;
@@ -571,12 +2796,12 @@ function extractTextContent2(value) {
571
2796
  }
572
2797
  if (isObject2(value)) {
573
2798
  const text = value[XML_TEXT_KEY2];
574
- if (typeof text === "string") {
575
- return text;
576
- }
577
- const nonAttributeEntries = Object.entries(value).filter(([key]) => !key.startsWith(XML_ATTRIBUTE_PREFIX2));
2799
+ const nonAttributeEntries = Object.entries(value).filter(([key]) => !key.startsWith(XML_ATTRIBUTE_PREFIX2) && key !== XML_TEXT_KEY2);
578
2800
  if (nonAttributeEntries.length === 0) {
579
- return void 0;
2801
+ return typeof text === "string" ? text : void 0;
2802
+ }
2803
+ if (typeof text === "string" && text.trim()) {
2804
+ nonAttributeEntries.push([XML_TEXT_KEY2, text]);
580
2805
  }
581
2806
  return JSON.stringify(Object.fromEntries(nonAttributeEntries));
582
2807
  }
@@ -637,14 +2862,23 @@ function parseBoolean2(value) {
637
2862
  if (normalized === "false" || normalized === "0" || normalized === "no" || normalized === "n") {
638
2863
  return false;
639
2864
  }
640
- return Boolean(value);
2865
+ return Boolean(normalized);
641
2866
  }
642
2867
 
643
2868
  // dist/graphml-loader.js
644
2869
  var GraphMLLoaderWithParser2 = {
645
2870
  ...GraphMLLoader2,
646
- parse: async (data) => parseGraphML2(data),
647
- parseSync: parseGraphML2,
648
- parseTextSync: parseGraphML2
2871
+ parse: async (data, options) => {
2872
+ var _a;
2873
+ return parseGraphML2(data, ((_a = options == null ? void 0 : options.graphml) == null ? void 0 : _a.shape) ?? "arrow-table");
2874
+ },
2875
+ parseSync: (data, options) => {
2876
+ var _a;
2877
+ return parseGraphML2(data, ((_a = options == null ? void 0 : options.graphml) == null ? void 0 : _a.shape) ?? "arrow-table");
2878
+ },
2879
+ parseTextSync: (data, options) => {
2880
+ var _a;
2881
+ return parseGraphML2(data, ((_a = options == null ? void 0 : options.graphml) == null ? void 0 : _a.shape) ?? "arrow-table");
2882
+ }
649
2883
  };
650
2884
  //# sourceMappingURL=graphml-loader.cjs.map