@topolab/tda 0.0.0-stage → 0.4.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 (105) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/CITATION.cff +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +100 -2
  5. package/SECURITY.md +34 -0
  6. package/THIRD_PARTY_LICENSES.md +697 -0
  7. package/dist/arrangement.d.ts +50 -0
  8. package/dist/arrangement.d.ts.map +1 -0
  9. package/dist/arrangement.js +63 -0
  10. package/dist/arrangement.js.map +1 -0
  11. package/dist/build_info.json +12 -0
  12. package/dist/check.d.ts +118 -0
  13. package/dist/check.d.ts.map +1 -0
  14. package/dist/check.js +298 -0
  15. package/dist/check.js.map +1 -0
  16. package/dist/complex.d.ts +543 -0
  17. package/dist/complex.d.ts.map +1 -0
  18. package/dist/complex.js +712 -0
  19. package/dist/complex.js.map +1 -0
  20. package/dist/diagram.d.ts +116 -0
  21. package/dist/diagram.d.ts.map +1 -0
  22. package/dist/diagram.js +238 -0
  23. package/dist/diagram.js.map +1 -0
  24. package/dist/diagram_of.d.ts +17 -0
  25. package/dist/diagram_of.d.ts.map +1 -0
  26. package/dist/diagram_of.js +40 -0
  27. package/dist/diagram_of.js.map +1 -0
  28. package/dist/experimental.d.ts +18 -0
  29. package/dist/experimental.d.ts.map +1 -0
  30. package/dist/experimental.js +16 -0
  31. package/dist/experimental.js.map +1 -0
  32. package/dist/flat.d.ts +64 -0
  33. package/dist/flat.d.ts.map +1 -0
  34. package/dist/flat.js +158 -0
  35. package/dist/flat.js.map +1 -0
  36. package/dist/index.d.ts +42 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +31 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/ladder/tda_ladder.d.ts +223 -0
  41. package/dist/ladder/tda_ladder.js +1360 -0
  42. package/dist/ladder/tda_ladder_bg.wasm +0 -0
  43. package/dist/ladder/tda_ladder_bg.wasm.d.ts +43 -0
  44. package/dist/ladder.d.ts +306 -0
  45. package/dist/ladder.d.ts.map +1 -0
  46. package/dist/ladder.js +607 -0
  47. package/dist/ladder.js.map +1 -0
  48. package/dist/load.d.ts +53 -0
  49. package/dist/load.d.ts.map +1 -0
  50. package/dist/load.js +173 -0
  51. package/dist/load.js.map +1 -0
  52. package/dist/memory.d.ts +58 -0
  53. package/dist/memory.d.ts.map +1 -0
  54. package/dist/memory.js +2 -0
  55. package/dist/memory.js.map +1 -0
  56. package/dist/persistence.d.ts +349 -0
  57. package/dist/persistence.d.ts.map +1 -0
  58. package/dist/persistence.js +478 -0
  59. package/dist/persistence.js.map +1 -0
  60. package/dist/pkg/tda_wasm.d.ts +13 -0
  61. package/dist/pkg/tda_wasm.js +2528 -0
  62. package/dist/prepared.d.ts +62 -0
  63. package/dist/prepared.d.ts.map +1 -0
  64. package/dist/prepared.js +81 -0
  65. package/dist/prepared.js.map +1 -0
  66. package/dist/rivet_input.d.ts +93 -0
  67. package/dist/rivet_input.d.ts.map +1 -0
  68. package/dist/rivet_input.js +132 -0
  69. package/dist/rivet_input.js.map +1 -0
  70. package/dist/source.d.ts +43 -0
  71. package/dist/source.d.ts.map +1 -0
  72. package/dist/source.js +99 -0
  73. package/dist/source.js.map +1 -0
  74. package/dist/tda.wasm +0 -0
  75. package/dist/two_parameter.d.ts +243 -0
  76. package/dist/two_parameter.d.ts.map +1 -0
  77. package/dist/two_parameter.js +275 -0
  78. package/dist/two_parameter.js.map +1 -0
  79. package/dist/types.d.ts +146 -0
  80. package/dist/types.d.ts.map +1 -0
  81. package/dist/types.js +2 -0
  82. package/dist/types.js.map +1 -0
  83. package/dist/vineyard.d.ts +278 -0
  84. package/dist/vineyard.d.ts.map +1 -0
  85. package/dist/vineyard.js +236 -0
  86. package/dist/vineyard.js.map +1 -0
  87. package/package.json +77 -4
  88. package/src/arrangement.ts +96 -0
  89. package/src/check.ts +338 -0
  90. package/src/complex.ts +1179 -0
  91. package/src/diagram.ts +299 -0
  92. package/src/diagram_of.ts +40 -0
  93. package/src/experimental.ts +17 -0
  94. package/src/flat.ts +204 -0
  95. package/src/index.ts +181 -0
  96. package/src/ladder.ts +903 -0
  97. package/src/load.ts +201 -0
  98. package/src/memory.ts +58 -0
  99. package/src/persistence.ts +752 -0
  100. package/src/prepared.ts +111 -0
  101. package/src/rivet_input.ts +195 -0
  102. package/src/source.ts +132 -0
  103. package/src/two_parameter.ts +480 -0
  104. package/src/types.ts +163 -0
  105. package/src/vineyard.ts +463 -0
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Prepared complexes: a native snapshot of a complex that answers repeated
3
+ * persistence queries. Exported only from `@topolab/tda/experimental`.
4
+ */
5
+ import { call, module, onUnload } from './load.js';
6
+ import { coeff as checkCoeff, minPersistence as checkMinPersistence, options } from './check.js';
7
+ import { complexArgs, PERSISTENCE_KEYS } from './persistence.js';
8
+ import type { PersistenceOptions } from './persistence.js';
9
+ import { diagramOf } from './diagram_of.js';
10
+ import type { ComplexLike, Diagram, Scale } from './types.js';
11
+
12
+ /**
13
+ * A complex validated, copied and prepared once by {@link prepareComplex}
14
+ * (canonical simplex order and boundary indices held in the module's memory),
15
+ * answering {@link PreparedComplex.persistence} without repeating that work.
16
+ * The object is frozen.
17
+ */
18
+ export interface PreparedComplex {
19
+ /** The number of simplices of the snapshot. */
20
+ readonly size: number;
21
+ /** The scale of the snapshot's values, copied from the input (`'value'` when it had none). */
22
+ readonly scale: Scale;
23
+ /** `true` once {@link PreparedComplex.dispose} or `unload()` has released the native snapshot. */
24
+ readonly disposed: boolean;
25
+ /**
26
+ * The persistence diagram of the snapshot: the same arrays, in the same
27
+ * order, as `persistence(complex, opts)` of the complex as it was when it
28
+ * was prepared. Every call runs the reduction; no diagram is cached. The
29
+ * result is a plain copy that owns no wasm memory: it stays valid after
30
+ * disposal and after `unload()`, and survives `postMessage`. Throws an
31
+ * `Error` once the handle is disposed; a bad option throws as
32
+ * `persistence` does (`TypeError` or `RangeError`).
33
+ */
34
+ persistence(opts?: PersistenceOptions): Diagram;
35
+ /**
36
+ * Releases the native snapshot. Idempotent: a second call does nothing.
37
+ * Call it when done; until then the handle is held by the module's
38
+ * cleanup list, so dropping the last reference does not free it before
39
+ * `unload()`.
40
+ */
41
+ dispose(): void;
42
+ }
43
+
44
+ /**
45
+ * **Experimental.** Validate, copy and prepare `complex` once, for repeated
46
+ * persistence queries (other fields, other `minPersistence` cutoffs). The
47
+ * checks are those of `persistence`: a complex that `persistence` refuses,
48
+ * `prepareComplex` refuses with the same error, and no handle is created.
49
+ *
50
+ * Ownership:
51
+ * - The snapshot is a copy: changing the input arrays afterwards does not
52
+ * change it. A changed topology or filtration needs a new handle.
53
+ * - Every diagram is an independent copy and remains valid after disposal
54
+ * or `unload()`; diagrams can be sent through `postMessage`.
55
+ * - The handle belongs to the module instance (one per thread) that made it
56
+ * and cannot be transferred or cloned. Another worker prepares its own
57
+ * snapshot from the plain complex.
58
+ * - `dispose()` is idempotent; `persistence` on a disposed handle throws an
59
+ * `Error`.
60
+ * - `unload()` disposes every outstanding handle, and a later `load()` never
61
+ * revives one. So does a trap of the module (a call that runs out of
62
+ * memory), which replaces its instance. Undisposed handles stay allocated until `unload()`, so dispose
63
+ * each one explicitly.
64
+ * - Native allocations are freed on disposal, but the wasm linear memory
65
+ * does not shrink: its high-water mark stays until the module is unloaded
66
+ * and collected.
67
+ *
68
+ * The ordinary `persistence(complex)` stays stateless; nothing here caches a
69
+ * caller's object or a result.
70
+ */
71
+ export function prepareComplex(complex: ComplexLike): PreparedComplex {
72
+ module();
73
+ const c = complexArgs(complex, 'complex');
74
+ const { top, scale } = c;
75
+ // The native object stays in this closure: no pointer is exposed that could
76
+ // be forged or used after its module is unloaded.
77
+ let raw = call('prepareComplex', (m) => new m.PreparedComplex(c.vertices, c.offsets, c.filtrations));
78
+ let unregister: (() => void) | undefined;
79
+ // After a trap the instance may be mid-operation (wasm-bindgen's borrow of
80
+ // this handle never released): the handle is abandoned with the instance
81
+ // it belongs to, never freed in it. `__destroy_into_raw()` (wasm-bindgen's
82
+ // generated class, JavaScript only) zeroes the object's pointer and
83
+ // unregisters its finalizer, which would otherwise call into the trapped
84
+ // instance on a later garbage collection.
85
+ const release = (trapped: boolean) => {
86
+ if (raw === null) return;
87
+ const owned = raw;
88
+ raw = null;
89
+ unregister?.();
90
+ unregister = undefined;
91
+ if (trapped) owned.__destroy_into_raw();
92
+ else owned.delete();
93
+ };
94
+ const dispose = () => release(false);
95
+ unregister = onUnload(release);
96
+ return Object.freeze({
97
+ size: c.filtrations.length,
98
+ scale,
99
+ get disposed() {
100
+ return raw === null;
101
+ },
102
+ persistence(opts?: PersistenceOptions): Diagram {
103
+ if (raw === null) throw new Error('prepared complex has been disposed');
104
+ const o = options<PersistenceOptions>(opts, 'PreparedComplex.persistence', PERSISTENCE_KEYS);
105
+ const coeff = checkCoeff(o.coeff);
106
+ const minPersistence = checkMinPersistence(o.minPersistence);
107
+ return call('prepareComplex', () => diagramOf(raw!.persistence(coeff), top, scale, coeff, minPersistence));
108
+ },
109
+ dispose
110
+ });
111
+ }
@@ -0,0 +1,195 @@
1
+ /**
2
+ * RIVET input data files, the input format RIVET 1.1's documentation
3
+ * specifies, read into plain data, and the module a file describes. The
4
+ * Rust crate reads them (`parse_rivet_input` and `rivet_presentation` in
5
+ * `rust/tda-core/src/two_parameter/rivet.rs`); these functions check their
6
+ * arguments and shape the result. A file holds one of six kinds of data (a
7
+ * point cloud, a point cloud with a function, a metric space, a metric
8
+ * space with a function, a bifiltration or a short chain complex), with
9
+ * the flags that tell RIVET how to build a bifiltration from it.
10
+ *
11
+ * A line that starts with `#` is a comment and a blank line is ignored.
12
+ * A line that starts with `--` is a flag, `--name value`, the value the
13
+ * rest of the line (`true` when the flag has none); a repeated flag keeps
14
+ * its last line. Where the documentation allows commas, numbers are
15
+ * separated by spaces or commas; the bifiltration and firep formats
16
+ * separate their numbers by spaces only. Whitespace is JavaScript's (`\s`).
17
+ *
18
+ * A file that does not follow the documentation is refused with a
19
+ * `TypeError` (a value of the wrong kind, such as a token that is not a
20
+ * number) or a `RangeError` (a wrong count, an index out of range, an
21
+ * unknown `--datatype`), and every message names the 1-based line the
22
+ * error is on.
23
+ */
24
+ import { int, kind, options } from './check.js';
25
+ import { call, module } from './load.js';
26
+ import type { Keys, PointCloud } from './check.js';
27
+ import type { DistanceMatrix } from './types.js';
28
+ import { presentationOf } from './two_parameter.js';
29
+ import type { Bifiltration, Firep, Presentation } from './two_parameter.js';
30
+
31
+ /**
32
+ * One RIVET input data file as plain data. The kind of file decides which
33
+ * fields are present: `points` a cloud, `points_fn` values and a cloud,
34
+ * `metric` a distance matrix, `metric_fn` values and a distance matrix,
35
+ * `bifiltration` a bifiltration, `firep` a chain complex.
36
+ */
37
+ export interface RivetInput {
38
+ /** The kind of data, from `--datatype`; `points` when the flag is absent. */
39
+ datatype: 'points' | 'points_fn' | 'metric' | 'metric_fn' | 'bifiltration' | 'firep';
40
+ /** Every flag of the file: `--name value` as `name` -> value, a flag with no value as `true`. */
41
+ flags: Record<string, string | true>;
42
+ /** `points` and `points_fn`: the cloud. */
43
+ points?: PointCloud;
44
+ /** `metric` and `metric_fn`: the full `n x n` matrix, row-major (the upper-triangular form expanded). */
45
+ distances?: DistanceMatrix;
46
+ /** `points_fn` and `metric_fn`: the function values, one per point. */
47
+ values?: Float64Array;
48
+ /** `--maxdist` as a number; `Infinity` when the flag is absent. */
49
+ maxDistance: number;
50
+ /**
51
+ * `bifiltration`: the simplices as cells, in the file's order, every
52
+ * facet a cell of the file; `gradeOffsets` when any simplex has several
53
+ * grades. With `--xreverse` (`--yreverse`) the x (y) coordinate of every
54
+ * grade is negated, so that the result is an increasing bifiltration.
55
+ */
56
+ bifiltration?: Bifiltration;
57
+ /** `firep`: the chain complex `C2 -> C1 -> C0` over Z/2, both maps as CSR arrays. */
58
+ firep?: Firep;
59
+ }
60
+
61
+ /** What the module's `rivetInputFlat` returns: the data of the file's kind as flat arrays. */
62
+ interface RawInput {
63
+ datatype: RivetInput['datatype'];
64
+ flags: [string, string | true][];
65
+ maxDistance: number;
66
+ coords?: Float64Array;
67
+ d?: number;
68
+ distances?: Float64Array;
69
+ values?: Float64Array;
70
+ dims?: Uint8Array;
71
+ grades?: Float64Array;
72
+ offsets?: Uint32Array;
73
+ facets?: Uint32Array;
74
+ gradeOffsets?: Uint32Array;
75
+ highGrades?: Float64Array;
76
+ highOffsets?: Uint32Array;
77
+ highRows?: Uint32Array;
78
+ lowGrades?: Float64Array;
79
+ lowOffsets?: Uint32Array;
80
+ lowRows?: Uint32Array;
81
+ lowRank?: number;
82
+ }
83
+
84
+ /** The file's text as the UTF-8 bytes the module reads (a lone surrogate as U+FFFD). */
85
+ const encoder = new TextEncoder();
86
+
87
+ function textOf(v: unknown): Uint8Array {
88
+ if (typeof v !== 'string') throw new TypeError(`text must be a string, got ${kind(v)}`);
89
+ return encoder.encode(v);
90
+ }
91
+
92
+ /** The module's result as a {@link RivetInput}, its fields in the order of the kind. */
93
+ function inputOf(raw: RawInput): RivetInput {
94
+ const r = { datatype: raw.datatype, flags: Object.fromEntries(raw.flags) } as RivetInput;
95
+ switch (raw.datatype) {
96
+ case 'points':
97
+ case 'points_fn':
98
+ r.points = { coords: raw.coords!, d: raw.d! };
99
+ break;
100
+ case 'metric':
101
+ case 'metric_fn':
102
+ r.distances = { distances: raw.distances! };
103
+ break;
104
+ case 'bifiltration': {
105
+ const b: Bifiltration = { dims: raw.dims!, grades: raw.grades!, offsets: raw.offsets!, facets: raw.facets! };
106
+ if (raw.gradeOffsets !== undefined) b.gradeOffsets = raw.gradeOffsets;
107
+ r.bifiltration = b;
108
+ break;
109
+ }
110
+ case 'firep':
111
+ r.firep = {
112
+ high: { grades: raw.highGrades!, offsets: raw.highOffsets!, rows: raw.highRows! },
113
+ low: { grades: raw.lowGrades!, offsets: raw.lowOffsets!, rows: raw.lowRows! },
114
+ lowRank: raw.lowRank!
115
+ };
116
+ break;
117
+ }
118
+ if (raw.values !== undefined) r.values = raw.values;
119
+ r.maxDistance = raw.maxDistance;
120
+ return r;
121
+ }
122
+
123
+ /**
124
+ * Reads the text of a RIVET input data file into plain data, as
125
+ * {@link RivetInput}. The six kinds of file of RIVET 1.1 are read:
126
+ * `points`, `points_fn`, `metric`, `metric_fn`, `bifiltration`
127
+ * (multicritical allowed) and `firep`; `--datatype` selects the kind and
128
+ * `points` when the flag is absent. A distance matrix is read in either of
129
+ * the two forms the documentation gives, and the upper-triangular one is
130
+ * expanded to the full symmetric matrix. A bifiltration keeps the file's
131
+ * simplex order, and every facet must itself be listed as a simplex, on
132
+ * any line of the file; with `--xreverse` (`--yreverse`) the x (y)
133
+ * coordinate of every grade is negated, so that the result is an
134
+ * increasing bifiltration. The grades of a firep are as the file gives
135
+ * them; a firep's reverse flags are kept in `flags` only. The Rust crate
136
+ * reads the file (`parse_rivet_input`), so it needs the module.
137
+ */
138
+ export function parseRivetInput(text: string): RivetInput {
139
+ module();
140
+ const bytes = textOf(text);
141
+ return call('parseRivetInput', (m) => inputOf(m.rivetInputFlat(bytes) as RawInput));
142
+ }
143
+
144
+ /** Options of {@link rivetPresentation}. */
145
+ export interface RivetPresentationOptions {
146
+ /** Homology degree, a non-negative integer (RIVET's `--homology`). Default 0, as in RIVET. */
147
+ degree?: number;
148
+ }
149
+ const RIVET_PRESENTATION_KEYS: Keys<RivetPresentationOptions> = { degree: true };
150
+
151
+ /**
152
+ * The minimal presentation of the module the RIVET input file `text`
153
+ * describes, in degree `degree`, built as RIVET 1.1 builds it (by the Rust
154
+ * crate's `rivet_presentation`):
155
+ *
156
+ * - A point cloud or a metric space with function values (`points_fn`,
157
+ * `metric_fn`) gives the function-Rips bifiltration
158
+ * (`functionRipsPresentation`); `--xreverse` filters by decreasing value
159
+ * (the values negated), and `--bifil degree` gives the degree-Rips
160
+ * bifiltration instead.
161
+ * - Without function values (`points`, `metric`) it is the degree-Rips
162
+ * bifiltration (`degreeRipsPresentation`, whose first coordinate is minus
163
+ * the degree); `--bifil function` gives the function-Rips bifiltration of
164
+ * `balldensity[]`, by decreasing value.
165
+ * - `--function balldensity[r]`, `gaussian[σ]` or `eccentricity[p]`
166
+ * computes the function on the points or the metric space (values in the
167
+ * file are not used) and gives its function-Rips bifiltration, whatever
168
+ * `--bifil` says: the ball density `C·#{y : d(x, y) <= r}`, the Gaussian
169
+ * density `C·Σ_y exp(−d(x, y)²/(2σ²))` (`C` makes the values sum to 1) and
170
+ * the eccentricity `(Σ_y d(x, y)^p / n)^(1/p)`. Empty brackets take
171
+ * RIVET's defaults: `r` and `σ` RIVET 1.1's 20th percentile of the
172
+ * distances (entry `⌊M/5⌋ − 1` of the distances of all `M` pairs in
173
+ * increasing order, coincident points' zeros counted; 0 when `M < 5`, and
174
+ * then a point's density counts the points that coincide with it), and
175
+ * `p = 1`. `p` may be any real number at least 1, as RIVET's documentation
176
+ * defines it (RIVET 1.1 truncates it to an integer). The filtration is by
177
+ * decreasing value, with or without `--xreverse`, as RIVET's documentation
178
+ * sets it.
179
+ * - A bifiltration gives `bifiltrationPresentation`, a FIRep
180
+ * `firepPresentation`.
181
+ *
182
+ * Rips bifiltrations go up to `--maxdist`. The file is refused as
183
+ * {@link parseRivetInput} refuses it; `--function user` on a file without
184
+ * function values, a `--function` of another form, `--yreverse` on a Rips
185
+ * bifiltration, a negative `--maxdist` on one and a negative distance are
186
+ * refused with a `RangeError`, as is what the builder refuses. To read the
187
+ * file's data, use {@link parseRivetInput}.
188
+ */
189
+ export function rivetPresentation(text: string, opts?: RivetPresentationOptions): Presentation {
190
+ module();
191
+ const bytes = textOf(text);
192
+ const o = options<RivetPresentationOptions>(opts, 'rivetPresentation', RIVET_PRESENTATION_KEYS);
193
+ const degree = o.degree === undefined ? 0 : int(o.degree, 'degree', 0, 254);
194
+ return call('rivetPresentation', (m) => presentationOf(m.rivetPresentationFlat(bytes, degree), degree));
195
+ }
package/src/source.ts ADDED
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Turning a `load()` source into a compiled `WebAssembly.Module`, for the
3
+ * package root and for `./ladder` (internal).
4
+ *
5
+ * Nothing here writes to `globalThis`. In Node the default source is read
6
+ * with `fs`, and bytes or a compiled module are compiled or used without
7
+ * touching `Request`, `Response` or `fetch` (Node defines those lazily; the
8
+ * first read of one installs undici's global dispatcher on `globalThis`).
9
+ */
10
+
11
+ /**
12
+ * Where `load` reads a module from: a URL (or its string; in Node the
13
+ * string must be an absolute URL, such as a `file:` URL) or request, a fetch
14
+ * `Response` (or a promise of one), the bytes (an `ArrayBuffer`, or any
15
+ * view of one: a typed array, a Node `Buffer` or a `DataView`), or a
16
+ * compiled `WebAssembly.Module`. A WebAssembly module other than the
17
+ * package's is refused with a `TypeError`. Written without DOM-only names so that a Node
18
+ * project compiles without the DOM lib: the compiled module is typed
19
+ * `WebAssembly.Module` where the environment's types declare it, otherwise
20
+ * any object.
21
+ */
22
+ export type LoadSource =
23
+ | string
24
+ | Request
25
+ | URL
26
+ | Response
27
+ | ArrayBuffer
28
+ | ArrayBufferView
29
+ | (typeof globalThis extends { WebAssembly: { Module: abstract new (...args: never[]) => infer M } } ? M & object : object)
30
+ | Promise<
31
+ | string
32
+ | Request
33
+ | URL
34
+ | Response
35
+ | ArrayBuffer
36
+ | ArrayBufferView
37
+ | (typeof globalThis extends { WebAssembly: { Module: abstract new (...args: never[]) => infer M } } ? M & object : object)
38
+ >;
39
+
40
+ const isNode = typeof process !== 'undefined' && typeof process.versions?.node === 'string';
41
+
42
+ /**
43
+ * Node's `fs/promises`, reached so that no bundler sees a dependency on it:
44
+ * a literal `import('node:fs/promises')` stops esbuild ("Could not resolve"),
45
+ * fails webpack 5 (UnhandledSchemeError) and makes Vite warn that the module
46
+ * was externalized, in every browser bundle of the package, although this
47
+ * branch only runs in Node. `process.getBuiltinModule` (Node 22.3 and later)
48
+ * needs no import; the fallback (Node 22.0 to 22.2) builds the specifier at
49
+ * run time, which bundlers leave alone.
50
+ */
51
+ async function nodeFs(): Promise<typeof import('node:fs/promises')> {
52
+ const get = (process as { getBuiltinModule?: (id: string) => unknown }).getBuiltinModule;
53
+ if (typeof get === 'function') return get.call(process, 'node:fs/promises') as typeof import('node:fs/promises');
54
+ return import(/* @vite-ignore */ /* webpackIgnore: true */ ['node', 'fs/promises'].join(':'));
55
+ }
56
+
57
+ /** Whether `s` parses as an absolute URL (a scheme and the rest). */
58
+ function isAbsoluteUrl(s: string): boolean {
59
+ try {
60
+ new URL(s);
61
+ return true;
62
+ } catch {
63
+ return false;
64
+ }
65
+ }
66
+
67
+ /**
68
+ * The compiled module from `source`; without one, from `fallback()` (the
69
+ * binary next to the package's code: read from the file in Node, fetched in
70
+ * a browser). Any `ArrayBufferView` is read as the bytes it views, a
71
+ * `DataView` included. `expected` names an export only the right module
72
+ * has, and `file` the file it comes from, for the refusal of another
73
+ * WebAssembly module.
74
+ */
75
+ export async function compileSource(
76
+ source: LoadSource | undefined,
77
+ fallback: () => URL,
78
+ expected: { exports: readonly string[]; file: string; pkg: string }
79
+ ): Promise<Exclude<Awaited<LoadSource>, string | Request | URL | Response | ArrayBuffer | ArrayBufferView>> {
80
+ const compiled = await compile(source, fallback);
81
+ const names = new Set(WebAssembly.Module.exports(compiled).map((e) => e.name));
82
+ if (!expected.exports.every((name) => names.has(name))) {
83
+ throw new TypeError(`source is a WebAssembly module, but not ${expected.pkg}'s ${expected.file}`);
84
+ }
85
+ return compiled as Exclude<Awaited<LoadSource>, string | Request | URL | Response | ArrayBuffer | ArrayBufferView>;
86
+ }
87
+
88
+ /** The built-in kind of a value (`'ArrayBuffer'`, `'URL'`, …), the same for one made in another realm (an iframe, a `vm` context). */
89
+ function tag(v: unknown): string {
90
+ return Object.prototype.toString.call(v).slice(8, -1);
91
+ }
92
+
93
+ async function compile(source: LoadSource | undefined, fallback: () => URL): Promise<WebAssembly.Module> {
94
+ let s: unknown = await source;
95
+ if (s === undefined) s = fallback();
96
+ // Kinds are told by their tags, not instanceof, so that a source made in
97
+ // another realm is read as the same kind of source.
98
+ const kind = tag(s);
99
+ if (kind === 'WebAssembly.Module') return s as WebAssembly.Module;
100
+ if (kind === 'ArrayBuffer') return WebAssembly.compile(s as ArrayBuffer);
101
+ if (ArrayBuffer.isView(s)) {
102
+ // Every view as its bytes: WebAssembly.compile itself takes no DataView.
103
+ return WebAssembly.compile(new Uint8Array(s.buffer, s.byteOffset, s.byteLength) as Uint8Array<ArrayBuffer>);
104
+ }
105
+ if (isNode && typeof s === 'string' && !isAbsoluteUrl(s)) {
106
+ throw new TypeError(
107
+ `source "${s}" is not a URL: in Node, pass a URL (such as new URL('./tda.wasm', import.meta.url) or a file: URL) ` +
108
+ 'or the bytes (for example from fs.readFile)'
109
+ );
110
+ }
111
+ // A URL of another realm, as a URL of this one.
112
+ if (kind === 'URL') s = new URL(String(s));
113
+ if (isNode && (s instanceof URL || (typeof s === 'string' && s.startsWith('file:')))) {
114
+ const url = s instanceof URL ? s : new URL(s);
115
+ if (url.protocol === 'file:') {
116
+ const { readFile } = await nodeFs();
117
+ return WebAssembly.compile((await readFile(url)) as Uint8Array<ArrayBuffer>);
118
+ }
119
+ }
120
+ if (typeof s === 'string' || s instanceof URL || tag(s) === 'Request') {
121
+ s = await fetch(s as RequestInfo | URL);
122
+ }
123
+ if (tag(s) === 'Response') {
124
+ const r = s as Response;
125
+ if (!r.ok) throw new Error(`fetching the WebAssembly module failed: ${r.status} ${r.statusText} (${r.url})`);
126
+ if (typeof WebAssembly.compileStreaming === 'function' && r.headers.get('Content-Type') === 'application/wasm') {
127
+ return WebAssembly.compileStreaming(r);
128
+ }
129
+ return WebAssembly.compile(await r.arrayBuffer());
130
+ }
131
+ throw new TypeError('source must be a URL, a Request, a Response, the bytes or a WebAssembly.Module');
132
+ }