@loaders.gl/core 5.0.0 → 5.0.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 (219) hide show
  1. package/dist/api.cjs +4129 -0
  2. package/dist/api.cjs.map +6 -0
  3. package/dist/api.d.ts +34 -0
  4. package/dist/api.d.ts.map +1 -0
  5. package/dist/api.js +50 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/arrow-geometry/index.cjs +5 -2
  8. package/dist/arrow-geometry/index.cjs.map +2 -2
  9. package/dist/arrow-geometry/index.d.ts +1 -0
  10. package/dist/arrow-geometry/index.d.ts.map +1 -1
  11. package/dist/arrow-geometry/index.js +1 -0
  12. package/dist/arrow-geometry/index.js.map +1 -1
  13. package/dist/arrow-geometry/triangulate-wkb-geometry-column.cjs +100 -0
  14. package/dist/arrow-geometry/triangulate-wkb-geometry-column.cjs.map +7 -0
  15. package/dist/arrow-geometry/triangulate-wkb-geometry-column.d.ts +15 -0
  16. package/dist/arrow-geometry/triangulate-wkb-geometry-column.d.ts.map +1 -0
  17. package/dist/arrow-geometry/triangulate-wkb-geometry-column.js +87 -0
  18. package/dist/arrow-geometry/triangulate-wkb-geometry-column.js.map +1 -0
  19. package/dist/dist.dev.js +458 -539
  20. package/dist/dist.min.js +3 -3
  21. package/dist/geoarrow/geoarrow-converter/geoarrow-converter.d.ts +1 -1
  22. package/dist/geoarrow/geoarrow-converter/geoarrow-converter.d.ts.map +1 -1
  23. package/dist/geoarrow/index.cjs +1 -1
  24. package/dist/geoarrow/index.cjs.map +1 -1
  25. package/dist/geoarrow/index.d.ts +2 -2
  26. package/dist/geoarrow/index.d.ts.map +1 -1
  27. package/dist/geoarrow/index.js +1 -1
  28. package/dist/geoarrow/index.js.map +1 -1
  29. package/dist/geoarrow/lib/kernels/decode-wkt-native.cjs +1 -1
  30. package/dist/geoarrow/lib/kernels/decode-wkt-native.cjs.map +1 -1
  31. package/dist/geoarrow/lib/kernels/decode-wkt-native.d.ts +1 -1
  32. package/dist/geoarrow/lib/kernels/decode-wkt-native.d.ts.map +1 -1
  33. package/dist/geoarrow/lib/kernels/decode-wkt-native.js +1 -1
  34. package/dist/geoarrow/lib/kernels/decode-wkt-native.js.map +1 -1
  35. package/dist/index.cjs +67 -4114
  36. package/dist/index.cjs.map +3 -3
  37. package/dist/index.d.ts +1 -33
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +2 -46
  40. package/dist/index.js.map +1 -1
  41. package/dist/lib/api/encode-table.d.ts +4 -4
  42. package/dist/lib/api/encode-table.d.ts.map +1 -1
  43. package/dist/lib/api/encode-table.js +21 -3
  44. package/dist/lib/api/encode-table.js.map +1 -1
  45. package/dist/lib/api/encode.d.ts +6 -6
  46. package/dist/lib/api/encode.d.ts.map +1 -1
  47. package/dist/lib/api/encode.js +46 -7
  48. package/dist/lib/api/encode.js.map +1 -1
  49. package/dist/lib/init.js +1 -1
  50. package/dist/loader-utils/index.cjs +94 -24
  51. package/dist/loader-utils/index.cjs.map +3 -3
  52. package/dist/loader-utils/index.d.ts +3 -2
  53. package/dist/loader-utils/index.d.ts.map +1 -1
  54. package/dist/loader-utils/index.js +2 -1
  55. package/dist/loader-utils/index.js.map +1 -1
  56. package/dist/loader-utils/json-loader-metadata.cjs +85 -0
  57. package/dist/loader-utils/json-loader-metadata.cjs.map +6 -0
  58. package/dist/loader-utils/json-loader-metadata.d.ts +51 -0
  59. package/dist/loader-utils/json-loader-metadata.d.ts.map +1 -0
  60. package/dist/loader-utils/json-loader-metadata.js +31 -0
  61. package/dist/loader-utils/json-loader-metadata.js.map +1 -0
  62. package/dist/loader-utils/json-loader.cjs +80 -0
  63. package/dist/loader-utils/json-loader.cjs.map +6 -0
  64. package/dist/loader-utils/json-loader.d.ts +4 -4
  65. package/dist/loader-utils/json-loader.d.ts.map +1 -1
  66. package/dist/loader-utils/json-loader.js +3 -17
  67. package/dist/loader-utils/json-loader.js.map +1 -1
  68. package/dist/loader-utils/lib/log-utils/log.js +1 -1
  69. package/dist/loader-utils/lib/request-utils/authentication.d.ts +2 -0
  70. package/dist/loader-utils/lib/request-utils/authentication.d.ts.map +1 -1
  71. package/dist/loader-utils/lib/request-utils/authentication.js +12 -0
  72. package/dist/loader-utils/lib/request-utils/authentication.js.map +1 -1
  73. package/dist/loader-utils/lib/scan-utils/table-query.d.ts +1 -1
  74. package/dist/loader-utils/lib/scan-utils/table-query.d.ts.map +1 -1
  75. package/dist/loader-utils/lib/sources/data-source.d.ts +1 -1
  76. package/dist/loader-utils/lib/sources/data-source.d.ts.map +1 -1
  77. package/dist/loader-utils/lib/sources/raster-source.d.ts +21 -1
  78. package/dist/loader-utils/lib/sources/raster-source.d.ts.map +1 -1
  79. package/dist/loader-utils/lib/sources/raster-source.js.map +1 -1
  80. package/dist/loader-utils/lib/sources/raster-tile.d.ts +7 -0
  81. package/dist/loader-utils/lib/sources/raster-tile.d.ts.map +1 -0
  82. package/dist/loader-utils/lib/sources/raster-tile.js +34 -0
  83. package/dist/loader-utils/lib/sources/raster-tile.js.map +1 -0
  84. package/dist/loader-utils/lib/sources/utils/utils.d.ts +1 -1
  85. package/dist/loader-utils/lib/sources/utils/utils.d.ts.map +1 -1
  86. package/dist/loader-utils/tile-grid.d.ts +2 -1
  87. package/dist/loader-utils/tile-grid.d.ts.map +1 -1
  88. package/dist/loader-utils/tile-grid.js +1 -1
  89. package/dist/loader-utils/tile-grid.js.map +1 -1
  90. package/dist/loader-utils/writer-types.d.ts +2 -0
  91. package/dist/loader-utils/writer-types.d.ts.map +1 -1
  92. package/dist/null-loader-metadata.cjs +89 -0
  93. package/dist/null-loader-metadata.cjs.map +6 -0
  94. package/dist/null-loader-metadata.d.ts +48 -0
  95. package/dist/null-loader-metadata.d.ts.map +1 -0
  96. package/dist/null-loader-metadata.js +30 -0
  97. package/dist/null-loader-metadata.js.map +1 -0
  98. package/dist/null-loader.cjs +84 -0
  99. package/dist/null-loader.cjs.map +6 -0
  100. package/dist/null-loader.d.ts +6 -6
  101. package/dist/null-loader.d.ts.map +1 -1
  102. package/dist/null-loader.js +2 -15
  103. package/dist/null-loader.js.map +1 -1
  104. package/dist/null-worker-node.js +58 -28
  105. package/dist/null-worker.js +58 -28
  106. package/dist/scan/arrow-execution/expressions.d.ts +1 -1
  107. package/dist/scan/arrow-execution/expressions.d.ts.map +1 -1
  108. package/dist/scan/arrow-query.cjs +2 -0
  109. package/dist/scan/arrow-query.cjs.map +2 -2
  110. package/dist/scan/arrow-query.d.ts +1 -1
  111. package/dist/scan/arrow-query.d.ts.map +1 -1
  112. package/dist/scan/arrow-query.js +1 -1
  113. package/dist/scan/arrow-query.js.map +1 -1
  114. package/dist/scan/index.cjs +16 -22
  115. package/dist/scan/index.cjs.map +2 -2
  116. package/dist/scan/index.d.ts +7 -7
  117. package/dist/scan/index.d.ts.map +1 -1
  118. package/dist/scan/index.js +4 -6
  119. package/dist/scan/index.js.map +1 -1
  120. package/dist/scan/plan-arrow-table-query.d.ts +1 -1
  121. package/dist/scan/plan-arrow-table-query.d.ts.map +1 -1
  122. package/dist/scan/query-arrow-table-in-batches.cjs +7 -19
  123. package/dist/scan/query-arrow-table-in-batches.cjs.map +2 -2
  124. package/dist/scan/query-arrow-table-in-batches.d.ts.map +1 -1
  125. package/dist/scan/query-arrow-table-in-batches.js +7 -22
  126. package/dist/scan/query-arrow-table-in-batches.js.map +1 -1
  127. package/dist/scan/query-executor.cjs +202 -0
  128. package/dist/scan/query-executor.cjs.map +7 -0
  129. package/dist/scan/query-executor.d.ts +27 -0
  130. package/dist/scan/query-executor.d.ts.map +1 -0
  131. package/dist/scan/query-executor.js +203 -0
  132. package/dist/scan/query-executor.js.map +1 -0
  133. package/dist/scan/query.cjs +92 -205
  134. package/dist/scan/query.cjs.map +3 -3
  135. package/dist/scan/query.d.ts +5 -4
  136. package/dist/scan/query.d.ts.map +1 -1
  137. package/dist/scan/query.js +94 -238
  138. package/dist/scan/query.js.map +1 -1
  139. package/dist/schema-utils/index.cjs +182 -0
  140. package/dist/schema-utils/index.cjs.map +3 -3
  141. package/dist/schema-utils/index.d.ts +3 -0
  142. package/dist/schema-utils/index.d.ts.map +1 -1
  143. package/dist/schema-utils/index.js +3 -0
  144. package/dist/schema-utils/index.js.map +1 -1
  145. package/dist/schema-utils/lib/arrow/arrow-converter.d.ts +24 -0
  146. package/dist/schema-utils/lib/arrow/arrow-converter.d.ts.map +1 -0
  147. package/dist/schema-utils/lib/arrow/arrow-converter.js +43 -0
  148. package/dist/schema-utils/lib/arrow/arrow-converter.js.map +1 -0
  149. package/dist/schema-utils/lib/arrow/convert-arrow-variable-width.d.ts +29 -0
  150. package/dist/schema-utils/lib/arrow/convert-arrow-variable-width.d.ts.map +1 -0
  151. package/dist/schema-utils/lib/arrow/convert-arrow-variable-width.js +89 -0
  152. package/dist/schema-utils/lib/arrow/convert-arrow-variable-width.js.map +1 -0
  153. package/dist/schema-utils/lib/arrow/convert-arrow.d.ts +17 -0
  154. package/dist/schema-utils/lib/arrow/convert-arrow.d.ts.map +1 -0
  155. package/dist/schema-utils/lib/arrow/convert-arrow.js +24 -0
  156. package/dist/schema-utils/lib/arrow/convert-arrow.js.map +1 -0
  157. package/dist/schema-utils/lib/arrow/tighten-arrow-table-schema-nullability.d.ts +4 -0
  158. package/dist/schema-utils/lib/arrow/tighten-arrow-table-schema-nullability.d.ts.map +1 -0
  159. package/dist/schema-utils/lib/arrow/tighten-arrow-table-schema-nullability.js +51 -0
  160. package/dist/schema-utils/lib/arrow/tighten-arrow-table-schema-nullability.js.map +1 -0
  161. package/dist/worker-utils/index.cjs +2 -2
  162. package/dist/worker-utils/lib/env-utils/version.js +1 -1
  163. package/package.json +49 -23
  164. package/src/api.ts +99 -0
  165. package/src/arrow-geometry/index.ts +5 -0
  166. package/src/arrow-geometry/triangulate-wkb-geometry-column.ts +122 -0
  167. package/src/geoarrow/index.ts +2 -2
  168. package/src/geoarrow/lib/kernels/decode-wkt-native.ts +1 -1
  169. package/src/index.ts +2 -94
  170. package/src/lib/api/encode-table.ts +31 -6
  171. package/src/lib/api/encode.ts +61 -11
  172. package/src/loader-utils/index.ts +3 -0
  173. package/src/loader-utils/json-loader-metadata.ts +35 -0
  174. package/src/loader-utils/json-loader.ts +3 -18
  175. package/src/loader-utils/lib/request-utils/authentication.ts +17 -0
  176. package/src/loader-utils/lib/sources/raster-source.ts +22 -1
  177. package/src/loader-utils/lib/sources/raster-tile.ts +46 -0
  178. package/src/loader-utils/tile-grid.ts +16 -1
  179. package/src/loader-utils/writer-types.ts +2 -0
  180. package/src/null-loader-metadata.ts +32 -0
  181. package/src/null-loader.ts +2 -17
  182. package/src/scan/arrow-query.ts +1 -1
  183. package/src/scan/index.ts +24 -13
  184. package/src/scan/query-arrow-table-in-batches.ts +7 -24
  185. package/src/scan/query-executor.ts +286 -0
  186. package/src/scan/query.ts +112 -299
  187. package/src/schema-utils/index.ts +14 -0
  188. package/src/schema-utils/lib/arrow/arrow-converter.ts +74 -0
  189. package/src/schema-utils/lib/arrow/convert-arrow-variable-width.ts +121 -0
  190. package/src/schema-utils/lib/arrow/convert-arrow.ts +52 -0
  191. package/src/schema-utils/lib/arrow/tighten-arrow-table-schema-nullability.ts +83 -0
  192. package/dist/cluster-source.cjs +0 -6360
  193. package/dist/cluster-source.cjs.map +0 -6
  194. package/dist/cluster-source.d.ts +0 -2
  195. package/dist/cluster-source.d.ts.map +0 -1
  196. package/dist/cluster-source.js +0 -2
  197. package/dist/cluster-source.js.map +0 -1
  198. package/dist/federated-table-scan-source.cjs +0 -1905
  199. package/dist/federated-table-scan-source.cjs.map +0 -6
  200. package/dist/federated-table-scan-source.d.ts +0 -2
  201. package/dist/federated-table-scan-source.d.ts.map +0 -1
  202. package/dist/federated-table-scan-source.js +0 -2
  203. package/dist/federated-table-scan-source.js.map +0 -1
  204. package/dist/geoarrow/geoarrow-builder.cjs +0 -31
  205. package/dist/geoarrow/geoarrow-builder.cjs.map +0 -7
  206. package/dist/geoarrow/geoarrow-builder.d.ts +0 -3
  207. package/dist/geoarrow/geoarrow-builder.d.ts.map +0 -1
  208. package/dist/geoarrow/geoarrow-builder.js +0 -5
  209. package/dist/geoarrow/geoarrow-builder.js.map +0 -1
  210. package/dist/vector-table-scan-source.cjs +0 -1200
  211. package/dist/vector-table-scan-source.cjs.map +0 -6
  212. package/dist/vector-table-scan-source.d.ts +0 -2
  213. package/dist/vector-table-scan-source.d.ts.map +0 -1
  214. package/dist/vector-table-scan-source.js +0 -2
  215. package/dist/vector-table-scan-source.js.map +0 -1
  216. package/src/cluster-source.ts +0 -1
  217. package/src/federated-table-scan-source.ts +0 -1
  218. package/src/geoarrow/geoarrow-builder.ts +0 -21
  219. package/src/vector-table-scan-source.ts +0 -1
package/dist/api.cjs ADDED
@@ -0,0 +1,4129 @@
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
+ // dist/api.js
21
+ var api_exports = {};
22
+ __export(api_exports, {
23
+ FetchError: () => FetchError,
24
+ RequestScheduler: () => RequestScheduler,
25
+ _BrowserFileSystem: () => BrowserFileSystem,
26
+ _fetchProgress: () => fetchProgress,
27
+ _selectSource: () => selectSource,
28
+ _unregisterLoaders: () => _unregisterLoaders,
29
+ assert: () => assert,
30
+ compareLoaderOptions: () => compareLoaderOptions,
31
+ concatenateArrayBuffersAsync: () => concatenateArrayBuffersAsync,
32
+ coreApi: () => coreApi,
33
+ createDataSource: () => createDataSource,
34
+ createDataSourceSync: () => createDataSourceSync,
35
+ document: () => document_,
36
+ encode: () => encode,
37
+ encodeInBatches: () => encodeInBatches,
38
+ encodeSync: () => encodeSync,
39
+ encodeTable: () => encodeTable,
40
+ encodeTableAsText: () => encodeTableAsText,
41
+ encodeTableInBatches: () => encodeTableInBatches,
42
+ encodeText: () => encodeText,
43
+ encodeTextSync: () => encodeTextSync,
44
+ encodeURLtoURL: () => encodeURLtoURL,
45
+ fetchFile: () => fetchFile,
46
+ forEach: () => forEach,
47
+ getLoaderOptions: () => getGlobalLoaderOptions,
48
+ getPathPrefix: () => getPathPrefix,
49
+ global: () => global_,
50
+ isAsyncIterable: () => isAsyncIterable,
51
+ isBrowser: () => isBrowser,
52
+ isIterable: () => isIterable,
53
+ isIterator: () => isIterator,
54
+ isPromise: () => isPromise,
55
+ isPureObject: () => isPureObject,
56
+ isReadableStream: () => isReadableStream,
57
+ isResponse: () => isResponse,
58
+ isWorker: () => isWorker,
59
+ isWritableStream: () => isWritableStream,
60
+ load: () => load,
61
+ loadInBatches: () => loadInBatches,
62
+ makeIterator: () => makeIterator,
63
+ makeLineIterator: () => makeLineIterator,
64
+ makeNumberedLineIterator: () => makeNumberedLineIterator,
65
+ makeStream: () => makeStream,
66
+ makeTextDecoderIterator: () => makeTextDecoderIterator,
67
+ makeTextEncoderIterator: () => makeTextEncoderIterator,
68
+ parse: () => parse,
69
+ parseFile: () => parseFile,
70
+ parseInBatches: () => parseInBatches,
71
+ parseSync: () => parseSync,
72
+ preload: () => preload,
73
+ preloadSync: () => preloadSync,
74
+ readArrayBuffer: () => readArrayBuffer,
75
+ registerLoaders: () => registerLoaders,
76
+ resolvePath: () => resolvePath,
77
+ selectLoader: () => selectLoader,
78
+ selectLoaderSync: () => selectLoaderSync,
79
+ self: () => self_,
80
+ setLoaderOptions: () => setGlobalOptions,
81
+ setPathPrefix: () => setPathPrefix,
82
+ window: () => window_
83
+ });
84
+ module.exports = __toCommonJS(api_exports);
85
+
86
+ // src/loader-utils/lib/env-utils/assert.ts
87
+ function assert(condition, message) {
88
+ if (!condition) {
89
+ throw new Error(message || "loader assertion failed.");
90
+ }
91
+ }
92
+
93
+ // src/loader-utils/lib/env-utils/globals.ts
94
+ var globals = {
95
+ self: typeof self !== "undefined" && self,
96
+ window: typeof window !== "undefined" && window,
97
+ global: typeof global !== "undefined" && global,
98
+ document: typeof document !== "undefined" && document
99
+ };
100
+ var self_ = globals.self || globals.window || globals.global || {};
101
+ var window_ = globals.window || globals.self || globals.global || {};
102
+ var global_ = globals.global || globals.self || globals.window || {};
103
+ var document_ = globals.document || {};
104
+ var isBrowser = (
105
+ // @ts-ignore process does not exist on browser
106
+ Boolean(typeof process !== "object" || String(process) !== "[object process]" || process.browser)
107
+ );
108
+ var isWorker = typeof importScripts === "function";
109
+ var matches = typeof process !== "undefined" && process.version && /v([0-9]*)/.exec(process.version);
110
+ var nodeVersion = matches && parseFloat(matches[1]) || 0;
111
+
112
+ // src/loader-utils/lib/log-utils/log.ts
113
+ var import_log = require("probe.gl/log");
114
+ var VERSION = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
115
+ var version = VERSION[0] >= "0" && VERSION[0] <= "9" ? `v${VERSION}` : "";
116
+ function createLog() {
117
+ const log3 = new import_log.Log({ id: "loaders.gl" });
118
+ globalThis.loaders ||= {};
119
+ globalThis.loaders.log = log3;
120
+ globalThis.loaders.version = version;
121
+ globalThis.probe ||= {};
122
+ globalThis.probe.loaders = log3;
123
+ return log3;
124
+ }
125
+ var log = createLog();
126
+ var NullLog = class {
127
+ /** Discards debug messages. */
128
+ log() {
129
+ return ignoreMessage;
130
+ }
131
+ /** Discards informational messages. */
132
+ info() {
133
+ return ignoreMessage;
134
+ }
135
+ /** Discards messages marked to be emitted once. */
136
+ once() {
137
+ return ignoreMessage;
138
+ }
139
+ /** Discards warnings. */
140
+ warn() {
141
+ return ignoreMessage;
142
+ }
143
+ /** Discards errors. */
144
+ error() {
145
+ return ignoreMessage;
146
+ }
147
+ };
148
+ function ignoreMessage() {
149
+ }
150
+ var nullLog = new NullLog();
151
+ function getLoaderLog(options) {
152
+ var _a;
153
+ const logger = (_a = options == null ? void 0 : options.core) == null ? void 0 : _a.log;
154
+ return logger === null ? nullLog : logger || log;
155
+ }
156
+
157
+ // src/loader-utils/lib/javascript-utils/is-type.ts
158
+ var isBoolean = (value) => typeof value === "boolean";
159
+ var isFunction = (value) => typeof value === "function";
160
+ var isObject = (value) => value !== null && typeof value === "object";
161
+ var isPureObject = (value) => isObject(value) && value.constructor === {}.constructor;
162
+ var isSharedArrayBuffer = (value) => typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer;
163
+ var isArrayBufferLike = (value) => isObject(value) && typeof value.byteLength === "number" && typeof value.slice === "function";
164
+ var isPromise = (value) => isObject(value) && "then" in value && isFunction(value.then);
165
+ var isIterable = (value) => Boolean(value) && isFunction(value[Symbol.iterator]);
166
+ var isAsyncIterable = (value) => Boolean(value) && isFunction(value[Symbol.asyncIterator]);
167
+ var isIterator = (value) => Boolean(value) && isFunction(value.next);
168
+ var isResponse = (value) => typeof Response !== "undefined" && value instanceof Response || isObject(value) && isFunction(value.arrayBuffer) && isFunction(value.text) && isFunction(value.json);
169
+ var isBlob = (value) => typeof Blob !== "undefined" && value instanceof Blob;
170
+ var isWritableDOMStream = (value) => isObject(value) && isFunction(value.abort) && isFunction(value.getWriter);
171
+ var isReadableDOMStream = (value) => typeof ReadableStream !== "undefined" && value instanceof ReadableStream || isObject(value) && isFunction(value.tee) && isFunction(value.cancel) && isFunction(value.getReader);
172
+ var isWritableNodeStream = (value) => isObject(value) && isFunction(value.end) && isFunction(value.write) && isBoolean(value.writable);
173
+ var isReadableNodeStream = (value) => isObject(value) && isFunction(value.read) && isFunction(value.pipe) && isBoolean(value.readable);
174
+ var isReadableStream = (value) => isReadableDOMStream(value) || isReadableNodeStream(value);
175
+ var isWritableStream = (value) => isWritableDOMStream(value) || isWritableNodeStream(value);
176
+
177
+ // src/loader-utils/lib/option-utils/merge-options.ts
178
+ function mergeOptions(baseOptions, newOptions) {
179
+ return mergeOptionsRecursively(baseOptions || {}, newOptions);
180
+ }
181
+ function mergeOptionsRecursively(baseOptions, newOptions, level = 0) {
182
+ if (level > 3) {
183
+ return newOptions;
184
+ }
185
+ const options = { ...baseOptions };
186
+ for (const [key, newValue] of Object.entries(newOptions)) {
187
+ if (isPureObject(newValue)) {
188
+ options[key] = mergeOptionsRecursively(
189
+ options[key] || {},
190
+ newOptions[key],
191
+ level + 1
192
+ );
193
+ } else {
194
+ options[key] = newOptions[key];
195
+ }
196
+ }
197
+ return options;
198
+ }
199
+
200
+ // src/loader-utils/lib/module-utils/js-module-utils.ts
201
+ function registerJSModules(modules) {
202
+ globalThis.loaders ||= {};
203
+ globalThis.loaders.modules ||= {};
204
+ Object.assign(globalThis.loaders.modules, modules);
205
+ }
206
+
207
+ // src/constants/index.ts
208
+ var LOADERS_GL_FIXTURE_BRANCH = "5.0-release";
209
+ var LOADERS_GL_RAW_FIXTURE_URL = `https://raw.githubusercontent.com/visgl/loaders.gl/${LOADERS_GL_FIXTURE_BRANCH}/`;
210
+ var LOADERS_GL_REDIRECTING_FIXTURE_URL = `https://github.com/visgl/loaders.gl/raw/${LOADERS_GL_FIXTURE_BRANCH}/`;
211
+ var NPM_TAG = "latest";
212
+
213
+ // src/worker-utils/lib/env-utils/version.ts
214
+ function getVersion() {
215
+ const version3 = typeof __VERSION__ === "undefined" ? NPM_TAG : __VERSION__;
216
+ globalThis._loadersgl_ = globalThis._loadersgl_ || {};
217
+ globalThis._loadersgl_.version ||= version3;
218
+ return version3;
219
+ }
220
+ var VERSION2 = getVersion();
221
+
222
+ // src/worker-utils/lib/env-utils/assert.ts
223
+ function assert2(condition, message) {
224
+ if (!condition) {
225
+ throw new Error(message || "loaders.gl assertion failed.");
226
+ }
227
+ }
228
+
229
+ // src/worker-utils/lib/env-utils/globals.ts
230
+ var globals2 = {
231
+ self: typeof self !== "undefined" && self,
232
+ window: typeof window !== "undefined" && window,
233
+ global: typeof global !== "undefined" && global,
234
+ document: typeof document !== "undefined" && document
235
+ };
236
+ var self_2 = globals2.self || globals2.window || globals2.global || {};
237
+ var window_2 = globals2.window || globals2.self || globals2.global || {};
238
+ var global_2 = globals2.global || globals2.self || globals2.window || {};
239
+ var document_2 = globals2.document || {};
240
+ var isBrowser2 = (
241
+ // @ts-ignore process.browser
242
+ typeof process !== "object" || String(process) !== "[object process]" || process.browser
243
+ );
244
+ var isMobile = typeof window !== "undefined" && typeof window.orientation !== "undefined";
245
+ var matches2 = typeof process !== "undefined" && process.version && /v([0-9]*)/.exec(process.version);
246
+ var nodeVersion2 = matches2 && parseFloat(matches2[1]) || 0;
247
+
248
+ // src/worker-utils/lib/worker-api/process-on-worker.ts
249
+ var import_tasks2 = require("@math.gl/tasks");
250
+
251
+ // src/worker-utils/lib/worker-api/get-worker-url.ts
252
+ var warnedWorkerVersionFallbacks = /* @__PURE__ */ new Set();
253
+ function getCustomWorkerURL(worker, options = {}) {
254
+ var _a, _b;
255
+ const workerFile = isBrowser2 ? worker.workerFile || `${worker.id}-worker.js` : worker.workerNode || `${worker.id}-worker-node.js`;
256
+ let url = getConfiguredWorkerURL(worker, options);
257
+ const workerType = options._workerType || ((_a = options == null ? void 0 : options.core) == null ? void 0 : _a._workerType);
258
+ if (!url && workerType === "test") {
259
+ if (isBrowser2) {
260
+ url = `modules/${worker.module}/dist/${workerFile}`;
261
+ } else {
262
+ const workerSourceDirectory = worker.module === "core" && ((_b = worker.workerNode) == null ? void 0 : _b.startsWith("worker-utils/")) ? "worker-utils/workers" : "workers";
263
+ const workerSourceNode = worker.workerSourceNode || `${workerSourceDirectory}/${worker.id}-worker-node.ts`;
264
+ url = `modules/${worker.module}/src/${workerSourceNode}`;
265
+ }
266
+ }
267
+ return url || null;
268
+ }
269
+ function getConfiguredWorkerURL(worker, options = {}) {
270
+ const workerOptions = options[worker.id] || {};
271
+ return workerOptions.workerUrl || (worker.id === "compression" ? options.workerUrl : null) || null;
272
+ }
273
+ function getWorkerURL(worker, options = {}) {
274
+ const customWorkerUrl = getCustomWorkerURL(worker, options);
275
+ const descriptorWorkerUrl = typeof worker.worker === "string" ? worker.worker : null;
276
+ const url = customWorkerUrl || descriptorWorkerUrl || getDefaultWorkerURL(worker, true);
277
+ assert2(url);
278
+ return url;
279
+ }
280
+ function getDefaultWorkerURL(worker, warn = false) {
281
+ const workerFile = isBrowser2 ? worker.workerFile || `${worker.id}-worker.js` : worker.workerNode || `${worker.id}-worker-node.js`;
282
+ let version3 = worker.version;
283
+ if (version3 === "latest") {
284
+ version3 = NPM_TAG;
285
+ }
286
+ const versionTag = version3 ? `@${version3}` : "";
287
+ const url = `https://unpkg.com/@loaders.gl/${worker.module}${versionTag}/dist/${workerFile}`;
288
+ if (warn) {
289
+ warnIfUsingNpmTagFallback(worker, url);
290
+ }
291
+ return url;
292
+ }
293
+ function warnIfUsingNpmTagFallback(worker, url) {
294
+ if (worker.version !== "latest") {
295
+ return;
296
+ }
297
+ const workerId = `${worker.module}:${worker.id}`;
298
+ if (warnedWorkerVersionFallbacks.has(workerId)) {
299
+ return;
300
+ }
301
+ warnedWorkerVersionFallbacks.add(workerId);
302
+ log.warn(
303
+ `loaders.gl: ${worker.name} loader worker version is "latest" because __VERSION__ was not injected. Fetching ${url} from CDN.`
304
+ )();
305
+ }
306
+
307
+ // src/worker-utils/lib/worker-api/task-runtime.ts
308
+ var import_tasks = require("@math.gl/tasks");
309
+ function normalizeTaskProgress(progress) {
310
+ return { ...progress, phase: progress.phase ?? "process", unit: progress.unit ?? "items" };
311
+ }
312
+
313
+ // src/worker-utils/lib/worker-utils/get-transfer-list.ts
314
+ function getTransferList(object, recursive = true, transfers) {
315
+ const transfersSet = transfers || /* @__PURE__ */ new Set();
316
+ if (!object) {
317
+ } else if (isTransferable(object)) {
318
+ transfersSet.add(object);
319
+ } else if (isTransferable(object.buffer)) {
320
+ transfersSet.add(object.buffer);
321
+ } else if (ArrayBuffer.isView(object)) {
322
+ } else if (recursive && typeof object === "object") {
323
+ for (const key in object) {
324
+ getTransferList(object[key], recursive, transfersSet);
325
+ }
326
+ }
327
+ return transfers === void 0 ? Array.from(transfersSet) : [];
328
+ }
329
+ function isTransferable(object) {
330
+ if (!object) {
331
+ return false;
332
+ }
333
+ if (object instanceof ArrayBuffer) {
334
+ return true;
335
+ }
336
+ if (typeof MessagePort !== "undefined" && object instanceof MessagePort) {
337
+ return true;
338
+ }
339
+ if (typeof ImageBitmap !== "undefined" && object instanceof ImageBitmap) {
340
+ return true;
341
+ }
342
+ if (typeof OffscreenCanvas !== "undefined" && object instanceof OffscreenCanvas) {
343
+ return true;
344
+ }
345
+ return false;
346
+ }
347
+ function getTransferListForWriter(object) {
348
+ if (object === null) {
349
+ return {};
350
+ }
351
+ const clone = Object.assign({}, object);
352
+ Object.keys(clone).forEach((key) => {
353
+ if (object[key] !== null && typeof object[key] === "object" && !ArrayBuffer.isView(object[key]) && !(object[key] instanceof Array)) {
354
+ clone[key] = getTransferListForWriter(object[key]);
355
+ } else if (typeof clone[key] === "function" || clone[key] instanceof RegExp) {
356
+ clone[key] = {};
357
+ } else {
358
+ clone[key] = object[key];
359
+ }
360
+ });
361
+ return clone;
362
+ }
363
+
364
+ // src/worker-utils/lib/worker-api/process-on-worker.ts
365
+ var runners = /* @__PURE__ */ new WeakMap();
366
+ var activeRunners = /* @__PURE__ */ new Set();
367
+ var moduleWorkerUrls = /* @__PURE__ */ new Map();
368
+ function canProcessOnWorker(worker, options = {}) {
369
+ const supported = isBrowser2 ? typeof Worker !== "undefined" : Boolean(options._nodeWorkers);
370
+ return Boolean(
371
+ supported && options.worker && (worker.worker || worker.loadWorker || getConfiguredWorkerURL(worker, options))
372
+ );
373
+ }
374
+ function canProcessOnWorkerInBatches(worker, options = {}) {
375
+ if (!canProcessOnWorker(worker, options)) return false;
376
+ if (options.workerInBatches !== void 0) return options.workerInBatches;
377
+ return Boolean(worker.workerInBatches && !getConfiguredWorkerURL(worker, options));
378
+ }
379
+ async function processOnWorker(worker, data, options = {}, context = {}, jobContext = {}) {
380
+ const controller = new AbortController();
381
+ const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
382
+ const sessionPromise = openSession(worker, { ...options, signal }, context, jobContext);
383
+ void sessionPromise.catch(() => {
384
+ });
385
+ try {
386
+ const input = data instanceof Promise ? await waitForInput(data, signal) : data;
387
+ const session = await sessionPromise;
388
+ const result = await session.handle.runTask(
389
+ { value: input },
390
+ {
391
+ ...getControls(options),
392
+ options: getParserOptions(options)
393
+ }
394
+ );
395
+ return result.value;
396
+ } catch (error) {
397
+ controller.abort(error);
398
+ throw error;
399
+ } finally {
400
+ const session = await sessionPromise.catch(() => void 0);
401
+ await (session == null ? void 0 : session.close());
402
+ }
403
+ }
404
+ async function waitForInput(input, signal) {
405
+ let onAbort;
406
+ try {
407
+ const aborted = new Promise((_resolve, reject) => {
408
+ onAbort = () => reject(signal.reason);
409
+ signal.addEventListener("abort", onAbort, { once: true });
410
+ if (signal.aborted) {
411
+ onAbort();
412
+ }
413
+ });
414
+ return await Promise.race([input, aborted]);
415
+ } finally {
416
+ signal.removeEventListener("abort", onAbort);
417
+ }
418
+ }
419
+ async function* processOnWorkerInBatches(worker, input, options = {}, context = {}, jobContext = {}) {
420
+ var _a;
421
+ const taskInput = wrapInput(input);
422
+ let session;
423
+ try {
424
+ session = await openSession(worker, options, context, jobContext);
425
+ for await (const result of session.handle.runTaskInBatches(taskInput, {
426
+ ...getControls(options),
427
+ options: getParserOptions(options)
428
+ }))
429
+ yield result.value;
430
+ } finally {
431
+ const closingInput = (_a = taskInput.return) == null ? void 0 : _a.call(taskInput);
432
+ void (closingInput == null ? void 0 : closingInput.catch(() => {
433
+ }));
434
+ await (session == null ? void 0 : session.close());
435
+ }
436
+ }
437
+ function getTask(worker, options) {
438
+ var _a;
439
+ if (options.source || ((_a = options.core) == null ? void 0 : _a.source))
440
+ throw new Error(
441
+ "Inline legacy worker source is unsupported; use a TaskRunner worker URL or factory"
442
+ );
443
+ const create = !getCustomWorkerURL(worker, options) && isBrowser2 ? worker.loadWorker : void 0;
444
+ return {
445
+ id: `${worker.module}:${worker.id}`,
446
+ initialize: (state) => state,
447
+ worker: {
448
+ ...create ? { create: () => create() ?? createModuleWorker(getWorkerURL(worker, options)) } : { url: getWorkerURL(worker, options) },
449
+ capabilities: { atomic: true, streaming: true }
450
+ }
451
+ };
452
+ }
453
+ function getControls(options) {
454
+ return {
455
+ execution: "worker",
456
+ signal: options.signal,
457
+ inputOwnership: options.inputOwnership ?? "transfer",
458
+ outputOwnership: options.outputOwnership ?? "transfer",
459
+ onProgress: options.onProgress ? (progress) => {
460
+ var _a;
461
+ return (_a = options.onProgress) == null ? void 0 : _a.call(options, normalizeTaskProgress(progress));
462
+ } : void 0
463
+ };
464
+ }
465
+ function getParserOptions(options) {
466
+ const { signal, onProgress, parserOptions, ...workerOptions } = options;
467
+ return getTransferListForWriter(parserOptions ?? workerOptions);
468
+ }
469
+ async function openSession(worker, options, context, jobContext) {
470
+ var _a, _b;
471
+ (_a = options.signal) == null ? void 0 : _a.throwIfAborted();
472
+ const task = getTask(worker, options);
473
+ let state = runners.get(worker);
474
+ if (!state) {
475
+ state = {
476
+ runner: new import_tasks2.TaskRunner({
477
+ maxConcurrency: isMobile ? options.maxMobileConcurrency ?? 1 : options.maxConcurrency ?? 3
478
+ }),
479
+ requests: 0
480
+ };
481
+ runners.set(worker, state);
482
+ }
483
+ const runnerState = state;
484
+ const channel = context.process ? new MessageChannel() : void 0;
485
+ const callbackController = new AbortController();
486
+ let channelClosed = false;
487
+ const abortCallbacks = () => {
488
+ var _a2;
489
+ return callbackController.abort((_a2 = options.signal) == null ? void 0 : _a2.reason);
490
+ };
491
+ (_b = options.signal) == null ? void 0 : _b.addEventListener("abort", abortCallbacks, { once: true });
492
+ const closeChannel = () => {
493
+ var _a2;
494
+ channelClosed = true;
495
+ (_a2 = options.signal) == null ? void 0 : _a2.removeEventListener("abort", abortCallbacks);
496
+ callbackController.abort();
497
+ channel == null ? void 0 : channel.port1.close();
498
+ channel == null ? void 0 : channel.port2.close();
499
+ };
500
+ if (channel) {
501
+ channel.port1.onmessage = async ({ data }) => {
502
+ try {
503
+ const value = await context.process(
504
+ data.input,
505
+ data.options,
506
+ {
507
+ signal: callbackController.signal,
508
+ throwIfAborted: () => callbackController.signal.throwIfAborted()
509
+ },
510
+ data.context
511
+ );
512
+ if (!channelClosed && !callbackController.signal.aborted)
513
+ channel.port1.postMessage({ identifier: data.identifier, value }, getTransferList(value));
514
+ } catch (error) {
515
+ if (channelClosed || callbackController.signal.aborted) return;
516
+ channel.port1.postMessage({
517
+ identifier: data.identifier,
518
+ error: {
519
+ name: error instanceof Error ? error.name : "Error",
520
+ message: error instanceof Error ? error.message : String(error)
521
+ }
522
+ });
523
+ }
524
+ };
525
+ channel.port1.start();
526
+ }
527
+ runnerState.requests++;
528
+ activeRunners.add(runnerState);
529
+ let released = false;
530
+ const releaseRunner = () => {
531
+ if (released) return;
532
+ released = true;
533
+ runnerState.requests--;
534
+ if (!runnerState.requests) activeRunners.delete(runnerState);
535
+ };
536
+ let handle;
537
+ try {
538
+ handle = await runnerState.runner.initializeTask(
539
+ task,
540
+ {
541
+ context: structuredClone(jobContext),
542
+ ...channel ? { port: channel.port2 } : {}
543
+ },
544
+ // The callback port is setup state, independent of the caller's payload ownership.
545
+ { ...getControls(options), inputOwnership: "transfer" }
546
+ );
547
+ } catch (error) {
548
+ releaseRunner();
549
+ closeChannel();
550
+ throw error;
551
+ }
552
+ return {
553
+ handle,
554
+ /** Releases the worker and callback channel on success, failure, and early stream return. */
555
+ async close() {
556
+ try {
557
+ await handle.close();
558
+ } finally {
559
+ closeChannel();
560
+ releaseRunner();
561
+ }
562
+ }
563
+ };
564
+ }
565
+ function wrapInput(input) {
566
+ const iterator = Symbol.asyncIterator in input ? input[Symbol.asyncIterator]() : input[Symbol.iterator]();
567
+ let inputClosed = false;
568
+ return {
569
+ [Symbol.asyncIterator]() {
570
+ return this;
571
+ },
572
+ async next() {
573
+ if (inputClosed) return { done: true, value: void 0 };
574
+ const next = await iterator.next();
575
+ if (next.done || inputClosed) {
576
+ inputClosed = true;
577
+ return { done: true, value: void 0 };
578
+ }
579
+ return { done: false, value: { value: next.value } };
580
+ },
581
+ async return() {
582
+ var _a;
583
+ if (!inputClosed) {
584
+ inputClosed = true;
585
+ await ((_a = iterator.return) == null ? void 0 : _a.call(iterator));
586
+ }
587
+ return { done: true, value: void 0 };
588
+ }
589
+ };
590
+ }
591
+ function createModuleWorker(url) {
592
+ var _a;
593
+ const resolved = new URL(url, ((_a = globalThis.document) == null ? void 0 : _a.baseURI) ?? globalThis.location.href);
594
+ let workerUrl = resolved.href;
595
+ if (/^https?:$/.test(resolved.protocol) && resolved.origin !== globalThis.location.origin) {
596
+ let shimUrl = moduleWorkerUrls.get(resolved.href);
597
+ if (!shimUrl) {
598
+ shimUrl = URL.createObjectURL(
599
+ new Blob([`import ${JSON.stringify(resolved.href)};`], { type: "application/javascript" })
600
+ );
601
+ moduleWorkerUrls.set(resolved.href, shimUrl);
602
+ }
603
+ workerUrl = shimUrl;
604
+ }
605
+ return new Worker(workerUrl, { type: "module" });
606
+ }
607
+
608
+ // src/worker-utils/lib/worker-api/validate-worker-version.ts
609
+ function validateWorkerVersion(worker, coreVersion = VERSION2) {
610
+ assert2(worker, "no worker provided");
611
+ const workerVersion = worker.version;
612
+ if (!coreVersion || !workerVersion) {
613
+ return false;
614
+ }
615
+ return true;
616
+ }
617
+
618
+ // src/loader-utils/lib/worker-loader-utils/parse-with-worker.ts
619
+ function canParseWithWorker(loader, options) {
620
+ var _a, _b, _c, _d, _e;
621
+ const workerUrl = (_a = options == null ? void 0 : options[loader.id]) == null ? void 0 : _a.workerUrl;
622
+ if (((_b = options == null ? void 0 : options.core) == null ? void 0 : _b.worker) === false || !(loader.worker || loader.loadWorker || workerUrl))
623
+ return false;
624
+ if ((_d = (_c = options == null ? void 0 : options.core) == null ? void 0 : _c.credentials) == null ? void 0 : _d.some(
625
+ (credential) => credential.type === "request" || "token" in credential && typeof credential.token === "function"
626
+ ))
627
+ return false;
628
+ if (loader.id === "shapefile" && typeof ((_e = options == null ? void 0 : options.core) == null ? void 0 : _e.fetch) === "function") return false;
629
+ const workerOptions = getWorkerOptions(options);
630
+ const nodeWorkers = workerOptions._nodeWorkers;
631
+ if (!isBrowser2 && !nodeWorkers) {
632
+ return false;
633
+ }
634
+ if (loader.id === "csv" && !shouldParseCSVWithWorker(options)) {
635
+ return false;
636
+ }
637
+ return Boolean(canProcessOnWorker(loader, workerOptions));
638
+ }
639
+ function canParseWithWorkerInBatches(loader, options) {
640
+ const parquetOptions = options == null ? void 0 : options.parquet;
641
+ if (loader.id === "parquet" && typeof (parquetOptions == null ? void 0 : parquetOptions.keyRetriever) === "function") {
642
+ return false;
643
+ }
644
+ return Boolean(
645
+ loader.workerInBatches && canParseWithWorker(loader, options) && canProcessOnWorkerInBatches(loader, getWorkerOptions(options))
646
+ );
647
+ }
648
+ function shouldParseWithWorker(loader, data, options, context, estimateLoader = loader) {
649
+ var _a, _b;
650
+ if (!canParseWithWorker(loader, options)) {
651
+ return false;
652
+ }
653
+ if (((_a = options == null ? void 0 : options.core) == null ? void 0 : _a.worker) !== "auto" || !estimateLoader.getWorkerEstimate) {
654
+ return true;
655
+ }
656
+ try {
657
+ const estimate = estimateLoader.getWorkerEstimate(data, options, context);
658
+ if (estimate === void 0 || !Number.isFinite(estimate) || estimate < 0 || estimate > 1) {
659
+ return true;
660
+ }
661
+ return estimate >= (((_b = options.core) == null ? void 0 : _b.workerThreshold) ?? 0.1);
662
+ } catch {
663
+ return true;
664
+ }
665
+ }
666
+ async function parseWithWorker(loader, data, options, context, parseOnMainThread, signal) {
667
+ const workerSignal = signal || getWorkerAbortSignal(options) || (context == null ? void 0 : context.signal);
668
+ const result = await processOnWorker(
669
+ loader,
670
+ data,
671
+ {
672
+ ...getWorkerOptions(options, loader),
673
+ signal: workerSignal,
674
+ onProgress: (options == null ? void 0 : options.onProgress) || (context == null ? void 0 : context.reportProgress)
675
+ },
676
+ {
677
+ process: async (input, processOptions, workerContext, parseContext) => {
678
+ if (!parseOnMainThread) {
679
+ throw new Error("Worker not set up to parse on main thread");
680
+ }
681
+ const { _loaderIds, _loaderIsArray, ...workerParseContext } = parseContext || {};
682
+ const mainThreadContext = context || parseContext || (workerContext == null ? void 0 : workerContext.signal) ? {
683
+ ...context,
684
+ ...workerParseContext,
685
+ signal: (workerContext == null ? void 0 : workerContext.signal) ?? (context == null ? void 0 : context.signal)
686
+ } : void 0;
687
+ return await callParseOnMainThread(
688
+ parseOnMainThread,
689
+ input,
690
+ processOptions,
691
+ mainThreadContext,
692
+ resolveWorkerLoaders(loader, _loaderIds, _loaderIsArray, context, options)
693
+ );
694
+ }
695
+ },
696
+ getSerializableLoaderContext(context)
697
+ );
698
+ return isLoaderWithWorkerResultDeserializer(loader) ? loader.deserializeWorkerResult(result, options, context) : result;
699
+ }
700
+ async function* parseWithWorkerInBatches(loader, inputIterator, options, context, parseOnMainThread, signal) {
701
+ const workerSignal = signal || getWorkerAbortSignal(options) || (context == null ? void 0 : context.signal);
702
+ const outputIterator = processOnWorkerInBatches(
703
+ loader,
704
+ inputIterator,
705
+ {
706
+ ...getWorkerOptions(options, loader),
707
+ signal: workerSignal,
708
+ onProgress: (options == null ? void 0 : options.onProgress) || (context == null ? void 0 : context.reportProgress)
709
+ },
710
+ {
711
+ process: async (input, processOptions, workerContext, parseContext) => {
712
+ if (!parseOnMainThread) {
713
+ throw new Error("Worker not set up to parse on main thread");
714
+ }
715
+ const { _loaderIds, _loaderIsArray, ...workerParseContext } = parseContext || {};
716
+ const mainThreadContext = context || parseContext || (workerContext == null ? void 0 : workerContext.signal) ? {
717
+ ...context,
718
+ ...workerParseContext,
719
+ signal: (workerContext == null ? void 0 : workerContext.signal) ?? (context == null ? void 0 : context.signal)
720
+ } : void 0;
721
+ return await callParseOnMainThread(
722
+ parseOnMainThread,
723
+ input,
724
+ processOptions,
725
+ mainThreadContext,
726
+ resolveWorkerLoaders(loader, _loaderIds, _loaderIsArray, context, options)
727
+ );
728
+ }
729
+ },
730
+ getSerializableLoaderContext(context)
731
+ );
732
+ for await (const batch of outputIterator) {
733
+ yield loader.deserializeWorkerBatch ? loader.deserializeWorkerBatch(batch, options, context) : batch;
734
+ }
735
+ }
736
+ function getWorkerAbortSignal(options) {
737
+ var _a;
738
+ if (options == null ? void 0 : options.signal) return options.signal;
739
+ const parquetSignal = (_a = options == null ? void 0 : options.parquet) == null ? void 0 : _a.signal;
740
+ if (typeof AbortSignal !== "undefined" && parquetSignal instanceof AbortSignal) {
741
+ return parquetSignal;
742
+ }
743
+ return void 0;
744
+ }
745
+ function callParseOnMainThread(parseOnMainThread, input, options, context, loaders) {
746
+ if (!loaders && parseOnMainThread.length <= 2) {
747
+ return parseOnMainThread(input, options);
748
+ }
749
+ return parseOnMainThread(input, loaders, options, context);
750
+ }
751
+ function resolveWorkerLoaders(loader, loaderIds, loaderIsArray, context, options) {
752
+ if (!loaderIds) return void 0;
753
+ const availableLoaders = /* @__PURE__ */ new Map();
754
+ const visitedLoaders = /* @__PURE__ */ new Set();
755
+ for (const candidate of [loader, ...(context == null ? void 0 : context.loaders) || []]) {
756
+ visitLoader(candidate);
757
+ }
758
+ const selectedLoaders = loaderIds.map((loaderId) => {
759
+ const selectedLoader = availableLoaders.get(loaderId);
760
+ if (!selectedLoader) {
761
+ throw new Error(
762
+ `Worker requested unknown loader "${loaderId}". Declare it in loader.subloaders or pass it in context.loaders.`
763
+ );
764
+ }
765
+ return selectedLoader;
766
+ });
767
+ return loaderIsArray ? selectedLoaders : selectedLoaders[0];
768
+ function visitLoader(candidate) {
769
+ var _a, _b;
770
+ if (visitedLoaders.has(candidate)) return;
771
+ visitedLoaders.add(candidate);
772
+ availableLoaders.set(candidate.id, candidate);
773
+ for (const [name, dependency] of Object.entries(candidate.subloaders || {})) {
774
+ const replacement = ((_b = (_a = options == null ? void 0 : options.core) == null ? void 0 : _a.subloaders) == null ? void 0 : _b[name]) || dependency;
775
+ visitLoader(replacement);
776
+ availableLoaders.set(dependency.id, replacement);
777
+ }
778
+ }
779
+ }
780
+ function getWorkerOptions(options = {}, loader) {
781
+ var _a, _b;
782
+ const portableOptions = ((_a = loader == null ? void 0 : loader.serializeWorkerOptions) == null ? void 0 : _a.call(loader, options)) || options;
783
+ const optionsToSerialize = {
784
+ ...portableOptions,
785
+ signal: void 0,
786
+ onProgress: void 0,
787
+ ...portableOptions.core ? {
788
+ core: {
789
+ ...portableOptions.core,
790
+ authentications: void 0,
791
+ log: isDisabledLog(portableOptions.core.log) ? null : void 0
792
+ }
793
+ } : {}
794
+ };
795
+ const serializedOptions = JSON.parse(
796
+ JSON.stringify(optionsToSerialize, (_key, value) => {
797
+ if (typeof Headers !== "undefined" && value instanceof Headers)
798
+ return Object.fromEntries(value.entries());
799
+ if (typeof AbortSignal !== "undefined" && value instanceof AbortSignal) return void 0;
800
+ return typeof value === "bigint" ? null : value;
801
+ })
802
+ );
803
+ restoreBigIntOptions(optionsToSerialize, serializedOptions);
804
+ if (((_b = serializedOptions.core) == null ? void 0 : _b.worker) === "auto") {
805
+ serializedOptions.core.worker = true;
806
+ }
807
+ if (loader) {
808
+ serializedOptions._workerLoaderId = loader.id;
809
+ }
810
+ return {
811
+ ...serializedOptions,
812
+ ...serializedOptions.core,
813
+ parserOptions: serializedOptions
814
+ };
815
+ }
816
+ function restoreBigIntOptions(original, serialized) {
817
+ if (!serialized || typeof serialized !== "object") return;
818
+ for (const key of Object.keys(serialized)) {
819
+ const value = original == null ? void 0 : original[key];
820
+ if (typeof value === "bigint") serialized[key] = value;
821
+ else restoreBigIntOptions(value, serialized[key]);
822
+ }
823
+ }
824
+ function getSerializableLoaderContext(context) {
825
+ if (!context) {
826
+ return {};
827
+ }
828
+ const {
829
+ fetch: fetch2,
830
+ loaders,
831
+ coreApi: coreApi2,
832
+ signal,
833
+ reportProgress,
834
+ _parse,
835
+ _parseSync,
836
+ _parseInBatches,
837
+ ...serializableContext
838
+ } = context;
839
+ return JSON.parse(JSON.stringify(serializableContext));
840
+ }
841
+ function shouldParseCSVWithWorker(options) {
842
+ var _a, _b;
843
+ const csvOptions = options;
844
+ return (((_a = csvOptions == null ? void 0 : csvOptions.csv) == null ? void 0 : _a.shape) ?? ((_b = csvOptions == null ? void 0 : csvOptions.core) == null ? void 0 : _b.shape)) === "arrow";
845
+ }
846
+ function isLoaderWithWorkerResultDeserializer(loader) {
847
+ return typeof loader.deserializeWorkerResult === "function";
848
+ }
849
+ function isDisabledLog(logger) {
850
+ return logger === null || logger instanceof NullLog;
851
+ }
852
+
853
+ // src/loader-utils/lib/worker-loader-utils/encode-with-worker.ts
854
+ function canEncodeWithWorker(writer, options) {
855
+ var _a, _b;
856
+ const nodeWorkers = (options == null ? void 0 : options._nodeWorkers) ?? ((_a = options == null ? void 0 : options.core) == null ? void 0 : _a._nodeWorkers);
857
+ const useWorkers = (options == null ? void 0 : options.worker) ?? ((_b = options == null ? void 0 : options.core) == null ? void 0 : _b.worker);
858
+ if (!isBrowser && !nodeWorkers) {
859
+ return false;
860
+ }
861
+ return canProcessOnWorker(
862
+ { ...writer, options: writer.options || {} },
863
+ { worker: Boolean(useWorkers), _nodeWorkers: Boolean(nodeWorkers) }
864
+ );
865
+ }
866
+
867
+ // src/loader-utils/lib/binary-utils/array-buffer-utils.ts
868
+ function compareArrayBuffers(arrayBuffer1, arrayBuffer2, byteLength) {
869
+ byteLength = byteLength || arrayBuffer1.byteLength;
870
+ if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {
871
+ return false;
872
+ }
873
+ const array1 = new Uint8Array(arrayBuffer1);
874
+ const array2 = new Uint8Array(arrayBuffer2);
875
+ for (let i = 0; i < array1.length; ++i) {
876
+ if (array1[i] !== array2[i]) {
877
+ return false;
878
+ }
879
+ }
880
+ return true;
881
+ }
882
+ function concatenateArrayBuffers(...sources) {
883
+ return concatenateArrayBuffersFromArray(sources);
884
+ }
885
+ function concatenateArrayBuffersFromArray(sources) {
886
+ const sourceArrays = sources.map(
887
+ (source2) => source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2
888
+ );
889
+ const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);
890
+ const result = new Uint8Array(byteLength);
891
+ let offset = 0;
892
+ for (const sourceArray of sourceArrays) {
893
+ result.set(sourceArray, offset);
894
+ offset += sourceArray.byteLength;
895
+ }
896
+ return result.buffer;
897
+ }
898
+
899
+ // src/loader-utils/lib/binary-utils/encode-array-buffer-to-base64.ts
900
+ function encodeArrayBufferToBase64(arrayBuffer) {
901
+ const bytes = new Uint8Array(arrayBuffer);
902
+ const encodedChunks = [];
903
+ const chunkByteLength = 3 * 4096;
904
+ for (let byteOffset = 0; byteOffset < bytes.length; byteOffset += chunkByteLength) {
905
+ encodedChunks.push(
906
+ btoa(String.fromCharCode(...bytes.subarray(byteOffset, byteOffset + chunkByteLength)))
907
+ );
908
+ }
909
+ return encodedChunks.join("");
910
+ }
911
+
912
+ // src/loader-utils/lib/iterators/text-iterators.ts
913
+ async function* makeTextDecoderIterator(arrayBufferIterator, options = {}) {
914
+ const textDecoder = new TextDecoder(void 0, options);
915
+ for await (const arrayBuffer of arrayBufferIterator) {
916
+ yield typeof arrayBuffer === "string" ? arrayBuffer : textDecoder.decode(arrayBuffer, { stream: true });
917
+ }
918
+ }
919
+ async function* makeTextEncoderIterator(textIterator) {
920
+ const textEncoder = new TextEncoder();
921
+ for await (const text of textIterator) {
922
+ yield typeof text === "string" ? textEncoder.encode(text).buffer : text;
923
+ }
924
+ }
925
+ async function* makeLineIterator(textIterator) {
926
+ let previous = "";
927
+ for await (const textChunk of textIterator) {
928
+ previous += textChunk;
929
+ let eolIndex;
930
+ eolIndex = previous.indexOf("\n");
931
+ while (eolIndex >= 0) {
932
+ const line = previous.slice(0, eolIndex + 1);
933
+ previous = previous.slice(eolIndex + 1);
934
+ yield line;
935
+ eolIndex = previous.indexOf("\n");
936
+ }
937
+ }
938
+ if (previous.length > 0) {
939
+ yield previous;
940
+ }
941
+ }
942
+ async function* makeNumberedLineIterator(lineIterator) {
943
+ let counter = 1;
944
+ for await (const line of lineIterator) {
945
+ yield { counter, line };
946
+ counter++;
947
+ }
948
+ }
949
+
950
+ // src/loader-utils/lib/iterators/async-iteration.ts
951
+ async function forEach(iterable, visitor) {
952
+ const iterator = toAsyncIterator(iterable);
953
+ while (true) {
954
+ const { done, value } = await iterator.next();
955
+ if (done) {
956
+ if (iterator.return) {
957
+ iterator.return();
958
+ }
959
+ return;
960
+ }
961
+ const cancel = visitor(value);
962
+ if (cancel) {
963
+ return;
964
+ }
965
+ }
966
+ }
967
+ async function concatenateArrayBuffersAsync(asyncIterator) {
968
+ const arrayBuffers = [];
969
+ for await (const chunk of asyncIterator) {
970
+ arrayBuffers.push(copyToArrayBuffer(chunk));
971
+ }
972
+ return concatenateArrayBuffers(...arrayBuffers);
973
+ }
974
+ function copyToArrayBuffer(chunk) {
975
+ if (chunk instanceof ArrayBuffer) {
976
+ return chunk;
977
+ }
978
+ if (ArrayBuffer.isView(chunk)) {
979
+ const { buffer, byteOffset, byteLength } = chunk;
980
+ return copyFromBuffer(buffer, byteOffset, byteLength);
981
+ }
982
+ return copyFromBuffer(chunk);
983
+ }
984
+ function copyFromBuffer(buffer, byteOffset = 0, byteLength = buffer.byteLength - byteOffset) {
985
+ const view = new Uint8Array(buffer, byteOffset, byteLength);
986
+ const copy = new Uint8Array(view.length);
987
+ copy.set(view);
988
+ return copy.buffer;
989
+ }
990
+ function toAsyncIterator(iterable) {
991
+ if (typeof iterable[Symbol.asyncIterator] === "function") {
992
+ return iterable[Symbol.asyncIterator]();
993
+ }
994
+ if (typeof iterable[Symbol.iterator] === "function") {
995
+ const iterator = iterable[Symbol.iterator]();
996
+ return iteratorToAsyncIterator(iterator);
997
+ }
998
+ return iterable;
999
+ }
1000
+ function iteratorToAsyncIterator(iterator) {
1001
+ return {
1002
+ next(value) {
1003
+ return Promise.resolve(iterator.next(value));
1004
+ },
1005
+ return(value) {
1006
+ if (typeof iterator.return === "function") {
1007
+ return Promise.resolve(iterator.return(value));
1008
+ }
1009
+ return Promise.resolve({ done: true, value });
1010
+ },
1011
+ throw(error) {
1012
+ if (typeof iterator.throw === "function") {
1013
+ return Promise.resolve(iterator.throw(error));
1014
+ }
1015
+ return Promise.reject(error);
1016
+ }
1017
+ };
1018
+ }
1019
+
1020
+ // src/loader-utils/lib/request-utils/request-scheduler.ts
1021
+ var import_stats = require("probe.gl/stats");
1022
+ var STAT_QUEUED_REQUESTS = "Queued Requests";
1023
+ var STAT_ACTIVE_REQUESTS = "Active Requests";
1024
+ var STAT_CANCELLED_REQUESTS = "Cancelled Requests";
1025
+ var STAT_QUEUED_REQUESTS_EVER = "Queued Requests Ever";
1026
+ var STAT_ACTIVE_REQUESTS_EVER = "Active Requests Ever";
1027
+ var DEFAULT_PROPS = {
1028
+ id: "request-scheduler",
1029
+ /** Specifies if the request scheduler should throttle incoming requests, mainly for comparative testing. */
1030
+ throttleRequests: true,
1031
+ /** The maximum number of simultaneous active requests. Un-throttled requests do not observe this limit. */
1032
+ maxRequests: 6,
1033
+ /**
1034
+ * Specifies a debounce time, in milliseconds. All requests are queued, until no new requests have
1035
+ * been added to the queue for this amount of time.
1036
+ */
1037
+ debounceTime: 0
1038
+ };
1039
+ var RequestScheduler = class {
1040
+ props;
1041
+ stats;
1042
+ activeRequestCount = 0;
1043
+ /** Tracks the number of active requests and prioritizes/cancels queued requests. */
1044
+ requestQueue = [];
1045
+ requestMap = /* @__PURE__ */ new Map();
1046
+ /** Pending arrival debounce or next-tick refill; only new arrivals replace this timer. */
1047
+ updateTimer = null;
1048
+ constructor(props = {}) {
1049
+ this.props = { ...DEFAULT_PROPS, ...props };
1050
+ this.stats = new import_stats.Stats({ id: this.props.id });
1051
+ this.stats.get(STAT_QUEUED_REQUESTS);
1052
+ this.stats.get(STAT_ACTIVE_REQUESTS);
1053
+ this.stats.get(STAT_CANCELLED_REQUESTS);
1054
+ this.stats.get(STAT_QUEUED_REQUESTS_EVER);
1055
+ this.stats.get(STAT_ACTIVE_REQUESTS_EVER);
1056
+ }
1057
+ /**
1058
+ * Update scheduler props. Preserves active and queued requests.
1059
+ */
1060
+ setProps(props) {
1061
+ if (props.throttleRequests !== void 0) {
1062
+ this.props.throttleRequests = props.throttleRequests;
1063
+ }
1064
+ if (props.maxRequests !== void 0) {
1065
+ this.props.maxRequests = props.maxRequests;
1066
+ }
1067
+ if (props.debounceTime !== void 0) {
1068
+ this.props.debounceTime = props.debounceTime;
1069
+ }
1070
+ }
1071
+ /**
1072
+ * Called by an application that wants to issue a request, without having it deeply queued by the browser
1073
+ *
1074
+ * When the returned promise resolved, it is OK for the application to issue a request.
1075
+ * The promise resolves to an object that contains a `done` method.
1076
+ * When the application's request has completed (or failed), the application must call the `done` function
1077
+ *
1078
+ * @param handle
1079
+ * @param getPriority will be called when request "slots" open up,
1080
+ * allowing the caller to update priority or cancel the request
1081
+ * Highest priority executes first, priority < 0 cancels the request
1082
+ * @returns a promise
1083
+ * - resolves to a object (with a `done` field) when the request can be issued without queueing,
1084
+ * - resolves to `null` if the request has been cancelled (by the callback return < 0).
1085
+ * In this case the application should not issue the request
1086
+ */
1087
+ scheduleRequest(handle, getPriority = () => 0) {
1088
+ if (!this.props.throttleRequests) {
1089
+ return Promise.resolve({ done: () => {
1090
+ } });
1091
+ }
1092
+ if (this.requestMap.has(handle)) {
1093
+ return this.requestMap.get(handle);
1094
+ }
1095
+ const request = { handle, priority: 0, getPriority };
1096
+ const promise = new Promise((resolve2) => {
1097
+ request.resolve = resolve2;
1098
+ return request;
1099
+ });
1100
+ this.requestQueue.push(request);
1101
+ this.requestMap.set(handle, promise);
1102
+ this._issueNewRequests();
1103
+ return promise;
1104
+ }
1105
+ // PRIVATE
1106
+ _issueRequest(request) {
1107
+ const { handle, resolve: resolve2 } = request;
1108
+ let isDone = false;
1109
+ const done = () => {
1110
+ if (!isDone) {
1111
+ isDone = true;
1112
+ this.requestMap.delete(handle);
1113
+ this.activeRequestCount--;
1114
+ this.scheduleRefill();
1115
+ }
1116
+ };
1117
+ this.activeRequestCount++;
1118
+ return resolve2 ? resolve2({ done }) : Promise.resolve({ done });
1119
+ }
1120
+ /** Refills freed slots on the next tick while preserving any pending arrival debounce. */
1121
+ scheduleRefill() {
1122
+ if (this.updateTimer !== null) {
1123
+ return;
1124
+ }
1125
+ this.updateTimer = setTimeout(() => this._issueNewRequestsAsync(), 0);
1126
+ }
1127
+ /** Restarts the quiet period when a new request enters the queue. */
1128
+ _issueNewRequests() {
1129
+ if (this.updateTimer !== null) {
1130
+ clearTimeout(this.updateTimer);
1131
+ }
1132
+ this.updateTimer = setTimeout(() => this._issueNewRequestsAsync(), this.props.debounceTime);
1133
+ }
1134
+ /** Clears timer ownership before updating priorities and dispatching queued requests. */
1135
+ _issueNewRequestsAsync() {
1136
+ if (this.updateTimer !== null) {
1137
+ clearTimeout(this.updateTimer);
1138
+ }
1139
+ this.updateTimer = null;
1140
+ const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);
1141
+ if (freeSlots === 0) {
1142
+ return;
1143
+ }
1144
+ this._updateAllRequests();
1145
+ for (let i = 0; i < freeSlots; ++i) {
1146
+ const request = this.requestQueue.shift();
1147
+ if (request) {
1148
+ this._issueRequest(request);
1149
+ }
1150
+ }
1151
+ }
1152
+ /** Ensure all requests have updated priorities, and that no longer valid requests are cancelled */
1153
+ _updateAllRequests() {
1154
+ const requestQueue = this.requestQueue;
1155
+ for (let i = 0; i < requestQueue.length; ++i) {
1156
+ const request = requestQueue[i];
1157
+ if (!this._updateRequest(request)) {
1158
+ requestQueue.splice(i, 1);
1159
+ this.requestMap.delete(request.handle);
1160
+ i--;
1161
+ }
1162
+ }
1163
+ requestQueue.sort((a, b) => a.priority - b.priority);
1164
+ }
1165
+ /** Update a single request by calling the callback */
1166
+ _updateRequest(request) {
1167
+ request.priority = request.getPriority(request.handle);
1168
+ if (request.priority < 0) {
1169
+ request.resolve(null);
1170
+ return false;
1171
+ }
1172
+ return true;
1173
+ }
1174
+ };
1175
+
1176
+ // src/loader-utils/lib/request-utils/authentication.ts
1177
+ function resolveCredentials(credentials, authentications = []) {
1178
+ if (credentials.every(isAuthentication)) return credentials;
1179
+ return credentials.map((credential, index) => {
1180
+ if (isAuthentication(credential)) return credential;
1181
+ const AuthenticationClass = authentications.find(
1182
+ (authentication2) => authentication2.type === (credential == null ? void 0 : credential.type)
1183
+ );
1184
+ if (!AuthenticationClass) {
1185
+ throw new Error(`No authentication class registered for credential at index ${index}.`);
1186
+ }
1187
+ let authentication;
1188
+ try {
1189
+ authentication = new AuthenticationClass(credential);
1190
+ } catch {
1191
+ throw new Error(`Invalid authentication configuration at index ${index}.`);
1192
+ }
1193
+ if (!isAuthentication(authentication)) {
1194
+ throw new Error(`Authentication class returned an invalid credential at index ${index}.`);
1195
+ }
1196
+ return authentication;
1197
+ });
1198
+ }
1199
+ function resolveAuthenticationOptions(options) {
1200
+ var _a, _b;
1201
+ if (!((_b = (_a = options.core) == null ? void 0 : _a.credentials) == null ? void 0 : _b.length)) return options;
1202
+ const credentials = resolveCredentials(options.core.credentials, options.core.authentications);
1203
+ if (credentials === options.core.credentials) return options;
1204
+ return { ...options, core: { ...options.core, credentials } };
1205
+ }
1206
+ async function resolveLoaderAuthenticationOptions(loader, url, options) {
1207
+ var _a, _b, _c, _d;
1208
+ if (!((_b = (_a = options.core) == null ? void 0 : _a.credentials) == null ? void 0 : _b.length) || options.core.credentials.every(isAuthentication)) {
1209
+ return options;
1210
+ }
1211
+ const contributions = await ((_c = loader == null ? void 0 : loader.getAuthentications) == null ? void 0 : _c.call(loader, url, options));
1212
+ if (!(contributions == null ? void 0 : contributions.length)) return resolveAuthenticationOptions(options);
1213
+ return resolveAuthenticationOptions({
1214
+ ...options,
1215
+ core: {
1216
+ ...options.core,
1217
+ authentications: [...((_d = options.core) == null ? void 0 : _d.authentications) || [], ...contributions]
1218
+ }
1219
+ });
1220
+ }
1221
+ function isAuthentication(credential) {
1222
+ if (!credential || typeof credential !== "object") return false;
1223
+ if (typeof credential.id !== "string" || !Array.isArray(credential.origins)) return false;
1224
+ if (credential.type === "request") return typeof credential.authenticate === "function";
1225
+ return (credential.type === "header" || credential.type === "query-parameter") && typeof credential.name === "string" && (typeof credential.token === "string" || typeof credential.token === "function") && Array.isArray(credential.refreshStatusCodes);
1226
+ }
1227
+
1228
+ // src/loader-utils/lib/request-utils/request-credentials.ts
1229
+ var AUTHENTICATED_FETCH = /* @__PURE__ */ Symbol("loaders.gl.authenticated-fetch");
1230
+ var refreshPromises = /* @__PURE__ */ new WeakMap();
1231
+ function createAuthenticatedFetch(options) {
1232
+ const suppliedFetch = options.fetch || ((url, requestOptions) => fetch(url, requestOptions));
1233
+ const existingMetadata = suppliedFetch[AUTHENTICATED_FETCH];
1234
+ const credentialResolutions = new Map(existingMetadata == null ? void 0 : existingMetadata.credentialResolutions);
1235
+ const resolvedCredentials = resolveCredentials(
1236
+ options.credentials.map((credential) => credentialResolutions.get(credential) || credential),
1237
+ options.authentications
1238
+ );
1239
+ options.credentials.forEach((credential, index) => {
1240
+ credentialResolutions.set(credential, resolvedCredentials[index]);
1241
+ });
1242
+ if (!options.fetchOptions && (!resolvedCredentials.length || (existingMetadata == null ? void 0 : existingMetadata.credentials.length) === resolvedCredentials.length && resolvedCredentials.every(
1243
+ (credential, index) => credential === existingMetadata.credentials[index]
1244
+ )))
1245
+ return suppliedFetch;
1246
+ const baseFetch = (existingMetadata == null ? void 0 : existingMetadata.fetch) || suppliedFetch;
1247
+ const credentials = existingMetadata ? [.../* @__PURE__ */ new Set([...resolvedCredentials, ...existingMetadata.credentials])] : resolvedCredentials;
1248
+ const fetchOptions = mergeFetchOptions(
1249
+ (existingMetadata == null ? void 0 : existingMetadata.fetchOptions) || {},
1250
+ options.fetchOptions
1251
+ );
1252
+ const tokenCredentials = credentials.filter(
1253
+ (credential) => credential.type !== "request"
1254
+ );
1255
+ const requestCredentials = credentials.filter(
1256
+ (credential) => credential.type === "request"
1257
+ );
1258
+ for (const credential of requestCredentials) normalizeRequestOrigins(credential.origins);
1259
+ const authenticatedFetch = async (url, requestOptions = {}) => {
1260
+ var _a, _b, _c, _d, _e, _f, _g;
1261
+ requestOptions = mergeFetchOptions(fetchOptions, requestOptions);
1262
+ (_a = requestOptions.signal) == null ? void 0 : _a.throwIfAborted();
1263
+ if (!credentials.length) return baseFetch(url, requestOptions);
1264
+ const resolvedURL = parseHTTPURL(url);
1265
+ const authorization = resolvedURL ? await authorizeRequest(resolvedURL, requestOptions, tokenCredentials) : { url, options: requestOptions, credentials: [] };
1266
+ const signedRequest = await authenticateRequest(authorization, requestCredentials, "request");
1267
+ const response = await baseFetch(signedRequest.url, signedRequest.options);
1268
+ const refreshableCredentials = [];
1269
+ for (const resolvedCredential of authorization.credentials) {
1270
+ const { credential } = resolvedCredential;
1271
+ if (typeof credential.token === "function" && (isReplayableRequest(requestOptions) || ((_b = credential.canReplayRequest) == null ? void 0 : _b.call(credential, url, requestOptions))) && (isReplayableRequest(signedRequest.options) || ((_c = credential.canReplayRequest) == null ? void 0 : _c.call(credential, signedRequest.url, signedRequest.options))) && (credential.refreshStatusCodes.includes(response.status) || await ((_d = credential.shouldRefresh) == null ? void 0 : _d.call(credential, response))))
1272
+ refreshableCredentials.push(resolvedCredential);
1273
+ }
1274
+ const shouldRetrySignature = isReplayableRequest(requestOptions) && isReplayableRequest(signedRequest.options) && signedRequest.credentials.some(
1275
+ (credential) => {
1276
+ var _a2;
1277
+ return (_a2 = credential.refreshStatusCodes) == null ? void 0 : _a2.includes(response.status);
1278
+ }
1279
+ );
1280
+ if (!refreshableCredentials.length && !shouldRetrySignature) return response;
1281
+ (_e = requestOptions.signal) == null ? void 0 : _e.throwIfAborted();
1282
+ const refreshedTokens = /* @__PURE__ */ new Map();
1283
+ await Promise.all(
1284
+ refreshableCredentials.map(async ({ credential }) => {
1285
+ const token = await refreshCredential(credential, url, response);
1286
+ if (token) refreshedTokens.set(credential, token);
1287
+ })
1288
+ );
1289
+ if (!refreshedTokens.size && !shouldRetrySignature) return response;
1290
+ await ((_f = response.body) == null ? void 0 : _f.cancel().catch(() => {
1291
+ }));
1292
+ (_g = requestOptions.signal) == null ? void 0 : _g.throwIfAborted();
1293
+ const replayAuthorization = resolvedURL ? await authorizeRequest(
1294
+ resolvedURL,
1295
+ requestOptions,
1296
+ tokenCredentials,
1297
+ refreshedTokens,
1298
+ authorization.credentials
1299
+ ) : { url, options: requestOptions };
1300
+ const replayRequest = await authenticateRequest(
1301
+ replayAuthorization,
1302
+ requestCredentials,
1303
+ "retry",
1304
+ response
1305
+ );
1306
+ return baseFetch(replayRequest.url, replayRequest.options);
1307
+ };
1308
+ Object.defineProperty(authenticatedFetch, AUTHENTICATED_FETCH, {
1309
+ value: {
1310
+ fetch: baseFetch,
1311
+ credentials,
1312
+ credentialResolutions,
1313
+ fetchOptions
1314
+ }
1315
+ });
1316
+ return authenticatedFetch;
1317
+ }
1318
+ function mergeFetchOptions(defaultOptions, requestOptions) {
1319
+ const mergedOptions = { ...defaultOptions, ...requestOptions };
1320
+ if (defaultOptions.headers || (requestOptions == null ? void 0 : requestOptions.headers)) {
1321
+ const headers = new Headers(defaultOptions.headers);
1322
+ new Headers(requestOptions == null ? void 0 : requestOptions.headers).forEach((value, key) => headers.set(key, value));
1323
+ mergedOptions.headers = headers;
1324
+ }
1325
+ return mergedOptions;
1326
+ }
1327
+ async function authenticateRequest(request, credentials, reason, response) {
1328
+ const appliedCredentials = [];
1329
+ const signal = request.options.signal;
1330
+ for (const credential of credentials) {
1331
+ const origin = getRequestOrigin(request.url);
1332
+ if (!origin || !normalizeRequestOrigins(credential.origins).includes(origin)) continue;
1333
+ signal == null ? void 0 : signal.throwIfAborted();
1334
+ const authenticatedRequest = await credential.authenticate({
1335
+ url: request.url,
1336
+ options: { ...request.options, headers: new Headers(request.options.headers) },
1337
+ reason,
1338
+ response: response ? { status: response.status, headers: new Headers(response.headers) } : void 0
1339
+ });
1340
+ if (!authenticatedRequest || typeof authenticatedRequest.url !== "string" || !authenticatedRequest.options || typeof authenticatedRequest.options !== "object") {
1341
+ throw new Error("Authentication callback returned an invalid request.");
1342
+ }
1343
+ request = {
1344
+ url: authenticatedRequest.url,
1345
+ options: { ...authenticatedRequest.options, ...signal ? { signal } : {} }
1346
+ };
1347
+ appliedCredentials.push(credential);
1348
+ }
1349
+ signal == null ? void 0 : signal.throwIfAborted();
1350
+ return { ...request, credentials: appliedCredentials };
1351
+ }
1352
+ function getRequestOrigin(url) {
1353
+ try {
1354
+ const parsedURL = new URL(url);
1355
+ if (!parsedURL.host || parsedURL.username || parsedURL.password) return null;
1356
+ return parsedURL.origin !== "null" ? parsedURL.origin : `${parsedURL.protocol}//${parsedURL.host}`;
1357
+ } catch {
1358
+ return null;
1359
+ }
1360
+ }
1361
+ function normalizeRequestOrigins(origins) {
1362
+ if (!origins.length)
1363
+ throw new Error("Request authentication requires at least one exact origin.");
1364
+ return origins.map((origin) => {
1365
+ const resolvedOrigin = getRequestOrigin(origin);
1366
+ let url;
1367
+ try {
1368
+ url = new URL(origin);
1369
+ } catch {
1370
+ throw new Error("Invalid request authentication origin.");
1371
+ }
1372
+ if (!resolvedOrigin || url.pathname && url.pathname !== "/" || url.search || url.hash) {
1373
+ throw new Error("Invalid request authentication origin.");
1374
+ }
1375
+ return resolvedOrigin;
1376
+ });
1377
+ }
1378
+ async function authorizeRequest(sourceURL, requestOptions, credentials, tokenOverrides = /* @__PURE__ */ new Map(), previousCredentials = []) {
1379
+ const url = new URL(sourceURL);
1380
+ const headers = new Headers(requestOptions.headers);
1381
+ const resolvedCredentials = [];
1382
+ const previousTokens = new Map(
1383
+ previousCredentials.map(({ credential, token }) => [credential, token])
1384
+ );
1385
+ for (const credential of credentials) {
1386
+ if (!credential.origins.includes(url.origin)) continue;
1387
+ const overrideToken = tokenOverrides.get(credential);
1388
+ const previousToken = previousTokens.get(credential);
1389
+ const ownsQueryParameter = credential.type === "query-parameter" && previousToken !== void 0;
1390
+ const ownsHeader = credential.type === "header" && previousToken !== void 0;
1391
+ if (credential.type === "query-parameter" && url.searchParams.has(credential.name) && !ownsQueryParameter || credential.type === "header" && headers.has(credential.name) && !ownsHeader) {
1392
+ continue;
1393
+ }
1394
+ const token = overrideToken ?? previousToken ?? await resolveToken(credential.token, { url: sourceURL.toString(), reason: "request" });
1395
+ if (!token) continue;
1396
+ if (credential.type === "query-parameter") {
1397
+ url.searchParams.set(credential.name, token);
1398
+ } else {
1399
+ headers.set(credential.name, `${credential.prefix || ""}${token}`);
1400
+ }
1401
+ resolvedCredentials.push({ credential, token });
1402
+ }
1403
+ return {
1404
+ url: url.toString(),
1405
+ options: { ...requestOptions, headers },
1406
+ credentials: resolvedCredentials
1407
+ };
1408
+ }
1409
+ async function refreshCredential(credential, url, response) {
1410
+ const existingPromise = refreshPromises.get(credential);
1411
+ if (existingPromise) return existingPromise;
1412
+ const tokenProvider = credential.token;
1413
+ const promise = Promise.resolve(
1414
+ tokenProvider({
1415
+ url,
1416
+ reason: "refresh",
1417
+ response: { status: response.status, headers: response.headers }
1418
+ })
1419
+ ).finally(() => refreshPromises.delete(credential));
1420
+ refreshPromises.set(credential, promise);
1421
+ return promise;
1422
+ }
1423
+ async function resolveToken(token, context) {
1424
+ return typeof token === "function" ? token(context) : token;
1425
+ }
1426
+ function parseHTTPURL(url) {
1427
+ try {
1428
+ const parsedURL = new URL(url);
1429
+ return ["http:", "https:"].includes(parsedURL.protocol) ? parsedURL : null;
1430
+ } catch {
1431
+ return null;
1432
+ }
1433
+ }
1434
+ function isReplayableRequest(options) {
1435
+ const method = (options.method || "GET").toUpperCase();
1436
+ if (!["GET", "HEAD", "OPTIONS", "PUT", "DELETE"].includes(method)) return false;
1437
+ return !(options.body && typeof ReadableStream !== "undefined" && options.body instanceof ReadableStream);
1438
+ }
1439
+
1440
+ // src/loader-utils/lib/path-utils/file-aliases.ts
1441
+ var pathPrefix = "";
1442
+ var fileAliases = {};
1443
+ function setPathPrefix(prefix) {
1444
+ pathPrefix = prefix;
1445
+ }
1446
+ function getPathPrefix() {
1447
+ return pathPrefix;
1448
+ }
1449
+ function resolvePath(filename2) {
1450
+ for (const alias in fileAliases) {
1451
+ if (filename2.startsWith(alias)) {
1452
+ const replacement = fileAliases[alias];
1453
+ filename2 = filename2.replace(alias, replacement);
1454
+ }
1455
+ }
1456
+ if (!filename2.startsWith("http://") && !filename2.startsWith("https://")) {
1457
+ filename2 = `${pathPrefix}${filename2}`;
1458
+ }
1459
+ return filename2;
1460
+ }
1461
+
1462
+ // src/loader-utils/lib/path-utils/path.ts
1463
+ var path_exports = {};
1464
+ __export(path_exports, {
1465
+ dirname: () => dirname,
1466
+ filename: () => filename,
1467
+ join: () => join,
1468
+ resolve: () => resolve
1469
+ });
1470
+
1471
+ // src/loader-utils/lib/path-utils/get-cwd.ts
1472
+ function getCWD() {
1473
+ var _a;
1474
+ if (typeof process !== "undefined" && typeof process.cwd !== "undefined") {
1475
+ return process.cwd();
1476
+ }
1477
+ const pathname = (_a = globalThis.location) == null ? void 0 : _a.pathname;
1478
+ return (pathname == null ? void 0 : pathname.slice(0, pathname.lastIndexOf("/") + 1)) || "";
1479
+ }
1480
+
1481
+ // src/loader-utils/lib/path-utils/path.ts
1482
+ function filename(url) {
1483
+ const slashIndex = url ? url.lastIndexOf("/") : -1;
1484
+ return slashIndex >= 0 ? url.substr(slashIndex + 1) : url;
1485
+ }
1486
+ function dirname(url) {
1487
+ const slashIndex = url ? url.lastIndexOf("/") : -1;
1488
+ return slashIndex >= 0 ? url.substr(0, slashIndex) : "";
1489
+ }
1490
+ function join(...parts) {
1491
+ const separator = "/";
1492
+ parts = parts.map((part, index) => {
1493
+ if (index) {
1494
+ part = part.replace(new RegExp(`^${separator}`), "");
1495
+ }
1496
+ if (index !== parts.length - 1) {
1497
+ part = part.replace(new RegExp(`${separator}$`), "");
1498
+ }
1499
+ return part;
1500
+ });
1501
+ return parts.join(separator);
1502
+ }
1503
+ function resolve(...components) {
1504
+ const paths = [];
1505
+ for (let _i = 0; _i < components.length; _i++) {
1506
+ paths[_i] = components[_i];
1507
+ }
1508
+ let resolvedPath = "";
1509
+ let resolvedAbsolute = false;
1510
+ let cwd;
1511
+ for (let i = paths.length - 1; i >= -1 && !resolvedAbsolute; i--) {
1512
+ let path;
1513
+ if (i >= 0) {
1514
+ path = paths[i];
1515
+ } else {
1516
+ if (cwd === void 0) {
1517
+ cwd = getCWD();
1518
+ }
1519
+ path = cwd;
1520
+ }
1521
+ if (path.length === 0) {
1522
+ continue;
1523
+ }
1524
+ resolvedPath = `${path}/${resolvedPath}`;
1525
+ resolvedAbsolute = path.charCodeAt(0) === SLASH;
1526
+ }
1527
+ resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);
1528
+ if (resolvedAbsolute) {
1529
+ return `/${resolvedPath}`;
1530
+ } else if (resolvedPath.length > 0) {
1531
+ return resolvedPath;
1532
+ }
1533
+ return ".";
1534
+ }
1535
+ var SLASH = 47;
1536
+ var DOT = 46;
1537
+ function normalizeStringPosix(path, allowAboveRoot) {
1538
+ let res = "";
1539
+ let lastSlash = -1;
1540
+ let dots = 0;
1541
+ let code;
1542
+ let isAboveRoot = false;
1543
+ for (let i = 0; i <= path.length; ++i) {
1544
+ if (i < path.length) {
1545
+ code = path.charCodeAt(i);
1546
+ } else if (code === SLASH) {
1547
+ break;
1548
+ } else {
1549
+ code = SLASH;
1550
+ }
1551
+ if (code === SLASH) {
1552
+ if (lastSlash === i - 1 || dots === 1) {
1553
+ } else if (lastSlash !== i - 1 && dots === 2) {
1554
+ if (res.length < 2 || !isAboveRoot || res.charCodeAt(res.length - 1) !== DOT || res.charCodeAt(res.length - 2) !== DOT) {
1555
+ if (res.length > 2) {
1556
+ const start = res.length - 1;
1557
+ let j = start;
1558
+ for (; j >= 0; --j) {
1559
+ if (res.charCodeAt(j) === SLASH) {
1560
+ break;
1561
+ }
1562
+ }
1563
+ if (j !== start) {
1564
+ res = j === -1 ? "" : res.slice(0, j);
1565
+ lastSlash = i;
1566
+ dots = 0;
1567
+ isAboveRoot = false;
1568
+ continue;
1569
+ }
1570
+ } else if (res.length === 2 || res.length === 1) {
1571
+ res = "";
1572
+ lastSlash = i;
1573
+ dots = 0;
1574
+ isAboveRoot = false;
1575
+ continue;
1576
+ }
1577
+ }
1578
+ if (allowAboveRoot) {
1579
+ if (res.length > 0) {
1580
+ res += "/..";
1581
+ } else {
1582
+ res = "..";
1583
+ }
1584
+ isAboveRoot = true;
1585
+ }
1586
+ } else {
1587
+ const slice = path.slice(lastSlash + 1, i);
1588
+ if (res.length > 0) {
1589
+ res += `/${slice}`;
1590
+ } else {
1591
+ res = slice;
1592
+ }
1593
+ isAboveRoot = false;
1594
+ }
1595
+ lastSlash = i;
1596
+ dots = 0;
1597
+ } else if (code === DOT && dots !== -1) {
1598
+ ++dots;
1599
+ } else {
1600
+ dots = -1;
1601
+ }
1602
+ }
1603
+ return res;
1604
+ }
1605
+
1606
+ // src/loader-utils/lib/node/buffer.browser.ts
1607
+ function toArrayBuffer(buffer) {
1608
+ return buffer;
1609
+ }
1610
+
1611
+ // src/loader-utils/lib/binary-utils/memory-conversion-utils.ts
1612
+ function isBuffer(value) {
1613
+ return value && typeof value === "object" && value.isBuffer;
1614
+ }
1615
+ function toArrayBuffer2(data) {
1616
+ if (isBuffer(data)) {
1617
+ return toArrayBuffer(data);
1618
+ }
1619
+ if (data instanceof ArrayBuffer) {
1620
+ return data;
1621
+ }
1622
+ if (isSharedArrayBuffer(data)) {
1623
+ return copyToArrayBuffer2(data);
1624
+ }
1625
+ if (ArrayBuffer.isView(data)) {
1626
+ const buffer = data.buffer;
1627
+ if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
1628
+ return buffer;
1629
+ }
1630
+ return buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
1631
+ }
1632
+ if (typeof data === "string") {
1633
+ const text = data;
1634
+ const uint8Array = new TextEncoder().encode(text);
1635
+ return uint8Array.buffer;
1636
+ }
1637
+ if (data && typeof data === "object" && data._toArrayBuffer) {
1638
+ return data._toArrayBuffer();
1639
+ }
1640
+ throw new Error("toArrayBuffer");
1641
+ }
1642
+ function ensureArrayBuffer(bufferSource) {
1643
+ if (bufferSource instanceof ArrayBuffer) {
1644
+ return bufferSource;
1645
+ }
1646
+ if (isSharedArrayBuffer(bufferSource)) {
1647
+ return copyToArrayBuffer2(bufferSource);
1648
+ }
1649
+ const { buffer, byteOffset, byteLength } = bufferSource;
1650
+ if (buffer instanceof ArrayBuffer && byteOffset === 0 && byteLength === buffer.byteLength) {
1651
+ return buffer;
1652
+ }
1653
+ return copyToArrayBuffer2(buffer, byteOffset, byteLength);
1654
+ }
1655
+ function copyToArrayBuffer2(buffer, byteOffset = 0, byteLength = buffer.byteLength - byteOffset) {
1656
+ const view = new Uint8Array(buffer, byteOffset, byteLength);
1657
+ const copy = new Uint8Array(view.length);
1658
+ copy.set(view);
1659
+ return copy.buffer;
1660
+ }
1661
+ function toArrayBufferView(data) {
1662
+ if (ArrayBuffer.isView(data)) {
1663
+ return data;
1664
+ }
1665
+ return new Uint8Array(data);
1666
+ }
1667
+
1668
+ // src/loader-utils/lib/files/blob-file.ts
1669
+ var BlobFile = class {
1670
+ handle;
1671
+ size;
1672
+ bigsize;
1673
+ url;
1674
+ constructor(blob) {
1675
+ this.handle = blob instanceof ArrayBuffer ? new Blob([blob]) : blob;
1676
+ this.size = blob instanceof ArrayBuffer ? blob.byteLength : blob.size;
1677
+ this.bigsize = BigInt(this.size);
1678
+ this.url = blob instanceof File ? blob.name : "";
1679
+ }
1680
+ async close() {
1681
+ }
1682
+ async stat() {
1683
+ return {
1684
+ size: this.handle.size,
1685
+ bigsize: BigInt(this.handle.size),
1686
+ isDirectory: false
1687
+ };
1688
+ }
1689
+ async read(start, length, signal) {
1690
+ if (signal == null ? void 0 : signal.aborted) {
1691
+ throw new Error("Request aborted");
1692
+ }
1693
+ const arrayBuffer = await this.handle.slice(Number(start), Number(start) + Number(length)).arrayBuffer();
1694
+ if (signal == null ? void 0 : signal.aborted) {
1695
+ throw new Error("Request aborted");
1696
+ }
1697
+ return arrayBuffer;
1698
+ }
1699
+ };
1700
+
1701
+ // src/loader-utils/lib/files/node-file-facade.ts
1702
+ var NOT_IMPLEMENTED = new Error("Not implemented");
1703
+ var NodeFileFacade = class {
1704
+ handle;
1705
+ size = 0;
1706
+ bigsize = 0n;
1707
+ url = "";
1708
+ constructor(url, flags, mode) {
1709
+ var _a;
1710
+ if ((_a = globalThis.loaders) == null ? void 0 : _a.NodeFile) {
1711
+ return new globalThis.loaders.NodeFile(url, flags, mode);
1712
+ }
1713
+ if (isBrowser) {
1714
+ throw new Error("Can't instantiate NodeFile in browser.");
1715
+ }
1716
+ throw new Error(
1717
+ "Can't instantiate NodeFile. Make sure to import @loaders.gl/core/polyfills first."
1718
+ );
1719
+ }
1720
+ /** Read data */
1721
+ async read(start, length) {
1722
+ throw NOT_IMPLEMENTED;
1723
+ }
1724
+ /** Write to file. The number of bytes written will be returned */
1725
+ async write(arrayBuffer, offset, length) {
1726
+ throw NOT_IMPLEMENTED;
1727
+ }
1728
+ /** Get information about file */
1729
+ async stat() {
1730
+ throw NOT_IMPLEMENTED;
1731
+ }
1732
+ /** Truncates the file descriptor. Only available on NodeFile. */
1733
+ async truncate(length) {
1734
+ throw NOT_IMPLEMENTED;
1735
+ }
1736
+ /** Append data to a file. Only available on NodeFile. */
1737
+ async append(data) {
1738
+ throw NOT_IMPLEMENTED;
1739
+ }
1740
+ /** Close the file */
1741
+ async close() {
1742
+ }
1743
+ };
1744
+
1745
+ // src/loader-utils/lib/pace-batch-iterator.ts
1746
+ function validateBatchDeliveryRate(rate) {
1747
+ if (!Number.isFinite(rate) || rate < 0) {
1748
+ throw new RangeError("core.batchMaxRowsPerSecond must be a finite nonnegative number");
1749
+ }
1750
+ }
1751
+ async function* paceBatchIterator(batches, { batchMaxRowsPerSecond = 0, getRowCount, signal }) {
1752
+ validateBatchDeliveryRate(batchMaxRowsPerSecond);
1753
+ signal == null ? void 0 : signal.throwIfAborted();
1754
+ if (batchMaxRowsPerSecond === 0) {
1755
+ yield* batches;
1756
+ return;
1757
+ }
1758
+ let deadline = 0;
1759
+ for await (const batch of batches) {
1760
+ signal == null ? void 0 : signal.throwIfAborted();
1761
+ const rowCount = getRowCount(batch);
1762
+ if (rowCount !== void 0 && rowCount > 0) {
1763
+ let remaining = deadline - performance.now();
1764
+ while (remaining > 0) {
1765
+ await waitForBatch(Math.min(Math.ceil(remaining), 2 ** 31 - 1), signal);
1766
+ remaining = deadline - performance.now();
1767
+ }
1768
+ signal == null ? void 0 : signal.throwIfAborted();
1769
+ deadline = performance.now() + rowCount / batchMaxRowsPerSecond * 1e3;
1770
+ }
1771
+ yield batch;
1772
+ signal == null ? void 0 : signal.throwIfAborted();
1773
+ }
1774
+ }
1775
+ function waitForBatch(delay, signal) {
1776
+ signal == null ? void 0 : signal.throwIfAborted();
1777
+ return new Promise((resolve2, reject) => {
1778
+ const timer = setTimeout(() => {
1779
+ signal == null ? void 0 : signal.removeEventListener("abort", abort);
1780
+ resolve2();
1781
+ }, delay);
1782
+ function abort() {
1783
+ clearTimeout(timer);
1784
+ signal == null ? void 0 : signal.removeEventListener("abort", abort);
1785
+ reject(signal == null ? void 0 : signal.reason);
1786
+ }
1787
+ signal == null ? void 0 : signal.addEventListener("abort", abort, { once: true });
1788
+ });
1789
+ }
1790
+
1791
+ // dist/lib/fetch/fetch-error.js
1792
+ var FetchError = class extends Error {
1793
+ constructor(message, info) {
1794
+ super(message);
1795
+ this.reason = info.reason;
1796
+ this.url = info.url;
1797
+ this.response = info.response;
1798
+ }
1799
+ /** A best effort reason for why the fetch failed */
1800
+ reason;
1801
+ /** The URL that failed to load. Empty string if not available. */
1802
+ url;
1803
+ /** The Response object, if any. */
1804
+ response;
1805
+ };
1806
+
1807
+ // dist/lib/utils/mime-type-utils.js
1808
+ var DATA_URL_PATTERN = /^data:([-\w.]+\/[-\w.+]+)(;|,)/;
1809
+ var MIME_TYPE_PATTERN = /^([-\w.]+\/[-\w.+]+)/;
1810
+ function compareMIMETypes(mimeType1, mimeType2) {
1811
+ if (mimeType1.toLowerCase() === mimeType2.toLowerCase()) {
1812
+ return true;
1813
+ }
1814
+ return false;
1815
+ }
1816
+ function parseMIMEType(mimeString) {
1817
+ const matches3 = MIME_TYPE_PATTERN.exec(mimeString);
1818
+ if (matches3) {
1819
+ return matches3[1];
1820
+ }
1821
+ return mimeString;
1822
+ }
1823
+ function parseMIMETypeFromURL(url) {
1824
+ const matches3 = DATA_URL_PATTERN.exec(url);
1825
+ if (matches3) {
1826
+ return matches3[1];
1827
+ }
1828
+ return "";
1829
+ }
1830
+
1831
+ // dist/lib/utils/url-utils.js
1832
+ var QUERY_STRING_PATTERN = /\?.*/;
1833
+ function extractQueryString(url) {
1834
+ const matches3 = url.match(QUERY_STRING_PATTERN);
1835
+ return matches3 && matches3[0];
1836
+ }
1837
+ function stripQueryString(url) {
1838
+ return url.replace(QUERY_STRING_PATTERN, "");
1839
+ }
1840
+ function shortenUrlForDisplay(url) {
1841
+ if (url.length < 50) {
1842
+ return url;
1843
+ }
1844
+ const urlEnd = url.slice(url.length - 15);
1845
+ const urlStart = url.substr(0, 32);
1846
+ return `${urlStart}...${urlEnd}`;
1847
+ }
1848
+
1849
+ // dist/lib/utils/resource-utils.js
1850
+ function getResourceUrl(resource) {
1851
+ if (isResponse(resource)) {
1852
+ return resource.url;
1853
+ }
1854
+ if (isBlob(resource)) {
1855
+ const fileName = "name" in resource ? resource.name : "";
1856
+ return fileName || "";
1857
+ }
1858
+ if (typeof resource === "string") {
1859
+ return resource;
1860
+ }
1861
+ return "";
1862
+ }
1863
+ function getResourceMIMEType(resource) {
1864
+ if (isResponse(resource)) {
1865
+ const contentTypeHeader = resource.headers.get("content-type") || "";
1866
+ const noQueryUrl = stripQueryString(resource.url);
1867
+ return parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(noQueryUrl);
1868
+ }
1869
+ if (isBlob(resource)) {
1870
+ return resource.type || "";
1871
+ }
1872
+ if (typeof resource === "string") {
1873
+ return parseMIMETypeFromURL(resource);
1874
+ }
1875
+ return "";
1876
+ }
1877
+ function getResourceContentLength(resource) {
1878
+ if (isResponse(resource)) {
1879
+ const response = resource;
1880
+ return response.headers["content-length"] || -1;
1881
+ }
1882
+ if (isBlob(resource)) {
1883
+ const blob = resource;
1884
+ return blob.size;
1885
+ }
1886
+ if (typeof resource === "string") {
1887
+ return resource.length;
1888
+ }
1889
+ if (resource instanceof ArrayBuffer) {
1890
+ return resource.byteLength;
1891
+ }
1892
+ if (ArrayBuffer.isView(resource)) {
1893
+ return resource.byteLength;
1894
+ }
1895
+ return -1;
1896
+ }
1897
+
1898
+ // dist/lib/utils/response-utils.js
1899
+ async function makeResponse(resource) {
1900
+ if (isResponse(resource)) {
1901
+ return resource;
1902
+ }
1903
+ const headers = {};
1904
+ const contentLength = getResourceContentLength(resource);
1905
+ if (contentLength >= 0) {
1906
+ headers["content-length"] = String(contentLength);
1907
+ }
1908
+ const url = getResourceUrl(resource);
1909
+ const type = getResourceMIMEType(resource);
1910
+ if (type) {
1911
+ headers["content-type"] = type;
1912
+ }
1913
+ const initialDataUrl = await getInitialDataUrl(resource);
1914
+ if (initialDataUrl) {
1915
+ headers["x-first-bytes"] = initialDataUrl;
1916
+ }
1917
+ if (typeof resource === "string") {
1918
+ resource = new TextEncoder().encode(resource);
1919
+ }
1920
+ const response = new Response(resource, { headers });
1921
+ Object.defineProperty(response, "url", { value: url });
1922
+ return response;
1923
+ }
1924
+ async function checkResponse(response) {
1925
+ if (!response.ok) {
1926
+ const error = await getResponseError(response);
1927
+ throw error;
1928
+ }
1929
+ }
1930
+ async function getResponseError(response) {
1931
+ const shortUrl = shortenUrlForDisplay(response.url);
1932
+ let message = `Failed to fetch resource (${response.status}) ${response.statusText}: ${shortUrl}`;
1933
+ message = message.length > 100 ? `${message.slice(0, 100)}...` : message;
1934
+ const info = {
1935
+ reason: response.statusText,
1936
+ url: response.url,
1937
+ response
1938
+ };
1939
+ try {
1940
+ const contentType = response.headers.get("Content-Type");
1941
+ info.reason = !response.bodyUsed && (contentType == null ? void 0 : contentType.includes("application/json")) ? await response.json() : await response.text();
1942
+ } catch (_error) {
1943
+ }
1944
+ return new FetchError(message, info);
1945
+ }
1946
+ async function getInitialDataUrl(resource) {
1947
+ const INITIAL_DATA_LENGTH = 5;
1948
+ if (typeof resource === "string") {
1949
+ return `data:,${resource.slice(0, INITIAL_DATA_LENGTH)}`;
1950
+ }
1951
+ if (resource instanceof Blob) {
1952
+ const blobSlice = resource.slice(0, 5);
1953
+ return await new Promise((resolve2) => {
1954
+ const reader = new FileReader();
1955
+ reader.onload = (event) => {
1956
+ var _a;
1957
+ return resolve2((_a = event == null ? void 0 : event.target) == null ? void 0 : _a.result);
1958
+ };
1959
+ reader.readAsDataURL(blobSlice);
1960
+ });
1961
+ }
1962
+ if (resource instanceof ArrayBuffer) {
1963
+ const slice = resource.slice(0, INITIAL_DATA_LENGTH);
1964
+ const base64 = encodeArrayBufferToBase64(slice);
1965
+ return `data:base64,${base64}`;
1966
+ }
1967
+ return null;
1968
+ }
1969
+
1970
+ // dist/lib/fetch/fetch-file.js
1971
+ function isNodePath(url) {
1972
+ return !isRequestURL(url) && !isDataURL(url);
1973
+ }
1974
+ function isRequestURL(url) {
1975
+ return url.startsWith("http:") || url.startsWith("https:");
1976
+ }
1977
+ function isDataURL(url) {
1978
+ return url.startsWith("data:");
1979
+ }
1980
+ async function fetchFile(urlOrData, fetchOptions) {
1981
+ var _a, _b;
1982
+ if (typeof urlOrData === "string") {
1983
+ const url = resolvePath(urlOrData);
1984
+ if (isNodePath(url)) {
1985
+ if ((_a = globalThis.loaders) == null ? void 0 : _a.fetchNode) {
1986
+ return (_b = globalThis.loaders) == null ? void 0 : _b.fetchNode(url, fetchOptions);
1987
+ }
1988
+ }
1989
+ return await fetch(url, fetchOptions);
1990
+ }
1991
+ return await makeResponse(urlOrData);
1992
+ }
1993
+
1994
+ // dist/lib/fetch/read-array-buffer.js
1995
+ async function readArrayBuffer(file, start, length) {
1996
+ if (!(file instanceof Blob)) {
1997
+ file = new Blob([file]);
1998
+ }
1999
+ const slice = file.slice(start, start + length);
2000
+ return await readBlob(slice);
2001
+ }
2002
+ async function readBlob(blob) {
2003
+ return await new Promise((resolve2, reject) => {
2004
+ const fileReader = new FileReader();
2005
+ fileReader.onload = (event) => {
2006
+ var _a;
2007
+ return resolve2((_a = event == null ? void 0 : event.target) == null ? void 0 : _a.result);
2008
+ };
2009
+ fileReader.onerror = (error) => reject(error);
2010
+ fileReader.readAsArrayBuffer(blob);
2011
+ });
2012
+ }
2013
+
2014
+ // dist/lib/loader-utils/loggers.js
2015
+ var import_log6 = require("probe.gl/log");
2016
+
2017
+ // dist/loader-utils/lib/log-utils/log.js
2018
+ var import_log5 = require("probe.gl/log");
2019
+ var VERSION3 = true ? "5.0.2" : "latest";
2020
+ var version2 = VERSION3[0] >= "0" && VERSION3[0] <= "9" ? `v${VERSION3}` : "";
2021
+ function createLog2() {
2022
+ const log3 = new import_log5.Log({ id: "loaders.gl" });
2023
+ globalThis.loaders ||= {};
2024
+ globalThis.loaders.log = log3;
2025
+ globalThis.loaders.version = version2;
2026
+ globalThis.probe ||= {};
2027
+ globalThis.probe.loaders = log3;
2028
+ return log3;
2029
+ }
2030
+ var log2 = createLog2();
2031
+ var NullLog2 = class {
2032
+ /** Discards debug messages. */
2033
+ log() {
2034
+ return ignoreMessage2;
2035
+ }
2036
+ /** Discards informational messages. */
2037
+ info() {
2038
+ return ignoreMessage2;
2039
+ }
2040
+ /** Discards messages marked to be emitted once. */
2041
+ once() {
2042
+ return ignoreMessage2;
2043
+ }
2044
+ /** Discards warnings. */
2045
+ warn() {
2046
+ return ignoreMessage2;
2047
+ }
2048
+ /** Discards errors. */
2049
+ error() {
2050
+ return ignoreMessage2;
2051
+ }
2052
+ };
2053
+ function ignoreMessage2() {
2054
+ }
2055
+ var nullLog2 = new NullLog2();
2056
+
2057
+ // dist/lib/loader-utils/option-defaults.js
2058
+ var DEFAULT_LOADER_OPTIONS = {
2059
+ searchParams: void 0,
2060
+ core: {
2061
+ baseUrl: void 0,
2062
+ // baseUrl
2063
+ fetch: null,
2064
+ mimeType: void 0,
2065
+ fallbackMimeType: void 0,
2066
+ ignoreRegisteredLoaders: void 0,
2067
+ nothrow: false,
2068
+ shape: void 0,
2069
+ log: log2,
2070
+ useLocalLibraries: false,
2071
+ subloaders: void 0,
2072
+ CDN: "https://unpkg.com/@loaders.gl",
2073
+ worker: true,
2074
+ // By default, use worker if provided by loader.
2075
+ workerThreshold: 0.1,
2076
+ workerInBatches: void 0,
2077
+ maxConcurrency: 3,
2078
+ // How many worker instances should be created for each loader.
2079
+ maxMobileConcurrency: 1,
2080
+ // How many worker instances should be created for each loader on mobile devices.
2081
+ reuseWorkers: isBrowser,
2082
+ // By default reuse workers in browser (Node.js refuses to terminate if browsers are running)
2083
+ _nodeWorkers: false,
2084
+ // By default do not support node workers
2085
+ _workerType: "",
2086
+ // 'test' to use locally generated workers
2087
+ batchSize: "auto",
2088
+ batchMaxRowsPerSecond: 0,
2089
+ metadata: false,
2090
+ // TODO - currently only implemented for parseInBatches, adds initial metadata batch,
2091
+ transforms: []
2092
+ }
2093
+ };
2094
+ var REMOVED_LOADER_OPTIONS = {
2095
+ // Removed top-level aliases
2096
+ baseUri: "core.baseUrl",
2097
+ baseUrl: "core.baseUrl",
2098
+ fetch: "core.fetch",
2099
+ mimeType: "core.mimeType",
2100
+ fallbackMimeType: "core.fallbackMimeType",
2101
+ ignoreRegisteredLoaders: "core.ignoreRegisteredLoaders",
2102
+ nothrow: "core.nothrow",
2103
+ log: "core.log",
2104
+ useLocalLibraries: "core.useLocalLibraries",
2105
+ CDN: "core.CDN",
2106
+ worker: "core.worker",
2107
+ workerThreshold: "core.workerThreshold",
2108
+ workerTransferBufferCopy: "core.workerTransferBufferCopy",
2109
+ maxConcurrency: "core.maxConcurrency",
2110
+ maxMobileConcurrency: "core.maxMobileConcurrency",
2111
+ reuseWorkers: "core.reuseWorkers",
2112
+ _nodeWorkers: "core._nodeWorkers",
2113
+ _workerType: "core._workerType",
2114
+ _worker: "core._workerType",
2115
+ shape: "core.shape",
2116
+ batchSize: "core.batchSize",
2117
+ batchDebounceMs: "(removed; use core.batchMaxRowsPerSecond)",
2118
+ metadata: "core.metadata",
2119
+ transforms: "core.transforms",
2120
+ // Older deprecations
2121
+ throws: "nothrow",
2122
+ dataType: "(no longer used)",
2123
+ uri: "core.baseUrl",
2124
+ // Warn if fetch options are used on toplevel
2125
+ method: "core.fetch.method",
2126
+ headers: "core.fetch.headers",
2127
+ body: "core.fetch.body",
2128
+ mode: "core.fetch.mode",
2129
+ credentials: "core.fetch.credentials",
2130
+ cache: "core.fetch.cache",
2131
+ redirect: "core.fetch.redirect",
2132
+ referrer: "core.fetch.referrer",
2133
+ referrerPolicy: "core.fetch.referrerPolicy",
2134
+ integrity: "core.fetch.integrity",
2135
+ keepalive: "core.fetch.keepalive",
2136
+ signal: "core.fetch.signal"
2137
+ };
2138
+
2139
+ // dist/lib/loader-utils/native-arrow.js
2140
+ function getShapeOptionKey(loader) {
2141
+ const keys = Object.keys(loader.options || {}).filter((key) => {
2142
+ var _a;
2143
+ const value = (_a = loader.options) == null ? void 0 : _a[key];
2144
+ return key !== "core" && value && typeof value === "object" && "shape" in value;
2145
+ });
2146
+ return keys.includes(loader.id) ? loader.id : keys.length === 1 ? keys[0] : void 0;
2147
+ }
2148
+ function usesNativeArrowBatches(loader, options) {
2149
+ var _a;
2150
+ const key = getShapeOptionKey(loader);
2151
+ const scopedOptions = key && options[key];
2152
+ if (!scopedOptions || typeof scopedOptions !== "object" || !("shape" in scopedOptions) || scopedOptions.shape !== "arrow") {
2153
+ return false;
2154
+ }
2155
+ if ((_a = options.core) == null ? void 0 : _a.metadata) {
2156
+ throw new Error('shape: "arrow" carries metadata in the Arrow schema and does not support core.metadata envelopes');
2157
+ }
2158
+ return true;
2159
+ }
2160
+ async function* normalizeNativeArrowBatches(batches) {
2161
+ for await (const batch of batches) {
2162
+ const batchType = batch == null ? void 0 : batch.batchType;
2163
+ if (batchType === "metadata" || batchType === "partial-result" || batchType === "final-result") {
2164
+ continue;
2165
+ }
2166
+ if (isArrowRecordBatch(batch)) {
2167
+ yield batch;
2168
+ } else if (isArrowTable(batch)) {
2169
+ yield* batch.batches;
2170
+ } else {
2171
+ throw new Error('shape: "arrow" requires a native Arrow table or record batch');
2172
+ }
2173
+ }
2174
+ }
2175
+ function isArrowTable(value) {
2176
+ return Boolean(value && typeof value === "object" && "schema" in value && "batches" in value && Array.isArray(value.batches) && "numRows" in value && typeof value.numRows === "number" && "getChildAt" in value && typeof value.getChildAt === "function");
2177
+ }
2178
+ function isArrowRecordBatch(value) {
2179
+ return Boolean(value && typeof value === "object" && value[/* @__PURE__ */ Symbol.for("apache-arrow/RecordBatch")] === true);
2180
+ }
2181
+
2182
+ // dist/lib/loader-utils/option-utils.js
2183
+ function applySearchParamsToUrl(url, options) {
2184
+ const searchParams = options == null ? void 0 : options.searchParams;
2185
+ if (!searchParams || Object.keys(searchParams).length === 0 || /^(?:data|blob):/i.test(url)) {
2186
+ return url;
2187
+ }
2188
+ const hashIndex = url.indexOf("#");
2189
+ const hash = hashIndex >= 0 ? url.slice(hashIndex) : "";
2190
+ const urlWithoutHash = hashIndex >= 0 ? url.slice(0, hashIndex) : url;
2191
+ const queryIndex = urlWithoutHash.indexOf("?");
2192
+ const path = queryIndex >= 0 ? urlWithoutHash.slice(0, queryIndex) : urlWithoutHash;
2193
+ const query = queryIndex >= 0 ? urlWithoutHash.slice(queryIndex + 1) : "";
2194
+ const existingSearchParams = new URLSearchParams(query);
2195
+ const appendedSearchParams = new URLSearchParams();
2196
+ for (const [key, value] of Object.entries(searchParams)) {
2197
+ if (!existingSearchParams.has(key)) {
2198
+ appendedSearchParams.set(key, String(value));
2199
+ }
2200
+ }
2201
+ const serializedAppendedSearchParams = appendedSearchParams.toString();
2202
+ return `${path}${queryIndex >= 0 ? `?${query}` : ""}${serializedAppendedSearchParams ? `${queryIndex >= 0 ? "&" : "?"}${serializedAppendedSearchParams}` : ""}${hash}`;
2203
+ }
2204
+ function getGlobalLoaderState() {
2205
+ globalThis.loaders = globalThis.loaders || {};
2206
+ const { loaders } = globalThis;
2207
+ if (!loaders._state) {
2208
+ loaders._state = {};
2209
+ }
2210
+ return loaders._state;
2211
+ }
2212
+ function getGlobalLoaderOptions() {
2213
+ const state = getGlobalLoaderState();
2214
+ state.globalOptions = state.globalOptions || {
2215
+ ...DEFAULT_LOADER_OPTIONS,
2216
+ core: { ...DEFAULT_LOADER_OPTIONS.core }
2217
+ };
2218
+ return cloneLoaderOptions(state.globalOptions);
2219
+ }
2220
+ function setGlobalOptions(options) {
2221
+ const state = getGlobalLoaderState();
2222
+ const globalOptions = getGlobalLoaderOptions();
2223
+ validateOptions(options, []);
2224
+ validateWorkerThreshold(options);
2225
+ mergeNestedFields(globalOptions, options);
2226
+ state.globalOptions = globalOptions;
2227
+ registerJSModules(options.modules);
2228
+ }
2229
+ function normalizeOptions(options, loader, loaders, url) {
2230
+ loaders = loaders || [];
2231
+ loaders = Array.isArray(loaders) ? loaders : [loaders];
2232
+ validateOptions(options, loaders);
2233
+ validateWorkerThreshold(options);
2234
+ const normalizedOptions = normalizeOptionsInternal(loader, options, url);
2235
+ validateWorkerThreshold(normalizedOptions);
2236
+ return normalizedOptions;
2237
+ }
2238
+ function validateOptions(options, loaders) {
2239
+ validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders);
2240
+ for (const loader of loaders) {
2241
+ const idOptions = options && options[loader.id] || {};
2242
+ const loaderOptions = loader.options && loader.options[loader.id] || {};
2243
+ const deprecatedOptions = loader.deprecatedOptions && loader.deprecatedOptions[loader.id] || {};
2244
+ validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders);
2245
+ }
2246
+ }
2247
+ function validateWorkerThreshold(options) {
2248
+ var _a;
2249
+ const threshold = (_a = options.core) == null ? void 0 : _a.workerThreshold;
2250
+ if (threshold !== void 0 && (!Number.isFinite(threshold) || threshold < 0 || threshold > 1)) {
2251
+ throw new Error("core.workerThreshold must be a finite number between 0 and 1");
2252
+ }
2253
+ }
2254
+ function validateOptionsObject(options, id, defaultOptions, deprecatedOptions, loaders) {
2255
+ const loaderName = id || "Top level";
2256
+ const prefix = id ? `${id}.` : "";
2257
+ for (const key in options) {
2258
+ const isSubOptions = !id && isObject(options[key]);
2259
+ const isLifecycleOption = !id && ["signal", "onProgress"].includes(key);
2260
+ const isWorkerUrlOption = key === "workerUrl" && id;
2261
+ if (!(key in defaultOptions) && !isLifecycleOption && !isWorkerUrlOption) {
2262
+ if (key in deprecatedOptions) {
2263
+ if (log2.level > 0) {
2264
+ log2.warn(`${loaderName} loader option '${prefix}${key}' no longer supported, use '${deprecatedOptions[key]}'`)();
2265
+ }
2266
+ } else if (!isSubOptions) {
2267
+ if (log2.level > 0) {
2268
+ const suggestion = findSimilarOption(key, loaders);
2269
+ log2.warn(`${loaderName} loader option '${prefix}${key}' not recognized. ${suggestion}`)();
2270
+ }
2271
+ }
2272
+ }
2273
+ }
2274
+ }
2275
+ function findSimilarOption(optionKey, loaders) {
2276
+ const lowerCaseOptionKey = optionKey.toLowerCase();
2277
+ let bestSuggestion = "";
2278
+ for (const loader of loaders) {
2279
+ for (const key in loader.options) {
2280
+ if (optionKey === key) {
2281
+ return `Did you mean '${loader.id}.${key}'?`;
2282
+ }
2283
+ const lowerCaseKey = key.toLowerCase();
2284
+ const isPartialMatch = lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey);
2285
+ if (isPartialMatch) {
2286
+ bestSuggestion = bestSuggestion || `Did you mean '${loader.id}.${key}'?`;
2287
+ }
2288
+ }
2289
+ }
2290
+ return bestSuggestion;
2291
+ }
2292
+ function normalizeOptionsInternal(loader, options, url) {
2293
+ var _a;
2294
+ const loaderDefaultOptions = loader.options || {};
2295
+ const mergedOptions = { ...loaderDefaultOptions };
2296
+ if (loaderDefaultOptions.core) {
2297
+ mergedOptions.core = { ...loaderDefaultOptions.core };
2298
+ }
2299
+ const shapeKey = loader.defaultShape && getShapeOptionKey(loader);
2300
+ if (shapeKey) {
2301
+ mergedOptions[shapeKey] = {
2302
+ ...loaderDefaultOptions[shapeKey],
2303
+ shape: loader.defaultShape
2304
+ };
2305
+ }
2306
+ mergeNestedFields(mergedOptions, getGlobalLoaderOptions());
2307
+ mergeNestedFields(mergedOptions, options);
2308
+ applyCoreShapeDefault(mergedOptions, options, loader);
2309
+ if (((_a = mergedOptions.core) == null ? void 0 : _a.log) === null) {
2310
+ mergedOptions.core = { ...mergedOptions.core, log: getLoaderLog(mergedOptions) };
2311
+ }
2312
+ addUrlOptions(mergedOptions, url);
2313
+ return mergedOptions;
2314
+ }
2315
+ function applyCoreShapeDefault(mergedOptions, userOptions, loader) {
2316
+ var _a, _b;
2317
+ const coreShape = (_a = mergedOptions.core) == null ? void 0 : _a.shape;
2318
+ if (coreShape === void 0) {
2319
+ return;
2320
+ }
2321
+ const shapeOptionKey = getShapeOptionKey(loader);
2322
+ if (!shapeOptionKey) {
2323
+ return;
2324
+ }
2325
+ const loaderScopedDefaults = (_b = loader.options) == null ? void 0 : _b[shapeOptionKey];
2326
+ if (!isPureObject(loaderScopedDefaults) || !("shape" in loaderScopedDefaults)) {
2327
+ return;
2328
+ }
2329
+ const globalLoaderScopedOptions = getGlobalLoaderOptions()[shapeOptionKey];
2330
+ if (isPureObject(globalLoaderScopedOptions) && "shape" in globalLoaderScopedOptions) {
2331
+ return;
2332
+ }
2333
+ const userLoaderScopedOptions = userOptions[shapeOptionKey];
2334
+ if (isPureObject(userLoaderScopedOptions) && "shape" in userLoaderScopedOptions) {
2335
+ return;
2336
+ }
2337
+ const loaderScopedOptions = mergedOptions[shapeOptionKey];
2338
+ mergedOptions[shapeOptionKey] = {
2339
+ ...isPureObject(loaderScopedOptions) ? loaderScopedOptions : {},
2340
+ shape: coreShape
2341
+ };
2342
+ }
2343
+ function mergeNestedFields(mergedOptions, options) {
2344
+ for (const key in options) {
2345
+ if (key in options) {
2346
+ const value = options[key];
2347
+ if (isPureObject(value) && isPureObject(mergedOptions[key])) {
2348
+ mergedOptions[key] = {
2349
+ ...mergedOptions[key],
2350
+ ...options[key]
2351
+ };
2352
+ } else {
2353
+ mergedOptions[key] = options[key];
2354
+ }
2355
+ }
2356
+ }
2357
+ }
2358
+ function addUrlOptions(options, url) {
2359
+ var _a;
2360
+ if (!url) {
2361
+ return;
2362
+ }
2363
+ const hasCoreBaseUrl = ((_a = options.core) == null ? void 0 : _a.baseUrl) !== void 0;
2364
+ if (!hasCoreBaseUrl) {
2365
+ options.core ||= {};
2366
+ options.core.baseUrl = path_exports.dirname(stripQueryString(url));
2367
+ }
2368
+ }
2369
+ function cloneLoaderOptions(options) {
2370
+ const clonedOptions = { ...options };
2371
+ if (options.core) {
2372
+ clonedOptions.core = { ...options.core };
2373
+ }
2374
+ return clonedOptions;
2375
+ }
2376
+
2377
+ // dist/lib/api/loader-options.js
2378
+ function compareLoaderOptions(left, right) {
2379
+ return Object.is(left, right) || compareOptionValues(left, right, /* @__PURE__ */ new WeakMap());
2380
+ }
2381
+ function compareOptionValues(left, right, visited) {
2382
+ if (Object.is(left, right)) {
2383
+ return true;
2384
+ }
2385
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") {
2386
+ return false;
2387
+ }
2388
+ const leftPrototype = Object.getPrototypeOf(left);
2389
+ if (leftPrototype !== Object.getPrototypeOf(right)) {
2390
+ return false;
2391
+ }
2392
+ if (Array.isArray(left)) {
2393
+ if (!Array.isArray(right) || left.length !== right.length) {
2394
+ return false;
2395
+ }
2396
+ } else if (leftPrototype !== Object.prototype && leftPrototype !== null) {
2397
+ return false;
2398
+ }
2399
+ let rightValues = visited.get(left);
2400
+ if (rightValues == null ? void 0 : rightValues.has(right)) {
2401
+ return true;
2402
+ }
2403
+ if (!rightValues) {
2404
+ rightValues = /* @__PURE__ */ new WeakSet();
2405
+ visited.set(left, rightValues);
2406
+ }
2407
+ rightValues.add(right);
2408
+ const leftKeys = getEnumerableKeys(left);
2409
+ const rightKeys = getEnumerableKeys(right);
2410
+ const leftOptions = left;
2411
+ const rightOptions = right;
2412
+ return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.prototype.propertyIsEnumerable.call(right, key) && compareOptionValues(leftOptions[key], rightOptions[key], visited));
2413
+ }
2414
+ function getEnumerableKeys(value) {
2415
+ return Reflect.ownKeys(value).filter((key) => Object.prototype.propertyIsEnumerable.call(value, key));
2416
+ }
2417
+
2418
+ // dist/lib/loader-utils/normalize-loader.js
2419
+ function isLoaderObject(loader) {
2420
+ if (!loader) {
2421
+ return false;
2422
+ }
2423
+ if (Array.isArray(loader)) {
2424
+ loader = loader[0];
2425
+ }
2426
+ const hasExtensions = Array.isArray(loader == null ? void 0 : loader.extensions);
2427
+ return hasExtensions;
2428
+ }
2429
+ function normalizeLoader(loader) {
2430
+ assert(loader, "null loader");
2431
+ assert(isLoaderObject(loader), "invalid loader");
2432
+ let options;
2433
+ if (Array.isArray(loader)) {
2434
+ options = loader[1];
2435
+ loader = loader[0];
2436
+ loader = {
2437
+ ...loader,
2438
+ options: { ...loader.options, ...options }
2439
+ };
2440
+ }
2441
+ if ((loader == null ? void 0 : loader.parseTextSync) || (loader == null ? void 0 : loader.parseText)) {
2442
+ loader.text = true;
2443
+ }
2444
+ if (!loader.text) {
2445
+ loader.binary = true;
2446
+ }
2447
+ return loader;
2448
+ }
2449
+
2450
+ // dist/lib/api/register-loaders.js
2451
+ var getGlobalLoaderRegistry = () => {
2452
+ const state = getGlobalLoaderState();
2453
+ state.loaderRegistry = state.loaderRegistry || [];
2454
+ return state.loaderRegistry;
2455
+ };
2456
+ function registerLoaders(loaders) {
2457
+ const loaderRegistry = getGlobalLoaderRegistry();
2458
+ loaders = Array.isArray(loaders) ? loaders : [loaders];
2459
+ for (const loader of loaders) {
2460
+ const normalizedLoader = normalizeLoader(loader);
2461
+ if (!loaderRegistry.find((registeredLoader) => normalizedLoader === registeredLoader)) {
2462
+ loaderRegistry.unshift(normalizedLoader);
2463
+ }
2464
+ }
2465
+ }
2466
+ function getRegisteredLoaders() {
2467
+ return getGlobalLoaderRegistry();
2468
+ }
2469
+ function _unregisterLoaders() {
2470
+ const state = getGlobalLoaderState();
2471
+ state.loaderRegistry = [];
2472
+ }
2473
+
2474
+ // dist/lib/api/select-loader.js
2475
+ var EXT_PATTERN = /\.([^.]+)$/;
2476
+ async function selectLoader(data, loaders = [], options, context, operation = "parse") {
2477
+ var _a, _b;
2478
+ if (!validHTTPResponse(data)) {
2479
+ return null;
2480
+ }
2481
+ if (loaders && !Array.isArray(loaders)) {
2482
+ return normalizeLoader(loaders);
2483
+ }
2484
+ const text = data instanceof Response && mayContainText(data) ? await data.clone().text() : null;
2485
+ let initialBytes;
2486
+ async function matchCandidates(candidates) {
2487
+ normalizeLoaders(candidates);
2488
+ const loader2 = text !== null && selectLoaderInternal(text, candidates, options, context, operation) || selectLoaderInternal(data, candidates, options, context, operation);
2489
+ if (!loader2 && isBlob(data) && candidates.length) {
2490
+ initialBytes ??= await data.slice(0, 10).arrayBuffer();
2491
+ return selectLoaderInternal(initialBytes, candidates, options, context, operation);
2492
+ }
2493
+ return loader2;
2494
+ }
2495
+ let loader = await matchCandidates(loaders || []);
2496
+ if (!loader && !((_a = options == null ? void 0 : options.core) == null ? void 0 : _a.ignoreRegisteredLoaders)) {
2497
+ loader = await matchCandidates(getRegisteredLoaders());
2498
+ }
2499
+ if (!loader && !((_b = options == null ? void 0 : options.core) == null ? void 0 : _b.nothrow)) {
2500
+ throw new Error(getNoValidLoaderMessage(data));
2501
+ }
2502
+ return loader;
2503
+ }
2504
+ function mayContainText(response) {
2505
+ const mimeType = getResourceMIMEType(response);
2506
+ return Boolean(mimeType && (mimeType.startsWith("text/") || mimeType === "application/json" || mimeType.endsWith("+json")));
2507
+ }
2508
+ function selectLoaderSync(data, loaders = [], options, context, operation = "parse") {
2509
+ var _a, _b;
2510
+ if (!validHTTPResponse(data)) {
2511
+ return null;
2512
+ }
2513
+ if (loaders && !Array.isArray(loaders)) {
2514
+ return normalizeLoader(loaders);
2515
+ }
2516
+ const candidates = loaders || [];
2517
+ normalizeLoaders(candidates);
2518
+ let loader = selectLoaderInternal(data, candidates, options, context, operation);
2519
+ if (!loader && !((_a = options == null ? void 0 : options.core) == null ? void 0 : _a.ignoreRegisteredLoaders)) {
2520
+ loader = selectLoaderInternal(data, getRegisteredLoaders(), options, context, operation);
2521
+ }
2522
+ if (!loader && !((_b = options == null ? void 0 : options.core) == null ? void 0 : _b.nothrow)) {
2523
+ throw new Error(getNoValidLoaderMessage(data));
2524
+ }
2525
+ return loader;
2526
+ }
2527
+ function selectLoaderInternal(data, loaders, options, context, operation = "parse") {
2528
+ var _a, _b, _c, _d, _e;
2529
+ const url = getResourceUrl(data);
2530
+ const type = getResourceMIMEType(data);
2531
+ const testUrl = stripQueryString(url) || (context == null ? void 0 : context.url);
2532
+ let loader = null;
2533
+ let reason = "";
2534
+ const sourceType = (options == null ? void 0 : options.core) && "type" in options.core ? options.core.type : void 0;
2535
+ if (sourceType && sourceType !== "auto") {
2536
+ loader = findSourceLoaderByType(loaders, sourceType);
2537
+ reason = loader ? `match forced by supplied source type ${sourceType}` : "";
2538
+ }
2539
+ if ((_a = options == null ? void 0 : options.core) == null ? void 0 : _a.mimeType) {
2540
+ loader = findLoaderByMIMEType(loaders, (_b = options == null ? void 0 : options.core) == null ? void 0 : _b.mimeType);
2541
+ reason = `match forced by supplied MIME type ${(_c = options == null ? void 0 : options.core) == null ? void 0 : _c.mimeType}`;
2542
+ }
2543
+ if (!loader && operation === "source") {
2544
+ loader = findSourceLoaderByTestURL(loaders, testUrl);
2545
+ reason = loader ? `matched source url ${testUrl}` : "";
2546
+ }
2547
+ const fallbackLoaders = operation === "source" && testUrl ? loaders.filter((candidate) => !candidate.testURL) : loaders;
2548
+ loader = loader || findLoaderByUrl(fallbackLoaders, testUrl);
2549
+ reason = reason || (loader ? `matched url ${testUrl}` : "");
2550
+ if (!loader && operation === "parse") {
2551
+ loader = findSourceLoaderByTestURL(loaders, testUrl);
2552
+ reason = loader ? `matched source url ${testUrl}` : "";
2553
+ }
2554
+ loader = loader || findLoaderByMIMEType(fallbackLoaders, type);
2555
+ reason = reason || (loader ? `matched MIME type ${type}` : "");
2556
+ loader = loader || findLoaderByInitialBytes(fallbackLoaders, data);
2557
+ reason = reason || (loader ? `matched initial data ${getFirstCharacters(data)}` : "");
2558
+ if (!loader && isBlob(data)) {
2559
+ loader = findSourceLoaderByTestData(loaders, data);
2560
+ reason = reason || (loader ? "matched source testData" : "");
2561
+ }
2562
+ if ((_d = options == null ? void 0 : options.core) == null ? void 0 : _d.fallbackMimeType) {
2563
+ loader = loader || findLoaderByMIMEType(fallbackLoaders, (_e = options == null ? void 0 : options.core) == null ? void 0 : _e.fallbackMimeType);
2564
+ reason = reason || (loader ? `matched fallback MIME type ${type}` : "");
2565
+ }
2566
+ if (reason) {
2567
+ log.log(1, `selectLoader selected ${loader == null ? void 0 : loader.name}: ${reason}.`);
2568
+ }
2569
+ return loader;
2570
+ }
2571
+ function validHTTPResponse(data) {
2572
+ if (data instanceof Response) {
2573
+ if (data.status === 204) {
2574
+ return false;
2575
+ }
2576
+ }
2577
+ return true;
2578
+ }
2579
+ function getNoValidLoaderMessage(data) {
2580
+ const url = getResourceUrl(data);
2581
+ const type = getResourceMIMEType(data);
2582
+ let message = "No valid loader found (";
2583
+ message += url ? `${path_exports.filename(url)}, ` : "no url provided, ";
2584
+ message += `MIME type: ${type ? `"${type}"` : "not provided"}, `;
2585
+ const firstCharacters = data ? getFirstCharacters(data) : "";
2586
+ message += firstCharacters ? ` first bytes: "${firstCharacters}"` : "first bytes: not available";
2587
+ message += ")";
2588
+ return message;
2589
+ }
2590
+ function normalizeLoaders(loaders) {
2591
+ for (const loader of loaders) {
2592
+ normalizeLoader(loader);
2593
+ }
2594
+ }
2595
+ function findLoaderByUrl(loaders, url) {
2596
+ const match = url && EXT_PATTERN.exec(url);
2597
+ const extension = match && match[1];
2598
+ return extension ? findLoaderByExtension(loaders, extension) : null;
2599
+ }
2600
+ function findLoaderByExtension(loaders, extension) {
2601
+ extension = extension.toLowerCase();
2602
+ for (const loader of loaders) {
2603
+ for (const loaderExtension of loader.extensions) {
2604
+ if (loaderExtension.toLowerCase() === extension) {
2605
+ return loader;
2606
+ }
2607
+ }
2608
+ }
2609
+ return null;
2610
+ }
2611
+ function findSourceLoaderByType(loaders, type) {
2612
+ for (const loader of loaders) {
2613
+ if ((loader.type ?? loader.id) === type) {
2614
+ return loader;
2615
+ }
2616
+ }
2617
+ return null;
2618
+ }
2619
+ function findSourceLoaderByTestURL(loaders, url) {
2620
+ var _a;
2621
+ if (!url) {
2622
+ return null;
2623
+ }
2624
+ for (const loader of loaders) {
2625
+ if ((_a = loader.testURL) == null ? void 0 : _a.call(loader, url)) {
2626
+ return loader;
2627
+ }
2628
+ }
2629
+ return null;
2630
+ }
2631
+ function findSourceLoaderByTestData(loaders, data) {
2632
+ var _a;
2633
+ for (const loader of loaders) {
2634
+ if (loader.testData) {
2635
+ if ((_a = loader.testData) == null ? void 0 : _a.call(loader, data)) {
2636
+ return loader;
2637
+ }
2638
+ }
2639
+ }
2640
+ return null;
2641
+ }
2642
+ function findLoaderByMIMEType(loaders, mimeType) {
2643
+ var _a;
2644
+ for (const loader of loaders) {
2645
+ if ((_a = loader.mimeTypes) == null ? void 0 : _a.some((mimeType1) => compareMIMETypes(mimeType, mimeType1))) {
2646
+ return loader;
2647
+ }
2648
+ if (compareMIMETypes(mimeType, `application/x.${loader.id}`)) {
2649
+ return loader;
2650
+ }
2651
+ }
2652
+ return null;
2653
+ }
2654
+ function findLoaderByInitialBytes(loaders, data) {
2655
+ if (!data) {
2656
+ return null;
2657
+ }
2658
+ for (const loader of loaders) {
2659
+ if (typeof data === "string") {
2660
+ if (testDataAgainstText(data, loader)) {
2661
+ return loader;
2662
+ }
2663
+ } else if (ArrayBuffer.isView(data)) {
2664
+ if (testDataAgainstBinary(data.buffer, data.byteOffset, loader)) {
2665
+ return loader;
2666
+ }
2667
+ } else if (data instanceof ArrayBuffer) {
2668
+ const byteOffset = 0;
2669
+ if (testDataAgainstBinary(data, byteOffset, loader)) {
2670
+ return loader;
2671
+ }
2672
+ }
2673
+ }
2674
+ return null;
2675
+ }
2676
+ function testDataAgainstText(data, loader) {
2677
+ if (loader.testText) {
2678
+ return loader.testText(data);
2679
+ }
2680
+ const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
2681
+ return tests.some((test) => data.startsWith(test));
2682
+ }
2683
+ function testDataAgainstBinary(data, byteOffset, loader) {
2684
+ const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
2685
+ return tests.some((test) => testBinary(data, byteOffset, loader, test));
2686
+ }
2687
+ function testBinary(data, byteOffset, loader, test) {
2688
+ if (isArrayBufferLike(test)) {
2689
+ return compareArrayBuffers(test, data, test.byteLength);
2690
+ }
2691
+ switch (typeof test) {
2692
+ case "function":
2693
+ return test(ensureArrayBuffer(data));
2694
+ case "string":
2695
+ const magic = getMagicString(data, byteOffset, test.length);
2696
+ return test === magic;
2697
+ default:
2698
+ return false;
2699
+ }
2700
+ }
2701
+ function getFirstCharacters(data, length = 5) {
2702
+ if (typeof data === "string") {
2703
+ return data.slice(0, length);
2704
+ } else if (ArrayBuffer.isView(data)) {
2705
+ return getMagicString(data.buffer, data.byteOffset, length);
2706
+ } else if (data instanceof ArrayBuffer) {
2707
+ const byteOffset = 0;
2708
+ return getMagicString(data, byteOffset, length);
2709
+ }
2710
+ return "";
2711
+ }
2712
+ function getMagicString(arrayBuffer, byteOffset, length) {
2713
+ if (arrayBuffer.byteLength < byteOffset + length) {
2714
+ return "";
2715
+ }
2716
+ const dataView = new DataView(arrayBuffer);
2717
+ let magic = "";
2718
+ for (let i = 0; i < length; i++) {
2719
+ magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
2720
+ }
2721
+ return magic;
2722
+ }
2723
+
2724
+ // dist/iterators/make-iterator/make-string-iterator.js
2725
+ var DEFAULT_CHUNK_SIZE = 256 * 1024;
2726
+ function* makeStringIterator(string, options) {
2727
+ const chunkSize = (options == null ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE;
2728
+ let offset = 0;
2729
+ const textEncoder = new TextEncoder();
2730
+ while (offset < string.length) {
2731
+ const chunkLength = Math.min(string.length - offset, chunkSize);
2732
+ const chunk = string.slice(offset, offset + chunkLength);
2733
+ offset += chunkLength;
2734
+ yield ensureArrayBuffer(textEncoder.encode(chunk));
2735
+ }
2736
+ }
2737
+
2738
+ // dist/iterators/make-iterator/make-array-buffer-iterator.js
2739
+ var DEFAULT_CHUNK_SIZE2 = 256 * 1024;
2740
+ function* makeArrayBufferIterator(arrayBuffer, options = {}) {
2741
+ const { chunkSize = DEFAULT_CHUNK_SIZE2 } = options;
2742
+ let byteOffset = 0;
2743
+ while (byteOffset < arrayBuffer.byteLength) {
2744
+ const chunkByteLength = Math.min(arrayBuffer.byteLength - byteOffset, chunkSize);
2745
+ const chunk = new ArrayBuffer(chunkByteLength);
2746
+ const sourceArray = new Uint8Array(arrayBuffer, byteOffset, chunkByteLength);
2747
+ const chunkArray = new Uint8Array(chunk);
2748
+ chunkArray.set(sourceArray);
2749
+ byteOffset += chunkByteLength;
2750
+ yield chunk;
2751
+ }
2752
+ }
2753
+
2754
+ // dist/iterators/make-iterator/make-blob-iterator.js
2755
+ var DEFAULT_CHUNK_SIZE3 = 1024 * 1024;
2756
+ async function* makeBlobIterator(blob, options) {
2757
+ const chunkSize = (options == null ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE3;
2758
+ let offset = 0;
2759
+ while (offset < blob.size) {
2760
+ const end = offset + chunkSize;
2761
+ const chunk = await blob.slice(offset, end).arrayBuffer();
2762
+ offset = end;
2763
+ yield chunk;
2764
+ }
2765
+ }
2766
+
2767
+ // dist/iterators/make-iterator/make-stream-iterator.js
2768
+ function makeStreamIterator(stream, options) {
2769
+ return isBrowser ? makeBrowserStreamIterator(stream, options) : makeNodeStreamIterator(stream, options);
2770
+ }
2771
+ async function* makeBrowserStreamIterator(stream, options) {
2772
+ const reader = stream.getReader();
2773
+ let nextBatchPromise;
2774
+ let streamFinished = false;
2775
+ let streamReadFailed = false;
2776
+ let iteratorFailed = false;
2777
+ try {
2778
+ while (true) {
2779
+ const currentBatchPromise = nextBatchPromise || reader.read();
2780
+ nextBatchPromise = void 0;
2781
+ let batch;
2782
+ try {
2783
+ batch = await currentBatchPromise;
2784
+ } catch (error) {
2785
+ streamReadFailed = true;
2786
+ throw error;
2787
+ }
2788
+ const { done, value } = batch;
2789
+ if (done) {
2790
+ streamFinished = true;
2791
+ return;
2792
+ }
2793
+ if (options == null ? void 0 : options._streamReadAhead) {
2794
+ nextBatchPromise = reader.read();
2795
+ void nextBatchPromise.catch(() => {
2796
+ });
2797
+ }
2798
+ yield toArrayBuffer2(value);
2799
+ }
2800
+ } catch (error) {
2801
+ iteratorFailed = true;
2802
+ throw error;
2803
+ } finally {
2804
+ let cleanupFailed = false;
2805
+ let cleanupError;
2806
+ if (!streamFinished && !streamReadFailed) {
2807
+ try {
2808
+ await reader.cancel();
2809
+ } catch (error) {
2810
+ cleanupFailed = true;
2811
+ cleanupError = error;
2812
+ }
2813
+ }
2814
+ try {
2815
+ reader.releaseLock();
2816
+ } catch (error) {
2817
+ if (!cleanupFailed) {
2818
+ cleanupFailed = true;
2819
+ cleanupError = error;
2820
+ }
2821
+ }
2822
+ if (!iteratorFailed && cleanupFailed) {
2823
+ throw cleanupError;
2824
+ }
2825
+ }
2826
+ }
2827
+ async function* makeNodeStreamIterator(stream, options) {
2828
+ for await (const chunk of stream) {
2829
+ yield toArrayBuffer2(chunk);
2830
+ }
2831
+ }
2832
+
2833
+ // dist/iterators/make-iterator/make-iterator.js
2834
+ function makeIterator(data, options) {
2835
+ if (typeof data === "string") {
2836
+ return makeStringIterator(data, options);
2837
+ }
2838
+ if (data instanceof ArrayBuffer) {
2839
+ return makeArrayBufferIterator(data, options);
2840
+ }
2841
+ if (isBlob(data)) {
2842
+ return makeBlobIterator(data, options);
2843
+ }
2844
+ if (isReadableStream(data)) {
2845
+ return makeStreamIterator(data, options);
2846
+ }
2847
+ if (isResponse(data)) {
2848
+ const responseBody = data.body;
2849
+ if (!responseBody) {
2850
+ throw new Error("Readable stream not available on Response");
2851
+ }
2852
+ return makeStreamIterator(responseBody, options);
2853
+ }
2854
+ throw new Error("makeIterator");
2855
+ }
2856
+
2857
+ // dist/lib/loader-utils/get-data.js
2858
+ var ERR_DATA = "Cannot convert supplied data type";
2859
+ function getArrayBufferOrStringFromDataSync(data, loader, options) {
2860
+ if (loader.text && typeof data === "string") {
2861
+ return data;
2862
+ }
2863
+ if (isBuffer(data)) {
2864
+ data = data.buffer;
2865
+ }
2866
+ if (isArrayBufferLike(data)) {
2867
+ const bufferSource = toArrayBufferView(data);
2868
+ if (loader.text && !loader.binary) {
2869
+ const textDecoder = new TextDecoder("utf8");
2870
+ return textDecoder.decode(bufferSource);
2871
+ }
2872
+ return toArrayBuffer2(bufferSource);
2873
+ }
2874
+ throw new Error(ERR_DATA);
2875
+ }
2876
+ async function getArrayBufferOrStringFromData(data, loader, options) {
2877
+ if (typeof data === "string" || isArrayBufferLike(data)) {
2878
+ return getArrayBufferOrStringFromDataSync(data, loader, options);
2879
+ }
2880
+ if (isBlob(data)) {
2881
+ data = await makeResponse(data);
2882
+ }
2883
+ if (isResponse(data)) {
2884
+ await checkResponse(data);
2885
+ return loader.binary ? await data.arrayBuffer() : await data.text();
2886
+ }
2887
+ if (isReadableStream(data)) {
2888
+ data = makeIterator(data, options);
2889
+ }
2890
+ if (isIterable(data) || isAsyncIterable(data)) {
2891
+ return concatenateArrayBuffersAsync(data);
2892
+ }
2893
+ throw new Error(ERR_DATA);
2894
+ }
2895
+ async function getArrayBufferFromData(data, options) {
2896
+ if (typeof data === "string") {
2897
+ return new TextEncoder().encode(data).buffer;
2898
+ }
2899
+ if (isArrayBufferLike(data)) {
2900
+ return toArrayBuffer2(toArrayBufferView(data));
2901
+ }
2902
+ if (isBlob(data)) {
2903
+ data = await makeResponse(data);
2904
+ }
2905
+ if (isResponse(data)) {
2906
+ await checkResponse(data);
2907
+ return await data.arrayBuffer();
2908
+ }
2909
+ if (isReadableStream(data)) {
2910
+ data = makeIterator(data, options);
2911
+ }
2912
+ if (isIterable(data) || isAsyncIterable(data)) {
2913
+ return concatenateArrayBuffersAsync(data);
2914
+ }
2915
+ throw new Error(ERR_DATA);
2916
+ }
2917
+ async function getAsyncIterableFromData(data, options) {
2918
+ if (isPromise(data)) {
2919
+ data = await data;
2920
+ }
2921
+ if (isIterator(data)) {
2922
+ return data;
2923
+ }
2924
+ if (isResponse(data)) {
2925
+ await checkResponse(data);
2926
+ const body = await data.body;
2927
+ if (!body) {
2928
+ throw new Error(ERR_DATA);
2929
+ }
2930
+ return makeIterator(body, options);
2931
+ }
2932
+ if (isBlob(data) || isReadableStream(data)) {
2933
+ return makeIterator(data, options);
2934
+ }
2935
+ if (isAsyncIterable(data)) {
2936
+ return data;
2937
+ }
2938
+ if (isIterable(data)) {
2939
+ return data;
2940
+ }
2941
+ return getIterableFromData(data);
2942
+ }
2943
+ function getIterableFromData(data) {
2944
+ if (ArrayBuffer.isView(data)) {
2945
+ return (function* oneChunk() {
2946
+ yield toArrayBuffer2(data);
2947
+ })();
2948
+ }
2949
+ if (isArrayBufferLike(data)) {
2950
+ return (function* oneChunk() {
2951
+ yield toArrayBuffer2(data);
2952
+ })();
2953
+ }
2954
+ if (isIterator(data)) {
2955
+ return data;
2956
+ }
2957
+ if (isIterable(data)) {
2958
+ return data[Symbol.iterator]();
2959
+ }
2960
+ throw new Error(ERR_DATA);
2961
+ }
2962
+
2963
+ // dist/lib/loader-utils/get-fetch-function.js
2964
+ function getFetchFunction(options, context) {
2965
+ var _a, _b, _c;
2966
+ const globalOptions = getGlobalLoaderOptions();
2967
+ const loaderOptions = options || globalOptions;
2968
+ const fetchOption = (_a = loaderOptions.core) == null ? void 0 : _a.fetch;
2969
+ let fetchFunction;
2970
+ if (typeof fetchOption === "function") {
2971
+ fetchFunction = fetchOption;
2972
+ } else if (isObject(fetchOption)) {
2973
+ fetchFunction = (context == null ? void 0 : context.fetch) || fetchFile;
2974
+ } else if (context == null ? void 0 : context.fetch) {
2975
+ fetchFunction = context.fetch;
2976
+ } else {
2977
+ fetchFunction = fetchFile;
2978
+ }
2979
+ const signal = loaderOptions.signal || (context == null ? void 0 : context.signal);
2980
+ const requestOptions = isObject(fetchOption) ? fetchOption : void 0;
2981
+ return createAuthenticatedFetch({
2982
+ fetch: fetchFunction,
2983
+ credentials: ((_b = loaderOptions.core) == null ? void 0 : _b.credentials) || [],
2984
+ authentications: (_c = loaderOptions.core) == null ? void 0 : _c.authentications,
2985
+ fetchOptions: signal ? { ...requestOptions, signal } : requestOptions
2986
+ });
2987
+ }
2988
+
2989
+ // dist/lib/api/load-loader.js
2990
+ var loaderImplementationPromises = /* @__PURE__ */ new Map();
2991
+ var loaderImplementations = /* @__PURE__ */ new Map();
2992
+ async function getLoaderImplementation(loader, options, url) {
2993
+ var _a;
2994
+ if (isLoaderWithParser(loader) || !loader.preload && loader.createDataSourceSync) {
2995
+ return loader;
2996
+ }
2997
+ const implementationCacheKey = getLoaderImplementationCacheKey(loader, options);
2998
+ const loaderImplementation = (_a = loaderImplementations.get(loader)) == null ? void 0 : _a.get(implementationCacheKey);
2999
+ if (loaderImplementation) {
3000
+ return loaderImplementation;
3001
+ }
3002
+ let loaderImplementationPromisesForLoader = loaderImplementationPromises.get(loader);
3003
+ if (!loaderImplementationPromisesForLoader) {
3004
+ loaderImplementationPromisesForLoader = /* @__PURE__ */ new Map();
3005
+ loaderImplementationPromises.set(loader, loaderImplementationPromisesForLoader);
3006
+ }
3007
+ let loaderImplementationPromise = loaderImplementationPromisesForLoader.get(implementationCacheKey);
3008
+ if (!loaderImplementationPromise) {
3009
+ loaderImplementationPromise = resolveLoaderImplementation(loader, options, url).then((implementation) => {
3010
+ let loaderImplementationsForLoader = loaderImplementations.get(loader);
3011
+ if (!loaderImplementationsForLoader) {
3012
+ loaderImplementationsForLoader = /* @__PURE__ */ new Map();
3013
+ loaderImplementations.set(loader, loaderImplementationsForLoader);
3014
+ }
3015
+ loaderImplementationsForLoader.set(implementationCacheKey, implementation);
3016
+ return implementation;
3017
+ }).catch((error) => {
3018
+ loaderImplementationPromisesForLoader.delete(implementationCacheKey);
3019
+ if (loaderImplementationPromisesForLoader.size === 0) {
3020
+ loaderImplementationPromises.delete(loader);
3021
+ }
3022
+ throw error;
3023
+ });
3024
+ loaderImplementationPromisesForLoader.set(implementationCacheKey, loaderImplementationPromise);
3025
+ }
3026
+ return await loaderImplementationPromise;
3027
+ }
3028
+ function getLoaderImplementationSync(loader, options) {
3029
+ var _a;
3030
+ if (loader.subloaders && !preparedLoaders.has(loader)) {
3031
+ const prepared = preparedDefaults.get(loader);
3032
+ if (prepared)
3033
+ return prepared;
3034
+ if (!isLoaderWithParser(loader))
3035
+ return null;
3036
+ }
3037
+ if (isLoaderWithParser(loader) || !loader.preload && loader.createDataSourceSync) {
3038
+ return loader;
3039
+ }
3040
+ const implementationCacheKey = getLoaderImplementationCacheKey(loader, options);
3041
+ return ((_a = loaderImplementations.get(loader)) == null ? void 0 : _a.get(implementationCacheKey)) || null;
3042
+ }
3043
+ function isLoaderWithParser(loader) {
3044
+ const candidate = loader;
3045
+ return Boolean(candidate.parse || candidate.parseBlob || candidate.parseUrl || candidate.parseSync || candidate.parseInBatches || candidate.parseText || candidate.parseTextSync || candidate.parseFile || candidate.parseFileInBatches);
3046
+ }
3047
+ async function resolveLoaderImplementation(loader, options, url) {
3048
+ if (loader.preload) {
3049
+ const preloadedLoader = await loader.preload(url || "", options);
3050
+ if (preloadedLoader && (isLoaderWithParser(preloadedLoader) || preloadedLoader.createDataSourceSync)) {
3051
+ return preloadedLoader;
3052
+ }
3053
+ throw new Error(`${loader.id} loader preload() did not return a parser-bearing loader or a source factory`);
3054
+ }
3055
+ const implementationSpecifier = getLoaderImplementationSpecifier(loader, options);
3056
+ return await importLoaderImplementation(implementationSpecifier, loader.id);
3057
+ }
3058
+ function getLoaderImplementationSpecifier(loader, options) {
3059
+ var _a;
3060
+ const workerType = (_a = options == null ? void 0 : options.core) == null ? void 0 : _a._workerType;
3061
+ if (workerType === "test") {
3062
+ const sourcePath = `modules/${loader.module}/src/${loader.id}-loader.ts`;
3063
+ if (typeof window !== "undefined") {
3064
+ return `/${sourcePath}`;
3065
+ }
3066
+ if (typeof process !== "undefined" && process.cwd) {
3067
+ return new URL(sourcePath, `file://${process.cwd()}/`).toString();
3068
+ }
3069
+ return sourcePath;
3070
+ }
3071
+ throw new Error(`${loader.id} loader does not provide a parser implementation. Import a parser-bearing loader directly, or use preload() before parse/load.`);
3072
+ }
3073
+ function getLoaderImplementationCacheKey(loader, options) {
3074
+ var _a;
3075
+ const loaderOptions = options == null ? void 0 : options[loader.id];
3076
+ const defaultLoaderOptions = (_a = loader.options) == null ? void 0 : _a[loader.id];
3077
+ return String((loaderOptions == null ? void 0 : loaderOptions.backend) || (defaultLoaderOptions == null ? void 0 : defaultLoaderOptions.backend) || "");
3078
+ }
3079
+ async function importLoaderImplementation(implementationSpecifier, loaderId) {
3080
+ const moduleExports = await import(
3081
+ /* webpackIgnore: true */
3082
+ /* @vite-ignore */
3083
+ implementationSpecifier
3084
+ );
3085
+ for (const exportValue of Object.values(moduleExports)) {
3086
+ if (exportValue && typeof exportValue === "object" && exportValue.id === loaderId && isLoaderWithParser(exportValue)) {
3087
+ return exportValue;
3088
+ }
3089
+ }
3090
+ throw new Error(`Could not find parser implementation for ${loaderId} in ${implementationSpecifier}`);
3091
+ }
3092
+ var preparedLoaders = /* @__PURE__ */ new WeakSet();
3093
+ var preparedDefaults = /* @__PURE__ */ new WeakMap();
3094
+ var subloaderPreparations = /* @__PURE__ */ new WeakMap();
3095
+ async function preloadLoaderDependencies(loader, options, url) {
3096
+ if (preparedLoaders.has(loader))
3097
+ return await getLoaderImplementation(loader, options, url);
3098
+ validateSubloaderGraph(loader, options);
3099
+ return await prepareLoaderDependencies(loader, options, url);
3100
+ }
3101
+ async function prepareLoaderDependencies(loader, options, url) {
3102
+ if (!options) {
3103
+ const cached = subloaderPreparations.get(loader);
3104
+ if (cached)
3105
+ return await cached;
3106
+ }
3107
+ const preparation = bindSubloaders(loader, options, url);
3108
+ if (!options) {
3109
+ subloaderPreparations.set(loader, preparation);
3110
+ void preparation.catch(() => subloaderPreparations.delete(loader));
3111
+ }
3112
+ const prepared = await preparation;
3113
+ if (!options)
3114
+ preparedDefaults.set(loader, prepared);
3115
+ return prepared;
3116
+ }
3117
+ function getSubloaders(loader, options) {
3118
+ var _a;
3119
+ const overrides = ((_a = options == null ? void 0 : options.core) == null ? void 0 : _a.subloaders) || {};
3120
+ return Object.fromEntries(Object.entries(loader.subloaders || {}).map(([name, dependency]) => [
3121
+ name,
3122
+ Object.hasOwn(overrides, name) ? overrides[name] : dependency
3123
+ ]));
3124
+ }
3125
+ function validateSubloaderGraph(loader, options) {
3126
+ visitLoader(loader, []);
3127
+ function visitLoader(currentLoader, ancestors) {
3128
+ if (ancestors.includes(currentLoader)) {
3129
+ throw new Error(`Subloader cycle: ${[...ancestors, currentLoader].map((value) => value.id).join(" -> ")}`);
3130
+ }
3131
+ for (const dependency of Object.values(getSubloaders(currentLoader, options))) {
3132
+ visitLoader(dependency, [...ancestors, currentLoader]);
3133
+ }
3134
+ }
3135
+ }
3136
+ async function bindSubloaders(loader, options, url) {
3137
+ const [implementation, entries] = await Promise.all([
3138
+ getLoaderImplementation(loader, options, url),
3139
+ Promise.all(Object.entries(getSubloaders(loader, options)).map(async ([name, dependency]) => [name, await prepareLoaderDependencies(dependency, options, url)]))
3140
+ ]);
3141
+ const subloaders = Object.fromEntries(entries);
3142
+ const defaultOptions = mergeOptions(implementation.options, options || {});
3143
+ defaultOptions.core = { ...defaultOptions.core, worker: false };
3144
+ const prepared = { ...implementation, options: defaultOptions, subloaders };
3145
+ delete prepared.preload;
3146
+ prepared.worker = false;
3147
+ for (const method of [
3148
+ "parseBlob",
3149
+ "createDataSourceSync",
3150
+ "parse",
3151
+ "parseSync",
3152
+ "parseText",
3153
+ "parseTextSync",
3154
+ "parseInBatches",
3155
+ "parseFile",
3156
+ "parseFileInBatches",
3157
+ "parseUrl"
3158
+ ]) {
3159
+ const parser = implementation[method];
3160
+ if (typeof parser === "function") {
3161
+ prepared[method] = (data, parseOptions, context) => {
3162
+ var _a, _b;
3163
+ const forwardedOptions = mergeOptions(options, parseOptions || {});
3164
+ return parser.call(implementation, data, {
3165
+ ...forwardedOptions,
3166
+ core: {
3167
+ ...forwardedOptions.core,
3168
+ subloaders: ((_a = options == null ? void 0 : options.core) == null ? void 0 : _a.subloaders) || ((_b = parseOptions == null ? void 0 : parseOptions.core) == null ? void 0 : _b.subloaders),
3169
+ worker: false
3170
+ },
3171
+ [loader.id]: { ...forwardedOptions[loader.id], subloaders }
3172
+ }, context);
3173
+ };
3174
+ }
3175
+ }
3176
+ preparedLoaders.add(prepared);
3177
+ return prepared;
3178
+ }
3179
+
3180
+ // dist/lib/api/parse-file.js
3181
+ async function parseFile(file, loaders, options, context) {
3182
+ var _a, _b, _c;
3183
+ if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) {
3184
+ context = void 0;
3185
+ options = loaders;
3186
+ loaders = void 0;
3187
+ }
3188
+ options = options || {};
3189
+ (_a = options.signal || (context == null ? void 0 : context.signal)) == null ? void 0 : _a.throwIfAborted();
3190
+ const url = file.url || "";
3191
+ const typedLoaders = loaders;
3192
+ const candidateLoaders = getLoadersFromContext(typedLoaders, context);
3193
+ const loader = await selectLoader(url, candidateLoaders, options);
3194
+ if (!loader) {
3195
+ return null;
3196
+ }
3197
+ const normalizedOptions = normalizeOptions(options, loader, candidateLoaders, url);
3198
+ const authenticationLoader = !loader.getAuthentications && ((_c = (_b = normalizedOptions.core) == null ? void 0 : _b.credentials) == null ? void 0 : _c.length) ? await getLoaderImplementation(loader, normalizedOptions, url || (context == null ? void 0 : context.url)) : loader;
3199
+ const strictOptions = await resolveLoaderAuthenticationOptions(authenticationLoader, url, normalizedOptions);
3200
+ context = getLoaderContext(
3201
+ // @ts-expect-error candidateLoaders may be a single forced loader
3202
+ { url, _parse: parse, loaders: candidateLoaders },
3203
+ strictOptions,
3204
+ context || null
3205
+ );
3206
+ return parseFileWithLoader(loader, file, strictOptions, context);
3207
+ }
3208
+ async function parseFileWithLoader(loader, file, options, context) {
3209
+ var _a, _b;
3210
+ (_a = options.signal || context.signal) == null ? void 0 : _a.throwIfAborted();
3211
+ validateWorkerVersion(loader);
3212
+ options = mergeOptions(loader.options, options);
3213
+ const loaderWithParser = await getLoaderImplementation(loader, options, context.url);
3214
+ if (loaderWithParser.parseFile) {
3215
+ const output = (_b = loaderWithParser.prepareParseOutput) == null ? void 0 : _b.call(loaderWithParser, options);
3216
+ const result = await loaderWithParser.parseFile(file, (output == null ? void 0 : output.options) ?? options, context);
3217
+ return output ? output.convert(result) : result;
3218
+ }
3219
+ const parseFunction = loaderWithParser.parse;
3220
+ if (parseFunction) {
3221
+ const length = file.bigsize > 0n ? Number(file.bigsize) : file.size;
3222
+ if (!length) {
3223
+ throw new Error(`${loader.id} loader - cannot fall back to parse without a file size`);
3224
+ }
3225
+ const data = await file.read(0n, length);
3226
+ return await parse(data, loaderWithParser, options, context);
3227
+ }
3228
+ if (loaderWithParser.createDataSourceSync) {
3229
+ throw new Error(`${loader.id} has no file parser. Use createDataSource() to open a source.`);
3230
+ }
3231
+ throw new Error(`${loader.id} loader - no file parser found`);
3232
+ }
3233
+
3234
+ // dist/lib/api/parse-sync.js
3235
+ function parseSync(data, loaders, options, context) {
3236
+ if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
3237
+ context = void 0;
3238
+ options = loaders;
3239
+ loaders = void 0;
3240
+ }
3241
+ options = options || {};
3242
+ const typedLoaders = loaders;
3243
+ const candidateLoaders = getLoadersFromContext(typedLoaders, context);
3244
+ const loader = selectLoaderSync(data, candidateLoaders, options);
3245
+ if (!loader) {
3246
+ return null;
3247
+ }
3248
+ const strictOptions = normalizeOptions(options, loader, candidateLoaders);
3249
+ const url = getResourceUrl(data);
3250
+ const parse2 = () => {
3251
+ throw new Error("parseSync called parse (which is async");
3252
+ };
3253
+ context = getLoaderContext({ url, _parseSync: parse2, _parse: parse2, loaders }, strictOptions, context || null);
3254
+ const loaderWithParser = getLoaderImplementationSync(loader);
3255
+ return parseWithLoaderSync(loaderWithParser || loader, data, strictOptions, context);
3256
+ }
3257
+ function parseWithLoaderSync(loader, data, options, context) {
3258
+ data = getArrayBufferOrStringFromDataSync(data, loader, options);
3259
+ if (loader.parseTextSync && typeof data === "string") {
3260
+ return loader.parseTextSync(data, options);
3261
+ }
3262
+ if (loader.parseSync && data instanceof ArrayBuffer) {
3263
+ return loader.parseSync(data, options, context);
3264
+ }
3265
+ if (loader.preload) {
3266
+ throw new Error(`${loader.name} loader: 'parseSync' requires a parser-bearing loader. Import the loader implementation directly, or call preload(loader) before parseSync(). ${context.url || ""}`);
3267
+ }
3268
+ if (loader.createDataSourceSync) {
3269
+ throw new Error(`${loader.id} has no synchronous parser. Use createDataSource() to open a source.`);
3270
+ }
3271
+ throw new Error(`${loader.name} loader: 'parseSync' not supported by this loader, use 'parse' instead. ${context.url || ""}`);
3272
+ }
3273
+
3274
+ // dist/lib/api/parse-in-batches.js
3275
+ async function parseInBatches(data, loaders, options, context) {
3276
+ var _a, _b, _c, _d;
3277
+ const loaderArray = Array.isArray(loaders) ? loaders : void 0;
3278
+ if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
3279
+ context = void 0;
3280
+ options = loaders;
3281
+ loaders = void 0;
3282
+ }
3283
+ (_a = (options == null ? void 0 : options.signal) || (context == null ? void 0 : context.signal)) == null ? void 0 : _a.throwIfAborted();
3284
+ data = await data;
3285
+ options = options || {};
3286
+ (_b = options.signal || (context == null ? void 0 : context.signal)) == null ? void 0 : _b.throwIfAborted();
3287
+ const url = getResourceUrl(data);
3288
+ const loader = await selectLoader(data, loaders, options);
3289
+ if (!loader) {
3290
+ return [];
3291
+ }
3292
+ const normalizedOptions = normalizeOptions(options, loader, loaderArray, url);
3293
+ const authenticationLoader = !loader.getAuthentications && ((_d = (_c = normalizedOptions.core) == null ? void 0 : _c.credentials) == null ? void 0 : _d.length) ? await getLoaderImplementation(loader, normalizedOptions, url || (context == null ? void 0 : context.url)) : loader;
3294
+ const strictOptions = await resolveLoaderAuthenticationOptions(authenticationLoader, url || "", normalizedOptions);
3295
+ const nativeArrow = usesNativeArrowBatches(loader, strictOptions);
3296
+ context = getLoaderContext({ url, _parseInBatches: parseInBatches, _parse: parse, loaders: loaderArray }, strictOptions, context || null);
3297
+ const loaderWithParser = await getLoaderImplementation(loader, strictOptions, context.url);
3298
+ const batches = await parseWithLoaderInBatches(loader, loaderWithParser, data, strictOptions, context);
3299
+ return nativeArrow ? normalizeNativeArrowBatches(batches) : batches;
3300
+ }
3301
+ async function parseWithLoaderInBatches(originalLoader, loader, data, options, context) {
3302
+ var _a, _b;
3303
+ const { batchMaxRowsPerSecond = 0, batchSize } = options.core ?? {};
3304
+ validateBatchDeliveryRate(batchMaxRowsPerSecond);
3305
+ if (batchSize !== void 0 && batchSize !== "auto" && (!Number.isSafeInteger(batchSize) || batchSize < 1)) {
3306
+ throw new RangeError('core.batchSize must be a positive integer or "auto"');
3307
+ }
3308
+ const parserOptions = batchMaxRowsPerSecond ? { ...options, core: { ...options.core, batchMaxRowsPerSecond: 0 } } : options;
3309
+ const output = loader.parseInBatches ? (_a = loader.prepareParseBatchOutput) == null ? void 0 : _a.call(loader, parserOptions) : null;
3310
+ const decoded = await parseToOutputIterator(loader, data, (output == null ? void 0 : output.options) ?? parserOptions, context);
3311
+ const batches = output ? convertOutputBatches(decoded, output.convert) : decoded;
3312
+ const outputIterator = batchMaxRowsPerSecond ? paceBatchIterator(batches, {
3313
+ batchMaxRowsPerSecond,
3314
+ getRowCount: (batch) => getBatchRowCount(batch, loader.module),
3315
+ signal: options.signal ?? context.signal
3316
+ }) : batches;
3317
+ if (!((_b = options == null ? void 0 : options.core) == null ? void 0 : _b.metadata)) {
3318
+ return outputIterator;
3319
+ }
3320
+ const metadataBatch = {
3321
+ shape: "metadata",
3322
+ batchType: "metadata",
3323
+ metadata: {
3324
+ _loader: originalLoader,
3325
+ _context: context
3326
+ },
3327
+ // Populate with some default fields to avoid crashing
3328
+ data: [],
3329
+ bytesUsed: 0
3330
+ };
3331
+ async function* makeMetadataBatchIterator(iterator) {
3332
+ yield metadataBatch;
3333
+ yield* iterator;
3334
+ }
3335
+ return makeMetadataBatchIterator(outputIterator);
3336
+ }
3337
+ async function* convertOutputBatches(batches, convert) {
3338
+ for await (const batch of batches) {
3339
+ yield convert(batch);
3340
+ }
3341
+ }
3342
+ async function parseToOutputIterator(loader, data, options, context) {
3343
+ var _a;
3344
+ const inputIterator = await getAsyncIterableFromData(data, options);
3345
+ const transformedIterator = await applyInputTransforms(inputIterator, ((_a = options == null ? void 0 : options.core) == null ? void 0 : _a.transforms) || []);
3346
+ if (loader.parseInBatches) {
3347
+ if (canParseWithWorkerInBatches(loader, options)) {
3348
+ return parseWithWorkerInBatches(loader, transformedIterator, options, context, parse);
3349
+ }
3350
+ return loader.parseInBatches(transformedIterator, options, context);
3351
+ }
3352
+ return parseChunkInBatches(transformedIterator, loader, options, context);
3353
+ }
3354
+ async function* parseChunkInBatches(transformedIterator, loader, options, context) {
3355
+ const arrayBuffer = await concatenateArrayBuffersAsync(transformedIterator);
3356
+ const parsedData = await parse(
3357
+ arrayBuffer,
3358
+ loader,
3359
+ // TODO - Hack: supply loaders MIME type to ensure we match it
3360
+ { ...options, core: { ...options == null ? void 0 : options.core, mimeType: loader.mimeTypes[0] } },
3361
+ context
3362
+ );
3363
+ if (isArrowTable(parsedData)) {
3364
+ yield* parsedData.batches;
3365
+ return;
3366
+ }
3367
+ const batch = convertDataToBatch(parsedData, loader);
3368
+ yield batch;
3369
+ }
3370
+ function convertDataToBatch(parsedData, loader) {
3371
+ const batch = isTable(parsedData) ? { ...parsedData, length: getTableLength(parsedData), batchType: "data" } : {
3372
+ shape: "unknown",
3373
+ batchType: "data",
3374
+ data: parsedData,
3375
+ length: Array.isArray(parsedData) ? parsedData.length : 1
3376
+ };
3377
+ batch.mimeType = loader.mimeTypes[0];
3378
+ return batch;
3379
+ }
3380
+ function isTable(value) {
3381
+ if (!value || typeof value !== "object" || !("shape" in value)) {
3382
+ return false;
3383
+ }
3384
+ const table = value;
3385
+ switch (table.shape) {
3386
+ case "array-row-table":
3387
+ case "object-row-table":
3388
+ return Array.isArray(table.data);
3389
+ case "geojson-table":
3390
+ return Array.isArray(table.features);
3391
+ case "columnar-table":
3392
+ return Boolean(table.data && typeof table.data === "object");
3393
+ default:
3394
+ return false;
3395
+ }
3396
+ }
3397
+ function getTableLength(table) {
3398
+ switch (table.shape) {
3399
+ case "array-row-table":
3400
+ case "object-row-table":
3401
+ return table.data.length;
3402
+ case "geojson-table":
3403
+ return table.features.length;
3404
+ case "columnar-table":
3405
+ for (const column of Object.values(table.data)) {
3406
+ return column.length || 0;
3407
+ }
3408
+ return 0;
3409
+ }
3410
+ }
3411
+ async function applyInputTransforms(inputIterator, transforms = []) {
3412
+ let iteratorChain = inputIterator;
3413
+ for await (const transformBatches of transforms) {
3414
+ iteratorChain = transformBatches(iteratorChain);
3415
+ }
3416
+ return iteratorChain;
3417
+ }
3418
+ function getBatchRowCount(batch, module2) {
3419
+ var _a, _b, _c;
3420
+ if (!batch || typeof batch !== "object")
3421
+ return void 0;
3422
+ if (module2 === "geospatial" && Array.isArray(batch))
3423
+ return batch.length;
3424
+ const result = batch;
3425
+ if (module2 === "traces" && result.table !== void 0 && result.table !== "spans" && result.table !== "slices") {
3426
+ return void 0;
3427
+ }
3428
+ if (result.batchType !== void 0 && result.batchType !== "data")
3429
+ return void 0;
3430
+ if (result.shape === "unknown")
3431
+ return void 0;
3432
+ return ((_a = result.data) == null ? void 0 : _a.numRows) ?? result.numRows ?? ((_b = result.header) == null ? void 0 : _b.vertexCount) ?? ((_c = result.features) == null ? void 0 : _c.length) ?? result.length;
3433
+ }
3434
+
3435
+ // dist/lib/api/load.js
3436
+ async function load(url, loaders, options, context) {
3437
+ var _a, _b;
3438
+ let resolvedLoaders;
3439
+ let resolvedOptions;
3440
+ if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
3441
+ resolvedLoaders = [];
3442
+ resolvedOptions = loaders;
3443
+ context = void 0;
3444
+ } else {
3445
+ resolvedLoaders = loaders;
3446
+ resolvedOptions = options;
3447
+ }
3448
+ resolvedOptions ||= getGlobalLoaderOptions();
3449
+ let fetchedResponse;
3450
+ if (typeof url === "string" || isBlob(url)) {
3451
+ const selectedLoader = await selectLoader(url, resolvedLoaders, {
3452
+ ...resolvedOptions,
3453
+ core: { ...resolvedOptions == null ? void 0 : resolvedOptions.core, nothrow: true }
3454
+ });
3455
+ const canFetchBeforePreload = typeof url === "string" && (selectedLoader == null ? void 0 : selectedLoader.fetchBeforePreload);
3456
+ const loaderImplementation = selectedLoader && (typeof url === "string" || selectedLoader.createDataSourceSync) ? getLoaderImplementation(selectedLoader, resolvedOptions, typeof url === "string" ? url : void 0) : null;
3457
+ if (canFetchBeforePreload) {
3458
+ const loadOptions = resolvedOptions;
3459
+ const controller = new AbortController();
3460
+ const fetchOption = (_a = loadOptions.core) == null ? void 0 : _a.fetch;
3461
+ const callerSignal = loadOptions.signal || (context == null ? void 0 : context.signal) || (typeof fetchOption === "object" ? fetchOption == null ? void 0 : fetchOption.signal : void 0);
3462
+ const signal = callerSignal ? AbortSignal.any([callerSignal, controller.signal]) : controller.signal;
3463
+ try {
3464
+ [, fetchedResponse] = await Promise.all([
3465
+ loaderImplementation,
3466
+ resolveLoaderAuthenticationOptions(selectedLoader, url, loadOptions).then((options2) => {
3467
+ signal.throwIfAborted();
3468
+ resolvedOptions = resolveAuthenticationOptions(options2);
3469
+ const fetch3 = getFetchFunction({ ...resolvedOptions, signal }, context);
3470
+ return fetch3(applySearchParamsToUrl(url, resolvedOptions));
3471
+ })
3472
+ ]);
3473
+ } catch (error) {
3474
+ controller.abort(error);
3475
+ throw error;
3476
+ }
3477
+ }
3478
+ const implementation = await loaderImplementation;
3479
+ if (selectedLoader && (implementation == null ? void 0 : implementation.createDataSourceSync) && !isLoaderWithParser(implementation)) {
3480
+ throw new Error(`${selectedLoader.id} creates sources. Use createDataSource() instead of load().`);
3481
+ }
3482
+ if (!fetchedResponse && selectedLoader && implementation && typeof url === "string") {
3483
+ resolvedOptions = await resolveLoaderAuthenticationOptions(selectedLoader.getAuthentications ? selectedLoader : implementation, url, resolvedOptions || {});
3484
+ const { parseUrl } = implementation;
3485
+ if (parseUrl) {
3486
+ const requestUrl = applySearchParamsToUrl(url, resolvedOptions);
3487
+ const options2 = normalizeOptions(resolvedOptions, selectedLoader, [selectedLoader], url);
3488
+ return parseUrl(requestUrl, options2, context);
3489
+ }
3490
+ }
3491
+ }
3492
+ if (resolvedOptions)
3493
+ resolvedOptions = resolveAuthenticationOptions(resolvedOptions);
3494
+ const fetch2 = getFetchFunction(resolvedOptions);
3495
+ let data = url;
3496
+ if (typeof url === "string") {
3497
+ data = fetchedResponse ?? await fetch2(applySearchParamsToUrl(url, resolvedOptions));
3498
+ }
3499
+ if (isBlob(url)) {
3500
+ data = await fetch2(url);
3501
+ }
3502
+ if (typeof url === "string") {
3503
+ if (!((_b = resolvedOptions == null ? void 0 : resolvedOptions.core) == null ? void 0 : _b.baseUrl)) {
3504
+ resolvedOptions = {
3505
+ ...resolvedOptions,
3506
+ core: {
3507
+ ...resolvedOptions == null ? void 0 : resolvedOptions.core,
3508
+ baseUrl: url
3509
+ }
3510
+ };
3511
+ }
3512
+ }
3513
+ return Array.isArray(resolvedLoaders) ? await parse(data, resolvedLoaders, resolvedOptions, context) : await parse(data, resolvedLoaders, resolvedOptions, context);
3514
+ }
3515
+
3516
+ // dist/lib/api/load-in-batches.js
3517
+ function loadInBatches(files, loaders, options, context) {
3518
+ let loadersArray;
3519
+ if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
3520
+ context = void 0;
3521
+ options = loaders;
3522
+ loadersArray = void 0;
3523
+ } else {
3524
+ loadersArray = loaders;
3525
+ }
3526
+ if (!Array.isArray(files)) {
3527
+ return loadOneFileInBatches(files, loadersArray, options || {});
3528
+ }
3529
+ const promises = files.map((file) => loadOneFileInBatches(file, loadersArray, options || {}));
3530
+ return promises;
3531
+ }
3532
+ async function loadOneFileInBatches(file, loaders, options) {
3533
+ var _a, _b;
3534
+ if (typeof file === "string") {
3535
+ const url = file;
3536
+ const loader = await selectLoader(url, loaders, {
3537
+ ...options,
3538
+ core: { ...options.core, nothrow: true }
3539
+ });
3540
+ const authenticationLoader = loader && !loader.getAuthentications && ((_b = (_a = options.core) == null ? void 0 : _a.credentials) == null ? void 0 : _b.length) ? await getLoaderImplementation(loader, options, url) : loader;
3541
+ options = await resolveLoaderAuthenticationOptions(authenticationLoader, url, options);
3542
+ const fetch2 = getFetchFunction(options);
3543
+ const response = await fetch2(applySearchParamsToUrl(url, options));
3544
+ return Array.isArray(loaders) ? await parseInBatches(response, loaders, options) : await parseInBatches(response, loaders, options);
3545
+ }
3546
+ return Array.isArray(loaders) ? await parseInBatches(file, loaders, options) : await parseInBatches(file, loaders, options);
3547
+ }
3548
+
3549
+ // dist/lib/api/core-api.js
3550
+ var coreApi = Object.freeze({
3551
+ fetchFile,
3552
+ parse,
3553
+ parseFile,
3554
+ parseSync,
3555
+ parseInBatches,
3556
+ load,
3557
+ loadInBatches
3558
+ });
3559
+
3560
+ // dist/lib/loader-utils/loader-context.js
3561
+ function getLoaderContext(context, options, parentContext) {
3562
+ if (parentContext) {
3563
+ return {
3564
+ ...parentContext,
3565
+ signal: options.signal || parentContext.signal,
3566
+ reportProgress: options.onProgress || parentContext.reportProgress,
3567
+ coreApi: parentContext.coreApi || context.coreApi || coreApi,
3568
+ _parse: parentContext._parse || context._parse,
3569
+ fetch: getFetchFunction(options, parentContext)
3570
+ };
3571
+ }
3572
+ const newContext = {
3573
+ ...context,
3574
+ signal: options.signal || context.signal,
3575
+ reportProgress: options.onProgress || context.reportProgress,
3576
+ fetch: getFetchFunction(options, context),
3577
+ coreApi: context.coreApi || coreApi
3578
+ };
3579
+ if (newContext.url) {
3580
+ const baseUrl = stripQueryString(newContext.url);
3581
+ newContext.baseUrl = baseUrl;
3582
+ newContext.queryString = extractQueryString(newContext.url);
3583
+ newContext.filename = path_exports.filename(baseUrl);
3584
+ newContext.baseUrl = path_exports.dirname(baseUrl);
3585
+ }
3586
+ if (!Array.isArray(newContext.loaders)) {
3587
+ newContext.loaders = null;
3588
+ }
3589
+ return newContext;
3590
+ }
3591
+ function getLoadersFromContext(loaders, context) {
3592
+ if (loaders && !Array.isArray(loaders)) {
3593
+ return loaders;
3594
+ }
3595
+ let candidateLoaders;
3596
+ if (loaders) {
3597
+ candidateLoaders = Array.isArray(loaders) ? loaders : [loaders];
3598
+ }
3599
+ if (context && context.loaders) {
3600
+ const contextLoaders = Array.isArray(context.loaders) ? context.loaders : [context.loaders];
3601
+ candidateLoaders = candidateLoaders ? [...candidateLoaders, ...contextLoaders] : contextLoaders;
3602
+ }
3603
+ return candidateLoaders && candidateLoaders.length ? candidateLoaders : void 0;
3604
+ }
3605
+
3606
+ // dist/lib/api/parse.js
3607
+ async function parse(data, loaders, options, context) {
3608
+ var _a, _b, _c, _d;
3609
+ if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) {
3610
+ context = void 0;
3611
+ options = loaders;
3612
+ loaders = void 0;
3613
+ }
3614
+ (_a = (options == null ? void 0 : options.signal) || (context == null ? void 0 : context.signal)) == null ? void 0 : _a.throwIfAborted();
3615
+ data = await data;
3616
+ options = options || {};
3617
+ (_b = options.signal || (context == null ? void 0 : context.signal)) == null ? void 0 : _b.throwIfAborted();
3618
+ const url = getResourceUrl(data);
3619
+ const typedLoaders = loaders;
3620
+ const candidateLoaders = getLoadersFromContext(typedLoaders, context);
3621
+ const loader = await selectLoader(data, candidateLoaders, options);
3622
+ if (!loader) {
3623
+ return null;
3624
+ }
3625
+ const normalizedOptions = normalizeOptions(options, loader, candidateLoaders, url);
3626
+ const authenticationLoader = !loader.getAuthentications && ((_d = (_c = normalizedOptions.core) == null ? void 0 : _c.credentials) == null ? void 0 : _d.length) ? await getLoaderImplementation(loader, normalizedOptions, url || (context == null ? void 0 : context.url)) : loader;
3627
+ const strictOptions = await resolveLoaderAuthenticationOptions(authenticationLoader, url || "", normalizedOptions);
3628
+ context = getLoaderContext(
3629
+ // @ts-expect-error
3630
+ { url, _parse: parse, loaders: candidateLoaders },
3631
+ strictOptions,
3632
+ context || null
3633
+ );
3634
+ return parseWithLoader(loader, data, strictOptions, context);
3635
+ }
3636
+ async function parseWithLoader(loader, data, options, context) {
3637
+ var _a, _b;
3638
+ (_a = options.signal || context.signal) == null ? void 0 : _a.throwIfAborted();
3639
+ validateWorkerVersion(loader);
3640
+ options = mergeOptions(loader.options, options);
3641
+ if (isResponse(data)) {
3642
+ const { ok, redirected, status, statusText, type, url } = data;
3643
+ const headers = Object.fromEntries(data.headers.entries());
3644
+ context.response = { headers, ok, redirected, status, statusText, type, url };
3645
+ }
3646
+ const loaderWithParser = await getLoaderImplementation(loader, options, context.url);
3647
+ if (loaderWithParser.createDataSourceSync && !isLoaderWithParser(loaderWithParser)) {
3648
+ throw new Error(`${loader.id} creates sources. Use createDataSource() to open a source.`);
3649
+ }
3650
+ const output = (_b = loaderWithParser.prepareParseOutput) == null ? void 0 : _b.call(loaderWithParser, options);
3651
+ const parseOptions = (output == null ? void 0 : output.options) ?? options;
3652
+ let result;
3653
+ if (shouldParseWithWorker(loaderWithParser, data, parseOptions, context, loader)) {
3654
+ const input = isResponse(data) && data.ok ? getArrayBufferFromData(data, parseOptions) : await getArrayBufferFromData(data, parseOptions);
3655
+ result = await parseWithWorker(loaderWithParser, input, parseOptions, context, parse);
3656
+ } else if (isBlob(data) && loaderWithParser.parseBlob) {
3657
+ result = await loaderWithParser.parseBlob(data, parseOptions, context);
3658
+ } else {
3659
+ data = await getArrayBufferOrStringFromData(data, loader, parseOptions);
3660
+ result = await parseWithLoaderImplementation(loaderWithParser, data, parseOptions, context);
3661
+ }
3662
+ return output ? output.convert(result) : result;
3663
+ }
3664
+ async function parseWithLoaderImplementation(loader, data, options, context) {
3665
+ if (loader.parseText && typeof data === "string") {
3666
+ return await loader.parseText(data, options, context);
3667
+ }
3668
+ if (loader.parseTextSync && typeof data === "string") {
3669
+ return loader.parseTextSync(data, options, context);
3670
+ }
3671
+ if (loader.parse) {
3672
+ return await loader.parse(data, options, context);
3673
+ }
3674
+ if (loader.parseSync) {
3675
+ throw new Error(`${loader.name} loader: 'parse' not available on parser-bearing sync loader. Add an async 'parse' function to this loader, or call preload(loader) before parseSync(). ${context.url || ""}`);
3676
+ }
3677
+ if (loader.createDataSourceSync) {
3678
+ throw new Error(`${loader.id} creates sources. Use createDataSource() to open a source.`);
3679
+ }
3680
+ throw new Error(`${loader.id} loader - no parser found and worker is disabled`);
3681
+ }
3682
+
3683
+ // dist/lib/api/preload.js
3684
+ async function preload(loader, options, url) {
3685
+ return loader.subloaders ? await preloadLoaderDependencies(loader, options, url) : await getLoaderImplementation(loader, options, url);
3686
+ }
3687
+ function preloadSync(loader) {
3688
+ return getLoaderImplementationSync(loader);
3689
+ }
3690
+
3691
+ // dist/lib/api/encode-table.js
3692
+ async function encodeTable(data, writerDefinition, options) {
3693
+ const writer = writerDefinition.preload ? await writerDefinition.preload() : writerDefinition;
3694
+ if (writer.encode) {
3695
+ return await writer.encode(data, options);
3696
+ }
3697
+ if (writer.encodeText) {
3698
+ const text = await writer.encodeText(data, options);
3699
+ return ensureArrayBuffer(new TextEncoder().encode(text));
3700
+ }
3701
+ if (writer.encodeInBatches) {
3702
+ const batches = encodeTableInBatches(data, writer, options);
3703
+ const chunks = [];
3704
+ for await (const batch of batches) {
3705
+ chunks.push(batch);
3706
+ }
3707
+ return concatenateArrayBuffers(...chunks);
3708
+ }
3709
+ throw new Error("Writer could not encode data");
3710
+ }
3711
+ async function encodeTableAsText(data, writerDefinition, options) {
3712
+ const writer = writerDefinition.preload ? await writerDefinition.preload() : writerDefinition;
3713
+ if (writer.text && writer.encodeText) {
3714
+ return await writer.encodeText(data, options);
3715
+ }
3716
+ if (writer.text) {
3717
+ const arrayBuffer = await encodeTable(data, writer, options);
3718
+ return new TextDecoder().decode(arrayBuffer);
3719
+ }
3720
+ throw new Error(`Writer ${writer.name} could not encode data as text`);
3721
+ }
3722
+ function encodeTableInBatches(data, writerDefinition, options) {
3723
+ const writer = writerDefinition;
3724
+ if (!writer.encodeInBatches && writer.preload) {
3725
+ const preload2 = writer.preload.bind(writer);
3726
+ return (async function* () {
3727
+ const implementation = await preload2();
3728
+ yield* encodeWriterTableInBatches(data, implementation, options);
3729
+ })();
3730
+ }
3731
+ return encodeWriterTableInBatches(data, writer, options);
3732
+ }
3733
+ function encodeWriterTableInBatches(data, writer, options) {
3734
+ if (writer.encodeInBatches) {
3735
+ const dataIterator = getIterator(data);
3736
+ return writer.encodeInBatches(dataIterator, options);
3737
+ }
3738
+ throw new Error("Writer could not encode data in batches");
3739
+ }
3740
+ function getIterator(data) {
3741
+ const dataIterator = [{ ...data, start: 0, end: data.length }];
3742
+ return dataIterator;
3743
+ }
3744
+
3745
+ // dist/lib/api/encode.js
3746
+ async function encode(data, writerDefinition, options_) {
3747
+ const writer = writerDefinition.preload ? await writerDefinition.preload() : writerDefinition;
3748
+ const globalOptions = getGlobalLoaderOptions();
3749
+ const options = { ...globalOptions, ...options_ };
3750
+ if (writer.encodeURLtoURL) {
3751
+ return encodeWithCommandLineTool(writer, data, options);
3752
+ }
3753
+ if (canEncodeWithWorker(writer, options)) {
3754
+ return await processOnWorker(writer, data, options);
3755
+ }
3756
+ if (!writer.encode) {
3757
+ throw new Error(`Writer ${writer.name} could not encode data`);
3758
+ }
3759
+ return await writer.encode(data, options);
3760
+ }
3761
+ function encodeSync(data, writer, options) {
3762
+ if (writer.encodeSync) {
3763
+ return writer.encodeSync(data, options);
3764
+ }
3765
+ if (writer.encodeTextSync) {
3766
+ return ensureArrayBuffer(new TextEncoder().encode(writer.encodeTextSync(data, options)));
3767
+ }
3768
+ throw new Error(`Writer ${writer.name} could not synchronously encode data`);
3769
+ }
3770
+ async function encodeText(data, writerDefinition, options) {
3771
+ const writer = writerDefinition.preload ? await writerDefinition.preload() : writerDefinition;
3772
+ if (writer.encodeText) {
3773
+ return await writer.encodeText(data, options);
3774
+ }
3775
+ if (writer.encodeTextSync) {
3776
+ return writer.encodeTextSync(data, options);
3777
+ }
3778
+ if (writer.text && writer.encode) {
3779
+ const arrayBuffer = await writer.encode(data, options);
3780
+ return new TextDecoder().decode(arrayBuffer);
3781
+ }
3782
+ throw new Error(`Writer ${writer.name} could not encode data as text`);
3783
+ }
3784
+ function encodeTextSync(data, writer, options) {
3785
+ if (writer.encodeTextSync) {
3786
+ return writer.encodeTextSync(data, options);
3787
+ }
3788
+ if (writer.text && writer.encodeSync) {
3789
+ const arrayBuffer = encodeSync(data, writer, options);
3790
+ return new TextDecoder().decode(arrayBuffer);
3791
+ }
3792
+ throw new Error(`Writer ${writer.name} could not encode data as text`);
3793
+ }
3794
+ function encodeInBatches(data, writerDefinition, options) {
3795
+ const writer = writerDefinition;
3796
+ if (!writer.encodeInBatches && writer.preload) {
3797
+ const preload2 = writer.preload.bind(writer);
3798
+ return (async function* () {
3799
+ const implementation = await preload2();
3800
+ yield* encodeWriterInBatches(data, implementation, options);
3801
+ })();
3802
+ }
3803
+ return encodeWriterInBatches(data, writer, options);
3804
+ }
3805
+ function encodeWriterInBatches(data, writer, options) {
3806
+ if (writer.encodeInBatches) {
3807
+ let dataIterator;
3808
+ if (data && typeof data === "object") {
3809
+ if ("numRows" in data && "schema" in data) {
3810
+ dataIterator = [data];
3811
+ } else if (Symbol.iterator in data || Symbol.asyncIterator in data) {
3812
+ dataIterator = data;
3813
+ }
3814
+ }
3815
+ return writer.encodeInBatches(dataIterator ?? getIterator2(data), options);
3816
+ }
3817
+ throw new Error(`Writer ${writer.name} could not encode in batches`);
3818
+ }
3819
+ async function encodeURLtoURL(inputUrl, outputUrl, writerDefinition, options) {
3820
+ var _a;
3821
+ inputUrl = resolvePath(inputUrl);
3822
+ outputUrl = resolvePath(outputUrl);
3823
+ if (isBrowser) {
3824
+ throw new Error();
3825
+ }
3826
+ const writer = writerDefinition.encodeURLtoURL ? writerDefinition : await ((_a = writerDefinition.preload) == null ? void 0 : _a.call(writerDefinition)) ?? writerDefinition;
3827
+ if (!writer.encodeURLtoURL) {
3828
+ throw new Error();
3829
+ }
3830
+ const outputFilename = await writer.encodeURLtoURL(inputUrl, outputUrl, options);
3831
+ return outputFilename;
3832
+ }
3833
+ async function encodeWithCommandLineTool(writer, data, options) {
3834
+ if (isBrowser) {
3835
+ throw new Error(`Writer ${writer.name} not supported in browser`);
3836
+ }
3837
+ const tmpInputFilename = getTemporaryFilename("input");
3838
+ const file = new NodeFileFacade(tmpInputFilename, "w");
3839
+ await file.write(data);
3840
+ const tmpOutputFilename = getTemporaryFilename("output");
3841
+ const outputFilename = await encodeURLtoURL(tmpInputFilename, tmpOutputFilename, writer, options);
3842
+ const response = await fetchFile(outputFilename);
3843
+ return response.arrayBuffer();
3844
+ }
3845
+ function getIterator2(data) {
3846
+ const dataIterator = [{ ...data, start: 0, end: data.length }];
3847
+ return dataIterator;
3848
+ }
3849
+ function getTemporaryFilename(filename2) {
3850
+ return `/tmp/${filename2}`;
3851
+ }
3852
+
3853
+ // dist/lib/api/create-data-source.js
3854
+ async function createDataSource(data, loaders, options = {}) {
3855
+ var _a, _b, _c;
3856
+ (_a = options.signal) == null ? void 0 : _a.throwIfAborted();
3857
+ const candidates = getCandidates(loaders, options);
3858
+ const loader = candidates.length === 1 ? candidates[0] : await selectLoader(data, candidates, getSelectionOptions(options), void 0, "source");
3859
+ if (!loader) {
3860
+ throw new Error("No explicit source loader matches the input");
3861
+ }
3862
+ const url = typeof data === "string" ? data : "";
3863
+ const implementation = await preload(loader, options, url);
3864
+ (_b = options.signal) == null ? void 0 : _b.throwIfAborted();
3865
+ const authenticatedOptions = await resolveLoaderAuthenticationOptions(loader.getAuthentications ? loader : implementation, url, options);
3866
+ (_c = options.signal) == null ? void 0 : _c.throwIfAborted();
3867
+ return constructSource(implementation, data, authenticatedOptions);
3868
+ }
3869
+ function createDataSourceSync(data, loaders, options = {}) {
3870
+ var _a, _b, _c, _d;
3871
+ const candidates = getCandidates(loaders, options);
3872
+ const loader = candidates.length === 1 ? candidates[0] : selectLoaderSync(data, candidates, getSelectionOptions(options), void 0, "source");
3873
+ if (!loader) {
3874
+ throw new Error("No explicit source loader matches the input");
3875
+ }
3876
+ const implementation = getLoaderImplementationSync(loader, options);
3877
+ if (!implementation) {
3878
+ throw new Error(`${loader.id} has no synchronous source factory available. Call preload() first.`);
3879
+ }
3880
+ const authenticationLoader = loader.getAuthentications ? loader : implementation;
3881
+ const contributions = ((_b = (_a = options.core) == null ? void 0 : _a.credentials) == null ? void 0 : _b.length) ? (_c = authenticationLoader.getAuthentications) == null ? void 0 : _c.call(authenticationLoader, typeof data === "string" ? data : "", options) : void 0;
3882
+ if (contributions && "then" in contributions) {
3883
+ void contributions.catch(() => {
3884
+ });
3885
+ throw new Error("Use createDataSource() with an asynchronous getAuthentications() hook.");
3886
+ }
3887
+ const authenticatedOptions = resolveAuthenticationOptions((contributions == null ? void 0 : contributions.length) ? {
3888
+ ...options,
3889
+ core: {
3890
+ ...options.core,
3891
+ authentications: [...((_d = options.core) == null ? void 0 : _d.authentications) || [], ...contributions]
3892
+ }
3893
+ } : options);
3894
+ return constructSource(implementation, data, authenticatedOptions);
3895
+ }
3896
+ function getCandidates(loaders, options) {
3897
+ var _a;
3898
+ const candidates = Array.isArray(loaders) ? [...loaders] : [loaders];
3899
+ const type = ((_a = options.core) == null ? void 0 : _a.type) || options.type;
3900
+ return candidates.length > 1 && type && type !== "auto" ? candidates.filter((loader) => (loader.type ?? loader.id) === type) : candidates;
3901
+ }
3902
+ function getSelectionOptions(options) {
3903
+ return { ...options, core: { ...options.core, ignoreRegisteredLoaders: true, nothrow: true } };
3904
+ }
3905
+ function constructSource(loader, data, options) {
3906
+ if (loader.createDataSourceSync) {
3907
+ return loader.createDataSourceSync(data, options, coreApi);
3908
+ }
3909
+ throw new Error(`${loader.id} has no synchronous source factory. Use createDataSource() to preload the loader.`);
3910
+ }
3911
+
3912
+ // dist/lib/api/select-source.js
3913
+ function selectSource(url, sources, options) {
3914
+ const type = (options == null ? void 0 : options.type) || "auto";
3915
+ let selectedSource = null;
3916
+ if (type === "auto") {
3917
+ selectedSource = selectLoaderSync(url, sources, { core: { nothrow: true } }, void 0, "source");
3918
+ } else {
3919
+ selectedSource = getSourceOfType(type, sources);
3920
+ }
3921
+ if (!selectedSource && !(options == null ? void 0 : options.nothrow)) {
3922
+ throw new Error("Not a valid image source type");
3923
+ }
3924
+ return selectedSource;
3925
+ }
3926
+ function getSourceOfType(type, sources) {
3927
+ for (const service of sources) {
3928
+ if (service.type === type) {
3929
+ return service;
3930
+ }
3931
+ }
3932
+ return null;
3933
+ }
3934
+
3935
+ // dist/iterators/make-stream/make-stream.js
3936
+ function makeStream(source, options) {
3937
+ if (globalThis.loaders.makeNodeStream) {
3938
+ return globalThis.loaders.makeNodeStream(source, options);
3939
+ }
3940
+ const iterator = source[Symbol.asyncIterator] ? source[Symbol.asyncIterator]() : source[Symbol.iterator]();
3941
+ return new ReadableStream(
3942
+ {
3943
+ // Create a byte stream (enables `Response(stream).arrayBuffer()`)
3944
+ // Only supported on Chrome
3945
+ // See: https://developer.mozilla.org/en-US/docs/Web/API/ReadableByteStreamController
3946
+ // @ts-ignore
3947
+ type: "bytes",
3948
+ async pull(controller) {
3949
+ try {
3950
+ const { done, value } = await iterator.next();
3951
+ if (done) {
3952
+ controller.close();
3953
+ } else {
3954
+ controller.enqueue(new Uint8Array(value));
3955
+ }
3956
+ } catch (error) {
3957
+ controller.error(error);
3958
+ }
3959
+ },
3960
+ async cancel() {
3961
+ var _a;
3962
+ await ((_a = iterator == null ? void 0 : iterator.return) == null ? void 0 : _a.call(iterator));
3963
+ }
3964
+ },
3965
+ // options: QueingStrategy<Uint8Array>
3966
+ {
3967
+ // This is bytes, not chunks
3968
+ highWaterMark: 2 ** 24,
3969
+ ...options
3970
+ }
3971
+ );
3972
+ }
3973
+
3974
+ // dist/lib/progress/fetch-progress.js
3975
+ async function fetchProgress(response, onProgress, onDone = () => {
3976
+ }, onError = () => {
3977
+ }) {
3978
+ response = await response;
3979
+ if (!response.ok) {
3980
+ return response;
3981
+ }
3982
+ const body = response.body;
3983
+ if (!body) {
3984
+ return response;
3985
+ }
3986
+ const contentLength = response.headers.get("content-length") || 0;
3987
+ const totalBytes = contentLength ? parseInt(contentLength) : 0;
3988
+ if (!(totalBytes > 0)) {
3989
+ return response;
3990
+ }
3991
+ if (typeof ReadableStream === "undefined" || !body.getReader) {
3992
+ return response;
3993
+ }
3994
+ const progressStream = new ReadableStream({
3995
+ async start(controller) {
3996
+ const reader = body.getReader();
3997
+ await read(controller, reader, 0, totalBytes, onProgress, onDone, onError);
3998
+ }
3999
+ });
4000
+ return new Response(progressStream);
4001
+ }
4002
+ async function read(controller, reader, loadedBytes, totalBytes, onProgress, onDone, onError) {
4003
+ try {
4004
+ const { done, value } = await reader.read();
4005
+ if (done) {
4006
+ onDone();
4007
+ controller.close();
4008
+ return;
4009
+ }
4010
+ loadedBytes += value.byteLength;
4011
+ const percent = Math.round(loadedBytes / totalBytes * 100);
4012
+ onProgress(percent, { loadedBytes, totalBytes });
4013
+ controller.enqueue(value);
4014
+ await read(controller, reader, loadedBytes, totalBytes, onProgress, onDone, onError);
4015
+ } catch (error) {
4016
+ controller.error(error);
4017
+ onError(error);
4018
+ }
4019
+ }
4020
+
4021
+ // dist/lib/filesystems/browser-filesystem.js
4022
+ var BrowserFileSystem = class {
4023
+ _fetch;
4024
+ files = {};
4025
+ lowerCaseFiles = {};
4026
+ usedFiles = {};
4027
+ /**
4028
+ * A FileSystem API wrapper around a list of browser 'File' objects
4029
+ * @param files
4030
+ * @param options
4031
+ */
4032
+ constructor(files, options) {
4033
+ this._fetch = (options == null ? void 0 : options.fetch) || fetch;
4034
+ for (let i = 0; i < files.length; ++i) {
4035
+ const file = files[i];
4036
+ this.files[file.name] = file;
4037
+ this.lowerCaseFiles[file.name.toLowerCase()] = file;
4038
+ this.usedFiles[file.name] = false;
4039
+ }
4040
+ this.fetch = this.fetch.bind(this);
4041
+ }
4042
+ // implements IFileSystem
4043
+ /**
4044
+ * Implementation of fetch against this file system
4045
+ * Delegates to global fetch for http{s}:// or data://
4046
+ */
4047
+ async fetch(path, options) {
4048
+ if (path.includes("://")) {
4049
+ return this._fetch(path, options);
4050
+ }
4051
+ const file = this._getFile(path, true);
4052
+ if (!file) {
4053
+ return new Response(path, { status: 400, statusText: "NOT FOUND" });
4054
+ }
4055
+ const headers = new Headers(options == null ? void 0 : options.headers);
4056
+ const range = headers.get("Range");
4057
+ const bytes = range && /bytes=(\d+)-(\d+)/.exec(range);
4058
+ if (bytes) {
4059
+ const start = parseInt(bytes[1]);
4060
+ const end = Math.min(parseInt(bytes[2]), file.size - 1);
4061
+ if (start > end) {
4062
+ const response3 = new Response(null, {
4063
+ status: 416,
4064
+ headers: { "Content-Range": `bytes */${file.size}` }
4065
+ });
4066
+ Object.defineProperty(response3, "url", { value: path });
4067
+ return response3;
4068
+ }
4069
+ const data = await file.slice(start, end + 1).arrayBuffer();
4070
+ const response2 = new Response(data, {
4071
+ status: 206,
4072
+ headers: { "Content-Range": `bytes ${start}-${end}/${file.size}` }
4073
+ });
4074
+ Object.defineProperty(response2, "url", { value: path });
4075
+ return response2;
4076
+ }
4077
+ const response = new Response(file);
4078
+ Object.defineProperty(response, "url", { value: path });
4079
+ return response;
4080
+ }
4081
+ /**
4082
+ * List filenames in this filesystem
4083
+ * @param dirname
4084
+ * @returns
4085
+ */
4086
+ async readdir(dirname2) {
4087
+ const files = [];
4088
+ for (const path in this.files) {
4089
+ files.push(path);
4090
+ }
4091
+ return files;
4092
+ }
4093
+ /**
4094
+ * Return information (size) about files in this file system
4095
+ */
4096
+ async stat(path, options) {
4097
+ const file = this._getFile(path, false);
4098
+ if (!file) {
4099
+ throw new Error(path);
4100
+ }
4101
+ return { size: file.size };
4102
+ }
4103
+ /**
4104
+ * Just removes the file from the list
4105
+ */
4106
+ async unlink(path) {
4107
+ const file = this._getFile(path, false);
4108
+ if (file) {
4109
+ delete this.files[file.name];
4110
+ delete this.lowerCaseFiles[file.name.toLowerCase()];
4111
+ this.usedFiles[file.name] = true;
4112
+ }
4113
+ }
4114
+ // implements IRandomAccessFileSystem
4115
+ // RANDOM ACCESS
4116
+ async openReadableFile(pathname, flags) {
4117
+ return new BlobFile(this._getFile(pathname, true));
4118
+ }
4119
+ // PRIVATE
4120
+ // Supports case independent paths, and file usage tracking
4121
+ _getFile(path, used) {
4122
+ const file = this.files[path] || this.lowerCaseFiles[path.toLowerCase()];
4123
+ if (file && used) {
4124
+ this.usedFiles[path] = true;
4125
+ }
4126
+ return file;
4127
+ }
4128
+ };
4129
+ //# sourceMappingURL=api.cjs.map