@loaders.gl/json 4.0.0-beta.2 → 4.0.0-beta.3

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 (119) hide show
  1. package/dist/{dist.min.js → dist.dev.js} +1603 -1561
  2. package/dist/{esm/geojson-loader.js → geojson-loader.js} +2 -2
  3. package/dist/geojson-loader.js.map +1 -0
  4. package/dist/geojson-worker.js +345 -179
  5. package/dist/{esm/geojson-writer.js → geojson-writer.js} +1 -1
  6. package/dist/geojson-writer.js.map +1 -0
  7. package/dist/index.cjs +1259 -0
  8. package/dist/index.js +9 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/{esm/json-loader.js → json-loader.js} +3 -3
  11. package/dist/json-loader.js.map +1 -0
  12. package/dist/{esm/json-writer.js → json-writer.js} +1 -1
  13. package/dist/json-writer.js.map +1 -0
  14. package/dist/{esm/lib → lib}/clarinet/clarinet.js +33 -34
  15. package/dist/lib/clarinet/clarinet.js.map +1 -0
  16. package/dist/{esm/lib → lib}/encoder-utils/encode-table-row.js +1 -1
  17. package/dist/lib/encoder-utils/encode-table-row.js.map +1 -0
  18. package/dist/lib/encoder-utils/encode-utils.js.map +1 -0
  19. package/dist/{esm/lib → lib}/encoder-utils/utf8-encoder.js +4 -5
  20. package/dist/lib/encoder-utils/utf8-encoder.js.map +1 -0
  21. package/dist/{esm/lib → lib}/encoders/geojson-encoder.js +3 -3
  22. package/dist/lib/encoders/geojson-encoder.js.map +1 -0
  23. package/dist/{esm/lib → lib}/encoders/json-encoder.js +1 -1
  24. package/dist/lib/encoders/json-encoder.js.map +1 -0
  25. package/dist/{esm/lib → lib}/json-parser/json-parser.js +8 -9
  26. package/dist/lib/json-parser/json-parser.js.map +1 -0
  27. package/dist/{esm/lib → lib}/json-parser/streaming-json-parser.js +6 -7
  28. package/dist/lib/json-parser/streaming-json-parser.js.map +1 -0
  29. package/dist/{esm/lib → lib}/jsonpath/jsonpath.js +1 -2
  30. package/dist/lib/jsonpath/jsonpath.js.map +1 -0
  31. package/dist/{esm/lib → lib}/parsers/parse-json-in-batches.js +2 -2
  32. package/dist/lib/parsers/parse-json-in-batches.js.map +1 -0
  33. package/dist/lib/parsers/parse-json.js.map +1 -0
  34. package/dist/{esm/lib → lib}/parsers/parse-ndjson-in-batches.js +1 -1
  35. package/dist/lib/parsers/parse-ndjson-in-batches.js.map +1 -0
  36. package/dist/{esm/lib → lib}/parsers/parse-ndjson.js +1 -1
  37. package/dist/lib/parsers/parse-ndjson.js.map +1 -0
  38. package/dist/{esm/ndgeoson-loader.js → ndgeoson-loader.js} +3 -3
  39. package/dist/ndgeoson-loader.js.map +1 -0
  40. package/dist/{esm/ndjson-loader.js → ndjson-loader.js} +3 -3
  41. package/dist/ndjson-loader.js.map +1 -0
  42. package/dist/{esm/workers → workers}/geojson-worker.js +1 -1
  43. package/dist/workers/geojson-worker.js.map +1 -0
  44. package/package.json +17 -9
  45. package/dist/bundle.d.ts +0 -2
  46. package/dist/bundle.d.ts.map +0 -1
  47. package/dist/es5/bundle.js +0 -6
  48. package/dist/es5/bundle.js.map +0 -1
  49. package/dist/es5/geojson-loader.js +0 -166
  50. package/dist/es5/geojson-loader.js.map +0 -1
  51. package/dist/es5/geojson-writer.js +0 -27
  52. package/dist/es5/geojson-writer.js.map +0 -1
  53. package/dist/es5/index.js +0 -69
  54. package/dist/es5/index.js.map +0 -1
  55. package/dist/es5/json-loader.js +0 -67
  56. package/dist/es5/json-loader.js.map +0 -1
  57. package/dist/es5/json-writer.js +0 -42
  58. package/dist/es5/json-writer.js.map +0 -1
  59. package/dist/es5/lib/clarinet/clarinet.js +0 -446
  60. package/dist/es5/lib/clarinet/clarinet.js.map +0 -1
  61. package/dist/es5/lib/encoder-utils/encode-table-row.js +0 -54
  62. package/dist/es5/lib/encoder-utils/encode-table-row.js.map +0 -1
  63. package/dist/es5/lib/encoder-utils/encode-utils.js +0 -42
  64. package/dist/es5/lib/encoder-utils/encode-utils.js.map +0 -1
  65. package/dist/es5/lib/encoder-utils/utf8-encoder.js +0 -54
  66. package/dist/es5/lib/encoder-utils/utf8-encoder.js.map +0 -1
  67. package/dist/es5/lib/encoders/geojson-encoder.js +0 -141
  68. package/dist/es5/lib/encoders/geojson-encoder.js.map +0 -1
  69. package/dist/es5/lib/encoders/json-encoder.js +0 -30
  70. package/dist/es5/lib/encoders/json-encoder.js.map +0 -1
  71. package/dist/es5/lib/json-parser/json-parser.js +0 -140
  72. package/dist/es5/lib/json-parser/json-parser.js.map +0 -1
  73. package/dist/es5/lib/json-parser/streaming-json-parser.js +0 -123
  74. package/dist/es5/lib/json-parser/streaming-json-parser.js.map +0 -1
  75. package/dist/es5/lib/jsonpath/jsonpath.js +0 -119
  76. package/dist/es5/lib/jsonpath/jsonpath.js.map +0 -1
  77. package/dist/es5/lib/parsers/parse-json-in-batches.js +0 -206
  78. package/dist/es5/lib/parsers/parse-json-in-batches.js.map +0 -1
  79. package/dist/es5/lib/parsers/parse-json.js +0 -38
  80. package/dist/es5/lib/parsers/parse-json.js.map +0 -1
  81. package/dist/es5/lib/parsers/parse-ndjson-in-batches.js +0 -114
  82. package/dist/es5/lib/parsers/parse-ndjson-in-batches.js.map +0 -1
  83. package/dist/es5/lib/parsers/parse-ndjson.js +0 -19
  84. package/dist/es5/lib/parsers/parse-ndjson.js.map +0 -1
  85. package/dist/es5/ndgeoson-loader.js +0 -51
  86. package/dist/es5/ndgeoson-loader.js.map +0 -1
  87. package/dist/es5/ndjson-loader.js +0 -44
  88. package/dist/es5/ndjson-loader.js.map +0 -1
  89. package/dist/es5/workers/geojson-worker.js +0 -6
  90. package/dist/es5/workers/geojson-worker.js.map +0 -1
  91. package/dist/esm/bundle.js +0 -4
  92. package/dist/esm/bundle.js.map +0 -1
  93. package/dist/esm/geojson-loader.js.map +0 -1
  94. package/dist/esm/geojson-writer.js.map +0 -1
  95. package/dist/esm/index.js +0 -9
  96. package/dist/esm/index.js.map +0 -1
  97. package/dist/esm/json-loader.js.map +0 -1
  98. package/dist/esm/json-writer.js.map +0 -1
  99. package/dist/esm/lib/clarinet/LICENSE +0 -28
  100. package/dist/esm/lib/clarinet/clarinet.js.map +0 -1
  101. package/dist/esm/lib/encoder-utils/encode-table-row.js.map +0 -1
  102. package/dist/esm/lib/encoder-utils/encode-utils.js.map +0 -1
  103. package/dist/esm/lib/encoder-utils/utf8-encoder.js.map +0 -1
  104. package/dist/esm/lib/encoders/geojson-encoder.js.map +0 -1
  105. package/dist/esm/lib/encoders/json-encoder.js.map +0 -1
  106. package/dist/esm/lib/json-parser/json-parser.js.map +0 -1
  107. package/dist/esm/lib/json-parser/streaming-json-parser.js.map +0 -1
  108. package/dist/esm/lib/jsonpath/jsonpath.js.map +0 -1
  109. package/dist/esm/lib/parsers/parse-json-in-batches.js.map +0 -1
  110. package/dist/esm/lib/parsers/parse-json.js.map +0 -1
  111. package/dist/esm/lib/parsers/parse-ndjson-in-batches.js.map +0 -1
  112. package/dist/esm/lib/parsers/parse-ndjson.js.map +0 -1
  113. package/dist/esm/ndgeoson-loader.js.map +0 -1
  114. package/dist/esm/ndjson-loader.js.map +0 -1
  115. package/dist/esm/workers/geojson-worker.js.map +0 -1
  116. package/src/bundle.ts +0 -4
  117. /package/dist/{es5/lib → lib}/clarinet/LICENSE +0 -0
  118. /package/dist/{esm/lib → lib}/encoder-utils/encode-utils.js +0 -0
  119. /package/dist/{esm/lib → lib}/parsers/parse-json.js +0 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,1259 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ JSONLoader: () => JSONLoader,
24
+ JSONWriter: () => JSONWriter,
25
+ NDJSONLoader: () => NDJSONLoader,
26
+ _ClarinetParser: () => ClarinetParser,
27
+ _GeoJSONLoader: () => GeoJSONLoader,
28
+ _GeoJSONWorkerLoader: () => GeoJSONWorkerLoader,
29
+ _GeoJSONWriter: () => GeoJSONWriter,
30
+ _JSONPath: () => JSONPath,
31
+ _rebuildJsonObject: () => rebuildJsonObject
32
+ });
33
+ module.exports = __toCommonJS(src_exports);
34
+
35
+ // src/lib/parsers/parse-json.ts
36
+ var import_schema = require("@loaders.gl/schema");
37
+ function parseJSONSync(jsonText, options) {
38
+ var _a;
39
+ try {
40
+ const json = JSON.parse(jsonText);
41
+ if ((_a = options.json) == null ? void 0 : _a.table) {
42
+ const data = getFirstArray(json) || json;
43
+ return (0, import_schema.makeTableFromData)(data);
44
+ }
45
+ return json;
46
+ } catch (error) {
47
+ throw new Error("JSONLoader: failed to parse JSON");
48
+ }
49
+ }
50
+ function getFirstArray(json) {
51
+ if (Array.isArray(json)) {
52
+ return json;
53
+ }
54
+ if (json && typeof json === "object") {
55
+ for (const value of Object.values(json)) {
56
+ const array = getFirstArray(value);
57
+ if (array) {
58
+ return array;
59
+ }
60
+ }
61
+ }
62
+ return null;
63
+ }
64
+
65
+ // src/lib/parsers/parse-json-in-batches.ts
66
+ var import_schema2 = require("@loaders.gl/schema");
67
+ var import_loader_utils = require("@loaders.gl/loader-utils");
68
+
69
+ // src/lib/clarinet/clarinet.ts
70
+ var MAX_BUFFER_LENGTH = Number.MAX_SAFE_INTEGER;
71
+ var Char = {
72
+ tab: 9,
73
+ // \t
74
+ lineFeed: 10,
75
+ // \n
76
+ carriageReturn: 13,
77
+ // \r
78
+ space: 32,
79
+ // " "
80
+ doubleQuote: 34,
81
+ // "
82
+ plus: 43,
83
+ // +
84
+ comma: 44,
85
+ // ,
86
+ minus: 45,
87
+ // -
88
+ period: 46,
89
+ // .
90
+ _0: 48,
91
+ // 0
92
+ _9: 57,
93
+ // 9
94
+ colon: 58,
95
+ // :
96
+ E: 69,
97
+ // E
98
+ openBracket: 91,
99
+ // [
100
+ backslash: 92,
101
+ // \
102
+ closeBracket: 93,
103
+ // ]
104
+ a: 97,
105
+ // a
106
+ b: 98,
107
+ // b
108
+ e: 101,
109
+ // e
110
+ f: 102,
111
+ // f
112
+ l: 108,
113
+ // l
114
+ n: 110,
115
+ // n
116
+ r: 114,
117
+ // r
118
+ s: 115,
119
+ // s
120
+ t: 116,
121
+ // t
122
+ u: 117,
123
+ // u
124
+ openBrace: 123,
125
+ // {
126
+ closeBrace: 125
127
+ // }
128
+ };
129
+ var stringTokenPattern = /[\\"\n]/g;
130
+ var DEFAULT_OPTIONS = {
131
+ onready: () => {
132
+ },
133
+ onopenobject: () => {
134
+ },
135
+ onkey: () => {
136
+ },
137
+ oncloseobject: () => {
138
+ },
139
+ onopenarray: () => {
140
+ },
141
+ onclosearray: () => {
142
+ },
143
+ onvalue: () => {
144
+ },
145
+ onerror: () => {
146
+ },
147
+ onend: () => {
148
+ },
149
+ onchunkparsed: () => {
150
+ }
151
+ };
152
+ var ClarinetParser = class {
153
+ constructor(options = {}) {
154
+ this.options = DEFAULT_OPTIONS;
155
+ this.bufferCheckPosition = MAX_BUFFER_LENGTH;
156
+ this.q = "";
157
+ this.c = "";
158
+ this.p = "";
159
+ this.closed = false;
160
+ this.closedRoot = false;
161
+ this.sawRoot = false;
162
+ // tag = null;
163
+ this.error = null;
164
+ this.state = 0 /* BEGIN */;
165
+ this.stack = [];
166
+ // mostly just for error reporting
167
+ this.position = 0;
168
+ this.column = 0;
169
+ this.line = 1;
170
+ this.slashed = false;
171
+ this.unicodeI = 0;
172
+ this.unicodeS = null;
173
+ this.depth = 0;
174
+ this.options = { ...DEFAULT_OPTIONS, ...options };
175
+ this.textNode = void 0;
176
+ this.numberNode = "";
177
+ this.emit("onready");
178
+ }
179
+ end() {
180
+ if (this.state !== 1 /* VALUE */ || this.depth !== 0)
181
+ this._error("Unexpected end");
182
+ this._closeValue();
183
+ this.c = "";
184
+ this.closed = true;
185
+ this.emit("onend");
186
+ return this;
187
+ }
188
+ resume() {
189
+ this.error = null;
190
+ return this;
191
+ }
192
+ close() {
193
+ return this.write(null);
194
+ }
195
+ // protected
196
+ emit(event, data) {
197
+ var _a, _b;
198
+ (_b = (_a = this.options)[event]) == null ? void 0 : _b.call(_a, data, this);
199
+ }
200
+ emitNode(event, data) {
201
+ this._closeValue();
202
+ this.emit(event, data);
203
+ }
204
+ /* eslint-disable no-continue */
205
+ // eslint-disable-next-line complexity, max-statements
206
+ write(chunk) {
207
+ if (this.error) {
208
+ throw this.error;
209
+ }
210
+ if (this.closed) {
211
+ return this._error("Cannot write after close. Assign an onready handler.");
212
+ }
213
+ if (chunk === null) {
214
+ return this.end();
215
+ }
216
+ let i = 0;
217
+ let c = chunk.charCodeAt(0);
218
+ let p = this.p;
219
+ while (c) {
220
+ p = c;
221
+ this.c = c = chunk.charCodeAt(i++);
222
+ if (p !== c) {
223
+ this.p = p;
224
+ } else {
225
+ p = this.p;
226
+ }
227
+ if (!c)
228
+ break;
229
+ this.position++;
230
+ if (c === Char.lineFeed) {
231
+ this.line++;
232
+ this.column = 0;
233
+ } else
234
+ this.column++;
235
+ switch (this.state) {
236
+ case 0 /* BEGIN */:
237
+ if (c === Char.openBrace)
238
+ this.state = 2 /* OPEN_OBJECT */;
239
+ else if (c === Char.openBracket)
240
+ this.state = 4 /* OPEN_ARRAY */;
241
+ else if (!isWhitespace(c)) {
242
+ this._error("Non-whitespace before {[.");
243
+ }
244
+ continue;
245
+ case 10 /* OPEN_KEY */:
246
+ case 2 /* OPEN_OBJECT */:
247
+ if (isWhitespace(c))
248
+ continue;
249
+ if (this.state === 10 /* OPEN_KEY */)
250
+ this.stack.push(11 /* CLOSE_KEY */);
251
+ else if (c === Char.closeBrace) {
252
+ this.emit("onopenobject");
253
+ this.depth++;
254
+ this.emit("oncloseobject");
255
+ this.depth--;
256
+ this.state = this.stack.pop() || 1 /* VALUE */;
257
+ continue;
258
+ } else
259
+ this.stack.push(3 /* CLOSE_OBJECT */);
260
+ if (c === Char.doubleQuote)
261
+ this.state = 7 /* STRING */;
262
+ else
263
+ this._error('Malformed object key should start with "');
264
+ continue;
265
+ case 11 /* CLOSE_KEY */:
266
+ case 3 /* CLOSE_OBJECT */:
267
+ if (isWhitespace(c))
268
+ continue;
269
+ if (c === Char.colon) {
270
+ if (this.state === 3 /* CLOSE_OBJECT */) {
271
+ this.stack.push(3 /* CLOSE_OBJECT */);
272
+ this._closeValue("onopenobject");
273
+ this.depth++;
274
+ } else
275
+ this._closeValue("onkey");
276
+ this.state = 1 /* VALUE */;
277
+ } else if (c === Char.closeBrace) {
278
+ this.emitNode("oncloseobject");
279
+ this.depth--;
280
+ this.state = this.stack.pop() || 1 /* VALUE */;
281
+ } else if (c === Char.comma) {
282
+ if (this.state === 3 /* CLOSE_OBJECT */)
283
+ this.stack.push(3 /* CLOSE_OBJECT */);
284
+ this._closeValue();
285
+ this.state = 10 /* OPEN_KEY */;
286
+ } else
287
+ this._error("Bad object");
288
+ continue;
289
+ case 4 /* OPEN_ARRAY */:
290
+ case 1 /* VALUE */:
291
+ if (isWhitespace(c))
292
+ continue;
293
+ if (this.state === 4 /* OPEN_ARRAY */) {
294
+ this.emit("onopenarray");
295
+ this.depth++;
296
+ this.state = 1 /* VALUE */;
297
+ if (c === Char.closeBracket) {
298
+ this.emit("onclosearray");
299
+ this.depth--;
300
+ this.state = this.stack.pop() || 1 /* VALUE */;
301
+ continue;
302
+ } else {
303
+ this.stack.push(5 /* CLOSE_ARRAY */);
304
+ }
305
+ }
306
+ if (c === Char.doubleQuote)
307
+ this.state = 7 /* STRING */;
308
+ else if (c === Char.openBrace)
309
+ this.state = 2 /* OPEN_OBJECT */;
310
+ else if (c === Char.openBracket)
311
+ this.state = 4 /* OPEN_ARRAY */;
312
+ else if (c === Char.t)
313
+ this.state = 12 /* TRUE */;
314
+ else if (c === Char.f)
315
+ this.state = 15 /* FALSE */;
316
+ else if (c === Char.n)
317
+ this.state = 19 /* NULL */;
318
+ else if (c === Char.minus) {
319
+ this.numberNode += "-";
320
+ } else if (Char._0 <= c && c <= Char._9) {
321
+ this.numberNode += String.fromCharCode(c);
322
+ this.state = 23 /* NUMBER_DIGIT */;
323
+ } else
324
+ this._error("Bad value");
325
+ continue;
326
+ case 5 /* CLOSE_ARRAY */:
327
+ if (c === Char.comma) {
328
+ this.stack.push(5 /* CLOSE_ARRAY */);
329
+ this._closeValue("onvalue");
330
+ this.state = 1 /* VALUE */;
331
+ } else if (c === Char.closeBracket) {
332
+ this.emitNode("onclosearray");
333
+ this.depth--;
334
+ this.state = this.stack.pop() || 1 /* VALUE */;
335
+ } else if (isWhitespace(c))
336
+ continue;
337
+ else
338
+ this._error("Bad array");
339
+ continue;
340
+ case 7 /* STRING */:
341
+ if (this.textNode === void 0) {
342
+ this.textNode = "";
343
+ }
344
+ let starti = i - 1;
345
+ let slashed = this.slashed;
346
+ let unicodeI = this.unicodeI;
347
+ STRING_BIGLOOP:
348
+ while (true) {
349
+ while (unicodeI > 0) {
350
+ this.unicodeS += String.fromCharCode(c);
351
+ c = chunk.charCodeAt(i++);
352
+ this.position++;
353
+ if (unicodeI === 4) {
354
+ this.textNode += String.fromCharCode(parseInt(this.unicodeS, 16));
355
+ unicodeI = 0;
356
+ starti = i - 1;
357
+ } else {
358
+ unicodeI++;
359
+ }
360
+ if (!c)
361
+ break STRING_BIGLOOP;
362
+ }
363
+ if (c === Char.doubleQuote && !slashed) {
364
+ this.state = this.stack.pop() || 1 /* VALUE */;
365
+ this.textNode += chunk.substring(starti, i - 1);
366
+ this.position += i - 1 - starti;
367
+ break;
368
+ }
369
+ if (c === Char.backslash && !slashed) {
370
+ slashed = true;
371
+ this.textNode += chunk.substring(starti, i - 1);
372
+ this.position += i - 1 - starti;
373
+ c = chunk.charCodeAt(i++);
374
+ this.position++;
375
+ if (!c)
376
+ break;
377
+ }
378
+ if (slashed) {
379
+ slashed = false;
380
+ if (c === Char.n) {
381
+ this.textNode += "\n";
382
+ } else if (c === Char.r) {
383
+ this.textNode += "\r";
384
+ } else if (c === Char.t) {
385
+ this.textNode += " ";
386
+ } else if (c === Char.f) {
387
+ this.textNode += "\f";
388
+ } else if (c === Char.b) {
389
+ this.textNode += "\b";
390
+ } else if (c === Char.u) {
391
+ unicodeI = 1;
392
+ this.unicodeS = "";
393
+ } else {
394
+ this.textNode += String.fromCharCode(c);
395
+ }
396
+ c = chunk.charCodeAt(i++);
397
+ this.position++;
398
+ starti = i - 1;
399
+ if (!c)
400
+ break;
401
+ else
402
+ continue;
403
+ }
404
+ stringTokenPattern.lastIndex = i;
405
+ const reResult = stringTokenPattern.exec(chunk);
406
+ if (reResult === null) {
407
+ i = chunk.length + 1;
408
+ this.textNode += chunk.substring(starti, i - 1);
409
+ this.position += i - 1 - starti;
410
+ break;
411
+ }
412
+ i = reResult.index + 1;
413
+ c = chunk.charCodeAt(reResult.index);
414
+ if (!c) {
415
+ this.textNode += chunk.substring(starti, i - 1);
416
+ this.position += i - 1 - starti;
417
+ break;
418
+ }
419
+ }
420
+ this.slashed = slashed;
421
+ this.unicodeI = unicodeI;
422
+ continue;
423
+ case 12 /* TRUE */:
424
+ if (c === Char.r)
425
+ this.state = 13 /* TRUE2 */;
426
+ else
427
+ this._error(`Invalid true started with t${c}`);
428
+ continue;
429
+ case 13 /* TRUE2 */:
430
+ if (c === Char.u)
431
+ this.state = 14 /* TRUE3 */;
432
+ else
433
+ this._error(`Invalid true started with tr${c}`);
434
+ continue;
435
+ case 14 /* TRUE3 */:
436
+ if (c === Char.e) {
437
+ this.emit("onvalue", true);
438
+ this.state = this.stack.pop() || 1 /* VALUE */;
439
+ } else
440
+ this._error(`Invalid true started with tru${c}`);
441
+ continue;
442
+ case 15 /* FALSE */:
443
+ if (c === Char.a)
444
+ this.state = 16 /* FALSE2 */;
445
+ else
446
+ this._error(`Invalid false started with f${c}`);
447
+ continue;
448
+ case 16 /* FALSE2 */:
449
+ if (c === Char.l)
450
+ this.state = 17 /* FALSE3 */;
451
+ else
452
+ this._error(`Invalid false started with fa${c}`);
453
+ continue;
454
+ case 17 /* FALSE3 */:
455
+ if (c === Char.s)
456
+ this.state = 18 /* FALSE4 */;
457
+ else
458
+ this._error(`Invalid false started with fal${c}`);
459
+ continue;
460
+ case 18 /* FALSE4 */:
461
+ if (c === Char.e) {
462
+ this.emit("onvalue", false);
463
+ this.state = this.stack.pop() || 1 /* VALUE */;
464
+ } else
465
+ this._error(`Invalid false started with fals${c}`);
466
+ continue;
467
+ case 19 /* NULL */:
468
+ if (c === Char.u)
469
+ this.state = 20 /* NULL2 */;
470
+ else
471
+ this._error(`Invalid null started with n${c}`);
472
+ continue;
473
+ case 20 /* NULL2 */:
474
+ if (c === Char.l)
475
+ this.state = 21 /* NULL3 */;
476
+ else
477
+ this._error(`Invalid null started with nu${c}`);
478
+ continue;
479
+ case 21 /* NULL3 */:
480
+ if (c === Char.l) {
481
+ this.emit("onvalue", null);
482
+ this.state = this.stack.pop() || 1 /* VALUE */;
483
+ } else
484
+ this._error(`Invalid null started with nul${c}`);
485
+ continue;
486
+ case 22 /* NUMBER_DECIMAL_POINT */:
487
+ if (c === Char.period) {
488
+ this.numberNode += ".";
489
+ this.state = 23 /* NUMBER_DIGIT */;
490
+ } else
491
+ this._error("Leading zero not followed by .");
492
+ continue;
493
+ case 23 /* NUMBER_DIGIT */:
494
+ if (Char._0 <= c && c <= Char._9)
495
+ this.numberNode += String.fromCharCode(c);
496
+ else if (c === Char.period) {
497
+ if (this.numberNode.indexOf(".") !== -1)
498
+ this._error("Invalid number has two dots");
499
+ this.numberNode += ".";
500
+ } else if (c === Char.e || c === Char.E) {
501
+ if (this.numberNode.indexOf("e") !== -1 || this.numberNode.indexOf("E") !== -1)
502
+ this._error("Invalid number has two exponential");
503
+ this.numberNode += "e";
504
+ } else if (c === Char.plus || c === Char.minus) {
505
+ if (!(p === Char.e || p === Char.E))
506
+ this._error("Invalid symbol in number");
507
+ this.numberNode += String.fromCharCode(c);
508
+ } else {
509
+ this._closeNumber();
510
+ i--;
511
+ this.state = this.stack.pop() || 1 /* VALUE */;
512
+ }
513
+ continue;
514
+ default:
515
+ this._error(`Unknown state: ${this.state}`);
516
+ }
517
+ }
518
+ if (this.position >= this.bufferCheckPosition) {
519
+ checkBufferLength(this);
520
+ }
521
+ this.emit("onchunkparsed");
522
+ return this;
523
+ }
524
+ _closeValue(event = "onvalue") {
525
+ if (this.textNode !== void 0) {
526
+ this.emit(event, this.textNode);
527
+ }
528
+ this.textNode = void 0;
529
+ }
530
+ _closeNumber() {
531
+ if (this.numberNode)
532
+ this.emit("onvalue", parseFloat(this.numberNode));
533
+ this.numberNode = "";
534
+ }
535
+ _error(message = "") {
536
+ this._closeValue();
537
+ message += `
538
+ Line: ${this.line}
539
+ Column: ${this.column}
540
+ Char: ${this.c}`;
541
+ const error = new Error(message);
542
+ this.error = error;
543
+ this.emit("onerror", error);
544
+ }
545
+ };
546
+ function isWhitespace(c) {
547
+ return c === Char.carriageReturn || c === Char.lineFeed || c === Char.space || c === Char.tab;
548
+ }
549
+ function checkBufferLength(parser) {
550
+ const maxAllowed = Math.max(MAX_BUFFER_LENGTH, 10);
551
+ let maxActual = 0;
552
+ for (const buffer of ["textNode", "numberNode"]) {
553
+ const len = parser[buffer] === void 0 ? 0 : parser[buffer].length;
554
+ if (len > maxAllowed) {
555
+ switch (buffer) {
556
+ case "text":
557
+ break;
558
+ default:
559
+ parser._error(`Max buffer length exceeded: ${buffer}`);
560
+ }
561
+ }
562
+ maxActual = Math.max(maxActual, len);
563
+ }
564
+ parser.bufferCheckPosition = MAX_BUFFER_LENGTH - maxActual + parser.position;
565
+ }
566
+
567
+ // src/lib/jsonpath/jsonpath.ts
568
+ var JSONPath = class {
569
+ constructor(path = null) {
570
+ this.path = ["$"];
571
+ if (path instanceof JSONPath) {
572
+ this.path = [...path.path];
573
+ return;
574
+ }
575
+ if (Array.isArray(path)) {
576
+ this.path.push(...path);
577
+ return;
578
+ }
579
+ if (typeof path === "string") {
580
+ this.path = path.split(".");
581
+ if (this.path[0] !== "$") {
582
+ throw new Error("JSONPaths must start with $");
583
+ }
584
+ }
585
+ }
586
+ clone() {
587
+ return new JSONPath(this);
588
+ }
589
+ toString() {
590
+ return this.path.join(".");
591
+ }
592
+ push(name) {
593
+ this.path.push(name);
594
+ }
595
+ pop() {
596
+ return this.path.pop();
597
+ }
598
+ set(name) {
599
+ this.path[this.path.length - 1] = name;
600
+ }
601
+ equals(other) {
602
+ if (!this || !other || this.path.length !== other.path.length) {
603
+ return false;
604
+ }
605
+ for (let i = 0; i < this.path.length; ++i) {
606
+ if (this.path[i] !== other.path[i]) {
607
+ return false;
608
+ }
609
+ }
610
+ return true;
611
+ }
612
+ /**
613
+ * Sets the value pointed at by path
614
+ * TODO - handle root path
615
+ * @param object
616
+ * @param value
617
+ */
618
+ setFieldAtPath(object, value) {
619
+ const path = [...this.path];
620
+ path.shift();
621
+ const field = path.pop();
622
+ for (const component of path) {
623
+ object = object[component];
624
+ }
625
+ object[field] = value;
626
+ }
627
+ /**
628
+ * Gets the value pointed at by path
629
+ * TODO - handle root path
630
+ * @param object
631
+ */
632
+ getFieldAtPath(object) {
633
+ const path = [...this.path];
634
+ path.shift();
635
+ const field = path.pop();
636
+ for (const component of path) {
637
+ object = object[component];
638
+ }
639
+ return object[field];
640
+ }
641
+ };
642
+
643
+ // src/lib/json-parser/json-parser.ts
644
+ var JSONParser = class {
645
+ constructor(options) {
646
+ this.result = void 0;
647
+ this.previousStates = [];
648
+ this.currentState = Object.freeze({ container: [], key: null });
649
+ this.jsonpath = new JSONPath();
650
+ this.reset();
651
+ this.parser = new ClarinetParser({
652
+ onready: () => {
653
+ this.jsonpath = new JSONPath();
654
+ this.previousStates.length = 0;
655
+ this.currentState.container.length = 0;
656
+ },
657
+ onopenobject: (name) => {
658
+ this._openObject({});
659
+ if (typeof name !== "undefined") {
660
+ this.parser.emit("onkey", name);
661
+ }
662
+ },
663
+ onkey: (name) => {
664
+ this.jsonpath.set(name);
665
+ this.currentState.key = name;
666
+ },
667
+ oncloseobject: () => {
668
+ this._closeObject();
669
+ },
670
+ onopenarray: () => {
671
+ this._openArray();
672
+ },
673
+ onclosearray: () => {
674
+ this._closeArray();
675
+ },
676
+ onvalue: (value) => {
677
+ this._pushOrSet(value);
678
+ },
679
+ onerror: (error) => {
680
+ throw error;
681
+ },
682
+ onend: () => {
683
+ this.result = this.currentState.container.pop();
684
+ },
685
+ ...options
686
+ });
687
+ }
688
+ reset() {
689
+ this.result = void 0;
690
+ this.previousStates = [];
691
+ this.currentState = Object.freeze({ container: [], key: null });
692
+ this.jsonpath = new JSONPath();
693
+ }
694
+ write(chunk) {
695
+ this.parser.write(chunk);
696
+ }
697
+ close() {
698
+ this.parser.close();
699
+ }
700
+ // PRIVATE METHODS
701
+ _pushOrSet(value) {
702
+ const { container, key } = this.currentState;
703
+ if (key !== null) {
704
+ container[key] = value;
705
+ this.currentState.key = null;
706
+ } else {
707
+ container.push(value);
708
+ }
709
+ }
710
+ _openArray(newContainer = []) {
711
+ this.jsonpath.push(null);
712
+ this._pushOrSet(newContainer);
713
+ this.previousStates.push(this.currentState);
714
+ this.currentState = { container: newContainer, isArray: true, key: null };
715
+ }
716
+ _closeArray() {
717
+ this.jsonpath.pop();
718
+ this.currentState = this.previousStates.pop();
719
+ }
720
+ _openObject(newContainer = {}) {
721
+ this.jsonpath.push(null);
722
+ this._pushOrSet(newContainer);
723
+ this.previousStates.push(this.currentState);
724
+ this.currentState = { container: newContainer, isArray: false, key: null };
725
+ }
726
+ _closeObject() {
727
+ this.jsonpath.pop();
728
+ this.currentState = this.previousStates.pop();
729
+ }
730
+ };
731
+
732
+ // src/lib/json-parser/streaming-json-parser.ts
733
+ var StreamingJSONParser = class extends JSONParser {
734
+ constructor(options = {}) {
735
+ super({
736
+ onopenarray: () => {
737
+ if (!this.streamingArray) {
738
+ if (this._matchJSONPath()) {
739
+ this.streamingJsonPath = this.getJsonPath().clone();
740
+ this.streamingArray = [];
741
+ this._openArray(this.streamingArray);
742
+ return;
743
+ }
744
+ }
745
+ this._openArray();
746
+ },
747
+ // Redefine onopenarray to inject value for top-level object
748
+ onopenobject: (name) => {
749
+ if (!this.topLevelObject) {
750
+ this.topLevelObject = {};
751
+ this._openObject(this.topLevelObject);
752
+ } else {
753
+ this._openObject({});
754
+ }
755
+ if (typeof name !== "undefined") {
756
+ this.parser.emit("onkey", name);
757
+ }
758
+ }
759
+ });
760
+ this.streamingJsonPath = null;
761
+ this.streamingArray = null;
762
+ this.topLevelObject = null;
763
+ const jsonpaths = options.jsonpaths || [];
764
+ this.jsonPaths = jsonpaths.map((jsonpath) => new JSONPath(jsonpath));
765
+ }
766
+ /**
767
+ * write REDEFINITION
768
+ * - super.write() chunk to parser
769
+ * - get the contents (so far) of "topmost-level" array as batch of rows
770
+ * - clear top-level array
771
+ * - return the batch of rows\
772
+ */
773
+ write(chunk) {
774
+ super.write(chunk);
775
+ let array = [];
776
+ if (this.streamingArray) {
777
+ array = [...this.streamingArray];
778
+ this.streamingArray.length = 0;
779
+ }
780
+ return array;
781
+ }
782
+ /**
783
+ * Returns a partially formed result object
784
+ * Useful for returning the "wrapper" object when array is not top level
785
+ * e.g. GeoJSON
786
+ */
787
+ getPartialResult() {
788
+ return this.topLevelObject;
789
+ }
790
+ getStreamingJsonPath() {
791
+ return this.streamingJsonPath;
792
+ }
793
+ getStreamingJsonPathAsString() {
794
+ return this.streamingJsonPath && this.streamingJsonPath.toString();
795
+ }
796
+ getJsonPath() {
797
+ return this.jsonpath;
798
+ }
799
+ // PRIVATE METHODS
800
+ /**
801
+ * Checks is this.getJsonPath matches the jsonpaths provided in options
802
+ */
803
+ _matchJSONPath() {
804
+ const currentPath = this.getJsonPath();
805
+ if (this.jsonPaths.length === 0) {
806
+ return true;
807
+ }
808
+ for (const jsonPath of this.jsonPaths) {
809
+ if (jsonPath.equals(currentPath)) {
810
+ return true;
811
+ }
812
+ }
813
+ return false;
814
+ }
815
+ };
816
+
817
+ // src/lib/parsers/parse-json-in-batches.ts
818
+ async function* parseJSONInBatches(binaryAsyncIterator, options) {
819
+ var _a;
820
+ const asyncIterator = (0, import_loader_utils.makeTextDecoderIterator)(binaryAsyncIterator);
821
+ const { metadata } = options;
822
+ const { jsonpaths } = options.json || {};
823
+ let isFirstChunk = true;
824
+ const schema = null;
825
+ const shape = ((_a = options == null ? void 0 : options.json) == null ? void 0 : _a.shape) || "object-row-table";
826
+ const tableBatchBuilder = new import_schema2.TableBatchBuilder(schema, {
827
+ ...options,
828
+ shape
829
+ });
830
+ const parser = new StreamingJSONParser({ jsonpaths });
831
+ for await (const chunk of asyncIterator) {
832
+ const rows = parser.write(chunk);
833
+ const jsonpath2 = rows.length > 0 && parser.getStreamingJsonPathAsString();
834
+ if (rows.length > 0 && isFirstChunk) {
835
+ if (metadata) {
836
+ const initialBatch = {
837
+ // Common fields
838
+ shape,
839
+ batchType: "partial-result",
840
+ data: [],
841
+ length: 0,
842
+ bytesUsed: 0,
843
+ // JSON additions
844
+ container: parser.getPartialResult(),
845
+ jsonpath: jsonpath2
846
+ };
847
+ yield initialBatch;
848
+ }
849
+ isFirstChunk = false;
850
+ }
851
+ for (const row of rows) {
852
+ tableBatchBuilder.addRow(row);
853
+ const batch3 = tableBatchBuilder.getFullBatch({ jsonpath: jsonpath2 });
854
+ if (batch3) {
855
+ yield batch3;
856
+ }
857
+ }
858
+ tableBatchBuilder.chunkComplete(chunk);
859
+ const batch2 = tableBatchBuilder.getFullBatch({ jsonpath: jsonpath2 });
860
+ if (batch2) {
861
+ yield batch2;
862
+ }
863
+ }
864
+ const jsonpath = parser.getStreamingJsonPathAsString();
865
+ const batch = tableBatchBuilder.getFinalBatch({ jsonpath });
866
+ if (batch) {
867
+ yield batch;
868
+ }
869
+ if (metadata) {
870
+ const finalBatch = {
871
+ shape,
872
+ batchType: "final-result",
873
+ container: parser.getPartialResult(),
874
+ jsonpath: parser.getStreamingJsonPathAsString(),
875
+ data: [],
876
+ length: 0
877
+ // schema: null
878
+ };
879
+ yield finalBatch;
880
+ }
881
+ }
882
+ function rebuildJsonObject(batch, data) {
883
+ (0, import_loader_utils.assert)(batch.batchType === "final-result");
884
+ if (batch.jsonpath === "$") {
885
+ return data;
886
+ }
887
+ if (batch.jsonpath && batch.jsonpath.length > 1) {
888
+ const topLevelObject = batch.container;
889
+ const streamingPath = new JSONPath(batch.jsonpath);
890
+ streamingPath.setFieldAtPath(topLevelObject, data);
891
+ return topLevelObject;
892
+ }
893
+ return batch.container;
894
+ }
895
+
896
+ // src/json-loader.ts
897
+ var VERSION = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
898
+ var DEFAULT_JSON_LOADER_OPTIONS = {
899
+ json: {
900
+ shape: "object-row-table",
901
+ table: false,
902
+ jsonpaths: []
903
+ // batchSize: 'auto'
904
+ }
905
+ };
906
+ var JSONLoader = {
907
+ name: "JSON",
908
+ id: "json",
909
+ module: "json",
910
+ version: VERSION,
911
+ extensions: ["json", "geojson"],
912
+ mimeTypes: ["application/json"],
913
+ category: "table",
914
+ text: true,
915
+ parse,
916
+ parseTextSync,
917
+ parseInBatches,
918
+ options: DEFAULT_JSON_LOADER_OPTIONS
919
+ };
920
+ async function parse(arrayBuffer, options) {
921
+ return parseTextSync(new TextDecoder().decode(arrayBuffer), options);
922
+ }
923
+ function parseTextSync(text, options) {
924
+ const jsonOptions = { ...options, json: { ...DEFAULT_JSON_LOADER_OPTIONS.json, ...options == null ? void 0 : options.json } };
925
+ return parseJSONSync(text, jsonOptions);
926
+ }
927
+ function parseInBatches(asyncIterator, options) {
928
+ const jsonOptions = { ...options, json: { ...DEFAULT_JSON_LOADER_OPTIONS.json, ...options == null ? void 0 : options.json } };
929
+ return parseJSONInBatches(asyncIterator, jsonOptions);
930
+ }
931
+
932
+ // src/lib/parsers/parse-ndjson.ts
933
+ var import_schema3 = require("@loaders.gl/schema");
934
+ function parseNDJSONSync(ndjsonText) {
935
+ const lines = ndjsonText.trim().split("\n");
936
+ const parsedLines = lines.map((line, counter) => {
937
+ try {
938
+ return JSON.parse(line);
939
+ } catch (error) {
940
+ throw new Error(`NDJSONLoader: failed to parse JSON on line ${counter + 1}`);
941
+ }
942
+ });
943
+ return (0, import_schema3.makeTableFromData)(parsedLines);
944
+ }
945
+
946
+ // src/lib/parsers/parse-ndjson-in-batches.ts
947
+ var import_schema4 = require("@loaders.gl/schema");
948
+ var import_loader_utils2 = require("@loaders.gl/loader-utils");
949
+ async function* parseNDJSONInBatches(binaryAsyncIterator, options) {
950
+ const textIterator = (0, import_loader_utils2.makeTextDecoderIterator)(binaryAsyncIterator);
951
+ const lineIterator = (0, import_loader_utils2.makeLineIterator)(textIterator);
952
+ const numberedLineIterator = (0, import_loader_utils2.makeNumberedLineIterator)(lineIterator);
953
+ const schema = null;
954
+ const shape = "row-table";
955
+ const tableBatchBuilder = new import_schema4.TableBatchBuilder(schema, {
956
+ ...options,
957
+ shape
958
+ });
959
+ for await (const { counter, line } of numberedLineIterator) {
960
+ try {
961
+ const row = JSON.parse(line);
962
+ tableBatchBuilder.addRow(row);
963
+ tableBatchBuilder.chunkComplete(line);
964
+ const batch2 = tableBatchBuilder.getFullBatch();
965
+ if (batch2) {
966
+ yield batch2;
967
+ }
968
+ } catch (error) {
969
+ throw new Error(`NDJSONLoader: failed to parse JSON on line ${counter}`);
970
+ }
971
+ }
972
+ const batch = tableBatchBuilder.getFinalBatch();
973
+ if (batch) {
974
+ yield batch;
975
+ }
976
+ }
977
+
978
+ // src/ndjson-loader.ts
979
+ var VERSION2 = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
980
+ var NDJSONLoader = {
981
+ name: "NDJSON",
982
+ id: "ndjson",
983
+ module: "json",
984
+ version: VERSION2,
985
+ extensions: ["ndjson", "jsonl"],
986
+ mimeTypes: [
987
+ "application/x-ndjson",
988
+ "application/jsonlines",
989
+ // https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-inference.html#cm-batch
990
+ "application/json-seq"
991
+ ],
992
+ category: "table",
993
+ text: true,
994
+ parse: async (arrayBuffer) => parseNDJSONSync(new TextDecoder().decode(arrayBuffer)),
995
+ parseTextSync: parseNDJSONSync,
996
+ parseInBatches: parseNDJSONInBatches,
997
+ options: {}
998
+ };
999
+
1000
+ // src/lib/encoders/json-encoder.ts
1001
+ var import_schema5 = require("@loaders.gl/schema");
1002
+ function encodeTableAsJSON(table, options) {
1003
+ var _a;
1004
+ const shape = ((_a = options == null ? void 0 : options.json) == null ? void 0 : _a.shape) || "object-row-table";
1005
+ const strings = [];
1006
+ const rowIterator = (0, import_schema5.makeRowIterator)(table, shape);
1007
+ for (const row of rowIterator) {
1008
+ strings.push(JSON.stringify(row));
1009
+ }
1010
+ return `[${strings.join(",")}]`;
1011
+ }
1012
+
1013
+ // src/json-writer.ts
1014
+ var JSONWriter = {
1015
+ id: "json",
1016
+ version: "latest",
1017
+ module: "json",
1018
+ name: "JSON",
1019
+ extensions: ["json"],
1020
+ mimeTypes: ["application/json"],
1021
+ options: {},
1022
+ text: true,
1023
+ encode: async (table, options) => new TextEncoder().encode(encodeTableAsJSON(table, options)).buffer,
1024
+ encodeTextSync: (table, options) => encodeTableAsJSON(table, options)
1025
+ };
1026
+
1027
+ // src/geojson-loader.ts
1028
+ var import_gis = require("@loaders.gl/gis");
1029
+ var VERSION3 = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
1030
+ var GeoJSONWorkerLoader = {
1031
+ name: "GeoJSON",
1032
+ id: "geojson",
1033
+ module: "geojson",
1034
+ version: VERSION3,
1035
+ worker: true,
1036
+ extensions: ["geojson"],
1037
+ mimeTypes: ["application/geo+json"],
1038
+ category: "geometry",
1039
+ text: true,
1040
+ options: {
1041
+ geojson: {
1042
+ shape: "object-row-table"
1043
+ },
1044
+ json: {
1045
+ shape: "object-row-table",
1046
+ jsonpaths: ["$", "$.features"]
1047
+ },
1048
+ gis: {
1049
+ format: "geojson"
1050
+ }
1051
+ }
1052
+ };
1053
+ var GeoJSONLoader = {
1054
+ ...GeoJSONWorkerLoader,
1055
+ // @ts-expect-error
1056
+ parse: parse2,
1057
+ // @ts-expect-error
1058
+ parseTextSync: parseTextSync2,
1059
+ parseInBatches: parseInBatches2
1060
+ };
1061
+ async function parse2(arrayBuffer, options) {
1062
+ return parseTextSync2(new TextDecoder().decode(arrayBuffer), options);
1063
+ }
1064
+ function parseTextSync2(text, options) {
1065
+ options = { ...GeoJSONLoader.options, ...options };
1066
+ options.geojson = { ...GeoJSONLoader.options.geojson, ...options.geojson };
1067
+ options.gis = options.gis || {};
1068
+ let geojson;
1069
+ try {
1070
+ geojson = JSON.parse(text);
1071
+ } catch {
1072
+ geojson = {};
1073
+ }
1074
+ const table = {
1075
+ shape: "geojson-table",
1076
+ // TODO - deduce schema from geojson
1077
+ // TODO check that parsed data is of type FeatureCollection
1078
+ type: "FeatureCollection",
1079
+ features: (geojson == null ? void 0 : geojson.features) || []
1080
+ };
1081
+ switch (options.gis.format) {
1082
+ case "binary":
1083
+ return (0, import_gis.geojsonToBinary)(table.features);
1084
+ default:
1085
+ return table;
1086
+ }
1087
+ }
1088
+ function parseInBatches2(asyncIterator, options) {
1089
+ options = { ...GeoJSONLoader.options, ...options };
1090
+ options.json = { ...GeoJSONLoader.options.geojson, ...options.geojson };
1091
+ const geojsonIterator = parseJSONInBatches(asyncIterator, options);
1092
+ switch (options.gis.format) {
1093
+ case "binary":
1094
+ return makeBinaryGeometryIterator(geojsonIterator);
1095
+ default:
1096
+ return geojsonIterator;
1097
+ }
1098
+ }
1099
+ async function* makeBinaryGeometryIterator(geojsonIterator) {
1100
+ for await (const batch of geojsonIterator) {
1101
+ batch.data = (0, import_gis.geojsonToBinary)(batch.data);
1102
+ yield batch;
1103
+ }
1104
+ }
1105
+
1106
+ // src/lib/encoders/geojson-encoder.ts
1107
+ var import_schema8 = require("@loaders.gl/schema");
1108
+
1109
+ // src/lib/encoder-utils/encode-utils.ts
1110
+ var import_schema6 = require("@loaders.gl/schema");
1111
+ function detectGeometryColumnIndex(table) {
1112
+ var _a;
1113
+ const geometryIndex = ((_a = table.schema) == null ? void 0 : _a.fields.findIndex((field) => field.name === "geometry")) ?? -1;
1114
+ if (geometryIndex > -1) {
1115
+ return geometryIndex;
1116
+ }
1117
+ if ((0, import_schema6.getTableLength)(table) > 0) {
1118
+ const row = (0, import_schema6.getTableRowAsArray)(table, 0);
1119
+ for (let columnIndex = 0; columnIndex < (0, import_schema6.getTableNumCols)(table); columnIndex++) {
1120
+ const value = row == null ? void 0 : row[columnIndex];
1121
+ if (value && typeof value === "object") {
1122
+ return columnIndex;
1123
+ }
1124
+ }
1125
+ }
1126
+ throw new Error("Failed to detect geometry column");
1127
+ }
1128
+ function getRowPropertyObject(table, row, excludeColumnIndices = []) {
1129
+ var _a;
1130
+ const properties = {};
1131
+ for (let columnIndex = 0; columnIndex < (0, import_schema6.getTableNumCols)(table); ++columnIndex) {
1132
+ const columnName = (_a = table.schema) == null ? void 0 : _a.fields[columnIndex].name;
1133
+ if (columnName && !excludeColumnIndices.includes(columnIndex)) {
1134
+ properties[columnName] = row[columnName];
1135
+ }
1136
+ }
1137
+ return properties;
1138
+ }
1139
+
1140
+ // src/lib/encoder-utils/encode-table-row.ts
1141
+ var import_schema7 = require("@loaders.gl/schema");
1142
+ function encodeTableRow(table, rowIndex, geometryColumnIndex, utf8Encoder) {
1143
+ const row = (0, import_schema7.getTableRowAsObject)(table, rowIndex);
1144
+ if (!row)
1145
+ return;
1146
+ const featureWithProperties = getFeatureFromRow(table, row, geometryColumnIndex);
1147
+ const featureString = JSON.stringify(featureWithProperties);
1148
+ utf8Encoder.push(featureString);
1149
+ }
1150
+ function getFeatureFromRow(table, row, geometryColumnIndex) {
1151
+ var _a;
1152
+ const properties = getRowPropertyObject(table, row, [geometryColumnIndex]);
1153
+ const columnName = (_a = table.schema) == null ? void 0 : _a.fields[geometryColumnIndex].name;
1154
+ let featureOrGeometry = columnName && row[columnName];
1155
+ if (!featureOrGeometry) {
1156
+ return { type: "Feature", geometry: null, properties };
1157
+ }
1158
+ if (typeof featureOrGeometry === "string") {
1159
+ try {
1160
+ featureOrGeometry = JSON.parse(featureOrGeometry);
1161
+ } catch (err) {
1162
+ throw new Error("Invalid string geometry");
1163
+ }
1164
+ }
1165
+ if (typeof featureOrGeometry !== "object" || typeof (featureOrGeometry == null ? void 0 : featureOrGeometry.type) !== "string") {
1166
+ throw new Error("invalid geometry column value");
1167
+ }
1168
+ if ((featureOrGeometry == null ? void 0 : featureOrGeometry.type) === "Feature") {
1169
+ return { ...featureOrGeometry, properties };
1170
+ }
1171
+ return { type: "Feature", geometry: featureOrGeometry, properties };
1172
+ }
1173
+
1174
+ // src/lib/encoder-utils/utf8-encoder.ts
1175
+ var Utf8ArrayBufferEncoder = class {
1176
+ constructor(chunkSize) {
1177
+ this.strings = [];
1178
+ this.totalLength = 0;
1179
+ this.textEncoder = new TextEncoder();
1180
+ this.chunkSize = chunkSize;
1181
+ }
1182
+ push(...strings) {
1183
+ for (const string of strings) {
1184
+ this.strings.push(string);
1185
+ this.totalLength += string.length;
1186
+ }
1187
+ }
1188
+ isFull() {
1189
+ return this.totalLength >= this.chunkSize;
1190
+ }
1191
+ getArrayBufferBatch() {
1192
+ return this.textEncoder.encode(this.getStringBatch()).buffer;
1193
+ }
1194
+ getStringBatch() {
1195
+ const stringChunk = this.strings.join("");
1196
+ this.strings = [];
1197
+ this.totalLength = 0;
1198
+ return stringChunk;
1199
+ }
1200
+ };
1201
+
1202
+ // src/lib/encoders/geojson-encoder.ts
1203
+ async function* encodeTableAsGeojsonInBatches(batchIterator, inputOpts = {}) {
1204
+ const options = { geojson: {}, chunkSize: 1e4, ...inputOpts };
1205
+ const utf8Encoder = new Utf8ArrayBufferEncoder(options.chunkSize);
1206
+ if (!options.geojson.featureArray) {
1207
+ utf8Encoder.push("{\n", '"type": "FeatureCollection",\n', '"features":\n');
1208
+ }
1209
+ utf8Encoder.push("[");
1210
+ let geometryColumn = options.geojson.geometryColumn;
1211
+ let isFirstLine = true;
1212
+ let start = 0;
1213
+ for await (const tableBatch of batchIterator) {
1214
+ const end = start + (0, import_schema8.getTableLength)(tableBatch);
1215
+ if (!geometryColumn) {
1216
+ geometryColumn = geometryColumn || detectGeometryColumnIndex(tableBatch);
1217
+ }
1218
+ for (let rowIndex = start; rowIndex < end; ++rowIndex) {
1219
+ if (!isFirstLine) {
1220
+ utf8Encoder.push(",");
1221
+ }
1222
+ utf8Encoder.push("\n");
1223
+ isFirstLine = false;
1224
+ encodeTableRow(tableBatch, rowIndex, geometryColumn, utf8Encoder);
1225
+ if (utf8Encoder.isFull()) {
1226
+ yield utf8Encoder.getArrayBufferBatch();
1227
+ }
1228
+ start = end;
1229
+ }
1230
+ const arrayBufferBatch = utf8Encoder.getArrayBufferBatch();
1231
+ if (arrayBufferBatch.byteLength > 0) {
1232
+ yield arrayBufferBatch;
1233
+ }
1234
+ }
1235
+ utf8Encoder.push("\n");
1236
+ utf8Encoder.push("]\n");
1237
+ if (!options.geojson.featureArray) {
1238
+ utf8Encoder.push("}");
1239
+ }
1240
+ yield utf8Encoder.getArrayBufferBatch();
1241
+ }
1242
+
1243
+ // src/geojson-writer.ts
1244
+ var GeoJSONWriter = {
1245
+ id: "geojson",
1246
+ version: "latest",
1247
+ module: "geojson",
1248
+ name: "GeoJSON",
1249
+ extensions: ["geojson"],
1250
+ mimeTypes: ["application/geo+json"],
1251
+ options: {
1252
+ geojson: {
1253
+ featureArray: false,
1254
+ geometryColumn: null
1255
+ }
1256
+ },
1257
+ text: true,
1258
+ encodeInBatches: (tableIterator, options) => encodeTableAsGeojsonInBatches(tableIterator, options)
1259
+ };