@margoengine/loaders 0.0.0-stage → 1.0.0

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 (226) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1665 -2
  4. package/dist/3dm.d.ts +161 -0
  5. package/dist/3dm.js +289 -0
  6. package/dist/3ds.d.ts +124 -0
  7. package/dist/3ds.js +392 -0
  8. package/dist/acclaim.d.ts +90 -0
  9. package/dist/acclaim.js +312 -0
  10. package/dist/amf.d.ts +45 -0
  11. package/dist/amf.js +256 -0
  12. package/dist/babylon.d.ts +197 -0
  13. package/dist/babylon.js +701 -0
  14. package/dist/common.d.ts +7 -0
  15. package/dist/common.js +6 -0
  16. package/dist/crease.d.ts +7 -0
  17. package/dist/crease.js +67 -0
  18. package/dist/dae-animation.d.ts +66 -0
  19. package/dist/dae-animation.js +266 -0
  20. package/dist/dae-common.d.ts +95 -0
  21. package/dist/dae-common.js +226 -0
  22. package/dist/dae-controllers.d.ts +57 -0
  23. package/dist/dae-controllers.js +164 -0
  24. package/dist/dae-kinematics.d.ts +65 -0
  25. package/dist/dae-kinematics.js +461 -0
  26. package/dist/dae-pose.d.ts +131 -0
  27. package/dist/dae-pose.js +381 -0
  28. package/dist/dae-scene.d.ts +203 -0
  29. package/dist/dae-scene.js +279 -0
  30. package/dist/dae.d.ts +166 -0
  31. package/dist/dae.js +644 -0
  32. package/dist/detect.d.ts +20 -0
  33. package/dist/detect.js +72 -0
  34. package/dist/dxf-hatch.d.ts +8 -0
  35. package/dist/dxf-hatch.js +346 -0
  36. package/dist/dxf-leaders.d.ts +59 -0
  37. package/dist/dxf-leaders.js +258 -0
  38. package/dist/dxf.d.ts +122 -0
  39. package/dist/dxf.js +985 -0
  40. package/dist/engine.d.ts +41 -0
  41. package/dist/engine.js +120 -0
  42. package/dist/font-opentype.d.ts +14 -0
  43. package/dist/font-opentype.js +33 -0
  44. package/dist/font-woff.d.ts +23 -0
  45. package/dist/font-woff.js +293 -0
  46. package/dist/font.d.ts +41 -0
  47. package/dist/font.js +26 -0
  48. package/dist/gcode.d.ts +92 -0
  49. package/dist/gcode.js +369 -0
  50. package/dist/geo-model.d.ts +84 -0
  51. package/dist/geo-model.js +220 -0
  52. package/dist/geo-mvt.d.ts +15 -0
  53. package/dist/geo-mvt.js +302 -0
  54. package/dist/geo-shp.d.ts +15 -0
  55. package/dist/geo-shp.js +234 -0
  56. package/dist/geo-xml.d.ts +6 -0
  57. package/dist/geo-xml.js +165 -0
  58. package/dist/geo.d.ts +8 -0
  59. package/dist/geo.js +59 -0
  60. package/dist/geometry.d.ts +60 -0
  61. package/dist/geometry.js +273 -0
  62. package/dist/index.d.ts +54 -0
  63. package/dist/index.js +28 -0
  64. package/dist/kmz.d.ts +78 -0
  65. package/dist/kmz.js +173 -0
  66. package/dist/las.d.ts +92 -0
  67. package/dist/las.js +110 -0
  68. package/dist/ldraw.d.ts +118 -0
  69. package/dist/ldraw.js +474 -0
  70. package/dist/load.d.ts +72 -0
  71. package/dist/load.js +205 -0
  72. package/dist/lottie.d.ts +154 -0
  73. package/dist/lottie.js +893 -0
  74. package/dist/lwo.d.ts +81 -0
  75. package/dist/lwo.js +454 -0
  76. package/dist/lzf.d.ts +13 -0
  77. package/dist/lzf.js +56 -0
  78. package/dist/materialx.d.ts +120 -0
  79. package/dist/materialx.js +563 -0
  80. package/dist/md2.d.ts +52 -0
  81. package/dist/md2.js +112 -0
  82. package/dist/mmcif.d.ts +14 -0
  83. package/dist/mmcif.js +246 -0
  84. package/dist/mmd.d.ts +244 -0
  85. package/dist/mmd.js +958 -0
  86. package/dist/mocap.d.ts +71 -0
  87. package/dist/mocap.js +178 -0
  88. package/dist/molecule-common.d.ts +4 -0
  89. package/dist/molecule-common.js +54 -0
  90. package/dist/mtl.d.ts +125 -0
  91. package/dist/mtl.js +550 -0
  92. package/dist/normals.d.ts +7 -0
  93. package/dist/normals.js +31 -0
  94. package/dist/nrrd.d.ts +70 -0
  95. package/dist/nrrd.js +785 -0
  96. package/dist/nurbs.d.ts +118 -0
  97. package/dist/nurbs.js +265 -0
  98. package/dist/obj.d.ts +145 -0
  99. package/dist/obj.js +462 -0
  100. package/dist/off.d.ts +10 -0
  101. package/dist/off.js +155 -0
  102. package/dist/outline-font.d.ts +87 -0
  103. package/dist/outline-font.js +110 -0
  104. package/dist/outline.d.ts +20 -0
  105. package/dist/outline.js +215 -0
  106. package/dist/pcd.d.ts +34 -0
  107. package/dist/pcd.js +258 -0
  108. package/dist/pdb.d.ts +67 -0
  109. package/dist/pdb.js +126 -0
  110. package/dist/ply.d.ts +35 -0
  111. package/dist/ply.js +392 -0
  112. package/dist/polygon.d.ts +9 -0
  113. package/dist/polygon.js +49 -0
  114. package/dist/prwm.d.ts +24 -0
  115. package/dist/prwm.js +114 -0
  116. package/dist/render.d.ts +32 -0
  117. package/dist/render.js +181 -0
  118. package/dist/sfnt-cff.d.ts +37 -0
  119. package/dist/sfnt-cff.js +749 -0
  120. package/dist/sfnt-layout.d.ts +24 -0
  121. package/dist/sfnt-layout.js +266 -0
  122. package/dist/sfnt-reader.d.ts +28 -0
  123. package/dist/sfnt-reader.js +87 -0
  124. package/dist/sfnt-variation.d.ts +40 -0
  125. package/dist/sfnt-variation.js +318 -0
  126. package/dist/shared/asset-url.js +82 -0
  127. package/dist/shared/crc32.d.ts +2 -0
  128. package/dist/shared/crc32.js +47 -0
  129. package/dist/shared/errors.js +36 -0
  130. package/dist/shared/inflate.js +284 -0
  131. package/dist/shared/normals.js +26 -0
  132. package/dist/shared/scene-scope.js +56 -0
  133. package/dist/shared/trailing-data.js +45 -0
  134. package/dist/stl.d.ts +64 -0
  135. package/dist/stl.js +309 -0
  136. package/dist/svg.d.ts +90 -0
  137. package/dist/svg.js +1007 -0
  138. package/dist/tds.d.ts +2 -0
  139. package/dist/tds.js +2 -0
  140. package/dist/textures.d.ts +42 -0
  141. package/dist/textures.js +53 -0
  142. package/dist/threemf-beam-reader.d.ts +19 -0
  143. package/dist/threemf-beam-reader.js +165 -0
  144. package/dist/threemf-beams.d.ts +52 -0
  145. package/dist/threemf-beams.js +268 -0
  146. package/dist/threemf-boolean-read.d.ts +10 -0
  147. package/dist/threemf-boolean-read.js +113 -0
  148. package/dist/threemf-boolean.d.ts +59 -0
  149. package/dist/threemf-boolean.js +20 -0
  150. package/dist/threemf-csg.d.ts +14 -0
  151. package/dist/threemf-csg.js +193 -0
  152. package/dist/threemf-displacement-read.d.ts +8 -0
  153. package/dist/threemf-displacement-read.js +213 -0
  154. package/dist/threemf-displacement.d.ts +71 -0
  155. package/dist/threemf-displacement.js +18 -0
  156. package/dist/threemf-evaluate.d.ts +36 -0
  157. package/dist/threemf-evaluate.js +86 -0
  158. package/dist/threemf-functions.d.ts +33 -0
  159. package/dist/threemf-functions.js +359 -0
  160. package/dist/threemf-lattice-mesh.d.ts +9 -0
  161. package/dist/threemf-lattice-mesh.js +115 -0
  162. package/dist/threemf-lattice.d.ts +139 -0
  163. package/dist/threemf-lattice.js +379 -0
  164. package/dist/threemf-levelset.d.ts +23 -0
  165. package/dist/threemf-levelset.js +105 -0
  166. package/dist/threemf-materials.d.ts +162 -0
  167. package/dist/threemf-materials.js +497 -0
  168. package/dist/threemf-mesh.d.ts +75 -0
  169. package/dist/threemf-mesh.js +422 -0
  170. package/dist/threemf-secure.d.ts +50 -0
  171. package/dist/threemf-secure.js +153 -0
  172. package/dist/threemf-tessellate.d.ts +37 -0
  173. package/dist/threemf-tessellate.js +277 -0
  174. package/dist/threemf-volume-colour.d.ts +25 -0
  175. package/dist/threemf-volume-colour.js +233 -0
  176. package/dist/threemf-volume-sample.d.ts +8 -0
  177. package/dist/threemf-volume-sample.js +65 -0
  178. package/dist/threemf-volumetric-read.d.ts +15 -0
  179. package/dist/threemf-volumetric-read.js +539 -0
  180. package/dist/threemf-volumetric.d.ts +177 -0
  181. package/dist/threemf-volumetric.js +28 -0
  182. package/dist/threemf.d.ts +170 -0
  183. package/dist/threemf.js +609 -0
  184. package/dist/tilt.d.ts +62 -0
  185. package/dist/tilt.js +186 -0
  186. package/dist/tmx.d.ts +151 -0
  187. package/dist/tmx.js +394 -0
  188. package/dist/ttf.d.ts +78 -0
  189. package/dist/ttf.js +568 -0
  190. package/dist/types.d.ts +108 -0
  191. package/dist/types.js +35 -0
  192. package/dist/usd.d.ts +2 -0
  193. package/dist/usd.js +2 -0
  194. package/dist/usd.worker.d.ts +1 -0
  195. package/dist/usdz.d.ts +50 -0
  196. package/dist/usdz.js +646 -0
  197. package/dist/util.d.ts +75 -0
  198. package/dist/util.js +241 -0
  199. package/dist/vdb.d.ts +111 -0
  200. package/dist/vdb.js +663 -0
  201. package/dist/vrml.d.ts +53 -0
  202. package/dist/vrml.js +532 -0
  203. package/dist/vtk-cells.d.ts +29 -0
  204. package/dist/vtk-cells.js +211 -0
  205. package/dist/vtk-legacy.d.ts +57 -0
  206. package/dist/vtk-legacy.js +439 -0
  207. package/dist/vtk-reader.d.ts +19 -0
  208. package/dist/vtk-reader.js +134 -0
  209. package/dist/vtk-xml.d.ts +96 -0
  210. package/dist/vtk-xml.js +578 -0
  211. package/dist/vtk.d.ts +13 -0
  212. package/dist/vtk.js +234 -0
  213. package/dist/woff-glyf.d.ts +17 -0
  214. package/dist/woff-glyf.js +215 -0
  215. package/dist/worker.d.ts +10 -0
  216. package/dist/worker.js +93 -0
  217. package/dist/workers/usd.js +3 -0
  218. package/dist/xfile.d.ts +99 -0
  219. package/dist/xfile.js +706 -0
  220. package/dist/xml.d.ts +107 -0
  221. package/dist/xml.js +843 -0
  222. package/dist/xyz.d.ts +16 -0
  223. package/dist/xyz.js +110 -0
  224. package/dist/zip.d.ts +38 -0
  225. package/dist/zip.js +150 -0
  226. package/package.json +289 -4
package/dist/nrrd.js ADDED
@@ -0,0 +1,785 @@
1
+ // NRRD volumes (NRRD0001 to NRRD0005): the header, the raw, ascii, hex and gzip encodings, and detached data files.
2
+ import { LoaderError } from './types.js';
3
+ import { crc32 } from './shared/crc32.js';
4
+ import { findLineEnd, latin1, resolvePath, throwIfAborted, toBytes } from './util.js';
5
+ const F = 'NRRD';
6
+ const MAX_HEADER = 1 << 20;
7
+ const MAX_DIMENSION = 16;
8
+ const LITTLE = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
9
+ /** Compressed bytes handed to the gzip decoder per step, so decoding can stop once the samples are out. */
10
+ const FEED = 1 << 16;
11
+ const TYPES = Object.create(null);
12
+ for (const [type, names] of [
13
+ ['int8', 'signed char,int8,int8_t'],
14
+ ['uint8', 'uchar,unsigned char,uint8,uint8_t'],
15
+ ['int16', 'short,short int,signed short,signed short int,int16,int16_t'],
16
+ ['uint16', 'ushort,unsigned short,unsigned short int,uint16,uint16_t'],
17
+ ['int32', 'int,signed int,int32,int32_t'],
18
+ ['uint32', 'uint,unsigned int,uint32,uint32_t'],
19
+ ['int64', 'longlong,long long,long long int,signed long long,signed long long int,int64,int64_t'],
20
+ ['uint64', 'ulonglong,unsigned long long,unsigned long long int,uint64,uint64_t'],
21
+ ['float32', 'float'],
22
+ ['float64', 'double'],
23
+ ])
24
+ for (const name of names.split(','))
25
+ TYPES[name] = type;
26
+ const ENCODINGS = Object.assign(Object.create(null), {
27
+ raw: 'raw',
28
+ txt: 'ascii',
29
+ text: 'ascii',
30
+ ascii: 'ascii',
31
+ hex: 'hex',
32
+ gz: 'gzip',
33
+ gzip: 'gzip',
34
+ bz2: 'bzip2',
35
+ bzip2: 'bzip2',
36
+ });
37
+ /**
38
+ * bzip2 data, which `@margoengine/decoders` undoes, loaded only for a file that needs it. Decoding stops once `size`
39
+ * bytes are out: section 2 says data past what the header needs is ignored, and nothing more is ever inflated.
40
+ */
41
+ async function bunzip(body, size) {
42
+ const { decodeBzip2 } = await import('@margoengine/decoders/bzip2');
43
+ try {
44
+ return decodeBzip2(body, { maxBytes: size, stopAt: size });
45
+ }
46
+ catch (error) {
47
+ throw new LoaderError(F, 'zip', error.message);
48
+ }
49
+ }
50
+ /** The spaces the format names (section 4), by lower-case spelling, with their dimension. */
51
+ const SPACES = Object.create(null);
52
+ for (const [name, short] of [
53
+ ['right-anterior-superior', 'ras'],
54
+ ['left-anterior-superior', 'las'],
55
+ ['left-posterior-superior', 'lps'],
56
+ ['scanner-xyz', ''],
57
+ ['3D-right-handed', ''],
58
+ ['3D-left-handed', ''],
59
+ ])
60
+ for (const time of [false, true]) {
61
+ const full = time ? `${name}-time` : name;
62
+ SPACES[full.toLowerCase()] = [full, time ? 4 : 3];
63
+ if (short)
64
+ SPACES[time ? `${short}t` : short] = [full, time ? 4 : 3];
65
+ }
66
+ /** Kinds of the format (section 6) with the axis size each requires, 0 for none. */
67
+ const KINDS = Object.assign(Object.create(null), {
68
+ domain: 0,
69
+ space: 0,
70
+ time: 0,
71
+ list: 0,
72
+ point: 0,
73
+ vector: 0,
74
+ 'covariant-vector': 0,
75
+ normal: 0,
76
+ stub: 1,
77
+ scalar: 1,
78
+ complex: 2,
79
+ '2-vector': 2,
80
+ '3-color': 3,
81
+ 'rgb-color': 3,
82
+ 'hsv-color': 3,
83
+ 'xyz-color': 3,
84
+ '4-color': 4,
85
+ 'rgba-color': 4,
86
+ '3-vector': 3,
87
+ '3-gradient': 3,
88
+ '3-normal': 3,
89
+ '4-vector': 4,
90
+ quaternion: 4,
91
+ '2d-symmetric-matrix': 3,
92
+ '2d-masked-symmetric-matrix': 4,
93
+ '2d-matrix': 4,
94
+ // The spec's table gives 4 here but lists five components (a mask and four), so no size is required of it.
95
+ '2d-masked-matrix': 0,
96
+ '3d-symmetric-matrix': 6,
97
+ '3d-masked-symmetric-matrix': 7,
98
+ '3d-matrix': 9,
99
+ '3d-masked-matrix': 10,
100
+ '???': 0,
101
+ none: 0,
102
+ });
103
+ /** Second spellings of field identifiers, mapped to the first. */
104
+ const ALIASES = Object.assign(Object.create(null), {
105
+ blocksize: 'block size',
106
+ oldmin: 'old min',
107
+ oldmax: 'old max',
108
+ datafile: 'data file',
109
+ lineskip: 'line skip',
110
+ byteskip: 'byte skip',
111
+ sampleunits: 'sample units',
112
+ axismins: 'axis mins',
113
+ axismaxs: 'axis maxs',
114
+ centerings: 'centers',
115
+ });
116
+ /** The first magic version each field exists in (section 1.1). */
117
+ const SINCE = Object.assign(Object.create(null), {
118
+ kinds: 3,
119
+ thicknesses: 4,
120
+ 'sample units': 4,
121
+ space: 4,
122
+ 'space dimension': 4,
123
+ 'space units': 4,
124
+ 'space origin': 4,
125
+ 'space directions': 4,
126
+ 'measurement frame': 5,
127
+ });
128
+ /** Per-axis fields, which only come after `dimension` (section 1.3). */
129
+ const PER_AXIS = new Set([
130
+ 'sizes',
131
+ 'spacings',
132
+ 'thicknesses',
133
+ 'axis mins',
134
+ 'axis maxs',
135
+ 'centers',
136
+ 'labels',
137
+ 'units',
138
+ 'kinds',
139
+ 'space directions',
140
+ ]);
141
+ /** Orientation fields, which only come after `space` or `space dimension` (section 4). */
142
+ const ORIENTATION = new Set(['space units', 'space origin', 'space directions', 'measurement frame']);
143
+ const SIZE = {
144
+ int8: 1,
145
+ uint8: 1,
146
+ int16: 2,
147
+ uint16: 2,
148
+ int32: 4,
149
+ uint32: 4,
150
+ int64: 8,
151
+ uint64: 8,
152
+ float32: 4,
153
+ float64: 8,
154
+ };
155
+ function allocate(type, count) {
156
+ switch (type) {
157
+ case 'int8':
158
+ return new Int8Array(count);
159
+ case 'uint8':
160
+ return new Uint8Array(count);
161
+ case 'int16':
162
+ return new Int16Array(count);
163
+ case 'uint16':
164
+ return new Uint16Array(count);
165
+ case 'int32':
166
+ return new Int32Array(count);
167
+ case 'uint32':
168
+ return new Uint32Array(count);
169
+ case 'float32':
170
+ return new Float32Array(count);
171
+ default:
172
+ return new Float64Array(count);
173
+ }
174
+ }
175
+ function integers(value, name) {
176
+ const parts = value.trim().split(/\s+/).map(Number);
177
+ if (!parts.every(Number.isSafeInteger))
178
+ throw new LoaderError(F, 'syntax', `invalid ${name} "${value.slice(0, 64)}"`);
179
+ return parts;
180
+ }
181
+ function integer(value, name, fallback) {
182
+ if (value === undefined)
183
+ return fallback;
184
+ const [number, extra] = integers(value, name);
185
+ if (extra !== undefined)
186
+ throw new LoaderError(F, 'syntax', `invalid ${name} "${value.slice(0, 64)}"`);
187
+ return number;
188
+ }
189
+ /**
190
+ * Reads `(a,b,c)` vectors and `none` words, separated by spaces or tabs; `none` comes back as null. Anything else in
191
+ * the descriptor, between or inside the words, is a syntax error.
192
+ */
193
+ function vectors(value, name, size) {
194
+ const found = [], word = /[ \t]*(?:\(([^()]*)\)|(none))(?=[ \t]|$)/iy;
195
+ let at = 0;
196
+ for (let match = word.exec(value); match; match = word.exec(value)) {
197
+ at = word.lastIndex;
198
+ if (match[1] === undefined) {
199
+ found.push(null);
200
+ continue;
201
+ }
202
+ const vector = match[1].split(',').map((part) => (part.trim() === '' ? NaN : Number(part)));
203
+ if (vector.length !== size || !vector.every(Number.isFinite))
204
+ throw new LoaderError(F, 'syntax', `invalid vector "(${match[1].slice(0, 64)})" in ${name}`);
205
+ found.push(vector);
206
+ }
207
+ const rest = value.slice(at).trim();
208
+ if (rest)
209
+ throw new LoaderError(F, 'syntax', `unexpected "${rest.slice(0, 32)}" in ${name}`);
210
+ return found;
211
+ }
212
+ /** A floating point value by the rules of section 2: "nan" anywhere is NaN, then "-inf", then "inf". */
213
+ function float(word) {
214
+ if (/nan/i.test(word))
215
+ return NaN;
216
+ if (/-inf/i.test(word))
217
+ return -Infinity;
218
+ if (/inf/i.test(word))
219
+ return Infinity;
220
+ const value = Number(word);
221
+ if (word.trim() === '' || Number.isNaN(value))
222
+ throw new LoaderError(F, 'syntax', `invalid number "${word.slice(0, 32)}"`);
223
+ return value;
224
+ }
225
+ /** A per-axis list of doubles; infinite entries are refused (spacings, axis mins and axis maxs never hold one). */
226
+ function doubles(value, name, dimension) {
227
+ const parts = value
228
+ .trim()
229
+ .split(/[ \t]+/)
230
+ .map(float);
231
+ if (parts.length !== dimension)
232
+ throw new LoaderError(F, 'syntax', `${name} has ${parts.length} entries for ${dimension} axes`);
233
+ if (parts.some((part) => part === Infinity || part === -Infinity))
234
+ throw new LoaderError(F, 'range', `${name} holds an infinite value`);
235
+ return parts;
236
+ }
237
+ /** `\n` and `\\` are the only escapes of a key or value (section 1.2); any other backslash stays as written. */
238
+ const unescape = (text) => text.replace(/\\([n\\])/g, (_, c) => (c === 'n' ? '\n' : '\\'));
239
+ function readHeader(bytes) {
240
+ if (bytes.length < 4 || latin1(bytes, 0, 4) !== 'NRRD')
241
+ throw new LoaderError(F, 'header', 'missing the NRRD000x magic line');
242
+ const magicEnd = findLineEnd(bytes, 0, MAX_HEADER);
243
+ if (magicEnd < 0)
244
+ throw new LoaderError(F, 'truncated', 'the file ends after the magic line');
245
+ const magic = latin1(bytes, 0, magicEnd).replace(/\r$/, ''), numbered = /^NRRD000([1-5])$/.exec(magic);
246
+ if (!numbered && magic !== 'NRRD00.01')
247
+ throw new LoaderError(F, 'header', `the magic line "${magic.slice(0, 32)}" is not NRRD0001 to NRRD0005`);
248
+ const version = numbered ? Number(numbered[1]) : 1, fields = Object.create(null), known = Object.create(null), meta = Object.create(null), list = [];
249
+ let pos = magicEnd + 1, listing = false;
250
+ while (pos < bytes.length) {
251
+ const lineEnd = findLineEnd(bytes, pos, MAX_HEADER + 1), end = lineEnd < 0 ? bytes.length : lineEnd;
252
+ if (end > MAX_HEADER)
253
+ throw new LoaderError(F, 'limit', `the header is longer than ${MAX_HEADER} bytes`);
254
+ const line = latin1(bytes, pos, end).replace(/\r$/, '');
255
+ pos = end + 1;
256
+ if (line === '')
257
+ break;
258
+ if (listing) {
259
+ list.push(line.trim());
260
+ continue;
261
+ }
262
+ if (line[0] === '#')
263
+ continue;
264
+ const pair = line.indexOf(':='), colon = line.indexOf(': ');
265
+ if (pair > 0 && (colon < 0 || pair < colon)) {
266
+ if (version < 2)
267
+ throw new LoaderError(F, 'header', 'key/value pairs need NRRD0002 or later');
268
+ meta[unescape(line.slice(0, pair))] = unescape(line.slice(pair + 2));
269
+ continue;
270
+ }
271
+ if (colon <= 0)
272
+ throw new LoaderError(F, 'syntax', `bad header line "${line.slice(0, 64)}"`);
273
+ const name = line.slice(0, colon).toLowerCase(), first = ALIASES[name] ?? name, value = line.slice(colon + 2).trim();
274
+ if (first in known)
275
+ throw new LoaderError(F, 'syntax', `the field "${first.slice(0, 32)}" appears twice`);
276
+ if ((SINCE[first] ?? 1) > version)
277
+ throw new LoaderError(F, 'header', `the field "${first}" needs NRRD000${SINCE[first]} or later`);
278
+ if (PER_AXIS.has(first) && !('dimension' in known))
279
+ throw new LoaderError(F, 'syntax', `the field "${first}" comes before dimension`);
280
+ if (ORIENTATION.has(first) && !('space' in known) && !('space dimension' in known))
281
+ throw new LoaderError(F, 'syntax', `the field "${first}" comes before space or space dimension`);
282
+ fields[name] = value;
283
+ known[first] = value;
284
+ listing = first === 'data file' && value.split(/\s+/)[0] === 'LIST';
285
+ }
286
+ return { version, fields, known, meta, end: Math.min(pos, bytes.length), list };
287
+ }
288
+ /** One printf conversion of an int (C99 7.19.6.1): flags `-+ 0#`, a width, a precision, and `d i o u x X`. */
289
+ function printf(spec, value) {
290
+ const [, flags, widthText, precisionText, conversion] = spec, width = Number(widthText || 0), precision = precisionText === undefined ? undefined : Number(precisionText || 0), signed = conversion === 'd' || conversion === 'i', magnitude = signed ? Math.abs(value) : value >>> 0, hex = conversion === 'x' || conversion === 'X';
291
+ let digits = magnitude.toString(conversion === 'o' ? 8 : hex ? 16 : 10);
292
+ if (conversion === 'X')
293
+ digits = digits.toUpperCase();
294
+ if (precision !== undefined)
295
+ digits = precision === 0 && value === 0 ? '' : digits.padStart(precision, '0');
296
+ if (flags.includes('#') && conversion === 'o' && !digits.startsWith('0'))
297
+ digits = `0${digits}`;
298
+ const sign = !signed ? '' : value < 0 ? '-' : flags.includes('+') ? '+' : flags.includes(' ') ? ' ' : '', prefix = hex && flags.includes('#') && magnitude !== 0 ? `0${conversion}` : '', body = sign + prefix + digits;
299
+ if (body.length >= width)
300
+ return body;
301
+ if (flags.includes('-'))
302
+ return body.padEnd(width);
303
+ if (flags.includes('0') && precision === undefined)
304
+ return sign + prefix + digits.padStart(width - sign.length - prefix.length, '0');
305
+ return body.padStart(width);
306
+ }
307
+ /** Splits a `data file` pattern at its one integer conversion; `%%` is a literal percent sign. */
308
+ function pattern(format, value) {
309
+ const bad = () => new LoaderError(F, 'syntax', `bad data file pattern "${value.slice(0, 64)}"`), conversion = /%([-+ 0#]*)(\d{0,3})(?:\.(\d{0,3}))?([diouxX])/y;
310
+ let before = '', after = '', spec = null;
311
+ for (let i = 0; i < format.length; i++) {
312
+ if (format[i] === '%') {
313
+ if (format[i + 1] === '%')
314
+ i++;
315
+ else {
316
+ conversion.lastIndex = i;
317
+ const found = conversion.exec(format);
318
+ if (!found || spec)
319
+ throw bad();
320
+ spec = found;
321
+ i = conversion.lastIndex - 1;
322
+ continue;
323
+ }
324
+ }
325
+ if (spec)
326
+ after += format[i];
327
+ else
328
+ before += format[i];
329
+ }
330
+ if (!spec)
331
+ throw bad();
332
+ return { before, spec, after };
333
+ }
334
+ /** The data files of a detached header, empty for attached data, and the dimension of the data in each file. */
335
+ function dataFiles(header, dimension) {
336
+ const value = header.known['data file'], int32 = (n) => Number.isInteger(n) && n >= -(2 ** 31) && n < 2 ** 31;
337
+ if (value === undefined)
338
+ return { files: [], subdim: dimension };
339
+ const parts = value.split(/\s+/);
340
+ if (parts.length === 1 && parts[0] !== 'LIST')
341
+ return { files: parts, subdim: dimension };
342
+ if (header.version < 4)
343
+ throw new LoaderError(F, 'header', 'several data files need NRRD0004 or later');
344
+ const listed = parts[0] === 'LIST';
345
+ if (listed ? parts.length > 2 : parts.length !== 4 && parts.length !== 5)
346
+ throw new LoaderError(F, 'syntax', `bad data file pattern "${value.slice(0, 64)}"`);
347
+ const last = listed ? parts[1] : parts[4], subdim = last === undefined ? dimension - 1 : Number(last);
348
+ if (last !== undefined && !(Number.isInteger(subdim) && subdim >= 1 && subdim <= dimension))
349
+ throw new LoaderError(F, 'range', `data file subdim ${last.slice(0, 16)} is outside 1..${dimension}`);
350
+ if (listed) {
351
+ if (!header.list.length)
352
+ throw new LoaderError(F, 'syntax', 'data file: LIST names no files');
353
+ return { files: header.list, subdim };
354
+ }
355
+ const [format, ...numbers] = parts, [min, max, step] = numbers.map(Number), { before, spec, after } = pattern(format, value);
356
+ if (!int32(min) || !int32(max) || !int32(step) || !step)
357
+ throw new LoaderError(F, 'syntax', `bad data file pattern "${value.slice(0, 64)}"`);
358
+ if ((max - min) / step < 0 || (max - min) / step > 1_000_000)
359
+ throw new LoaderError(F, 'range', `data file pattern "${value.slice(0, 64)}" names no files or too many`);
360
+ const files = [];
361
+ for (let i = min; step > 0 ? i <= max : i >= max; i += step)
362
+ files.push(before + printf(spec, i) + after);
363
+ return { files, subdim };
364
+ }
365
+ function skipLines(bytes, lines) {
366
+ let pos = 0;
367
+ for (let i = 0; i < lines; i++) {
368
+ const end = findLineEnd(bytes, pos, bytes.length);
369
+ if (end < 0)
370
+ throw new LoaderError(F, 'truncated', `the data has fewer than ${lines} lines to skip`);
371
+ pos = end + 1;
372
+ }
373
+ return pos;
374
+ }
375
+ function swap(bytes, size) {
376
+ for (let i = 0; i + size <= bytes.length; i += size)
377
+ for (let a = i, b = i + size - 1; a < b; a++, b--) {
378
+ const t = bytes[a];
379
+ bytes[a] = bytes[b];
380
+ bytes[b] = t;
381
+ }
382
+ }
383
+ /** Writes `count` samples from native-order `bytes`, which own their buffer, into `out` at `offset`. */
384
+ function store(out, offset, bytes, type, count) {
385
+ if (type === 'int64' || type === 'uint64') {
386
+ const wide = type === 'int64' ? new BigInt64Array(bytes.buffer, 0, count) : new BigUint64Array(bytes.buffer, 0, count);
387
+ for (let i = 0; i < count; i++)
388
+ out[offset + i] = Number(wide[i]);
389
+ return;
390
+ }
391
+ const View = out.constructor;
392
+ out.set(new View(bytes.buffer, 0, count), offset);
393
+ }
394
+ function sample(word, floating) {
395
+ if (floating)
396
+ return float(word);
397
+ const value = Number(word);
398
+ if (Number.isSafeInteger(value))
399
+ return value;
400
+ throw new LoaderError(F, 'syntax', `invalid sample "${word.slice(0, 32)}"`);
401
+ }
402
+ function readText(text, out, offset, count, floating) {
403
+ const token = /[^\s,]+/g;
404
+ let i = 0;
405
+ for (let match = token.exec(text); match && i < count; match = token.exec(text), i++)
406
+ out[offset + i] = sample(match[0], floating);
407
+ if (i < count)
408
+ throw new LoaderError(F, 'truncated', `found ${i} samples, expected ${count}`);
409
+ }
410
+ function readHex(text, length) {
411
+ const out = new Uint8Array(length);
412
+ let filled = 0, high = -1;
413
+ for (let i = 0; i < text.length && filled < length; i++) {
414
+ const code = text.charCodeAt(i);
415
+ if (code === 32 || (code >= 9 && code <= 13))
416
+ continue;
417
+ const lower = code | 32, digit = code >= 48 && code <= 57 ? code - 48 : lower >= 97 && lower <= 102 ? lower - 87 : -1;
418
+ if (digit < 0)
419
+ throw new LoaderError(F, 'syntax', `invalid hex digit at character ${i}`);
420
+ if (high < 0)
421
+ high = digit;
422
+ else {
423
+ out[filled++] = high * 16 + digit;
424
+ high = -1;
425
+ }
426
+ }
427
+ if (filled < length)
428
+ throw new LoaderError(F, 'truncated', `found ${filled} bytes of hex, expected ${length}`);
429
+ return out;
430
+ }
431
+ const u32le = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0;
432
+ /**
433
+ * The first `size` bytes of gzip data. Each member (RFC 1952 2.2) is framed here and its DEFLATE data inflated a step
434
+ * at a time, stopping once `size` bytes are out: the rest of the stream, and anything after the last member, is ignored
435
+ * (section 5, "Data file contents remaining after all data has been read should be ignored"), and a small file cannot
436
+ * inflate to more than it needs. The runtime's 'gzip' decoder is not used: it refuses bytes after the last member and
437
+ * can drop the output of the step that holds them, so a valid stream followed by other data would not read.
438
+ */
439
+ async function gunzip(body, size, signal) {
440
+ if (typeof DecompressionStream !== 'function')
441
+ throw new LoaderError(F, 'unsupported', 'DecompressionStream is not available in this runtime');
442
+ const out = new Uint8Array(size), corrupt = (detail) => new LoaderError(F, 'zip', `the data has corrupt gzip data (${detail})`);
443
+ let at = 0, length = 0;
444
+ while (length < size) {
445
+ // After the first member, anything that is not another member is data past the stream, ignored.
446
+ if (at > 0 && (at + 1 >= body.length || body[at] !== 0x1f || body[at + 1] !== 0x8b))
447
+ break;
448
+ if (body[at] !== 0x1f || body[at + 1] !== 0x8b)
449
+ throw corrupt('no gzip header');
450
+ const flags = body[at + 3];
451
+ if (body[at + 2] !== 8 || flags & 0xe0)
452
+ throw corrupt('the method is not deflate or reserved flags are set');
453
+ let p = at + 10;
454
+ // FEXTRA (its length, then the field), FNAME and FCOMMENT (each up to a NUL), then FHCRC.
455
+ if (flags & 4)
456
+ p += 2 + (body[p] | (body[p + 1] << 8));
457
+ for (const flag of [8, 16]) {
458
+ if (!(flags & flag))
459
+ continue;
460
+ while (p < body.length && body[p] !== 0)
461
+ p++;
462
+ p++;
463
+ }
464
+ if (flags & 2) {
465
+ if ((crc32(body.subarray(at, p)) & 0xffff) !== (body[p] | (body[p + 1] << 8)))
466
+ throw corrupt('the header fails its CRC-16');
467
+ p += 2;
468
+ }
469
+ if (p >= body.length)
470
+ throw corrupt('the stream ends early');
471
+ // A file of one member ends with its trailer: feeding the DEFLATE data without those 8 bytes gives the decoder
472
+ // nothing past the stream's end, so no runtime fails on it. Other files fall back below.
473
+ const from = length, member = body.subarray(p), first = await inflateMember(at === 0 ? body.subarray(p, body.length - 8) : member, out, from, signal);
474
+ length = first.length;
475
+ if (length >= size)
476
+ break;
477
+ // The member ended before the samples did: find its trailer, the CRC-32 and size of what it gave.
478
+ let end = trailer(body, p, out.subarray(from, length)), failedAt = first.failedAt, step = FEED;
479
+ // A runtime that drops the output of the chunk holding the stream's end and the bytes after it (Firefox) gave
480
+ // less than the member holds. Inflate it again with that chunk fed in halves, then quarters, and so on, until the
481
+ // chunk that fails holds no byte of the stream and the trailer matches (KB5076): at most 16 more passes, only for data
482
+ // with more after a member.
483
+ while (end < 0 && failedAt >= 0 && step > 1) {
484
+ step >>= 1;
485
+ const again = await inflateMember(member, out, from, signal, failedAt, step);
486
+ length = again.length;
487
+ if (length >= size)
488
+ break;
489
+ end = trailer(body, p, out.subarray(from, length));
490
+ failedAt = again.failedAt;
491
+ }
492
+ if (length >= size)
493
+ break;
494
+ if (end < 0)
495
+ throw corrupt('a member has no matching CRC-32 and size trailer');
496
+ at = end + 8;
497
+ }
498
+ return out.subarray(0, length);
499
+ }
500
+ /** Where the 8-byte trailer (CRC-32, then size) of a member that gave `given` starts, from `p`, or -1. */
501
+ function trailer(body, p, given) {
502
+ const crc = crc32(given), isize = given.length % 2 ** 32;
503
+ for (let end = p; end + 8 <= body.length; end++)
504
+ if (u32le(body, end) === crc && u32le(body, end + 4) === isize)
505
+ return end;
506
+ return -1;
507
+ }
508
+ /**
509
+ * Inflates the DEFLATE data at the start of `data` into `out` from `length`, until `out` is full or the stream ends,
510
+ * and returns the new length and, when the decoder failed, where the chunk before the failing one started (-1 when it
511
+ * did not fail). Bytes after the end of the stream (the gzip trailer, what follows) make the decoder fail; Chromium and
512
+ * Node give that chunk's output first, Firefox does not, so from `fine` on the data is fed in chunks of `step` bytes,
513
+ * which the caller narrows until the failing chunk holds no byte of the stream. The caller's trailer check tells either
514
+ * failure apart from damage.
515
+ */
516
+ async function inflateMember(data, out, length, signal, fine = -1, step = FEED) {
517
+ let fed = 0, last = 0, before = 0;
518
+ const input = new ReadableStream({
519
+ pull(controller) {
520
+ if (fed >= data.length)
521
+ return controller.close();
522
+ const size = fine < 0 ? FEED : fed < fine ? Math.min(FEED, fine - fed) : step;
523
+ before = last;
524
+ last = fed;
525
+ controller.enqueue(data.subarray(fed, (fed += size)));
526
+ },
527
+ }, { highWaterMark: 0 });
528
+ const reader = input
529
+ .pipeThrough(new DecompressionStream('deflate-raw'))
530
+ .getReader();
531
+ let failedAt = -1;
532
+ try {
533
+ while (length < out.length) {
534
+ throwIfAborted(signal, F);
535
+ const { done, value } = await reader.read();
536
+ if (done)
537
+ break;
538
+ const take = Math.min(value.length, out.length - length);
539
+ out.set(value.subarray(0, take), length);
540
+ length += take;
541
+ }
542
+ }
543
+ catch (error) {
544
+ if (error instanceof LoaderError)
545
+ throw error;
546
+ // The pipe may have pulled one chunk ahead of the one that failed.
547
+ failedAt = before;
548
+ }
549
+ finally {
550
+ void reader.cancel().catch(() => { });
551
+ }
552
+ return { length, failedAt };
553
+ }
554
+ async function decode(file, out, offset, count, how) {
555
+ const { type, encoding, byteSkip } = how, size = SIZE[type], length = count * size;
556
+ // With byte skip -1 the data is found from the end of the file, so line skip is moot (section 5).
557
+ let body = file.subarray(byteSkip === -1 ? 0 : skipLines(file, how.lineSkip));
558
+ if (encoding === 'ascii') {
559
+ readText(latin1(body, byteSkip), out, offset, count, type === 'float32' || type === 'float64');
560
+ return;
561
+ }
562
+ let raw;
563
+ if (encoding === 'hex')
564
+ raw = readHex(latin1(body, byteSkip), length);
565
+ else {
566
+ if (encoding === 'gzip')
567
+ body = await gunzip(body, length + byteSkip, how.signal);
568
+ else if (encoding === 'bzip2')
569
+ body = await bunzip(body, length + Math.max(byteSkip, 0));
570
+ const start = byteSkip < 0 ? body.length - length : byteSkip;
571
+ if (start < 0 || start + length > body.length)
572
+ throw new LoaderError(F, 'truncated', `the data has ${body.length} bytes, expected ${length}`);
573
+ // A copy, never `slice`: on a Node Buffer that is a view of a shared pool, and `store` reads the buffer from 0.
574
+ raw = new Uint8Array(length);
575
+ raw.set(body.subarray(start, start + length));
576
+ }
577
+ if (how.swapped)
578
+ swap(raw, size);
579
+ store(out, offset, raw, type, count);
580
+ }
581
+ function layout(fields, sizes) {
582
+ const dimension = sizes.length, named = fields.space === undefined ? undefined : SPACES[fields.space.toLowerCase()];
583
+ if (fields.space !== undefined && !named)
584
+ throw new LoaderError(F, 'header', `unknown space "${fields.space.slice(0, 32)}"`);
585
+ const space = named?.[0];
586
+ if (space && fields['space dimension'] !== undefined)
587
+ throw new LoaderError(F, 'syntax', 'a file gives space or space dimension, never both');
588
+ const spaceDimension = integer(fields['space dimension'], 'space dimension', named ? named[1] : 0);
589
+ if (spaceDimension < 0 || spaceDimension > MAX_DIMENSION)
590
+ throw new LoaderError(F, 'range', `space dimension ${spaceDimension} is out of range`);
591
+ let directions;
592
+ if (fields['space directions'] !== undefined) {
593
+ if (!spaceDimension)
594
+ throw new LoaderError(F, 'syntax', 'space directions need a space');
595
+ directions = vectors(fields['space directions'], 'space directions', spaceDimension);
596
+ if (directions.length !== dimension)
597
+ throw new LoaderError(F, 'syntax', `space directions has ${directions.length} entries for ${dimension} axes`);
598
+ }
599
+ const kinds = fields.kinds
600
+ ?.trim()
601
+ .toLowerCase()
602
+ .split(/[ \t]+/);
603
+ if (kinds && kinds.length !== dimension)
604
+ throw new LoaderError(F, 'syntax', `kinds has ${kinds.length} entries for ${dimension} axes`);
605
+ kinds?.forEach((kind, axis) => {
606
+ const size = KINDS[kind];
607
+ if (size === undefined)
608
+ throw new LoaderError(F, 'syntax', `unknown kind "${kind.slice(0, 32)}"`);
609
+ if (size && sizes[axis] !== size)
610
+ throw new LoaderError(F, 'range', `axis ${axis} of kind ${kind} has size ${sizes[axis]}, not ${size}`);
611
+ });
612
+ // A space direction and a known spacing, axis min or axis max on the same axis exclude each other (section 4).
613
+ const spacings = fields.spacings === undefined ? undefined : doubles(fields.spacings, 'spacings', dimension);
614
+ if (spacings?.includes(0))
615
+ throw new LoaderError(F, 'range', 'spacings holds a zero');
616
+ for (const name of ['spacings', 'axis mins', 'axis maxs']) {
617
+ const values = name === 'spacings' ? spacings : fields[name] === undefined ? undefined : doubles(fields[name], name, dimension);
618
+ const axis = values?.findIndex((value, i) => !Number.isNaN(value) && directions?.[i]) ?? -1;
619
+ if (axis >= 0)
620
+ throw new LoaderError(F, 'syntax', `axis ${axis} has both a space direction and ${name}`);
621
+ }
622
+ const spatial = (axis) => {
623
+ const kind = kinds?.[axis];
624
+ if (directions)
625
+ return directions[axis] !== null && kind !== 'time';
626
+ return kind === undefined || kind === 'domain' || kind === 'space' || kind === 'none' || kind === '???';
627
+ };
628
+ let first = 0, components = 1;
629
+ while (first < dimension && !spatial(first))
630
+ components *= sizes[first++];
631
+ const axes = [];
632
+ for (let axis = first; axis < dimension && axes.length < 3 && spatial(axis); axis++)
633
+ axes.push(axis);
634
+ let frames = 1;
635
+ for (let axis = first + axes.length; axis < dimension; axis++)
636
+ frames *= sizes[axis];
637
+ let origin = null;
638
+ if (fields['space origin'] !== undefined) {
639
+ const found = vectors(fields['space origin'], 'space origin', spaceDimension);
640
+ if (found.length !== 1 || !found[0])
641
+ throw new LoaderError(F, 'syntax', 'space origin must be one vector');
642
+ origin = found[0];
643
+ }
644
+ const dims = [1, 1, 1], spacing = [1, 1, 1], matrix = new Float64Array(16);
645
+ matrix[15] = 1;
646
+ for (let k = 0; k < 3; k++) {
647
+ const axis = axes[k], direction = axis === undefined ? undefined : directions?.[axis];
648
+ if (axis !== undefined)
649
+ dims[k] = sizes[axis];
650
+ if (direction) {
651
+ const length = Math.hypot(...direction);
652
+ if (!(length > 0))
653
+ throw new LoaderError(F, 'range', `space direction of axis ${axis} has no length`);
654
+ spacing[k] = length;
655
+ for (let row = 0; row < 3; row++)
656
+ matrix[k * 4 + row] = direction[row] ?? 0;
657
+ continue;
658
+ }
659
+ const step = axis === undefined ? undefined : spacings?.[axis], usable = step !== undefined && !Number.isNaN(step);
660
+ if (usable)
661
+ spacing[k] = Math.abs(step);
662
+ matrix[k * 5] = usable ? step : 1;
663
+ }
664
+ for (let row = 0; row < 3; row++)
665
+ matrix[12 + row] = origin?.[row] ?? 0;
666
+ const result = {
667
+ dims,
668
+ components,
669
+ frames,
670
+ spacing,
671
+ bounds: [0, (dims[0] - 1) * spacing[0], 0, (dims[1] - 1) * spacing[1], 0, (dims[2] - 1) * spacing[2]],
672
+ matrix,
673
+ };
674
+ if (space)
675
+ result.space = space;
676
+ return result;
677
+ }
678
+ /**
679
+ * Reads a NRRD volume from a `.nrrd` file, or a `.nhdr` header with its detached data through `resolve`. Encodings are
680
+ * raw, ascii, hex, gzip and bzip2, with either byte order, `line skip` and `byte skip` (-1 for the end of a raw file)
681
+ * and one or many data files (a printf pattern or a `LIST`, with `subdim`). Data past what the header needs is
682
+ * ignored, and gzip decoding stops there. `space directions`, `space origin`, `spacings` and `kinds` set `dims`, `spacing`, `bounds` and
683
+ * `matrix`; a leading non-spatial axis is `components` and trailing ones are `frames`. A `block` file gives its blocks
684
+ * as bytes with `blockSize`; its encoding cannot be ascii (the format defines no text form for a block) and its bytes
685
+ * are never swapped.
686
+ *
687
+ * @param input The file's bytes.
688
+ * @param options A resolver for detached data, the sample limit and an AbortSignal.
689
+ * @returns The samples in the file's own type and where they sit.
690
+ * @throws LoaderError with code `header`, `syntax`, `truncated`, `range`, `limit`, `aborted`, `zip` or `unsupported`
691
+ * (detached data without `resolve`).
692
+ *
693
+ * @example
694
+ * ```ts
695
+ * import { parseNRRD } from '@margoengine/loaders/nrrd';
696
+ *
697
+ * const header = 'NRRD0004\ntype: uint8\ndimension: 3\nsizes: 2 1 1\nspacings: 2 1 1\nencoding: ascii\n\n';
698
+ * const { data, dims, bounds } = await parseNRRD(new TextEncoder().encode(`${header}10 20\n`));
699
+ * console.log(data, dims, bounds);
700
+ * ```
701
+ */
702
+ export async function parseNRRD(input, options = {}) {
703
+ const bytes = toBytes(input, F), { resolve, signal } = options, maxSamples = options.maxSamples ?? 2 ** 29;
704
+ throwIfAborted(signal, F);
705
+ if (!Number.isSafeInteger(maxSamples) || maxSamples < 0)
706
+ throw new LoaderError(F, 'range', 'maxSamples must be a non-negative integer');
707
+ const header = readHeader(bytes), { fields, known, meta } = header;
708
+ const missing = ['type', 'dimension', 'sizes', 'encoding'].find((name) => !(name in known));
709
+ if (missing)
710
+ throw new LoaderError(F, 'header', `the required field "${missing}" is missing`);
711
+ const block = fields.type.toLowerCase() === 'block', type = block ? 'uint8' : TYPES[fields.type.toLowerCase()];
712
+ if (!type)
713
+ throw new LoaderError(F, 'header', `unknown type "${fields.type.slice(0, 32)}"`);
714
+ const named = fields.encoding.toLowerCase();
715
+ const encoding = ENCODINGS[named];
716
+ if (!encoding)
717
+ throw new LoaderError(F, 'header', `unknown encoding "${fields.encoding.slice(0, 32)}"`);
718
+ const dimension = integer(fields.dimension, 'dimension', 0);
719
+ if (dimension < 1 || dimension > MAX_DIMENSION)
720
+ throw new LoaderError(F, 'range', `dimension ${dimension} is outside 1..${MAX_DIMENSION}`);
721
+ const sizes = integers(fields.sizes, 'sizes');
722
+ if (sizes.length !== dimension)
723
+ throw new LoaderError(F, 'syntax', `sizes has ${sizes.length} entries for ${dimension} axes`);
724
+ let total = 1;
725
+ for (const size of sizes) {
726
+ if (size < 1)
727
+ throw new LoaderError(F, 'range', `axis size ${size} is below 1`);
728
+ total *= size;
729
+ if (total > maxSamples)
730
+ throw new LoaderError(F, 'limit', `the array exceeds the limit of ${maxSamples} samples`);
731
+ }
732
+ const blockSize = block ? integer(known['block size'], 'block size', 0) : 1;
733
+ if (block) {
734
+ if (known['block size'] === undefined)
735
+ throw new LoaderError(F, 'header', 'the required field "block size" is missing');
736
+ if (blockSize < 1)
737
+ throw new LoaderError(F, 'range', `block size ${blockSize} is below 1`);
738
+ if (encoding === 'ascii')
739
+ throw new LoaderError(F, 'header', 'block data cannot be ascii');
740
+ // The same memory bound as the widest numeric type: 8 bytes a sample.
741
+ if (total * blockSize > maxSamples * 8)
742
+ throw new LoaderError(F, 'limit', `the blocks exceed ${maxSamples * 8} bytes (8 per sample of maxSamples)`);
743
+ }
744
+ const endian = fields.endian?.toLowerCase();
745
+ if (endian !== undefined && endian !== 'little' && endian !== 'big')
746
+ throw new LoaderError(F, 'header', `unknown endian "${endian.slice(0, 32)}"`);
747
+ if (endian === undefined && SIZE[type] > 1 && encoding !== 'ascii')
748
+ throw new LoaderError(F, 'header', 'the required field "endian" is missing');
749
+ const lineSkip = integer(known['line skip'], 'line skip', 0), byteSkip = integer(known['byte skip'], 'byte skip', 0);
750
+ if (lineSkip < 0)
751
+ throw new LoaderError(F, 'range', `line skip ${lineSkip} is negative`);
752
+ if (byteSkip < -1 || (byteSkip === -1 && encoding !== 'raw'))
753
+ throw new LoaderError(F, 'range', `byte skip ${byteSkip} is not allowed with ${encoding} data`);
754
+ const placed = layout(known, sizes);
755
+ const elements = total * blockSize, data = allocate(type, elements), how = {
756
+ type,
757
+ encoding,
758
+ swapped: !block && endian !== undefined && (endian === 'little') !== LITTLE,
759
+ lineSkip,
760
+ byteSkip,
761
+ signal,
762
+ }, { files, subdim } = dataFiles(header, dimension);
763
+ if (!files.length)
764
+ await decode(bytes.subarray(header.end), data, 0, elements, how);
765
+ else {
766
+ if (!resolve)
767
+ throw new LoaderError(F, 'unsupported', `the data is in "${files[0].slice(0, 64)}"; pass a resolve option`);
768
+ // Each file holds the first `subdim` axes and the axes after them count the files; with subdim equal to the
769
+ // dimension the files are equal slabs cut along the slowest axis (section 3).
770
+ let expected = 1;
771
+ for (let axis = subdim; axis < dimension; axis++)
772
+ expected *= sizes[axis];
773
+ const fits = subdim === dimension ? sizes[dimension - 1] % files.length === 0 : files.length === expected;
774
+ if (!fits)
775
+ throw new LoaderError(F, 'range', `${files.length} data files do not fit sizes ${sizes.join(' ')} with subdim ${subdim}`);
776
+ const each = elements / files.length;
777
+ for (let i = 0; i < files.length; i++) {
778
+ throwIfAborted(signal, F);
779
+ const content = await resolve(resolvePath('', files[i]));
780
+ const file = typeof content === 'string' ? new TextEncoder().encode(content) : content;
781
+ await decode(file, data, i * each, each, how);
782
+ }
783
+ }
784
+ return { data, type: block ? 'block' : type, ...(block ? { blockSize } : {}), sizes, ...placed, fields, meta };
785
+ }