-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.js
More file actions
245 lines (232 loc) · 7.83 KB
/
Copy pathloader.js
File metadata and controls
245 lines (232 loc) · 7.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// SPDX-License-Identifier: PMPL-1.0-or-later
// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) <j.d.a.jewell@open.ac.uk>
//
// affine-js/loader: host-agnostic loader bridge (INT-02, issue #179).
//
// Prior to this module `AffineModule.fromFile` was Deno-only: it called
// `Deno.readFile(url.pathname)`. `url.pathname` is *not* a filesystem path
// (it is percent-encoded, drops the Windows drive letter, and is meaningless
// for non-`file:` URLs), and `Deno.readFile` does not exist on Node or in a
// browser. That was SAT-02.
//
// This module provides the four pieces INT-02 requires:
//
// 1. relative URL resolution that is correct on every host;
// 2. a host-agnostic byte reader (Deno / Node / browser parity);
// 3. a full import-object builder (multi-namespace, for the cross-module
// WASM imports INT-01/#178 emits — not `env`-only);
// 4. an accessor for the `affinescript.ownership` custom section (the
// typed-wasm contract carrier — see docs/ECOSYSTEM.adoc).
//
// It has no dependency on `mod.js`; `mod.js` consumes it.
/**
* The JavaScript host we are running under.
* @typedef {"deno"|"node"|"browser"|"unknown"} Host
*/
/**
* Detect the current JavaScript host by feature, not by user agent.
* @returns {Host}
*/
export function detectHost() {
if (typeof Deno !== "undefined" && Deno?.version?.deno) return "deno";
if (
typeof process !== "undefined" &&
process?.versions?.node &&
// A bundled-for-browser build can shim `process`; require real fs too.
typeof globalThis.WebAssembly !== "undefined"
) {
return "node";
}
if (
typeof globalThis.fetch === "function" &&
(typeof window !== "undefined" || typeof self !== "undefined")
) {
return "browser";
}
return "unknown";
}
/**
* Resolve a module specifier to an absolute URL.
*
* Accepts a `URL`, an absolute URL string, a `file:`-relative specifier, or a
* filesystem path (POSIX or Windows). `base` is required for relative
* specifiers; callers pass their own `import.meta.url`.
*
* @param {string | URL} spec
* @param {string | URL} [base]
* @returns {URL}
*/
export function resolveUrl(spec, base) {
if (spec instanceof URL) return spec;
if (typeof spec !== "string") {
throw new TypeError(
`affine-js/loader: specifier must be a string or URL, got ${typeof spec}`,
);
}
// Absolute URL (has a scheme like file:, http:, https:, data:, blob:).
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(spec) && !/^[a-zA-Z]:[\\/]/.test(spec)) {
return new URL(spec);
}
// Windows absolute path, e.g. C:\dir\x.wasm -> file:///C:/dir/x.wasm
if (/^[a-zA-Z]:[\\/]/.test(spec)) {
return new URL(`file:///${spec.replace(/\\/g, "/")}`);
}
// POSIX absolute path.
if (spec.startsWith("/")) return new URL(`file://${spec}`);
// Relative specifier — needs a base.
if (base === undefined) {
throw new Error(
`affine-js/loader: relative specifier ${JSON.stringify(spec)} needs a ` +
`base URL; pass { base: import.meta.url }`,
);
}
return new URL(spec, base);
}
/**
* Read a WASM module's bytes from any source, on any host.
*
* @param {string | URL | Uint8Array | ArrayBuffer} source
* @param {{ base?: string | URL }} [options]
* @returns {Promise<Uint8Array>}
*/
export async function readBytes(source, options = {}) {
if (source instanceof Uint8Array) return source;
if (source instanceof ArrayBuffer) return new Uint8Array(source);
if (ArrayBuffer.isView(source)) {
return new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
}
const url = resolveUrl(source, options.base);
if (url.protocol === "file:") {
const host = detectHost();
if (host === "deno") {
// Deno.readFile accepts a URL directly — no pathname mangling.
return await Deno.readFile(url);
}
if (host === "node") {
const { readFile } = await import("node:fs/promises");
const { fileURLToPath } = await import("node:url");
const buf = await readFile(fileURLToPath(url));
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
}
// Browser: a `file:` URL may still be reachable via fetch when the page
// is itself served from disk; otherwise this throws a clear error.
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return new Uint8Array(await res.arrayBuffer());
} catch (cause) {
throw new Error(
`affine-js/loader: cannot read ${url.href} in a browser host; ` +
`serve the .wasm over http(s) or pass its bytes directly`,
{ cause },
);
}
}
// http:, https:, data:, blob: — fetch works on every host that has it.
if (typeof globalThis.fetch !== "function") {
throw new Error(
`affine-js/loader: no fetch available to read ${url.href} on this host`,
);
}
const res = await fetch(url);
if (!res.ok) {
throw new Error(
`affine-js/loader: failed to fetch ${url.href} (HTTP ${res.status})`,
);
}
return new Uint8Array(await res.arrayBuffer());
}
/**
* Build the full WebAssembly import object.
*
* The legacy shape merged everything into a single `env` namespace. INT-01
* (#178) emits genuine cross-module imports under the *callee module's* name,
* so the import object must carry arbitrary namespaces. This builder keeps
* `env` backward-compatible (runtime defaults + flat `options.imports`) and
* adds any `options.modules` namespaces verbatim.
*
* @param {Record<string, Function>} runtimeImports
* @param {{ imports?: Record<string, Function>,
* modules?: Record<string, Record<string, Function>> }} [options]
* @returns {WebAssembly.Imports}
*/
export function buildImportObject(runtimeImports, options = {}) {
/** @type {WebAssembly.Imports} */
const importObject = {
env: {
...runtimeImports,
...(options.imports ?? {}),
},
};
for (const [ns, members] of Object.entries(options.modules ?? {})) {
if (ns === "env") {
// Merge rather than clobber the runtime namespace.
Object.assign(importObject.env, members);
} else {
importObject[ns] = { ...(importObject[ns] ?? {}), ...members };
}
}
return importObject;
}
/** @typedef {"unrestricted"|"linear"|"sharedBorrow"|"exclBorrow"} OwnershipKind */
const OWNERSHIP_KINDS = /** @type {const} */ ([
"unrestricted",
"linear",
"sharedBorrow",
"exclBorrow",
]);
/**
* One per-function ownership annotation.
* @typedef {Object} OwnershipEntry
* @property {number} funcIdx
* @property {OwnershipKind[]} paramKinds
* @property {OwnershipKind} retKind
*/
/**
* Parse the `affinescript.ownership` custom section.
*
* Binary encoding (must match `Codegen.build_ownership_section` /
* `Tw_verify.parse_ownership_section_payload` in the compiler):
*
* u32le count
* for each entry:
* u32le func_idx
* u8 n_params
* u8[n] param_kinds (0=Unrestricted,1=Linear,2=SharedBorrow,3=ExclBorrow)
* u8 ret_kind
*
* @param {WebAssembly.Module} wasmModule
* @returns {OwnershipEntry[]}
*/
export function parseOwnershipSection(wasmModule) {
const sections = WebAssembly.Module.customSections(
wasmModule,
"affinescript.ownership",
);
if (sections.length === 0) return [];
const view = new DataView(sections[0]);
let pos = 0;
const u32 = () => {
const v = view.getUint32(pos, /* littleEndian */ true);
pos += 4;
return v;
};
const u8 = () => {
const v = view.getUint8(pos);
pos += 1;
return v;
};
const kind = (b) => OWNERSHIP_KINDS[b] ?? "unrestricted";
const count = u32();
/** @type {OwnershipEntry[]} */
const entries = [];
for (let i = 0; i < count; i++) {
const funcIdx = u32();
const nParams = u8();
const paramKinds = [];
for (let p = 0; p < nParams; p++) paramKinds.push(kind(u8()));
const retKind = kind(u8());
entries.push({ funcIdx, paramKinds, retKind });
}
return entries;
}