@tinyactors/wasm 0.0.0-stage → 0.3.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.
@@ -0,0 +1,379 @@
1
+ // The compiler, as the addon defines it (src/compile.c): compileCharts is
2
+ // ta_compile_charts, compileSystem is ta_compile_system (a <system>
3
+ // manifest), a compile result is the object both return, and a resolver,
4
+ // any callable (base, source) => string, is ta_compile_options.resolve:
5
+ // the only place a resolver is given, so it lives at compile time only.
6
+ //
7
+ // Who holds what:
8
+ // - a compile result holds the ta_compile_result in linear memory:
9
+ // close() frees it (ta_compile_free), a FinalizationRegistry frees it
10
+ // when close() was not called;
11
+ // - `image` is a Uint8Array copied from the result on its first read,
12
+ // kept on the object, the application's from then on;
13
+ // - the call's sources are views in the environment's arena (a mark per
14
+ // call); a resolver's texts and messages are copied into the
15
+ // compilation's scratch arena (request->scratch, ta_web_resolve_room),
16
+ // which lives until the compile call returns.
17
+ //
18
+ // After a compilation that succeeded, every expression and script of an
19
+ // "ecmascript" chart is parsed by the engine in the native datamodel's
20
+ // shapes, nothing run (the addon's check): each syntax error a warning at
21
+ // its line, an error with warningsAsErrors. The parser is node:vm's Script
22
+ // in node and bun (the addon's), the realm's Function in a browser, where
23
+ // a page finds the error's line and column by a <script> element that
24
+ // does not parse (it runs nothing: the source is inside a function
25
+ // expression); a Worker reports the expression's own position. Under a
26
+ // policy that refuses string evaluation (realms.mjs, policyRefusal) the
27
+ // check is skipped: the native datamodel cannot run there either.
28
+ import { CompileError, ResolveError, TinyactorsError, refusal } from './errors.mjs';
29
+ import { policyRefusal } from './realms.mjs';
30
+ import { instance } from './state.mjs';
31
+
32
+ const SEVERITIES = ['note', 'warning', 'error'];
33
+ const ERROR = 2;
34
+ const WERROR = 2; // TA_COMPILE_WERROR
35
+ const TA_OK = 0, TA_ERROR_INVALID = -3, TA_ERROR_NO_MEMORY = -4;
36
+ const encoder = new TextEncoder();
37
+
38
+ // The results not closed: freed by the collector as a fallback. The token
39
+ // is the module and the result's pointer, never the object.
40
+ const unclosed = new FinalizationRegistry(({ module, result }) => {
41
+ try {
42
+ if (!module.poisoned) module.call('ta_web_compile_free', result);
43
+ } catch {
44
+ // a poisoned module frees nothing more
45
+ }
46
+ });
47
+
48
+ // The token the constructor checks: only the compile calls make a result.
49
+ const MAKING = Symbol('making');
50
+
51
+ export class Compiled {
52
+ #module;
53
+ #result; // 0 once closed
54
+ #image;
55
+
56
+ constructor(making, module, result, diagnostics) {
57
+ if (making !== MAKING) throw new TypeError('a compile result is made by compileCharts and compileSystem');
58
+ this.#module = module;
59
+ this.#result = result;
60
+ Object.defineProperty(this, 'diagnostics', { value: diagnostics, enumerable: true });
61
+ unclosed.register(this, { module, result }, this);
62
+ }
63
+
64
+ static #of(self) {
65
+ if (self === null || typeof self !== 'object' || !(#result in self)) throw new TypeError('not a compile result');
66
+ return self;
67
+ }
68
+
69
+ // The image, copied on the first read and the same after; a first read
70
+ // after close() throws TA_ERROR_STALE.
71
+ get image() {
72
+ const self = Compiled.#of(this);
73
+ if (self.#image !== undefined) return self.#image;
74
+ if (self.#result === 0) throw refusal('TA_ERROR_STALE', 'the compile result was closed before its image was read');
75
+ const module = self.#module;
76
+ const at = module.call('ta_web_compile_image', module.env, self.#result) >>> 0;
77
+ self.#image = module.copyOut(at, module.word(0));
78
+ return self.#image;
79
+ }
80
+
81
+ // Frees the result; again, nothing.
82
+ close() {
83
+ const self = Compiled.#of(this);
84
+ if (self.#result === 0) return;
85
+ const result = self.#result;
86
+ self.#result = 0;
87
+ unclosed.unregister(self);
88
+ self.#module.call('ta_web_compile_free', result);
89
+ }
90
+
91
+ [Symbol.dispose]() {
92
+ this.close();
93
+ }
94
+ }
95
+
96
+ // One diagnostic as a frozen object; its record's words (compile.c).
97
+ function diagnosticAt(module, result, i) {
98
+ module.call('ta_web_compile_diagnostic', module.env, result, i);
99
+ const w = module.words().slice(module.record, module.record + 8);
100
+ const severity = w[0];
101
+ return Object.freeze({
102
+ severity: SEVERITIES[severity < 3 ? severity : 2],
103
+ code: w[1],
104
+ file: module.string(w[4], w[5]),
105
+ line: w[2],
106
+ column: w[3],
107
+ message: module.string(w[6], w[7]),
108
+ });
109
+ }
110
+
111
+ // A compile call's resolver: the import's owner while the call runs.
112
+ class Resolving {
113
+ constructor(module, resolver) {
114
+ this.module = module;
115
+ this.resolver = resolver;
116
+ this.error = undefined; // the first exception that is not a refusal, thrown after the call
117
+ this.thrown = false;
118
+ }
119
+
120
+ // Text into the compilation's scratch arena: [pointer, length].
121
+ room(text) {
122
+ const module = this.module;
123
+ if (!text.isWellFormed()) throw refusal('TA_ERROR_INVALID', 'a string with a lone surrogate is not text');
124
+ const bytes = encoder.encode(text);
125
+ const at = module.call('ta_web_resolve_room', module.env, bytes.length) >>> 0;
126
+ if (at === 0) throw refusal('TA_ERROR_NO_MEMORY', 'no memory for a string');
127
+ module.bytes().set(bytes, at);
128
+ return [at, bytes.length];
129
+ }
130
+
131
+ // ta_web.resolve: base and source in the record's words 0-3; the answer
132
+ // in it (compile.c).
133
+ resolve() {
134
+ const module = this.module;
135
+ const w = module.words().slice(module.record, module.record + 4);
136
+ const base = module.string(w[0], w[1]), source = module.string(w[2], w[3]);
137
+ let text;
138
+ try {
139
+ text = this.resolver(base, source);
140
+ if (typeof text !== 'string') throw new TypeError('a resolver (base, source) => string returns a string');
141
+ const [at, length] = this.room(text);
142
+ module.words().set([TA_OK, w[2], w[3], at, length], module.record);
143
+ return TA_OK;
144
+ } catch (error) {
145
+ let message = '', line = 0, column = 0;
146
+ const position = (value) => (typeof value === 'number' && value >= 1 && value <= 4294967295 ? Math.trunc(value) : 0);
147
+ if (error instanceof ResolveError) {
148
+ message = this.text(error.message);
149
+ line = position(error.line);
150
+ column = position(error.column);
151
+ } else {
152
+ message = this.text(error);
153
+ this.raised(error);
154
+ }
155
+ module.words().set([TA_ERROR_INVALID, w[2], w[3], 0, 0, line, column, message[0], message[1]], module.record);
156
+ return TA_OK;
157
+ }
158
+ }
159
+
160
+ // `value` as text in the scratch arena; empty when it cannot be had (the
161
+ // compiler then gives its generic message).
162
+ text(value) {
163
+ try {
164
+ return this.room(String(value));
165
+ } catch {
166
+ return [0, 0];
167
+ }
168
+ }
169
+
170
+ // The first exception that is not a refusal (and the import guard's,
171
+ // for one of resolve() itself): kept, thrown after the call.
172
+ raised(error) {
173
+ if (this.thrown) return;
174
+ this.thrown = true;
175
+ this.error = error;
176
+ }
177
+ }
178
+
179
+ // ---- the syntax check -------------------------------------------------------------------------
180
+
181
+ const KIND = { CONDITION: 1, VALUE: 2, LOCATION: 3, SCRIPT: 4, STRING: 5, CONTENT: 6, ITEM: 7, GLOBAL_SCRIPT: 8 };
182
+ const VALUE_SHAPE = ["(function(){'use strict';return (\n", '\n);})', 'expr'];
183
+
184
+ // The shape an expression is checked in (the datamodel's own), or null
185
+ // for <content> (JSON, XML or text, not ECMAScript).
186
+ function shapeOf(kind, source) {
187
+ switch (kind) {
188
+ case KIND.CONDITION: return [VALUE_SHAPE[0], VALUE_SHAPE[1], 'cond'];
189
+ case KIND.VALUE:
190
+ case KIND.STRING: return VALUE_SHAPE;
191
+ case KIND.LOCATION: return ["(function(__v){'use strict';(\n", '\n) = __v;})', 'location'];
192
+ case KIND.ITEM: return ["(function(__v){'use strict';(\n", '\n) = __v;})', 'item'];
193
+ case KIND.GLOBAL_SCRIPT: return ['\n', '', '<script>'];
194
+ case KIND.SCRIPT: return /^[ \t\n\r]*(['"])use strict\1/.test(source) ? ["'use strict';{\n", '\n}', '<script>'] : ['{\n', '\n}', '<script>'];
195
+ default: return null;
196
+ }
197
+ }
198
+
199
+ // The engine's parser over one source: null when it parses, else
200
+ // [message, line, column] of its SyntaxError in the source given.
201
+ function makeChecker() {
202
+ const vm = globalThis.process?.getBuiltinModule?.('node:vm');
203
+ if (vm) {
204
+ return (source) => {
205
+ try {
206
+ new vm.Script(source, { filename: 'chart' }); // eslint-disable-line no-new
207
+ return null;
208
+ } catch (error) {
209
+ if (!(error instanceof SyntaxError)) return null;
210
+ const lines = String(error.stack).split('\n');
211
+ const at = /:(\d+)$/.exec(lines[0]);
212
+ const caret = lines.length > 2 ? lines[2].indexOf('^') : -1;
213
+ return [error.message, at ? Number(at[1]) : 2, caret >= 0 ? caret + 1 : 1];
214
+ }
215
+ };
216
+ }
217
+ const document = globalThis.document;
218
+ return (source) => {
219
+ try {
220
+ new Function(source); // eslint-disable-line no-new
221
+ return null;
222
+ } catch (error) {
223
+ if (!(error instanceof SyntaxError)) return null;
224
+ let line = 2, column = 1;
225
+ if (typeof document?.createElement === 'function') { // a page: where, from a <script> that does not parse
226
+ const listener = (event) => {
227
+ line = event.lineno - 1;
228
+ column = event.colno;
229
+ event.preventDefault();
230
+ };
231
+ globalThis.addEventListener('error', listener);
232
+ try {
233
+ const script = document.createElement('script');
234
+ script.text = `(function(){\n${source}\n})`;
235
+ (document.head ?? document.documentElement).appendChild(script);
236
+ script.remove();
237
+ } finally {
238
+ globalThis.removeEventListener('error', listener);
239
+ }
240
+ }
241
+ return [error.message, line, column];
242
+ }
243
+ };
244
+ }
245
+
246
+ let checker = null;
247
+
248
+ // The SyntaxErrors of the result's "ecmascript" charts as diagnostics.
249
+ function checkImage(module, result, errors) {
250
+ if (policyRefusal() !== null) return [];
251
+ checker ??= makeChecker();
252
+ const found = [];
253
+ const image = module.call('ta_web_image_open', module.env, result) >>> 0;
254
+ if (image === 0) return found; // core's to refuse
255
+ const charts = module.word(0);
256
+ for (let c = 0; c < charts; c++) {
257
+ const count = module.call('ta_web_image_chart', module.env, image, c);
258
+ const w = module.words().slice(module.record, module.record + 4);
259
+ if (module.string(w[0], w[1]) !== 'ecmascript') continue;
260
+ const file = module.string(w[2], w[3]);
261
+ for (let e = 0; e < count; e++) {
262
+ module.setWord(0, c);
263
+ if (module.call('ta_web_image_expression', module.env, image, e) !== 0) continue;
264
+ const x = module.words().slice(module.record, module.record + 6);
265
+ const info = { kind: x[1], line: x[2], column: x[3], source: module.string(x[4], x[5]) };
266
+ const shape = shapeOf(info.kind, info.source);
267
+ if (shape === null) continue;
268
+ const script = info.kind === KIND.SCRIPT || info.kind === KIND.GLOBAL_SCRIPT;
269
+ const source = script ? info.source : info.source.replace(/[; \t\n\r]+$/, '');
270
+ const failure = checker(shape[0] + source + shape[1]);
271
+ if (failure === null) continue;
272
+ const [message, inShape] = failure;
273
+ let column = failure[2];
274
+ const lines = info.source.split('\n').length;
275
+ let sourceLine = inShape >= 2 ? inShape - 1 : 1;
276
+ if (sourceLine > lines) { // past the source: at its end
277
+ sourceLine = lines;
278
+ column = info.source.length - info.source.lastIndexOf('\n');
279
+ }
280
+ found.push(Object.freeze({
281
+ severity: errors ? 'error' : 'warning',
282
+ code: 0,
283
+ file,
284
+ line: info.line + sourceLine - 1,
285
+ column: sourceLine === 1 ? info.column : column,
286
+ message: `${shape[2]}: SyntaxError: ${message}`,
287
+ }));
288
+ }
289
+ }
290
+ return found;
291
+ }
292
+
293
+ function compileWith(manifest, [given, resolver, options], usage) {
294
+ let flags = 0;
295
+ if (options !== undefined) {
296
+ if (options === null || typeof options !== 'object') throw new TypeError('a compile call\'s options are an object: {warningsAsErrors}');
297
+ const werror = options.warningsAsErrors;
298
+ if (werror !== undefined && typeof werror !== 'boolean') throw new TypeError('warningsAsErrors is a boolean');
299
+ if (werror) flags |= WERROR;
300
+ }
301
+ if (resolver !== undefined && resolver !== null && typeof resolver !== 'function') {
302
+ throw new TypeError('a resolver is a function (base, source) => string');
303
+ }
304
+ const module = instance();
305
+ const scratch = module.scratch;
306
+ const sources = manifest ? [given] : given;
307
+ if (!manifest && !Array.isArray(given)) throw new TypeError(usage);
308
+ const resolving = typeof resolver === 'function' ? new Resolving(module, resolver) : null;
309
+ const id = resolving ? module.register(resolving) : 0;
310
+ try {
311
+ return module.scoped(scratch, () => {
312
+ const count = sources.length;
313
+ const pairs = module.room(scratch, 16 * (count || 1)) >>> 2;
314
+ for (let i = 0; i < count; i++) {
315
+ const source = sources[i];
316
+ if (source === null || typeof source !== 'object') throw new TypeError(usage);
317
+ if (typeof source.name !== 'string') throw new TypeError(usage);
318
+ const [n, nl] = module.text(scratch, source.name);
319
+ if (typeof source.text !== 'string') throw new TypeError(usage);
320
+ const [t, tl] = module.text(scratch, source.text);
321
+ module.words().set([n, nl, t, tl], pairs + 4 * i);
322
+ }
323
+ module.words().set([pairs << 2, count, flags, resolving ? 1 : 0, id], module.record);
324
+ const result = module.call('ta_web_compile', module.env, manifest ? 1 : 0) >>> 0;
325
+ const status = module.word(0) | 0;
326
+ let diagnostics, first;
327
+ try {
328
+ const list = [];
329
+ const n = result ? module.call('ta_web_compile_diagnostic_count', result) : 0;
330
+ for (let i = 0; i < n; i++) {
331
+ const diagnostic = diagnosticAt(module, result, i);
332
+ list.push(diagnostic);
333
+ if (first === undefined && diagnostic.severity === 'error') {
334
+ first = `${diagnostic.file}:${diagnostic.line}:${diagnostic.column}: error: ${diagnostic.message}`;
335
+ }
336
+ }
337
+ diagnostics = Object.freeze(list);
338
+ } catch (error) {
339
+ if (result) module.call('ta_web_compile_free', result);
340
+ throw error;
341
+ }
342
+ if (resolving?.thrown || status !== TA_OK || first !== undefined) {
343
+ if (result) module.call('ta_web_compile_free', result); // freed before it throws
344
+ if (resolving?.thrown) throw resolving.error;
345
+ if (status === TA_ERROR_NO_MEMORY) throw refusal('TA_ERROR_NO_MEMORY', 'the compiler\'s allocator refused memory');
346
+ const name = module.statusName(status === TA_OK ? TA_ERROR_INVALID : status);
347
+ throw new CompileError(first ?? name, { diagnostics, status: name });
348
+ }
349
+ // the charts' ECMAScript, parsed: warnings, or errors with warningsAsErrors
350
+ let found;
351
+ try {
352
+ found = checkImage(module, result, (flags & WERROR) !== 0);
353
+ } catch (error) {
354
+ module.call('ta_web_compile_free', result);
355
+ throw error;
356
+ }
357
+ if (found.length > 0) diagnostics = Object.freeze([...diagnostics, ...found]);
358
+ if (found.length > 0 && (flags & WERROR) !== 0) {
359
+ module.call('ta_web_compile_free', result); // freed before it throws
360
+ const d = found[0];
361
+ throw new CompileError(`${d.file}:${d.line}:${d.column}: error: ${d.message}`, { diagnostics, status: module.statusName(TA_ERROR_INVALID) });
362
+ }
363
+ return new Compiled(MAKING, module, result, diagnostics);
364
+ });
365
+ } finally {
366
+ if (id) module.unregister(id);
367
+ }
368
+ }
369
+
370
+ // each takes (sources or manifest, resolver?, options?): their lengths are 3
371
+ export function compileCharts(sources, resolver, options) { // eslint-disable-line no-unused-vars
372
+ return compileWith(false, [...arguments], 'compileCharts(sources, resolver?, options?): sources an array of {name, text} of strings');
373
+ }
374
+
375
+ export function compileSystem(manifest, resolver, options) { // eslint-disable-line no-unused-vars
376
+ return compileWith(true, [...arguments], 'compileSystem(manifest, resolver?, options?): the manifest a {name, text} of strings');
377
+ }
378
+
379
+ export { TinyactorsError };
@@ -0,0 +1,162 @@
1
+ // The convenience layer of @tinyactors/node and @tinyactors/wasm:
2
+ // JavaScript over the direct layer's exports only (AGENTS.md, "Layers and
3
+ // the resolver"). It adds shapes, not behaviour, and imports nothing but
4
+ // `#direct`, the package's direct exports (the lint rule
5
+ // convenience-imports-the-direct-layer): package.json's `imports` maps it
6
+ // to the addon's lib/direct.mjs, and under the export condition
7
+ // `tinyactors-wasm` to the wasm package's wasm/lib/direct.mjs
8
+ // (docs/browser.md, "One API"), so the two packages share this file.
9
+ //
10
+ // Then the shapes chosen for p3-shapes: host.addCharts, host.spawnChart,
11
+ // directoryResolver and Address.prototype.toJSON (below). The only
12
+ // built-ins it reaches are node:fs and node:path, for directoryResolver,
13
+ // through process.getBuiltinModule when the resolver is made: a runtime
14
+ // without them (a browser) refuses it there, with TA_ERROR_UNSUPPORTED.
15
+ //
16
+ // The typed methods return promises when given no handler (the
17
+ // maintainer, 2026-11-18): `host.actorState(params)` returns a promise that
18
+ // resolves with the result and rejects with the TinyactorsError, while
19
+ // `host.actorState(params, onResult, onError?)` is the direct method's call
20
+ // and returns nothing. Each direct method on Host.prototype is replaced by a
21
+ // function that passes a call with a handler straight to it (one argument
22
+ // check and one call more, measured in docs/log.xml,
23
+ // l-maint-promises-built) and otherwise calls it with a result handler that
24
+ // resolves and an error handler that rejects. The promise settles from the
25
+ // handler, in the drain; its continuation runs as a microtask after the
26
+ // turn's native call returns, outside the drain, on a result already
27
+ // converted. A refusal at the call (a closed host, a `this` that is not a
28
+ // Host, params the method cannot write) rejects too, as an async function's
29
+ // throw would. A method still pending at `close()` never settles: the
30
+ // direct layer drops its handlers uncalled. An `onError` without an
31
+ // `onResult` is the direct method's TypeError.
32
+ import { Address, compileCharts, Host, ResolveError, TinyactorsError } from './direct.mjs';
33
+
34
+ /** The direct method `direct` as one that returns a promise of its result
35
+ * when it is given no handler. */
36
+ function promising(direct) {
37
+ return function (params, onResult, onError) {
38
+ if (onResult !== undefined || (onError !== undefined && onError !== null)) return direct.call(this, params, onResult, onError);
39
+ return new Promise((resolve, reject) => {
40
+ direct.call(this, params, (host, result) => resolve(result), (host, error) => reject(error));
41
+ });
42
+ };
43
+ }
44
+
45
+ /** The direct typed methods of Host. */
46
+ const TYPED_METHODS = [
47
+ 'actorState', 'actorContext', 'actorList', 'actorGet', 'hostStats', 'hostConfig',
48
+ 'traceConfigure', 'traceWatch', 'traceUnwatch', 'traceEnd', 'traceSpansDecode',
49
+ ];
50
+
51
+ for (const name of TYPED_METHODS) {
52
+ const direct = Host.prototype[name];
53
+ if (typeof direct !== 'function') throw new Error(`@tinyactors/node: the direct layer has no Host method ${name}`);
54
+ const method = promising(direct);
55
+ // the direct method's name and length (index.d.ts declares them)
56
+ Object.defineProperty(method, 'name', { value: name });
57
+ Object.defineProperty(method, 'length', { value: direct.length });
58
+ // as a class's methods are: writable, configurable, not enumerable
59
+ Object.defineProperty(Host.prototype, name, { value: method, writable: true, configurable: true, enumerable: false });
60
+ }
61
+
62
+ // ---- shapes a JavaScript programmer would otherwise write (p3-shapes) ----
63
+
64
+ /** Defines `value` on `target` as a class's method is: writable,
65
+ * configurable, not enumerable, its `name` the property's. */
66
+ function method(target, name, value) {
67
+ Object.defineProperty(value, 'name', { value: name });
68
+ Object.defineProperty(target, name, { value, writable: true, configurable: true, enumerable: false });
69
+ }
70
+
71
+ /** The options of addCharts: the compile call's resolver, nothing else. */
72
+ const ADD_CHARTS_OPTIONS = new Set(['resolver']);
73
+
74
+ // host.addCharts({name: text}, {resolver}?) → segment: compileCharts of the
75
+ // mapping's entries in their order (the first the boot chart), addImage of
76
+ // the image, close of the result, in one call. The result is closed on every
77
+ // path, so a refused image leaves nothing behind; a CompileError is
78
+ // compileCharts's own, with every diagnostic.
79
+ method(Host.prototype, 'addCharts', function (charts, options) {
80
+ if (typeof charts !== 'object' || charts === null || Array.isArray(charts))
81
+ throw new TypeError('addCharts: charts must be an object of document names to texts');
82
+ if (options !== undefined) {
83
+ if (typeof options !== 'object' || options === null) throw new TypeError('addCharts: options must be an object');
84
+ for (const key of Object.keys(options))
85
+ if (!ADD_CHARTS_OPTIONS.has(key)) throw new TypeError(`addCharts: unknown option ${key}`);
86
+ }
87
+ const sources = Object.entries(charts).map(([name, text]) => ({ name, text }));
88
+ const compiled = compileCharts(sources, options?.resolver);
89
+ try {
90
+ return this.addImage(compiled.image);
91
+ } finally {
92
+ compiled.close();
93
+ }
94
+ });
95
+
96
+ // host.spawnChart(name, options?) → session: spawn of the chart's current
97
+ // version, host.chart(name) then host.spawn(ref, options).
98
+ method(Host.prototype, 'spawnChart', function (name, options) {
99
+ return this.spawn(this.chart(name), options);
100
+ });
101
+
102
+ // Address.prototype.toJSON: its text, so JSON.stringify writes an address
103
+ // as the string an Address is made from (new Address(text) reads it back).
104
+ method(Address.prototype, 'toJSON', function () {
105
+ return this.text;
106
+ });
107
+
108
+ // directoryResolver(root) → resolver: a resolver for the compile calls that
109
+ // reads `source` as a file under `root`, relative to the directory of
110
+ // `base` (a document named `charts/order.scxml` asking for `child.scxml`
111
+ // reads `root/charts/child.scxml`), and refuses, with a ResolveError, a
112
+ // path that leaves `root`: `..`, an absolute path, or a symbolic link
113
+ // anywhere on the way that points outside. `root` is resolved through its
114
+ // own links once, when the resolver is made (a root that does not exist
115
+ // throws there). A file that does not exist is a ResolveError too, so the
116
+ // compile call reports it as a diagnostic; any other error of the file
117
+ // system (a directory, no permission) is thrown from the compile call as it
118
+ // is. The text must be UTF-8: bytes that are not are refused, never
119
+ // replaced.
120
+ const UTF8 = new TextDecoder('utf-8', { fatal: true });
121
+
122
+ /** node:fs and node:path, from the runtime (node, bun); a runtime without
123
+ * them refuses directoryResolver. */
124
+ function builtins() {
125
+ const get = globalThis.process?.getBuiltinModule;
126
+ if (typeof get !== 'function') {
127
+ throw new TinyactorsError('directoryResolver reads files with node:fs, which this runtime does not have', {
128
+ status: 'TA_ERROR_UNSUPPORTED',
129
+ });
130
+ }
131
+ return { fs: get.call(globalThis.process, 'node:fs'), path: get.call(globalThis.process, 'node:path') };
132
+ }
133
+
134
+ /** Whether `file`, absolute, is `root` or under it (`path`: node:path). */
135
+ function inside(path, root, file) {
136
+ const rest = path.relative(root, file);
137
+ return rest !== '' && rest !== '..' && !rest.startsWith(`..${path.sep}`) && !path.isAbsolute(rest);
138
+ }
139
+
140
+ export function directoryResolver(root) {
141
+ const { fs, path } = builtins();
142
+ const top = fs.realpathSync(root);
143
+ return function resolve(base, source) {
144
+ const file = path.resolve(top, path.dirname(base), source);
145
+ if (!inside(path, top, file)) throw new ResolveError(`${source} (from ${base}) leaves the resolver's root`);
146
+ let real;
147
+ try {
148
+ real = fs.realpathSync(file);
149
+ } catch (error) {
150
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR')
151
+ throw new ResolveError(`${source} (from ${base}): no such file under the resolver's root`);
152
+ throw error;
153
+ }
154
+ if (!inside(path, top, real)) throw new ResolveError(`${source} (from ${base}) leaves the resolver's root through a symbolic link`);
155
+ const bytes = fs.readFileSync(real);
156
+ try {
157
+ return UTF8.decode(bytes);
158
+ } catch {
159
+ throw new ResolveError(`${source} (from ${base}) is not UTF-8`);
160
+ }
161
+ };
162
+ }