@pwfabric/compiler 0.0.0-stage → 1.0.0-rc.1

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,285 @@
1
+ /**
2
+ * compileAtom — the single atom compiler.
3
+ *
4
+ * Source files in, one ES module out: a block's `component.tsx` (or a
5
+ * capability's `handler.ts`, or a connector/provider engine) plus the
6
+ * companion files it imports, bundled with esbuild into one ESM module the
7
+ * runtime loads. The host-provided imports — the list in
8
+ * `@pwfabric/core` (`BLOCK_HOST_IMPORTS`) — stay external;
9
+ * the host's import map supplies them at load time.
10
+ *
11
+ * IN MEMORY ONLY. Every file comes from the caller's `files` map; an esbuild
12
+ * plugin resolves and loads from that map and nothing else. There are no disk
13
+ * writes, no disk reads of user paths and no network. A relative import that
14
+ * climbs out of the tree is a diagnostic, not a read of whatever sits there.
15
+ *
16
+ * THE SEAM. The compiler returns data — bytes, hash, diagnostics. Storing the
17
+ * bundle, recording it against an atom, licence checks and caching are the
18
+ * caller's job, never this package's.
19
+ *
20
+ * DETERMINISM. Same input + same compiler version + same esbuild version →
21
+ * identical `code` and `hash`. Both versions are returned so a caller can
22
+ * record them beside the hash.
23
+ *
24
+ * @module @pwfabric/compiler/compile
25
+ */
26
+ import { createHash } from 'node:crypto';
27
+ import { posix } from 'node:path';
28
+ import * as esbuild from 'esbuild';
29
+ import { atomKindMeta } from '@pwfabric/contracts';
30
+ import { blockBundleExternals } from '@pwfabric/core';
31
+ import { joinVirtual, normalizeVirtualPath, PathEscapeError, resolveCandidates } from './paths.js';
32
+ import { buildWrapperSource, isValidEngineName, isValidSourceBase } from './wrappers.js';
33
+ import { COMPILER_VERSION, ESBUILD_VERSION } from './version.js';
34
+ // ============================================================
35
+ // CONTRACT
36
+ // ============================================================
37
+ /** Default cap on one compiled bundle; the caller may raise or lower it. */
38
+ export const MAX_ATOM_BUNDLE_BYTES = 500 * 1024;
39
+ // ============================================================
40
+ // LOADERS
41
+ // ============================================================
42
+ const LOADERS = {
43
+ '.ts': 'ts',
44
+ '.mts': 'ts',
45
+ '.cts': 'ts',
46
+ '.tsx': 'tsx',
47
+ '.js': 'js',
48
+ '.mjs': 'js',
49
+ '.cjs': 'js',
50
+ '.jsx': 'jsx',
51
+ '.json': 'json',
52
+ };
53
+ const NAMESPACE = 'pwfabric-atom';
54
+ const OUTFILE = 'bundle.mjs';
55
+ // ============================================================
56
+ // COMPILER
57
+ // ============================================================
58
+ /** Compile one atom. Never throws for bad input — every problem is a diagnostic. */
59
+ export async function compileAtom(input) {
60
+ const diagnostics = [];
61
+ const fail = (extra) => {
62
+ if (extra)
63
+ diagnostics.push(extra);
64
+ return result({ ok: false, code: '', hash: '', size: 0, diagnostics, externals: [] });
65
+ };
66
+ // ── normalise the tree ─────────────────────────────────────────
67
+ const files = new Map();
68
+ for (const [rawKey, content] of Object.entries(input.files)) {
69
+ try {
70
+ files.set(normalizeVirtualPath(rawKey), content);
71
+ }
72
+ catch (e) {
73
+ if (e instanceof PathEscapeError)
74
+ return fail(error('PATH_ESCAPE', `file key '${rawKey}' resolves outside the source tree`));
75
+ throw e;
76
+ }
77
+ }
78
+ let entry;
79
+ let allowed = null;
80
+ try {
81
+ entry = normalizeVirtualPath(input.entry);
82
+ if (input.companions)
83
+ allowed = new Set(input.companions.map(normalizeVirtualPath));
84
+ }
85
+ catch (e) {
86
+ if (e instanceof PathEscapeError)
87
+ return fail(error('PATH_ESCAPE', `${e.message}`));
88
+ throw e;
89
+ }
90
+ // ── entry wrapper, by kind ─────────────────────────────────────
91
+ const kind = input.kind ?? 'block';
92
+ const meta = atomKindMeta(kind);
93
+ if (!meta.bundled)
94
+ return fail(error('INVALID_INPUT', `Atom kind "${kind}" is not a bundled kind`));
95
+ let esbuildEntry;
96
+ const ext = posix.extname(entry);
97
+ if (meta.entry === 'identity') {
98
+ const source = files.get(entry);
99
+ if (source === undefined)
100
+ return fail(error('INVALID_INPUT', `entry '${entry}' is not in the source tree`));
101
+ if (source.length === 0)
102
+ return fail(error('INVALID_INPUT', `Atom source for "${entry}" is empty`));
103
+ const sourceBase = posix.basename(entry, ext);
104
+ // The basename is written into the generated wrapper; it must be a plain name.
105
+ if (!isValidSourceBase(sourceBase)) {
106
+ return fail(error('INVALID_INPUT', `entry basename ${JSON.stringify(sourceBase)} may only contain letters, digits, '_', '-' and '.'`));
107
+ }
108
+ const wrapperPath = posix.join(posix.dirname(entry), `_bundle-entry${ext}`);
109
+ if (files.has(wrapperPath)) {
110
+ return fail(error('INVALID_INPUT', `'${wrapperPath}' is reserved for the generated entry wrapper`));
111
+ }
112
+ files.set(wrapperPath, buildWrapperSource(kind, { sourceBase }));
113
+ allowed?.add(entry);
114
+ esbuildEntry = wrapperPath;
115
+ }
116
+ else if (meta.entry === 'sibling-generated') {
117
+ if (!input.engineName)
118
+ return fail(error('INVALID_INPUT', `Atom "${entry}" (${kind}) needs engineName`));
119
+ // The engine name is written into the generated wrapper; it must be a plain name.
120
+ if (!isValidEngineName(input.engineName)) {
121
+ return fail(error('INVALID_INPUT', `engineName ${JSON.stringify(input.engineName)} may only contain letters, digits, '_' and '-'`));
122
+ }
123
+ if (files.has(entry)) {
124
+ return fail(error('INVALID_INPUT', `'${entry}' is generated by the compiler for ${kind} atoms; it must not be in the source tree`));
125
+ }
126
+ files.set(entry, buildWrapperSource(kind, { engineName: input.engineName }));
127
+ esbuildEntry = entry;
128
+ }
129
+ else {
130
+ return fail(error('INVALID_INPUT', `Atom kind "${kind}" has no bundleable entry`));
131
+ }
132
+ allowed?.add(esbuildEntry);
133
+ // ── bundle ─────────────────────────────────────────────────────
134
+ const hostImports = new Set(blockBundleExternals());
135
+ const plugin = virtualTreePlugin(files, allowed, hostImports);
136
+ let built;
137
+ try {
138
+ built = await esbuild.build({
139
+ entryPoints: [esbuildEntry],
140
+ outfile: OUTFILE,
141
+ write: false,
142
+ metafile: true,
143
+ bundle: true,
144
+ format: 'esm',
145
+ platform: 'browser',
146
+ target: input.target ?? 'es2022',
147
+ minify: input.minify ?? true,
148
+ treeShaking: true,
149
+ sourcemap: input.sourcemap ? 'external' : false,
150
+ jsx: 'automatic',
151
+ logLevel: 'silent',
152
+ plugins: [plugin],
153
+ });
154
+ }
155
+ catch (e) {
156
+ const failure = e;
157
+ if (!Array.isArray(failure.errors))
158
+ throw e;
159
+ diagnostics.push(...failure.errors.map((m) => fromMessage(m, 'error')));
160
+ diagnostics.push(...(failure.warnings ?? []).map((m) => fromMessage(m, 'warning')));
161
+ return fail();
162
+ }
163
+ diagnostics.push(...built.warnings.map((m) => fromMessage(m, 'warning')));
164
+ const out = built.outputFiles.find((f) => f.path.endsWith('.mjs'));
165
+ const mapFile = built.outputFiles.find((f) => f.path.endsWith('.mjs.map'));
166
+ /* c8 ignore next -- esbuild always emits the bundle when the build succeeds */
167
+ if (!out)
168
+ return fail(error('ESBUILD_FAILED', 'esbuild produced no output'));
169
+ const maxBytes = input.maxBytes ?? MAX_ATOM_BUNDLE_BYTES;
170
+ if (out.contents.length > maxBytes) {
171
+ return fail(error('BUNDLE_TOO_LARGE', `Atom "${entry}" bundle ${out.contents.length} bytes exceeds limit ${maxBytes}`));
172
+ }
173
+ const externals = new Set();
174
+ for (const output of Object.values(built.metafile.outputs)) {
175
+ for (const imp of output.imports)
176
+ if (imp.external)
177
+ externals.add(imp.path);
178
+ }
179
+ return result({
180
+ ok: true,
181
+ code: out.text,
182
+ ...(mapFile ? { map: mapFile.text } : {}),
183
+ hash: `sha256:${createHash('sha256').update(out.contents).digest('hex')}`,
184
+ size: out.contents.length,
185
+ diagnostics,
186
+ externals: [...externals].sort(),
187
+ });
188
+ }
189
+ // ============================================================
190
+ // THE VIRTUAL TREE
191
+ // ============================================================
192
+ /**
193
+ * Resolves every import against the in-memory tree. Bare host imports are
194
+ * external; every other bare import, every unresolvable or escaping relative
195
+ * import and every undeclared companion is an error carrying its code in
196
+ * `detail`, so all of them are reported in one pass.
197
+ */
198
+ function virtualTreePlugin(files, allowed, hostImports) {
199
+ const reject = (code, text) => ({
200
+ errors: [{ text, detail: code }],
201
+ });
202
+ return {
203
+ name: 'pwfabric-virtual-tree',
204
+ setup(build) {
205
+ build.onResolve({ filter: /.*/ }, (args) => {
206
+ const spec = args.path;
207
+ if (args.kind === 'entry-point')
208
+ return { path: spec, namespace: NAMESPACE };
209
+ if (spec.startsWith('/') || /^[A-Za-z]:[\\/]/.test(spec)) {
210
+ return reject('PATH_ESCAPE', `absolute import '${spec}' is not allowed; import relative to the file`);
211
+ }
212
+ if (spec.startsWith('.')) {
213
+ let joined;
214
+ try {
215
+ joined = joinVirtual(args.importer, spec);
216
+ }
217
+ catch {
218
+ return reject('PATH_ESCAPE', `relative import '${spec}' resolves outside the source tree`);
219
+ }
220
+ const hit = resolveCandidates(joined).find((c) => files.has(c));
221
+ if (!hit)
222
+ return reject('UNRESOLVED_IMPORT', `cannot resolve '${spec}' from '${args.importer}'`);
223
+ if (allowed && !allowed.has(hit)) {
224
+ return reject('NOT_A_COMPANION', `'${spec}' resolves to '${hit}', which is not a declared companion of this atom`);
225
+ }
226
+ return { path: hit, namespace: NAMESPACE };
227
+ }
228
+ if (hostImports.has(spec))
229
+ return { path: spec, external: true };
230
+ const hostRoot = [...hostImports].find((h) => spec.startsWith(`${h}/`));
231
+ if (hostRoot) {
232
+ return {
233
+ path: spec,
234
+ external: true,
235
+ warnings: [
236
+ {
237
+ text: `'${spec}' is a subpath of the host import '${hostRoot}'; it stays external, but a host import map resolves exact specifiers only, so the host must map it explicitly`,
238
+ detail: 'HOST_SUBPATH_IMPORT',
239
+ },
240
+ ],
241
+ };
242
+ }
243
+ return reject('NON_HOST_IMPORT', `'${spec}' is not a host import. A bare import must be one the host provides (${[...hostImports].sort().join(', ')}); bundle anything else as a companion file`);
244
+ });
245
+ build.onLoad({ filter: /.*/, namespace: NAMESPACE }, (args) => {
246
+ const loader = LOADERS[posix.extname(args.path)];
247
+ if (!loader) {
248
+ return { errors: [{ text: `no loader for '${args.path}' (supported: ${Object.keys(LOADERS).join(', ')})`, detail: 'UNSUPPORTED_FILE' }] };
249
+ }
250
+ return { contents: files.get(args.path), loader };
251
+ });
252
+ },
253
+ };
254
+ }
255
+ // ============================================================
256
+ // HELPERS
257
+ // ============================================================
258
+ function error(code, message) {
259
+ return { severity: 'error', code, message };
260
+ }
261
+ const KNOWN_CODES = new Set([
262
+ 'INVALID_INPUT',
263
+ 'PATH_ESCAPE',
264
+ 'NON_HOST_IMPORT',
265
+ 'HOST_SUBPATH_IMPORT',
266
+ 'UNRESOLVED_IMPORT',
267
+ 'NOT_A_COMPANION',
268
+ 'UNSUPPORTED_FILE',
269
+ 'ESBUILD_FAILED',
270
+ 'BUNDLE_TOO_LARGE',
271
+ ]);
272
+ function fromMessage(m, severity) {
273
+ const code = typeof m.detail === 'string' && KNOWN_CODES.has(m.detail) ? m.detail : 'ESBUILD_FAILED';
274
+ const loc = m.location;
275
+ return {
276
+ severity,
277
+ code,
278
+ message: m.text,
279
+ ...(loc ? { file: loc.file.replace(`${NAMESPACE}:`, ''), line: loc.line, column: loc.column } : {}),
280
+ };
281
+ }
282
+ function result(r) {
283
+ return { ...r, compilerVersion: COMPILER_VERSION, esbuildVersion: ESBUILD_VERSION };
284
+ }
285
+ //# sourceMappingURL=compile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile.js","sourceRoot":"","sources":["../src/compile.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAClC,OAAO,EAAE,YAAY,EAAiB,MAAM,qBAAqB,CAAA;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAA;AACrD,OAAO,EAAE,WAAW,EAAE,oBAAoB,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAClG,OA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,EAAE,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,SAAS,GAAG,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACpG,CAAA;AACH,CAAC;AAED,SAAS,MAAM,CACb,CAA4D;IAE5D,OAAO,EAAE,GAAG,CAAC,EAAE,eAAe,EAAE,gBAAgB,EAAE,cAAc,EAAE,eAAe,EAAE,CAAA;AACrF,CAAC","sourcesContent":["/**\n * compileAtom — the single atom compiler.\n *\n * Source files in, one ES module out: a block's `component.tsx` (or a\n * capability's `handler.ts`, or a connector/provider engine) plus the\n * companion files it imports, bundled with esbuild into one ESM module the\n * runtime loads. The host-provided imports — the list in\n * `@pwfabric/core` (`BLOCK_HOST_IMPORTS`) — stay external;\n * the host's import map supplies them at load time.\n *\n * IN MEMORY ONLY. Every file comes from the caller's `files` map; an esbuild\n * plugin resolves and loads from that map and nothing else. There are no disk\n * writes, no disk reads of user paths and no network. A relative import that\n * climbs out of the tree is a diagnostic, not a read of whatever sits there.\n *\n * THE SEAM. The compiler returns data — bytes, hash, diagnostics. Storing the\n * bundle, recording it against an atom, licence checks and caching are the\n * caller's job, never this package's.\n *\n * DETERMINISM. Same input + same compiler version + same esbuild version →\n * identical `code` and `hash`. Both versions are returned so a caller can\n * record them beside the hash.\n *\n * @module @pwfabric/compiler/compile\n */\nimport { createHash } from 'node:crypto'\nimport { posix } from 'node:path'\nimport * as esbuild from 'esbuild'\nimport { atomKindMeta, type AtomKind } from '@pwfabric/contracts'\nimport { blockBundleExternals } from '@pwfabric/core'\nimport { joinVirtual, normalizeVirtualPath, PathEscapeError, resolveCandidates } from './paths.js'\nimport { buildWrapperSource, isValidEngineName, isValidSourceBase } from './wrappers.js'\nimport { COMPILER_VERSION, ESBUILD_VERSION } from './version.js'\n\n// ============================================================\n// CONTRACT\n// ============================================================\n\n/** Default cap on one compiled bundle; the caller may raise or lower it. */\nexport const MAX_ATOM_BUNDLE_BYTES = 500 * 1024\n\n/** esbuild language targets the compiler accepts. */\nexport type CompileTarget =\n | 'es2018'\n | 'es2019'\n | 'es2020'\n | 'es2021'\n | 'es2022'\n | 'es2023'\n | 'es2024'\n | 'esnext'\n\n/** Machine-readable reason for a diagnostic. */\nexport type DiagnosticCode =\n /** Bad call shape: missing entry, empty source, a kind that is not bundled. */\n | 'INVALID_INPUT'\n /** A file key or a relative import resolves outside the source tree. */\n | 'PATH_ESCAPE'\n /** A bare import that is not a host import. */\n | 'NON_HOST_IMPORT'\n /** A subpath of a host import — compiled external, but the host import map only resolves exact specifiers. */\n | 'HOST_SUBPATH_IMPORT'\n /** A relative import that names no file in the tree. */\n | 'UNRESOLVED_IMPORT'\n /** A relative import that names a file the caller did not declare as a companion. */\n | 'NOT_A_COMPANION'\n /** A file type the compiler has no loader for. */\n | 'UNSUPPORTED_FILE'\n /** A syntax or type-strip error reported by esbuild itself. */\n | 'ESBUILD_FAILED'\n /** The bundle is larger than `maxBytes`. */\n | 'BUNDLE_TOO_LARGE'\n\nexport interface Diagnostic {\n readonly severity: 'error' | 'warning'\n readonly code: DiagnosticCode\n readonly message: string\n /** Virtual path of the file the diagnostic points at, when esbuild knows it. */\n readonly file?: string\n readonly line?: number\n readonly column?: number\n}\n\nexport interface CompileInput {\n /**\n * The source tree: POSIX path relative to a virtual root → file content.\n * Backslashes are normalised; absolute or root-escaping keys are refused.\n */\n readonly files: Readonly<Record<string, string | Uint8Array>>\n /**\n * The entry's path in `files`. For `identity` kinds (block, capability) it is\n * the atom's own source (`blocks/<cat>/<name>/component.tsx`). For\n * `sibling-generated` kinds (connector, provider) it is the wrapper path the\n * contract derives (`resolveSiblingEntry(...).wrapperPath`); the compiler\n * generates that file, and the engine source must be in `files`.\n */\n readonly entry: string\n /**\n * Paths in `files` the entry may reach through relative imports (shared lib\n * code, `_shared-*` siblings, an engine source). Omitted → every file in\n * `files` may be reached. Given → importing any other file is a\n * `NOT_A_COMPANION` error. `collectCompanions()` computes this list.\n */\n readonly companions?: readonly string[]\n /** Atom kind; drives the entry wrapper. Default `'block'`. */\n readonly kind?: AtomKind\n /** `sibling-generated` kinds only: the engine's base name (connector `<Name>`, provider `<domain>`). */\n readonly engineName?: string\n /** Default `'es2022'`. */\n readonly target?: CompileTarget\n /** Default `true`. */\n readonly minify?: boolean\n /** Produce a source map in `map`. Default `false`. */\n readonly sourcemap?: boolean\n /** Bundle size cap in bytes. Default {@link MAX_ATOM_BUNDLE_BYTES}. */\n readonly maxBytes?: number\n}\n\nexport interface CompileResult {\n readonly ok: boolean\n /** The ES module. Empty when `ok` is false. */\n readonly code: string\n /** Source map JSON, when `sourcemap` was requested and the compile succeeded. */\n readonly map?: string\n /** `sha256:<hex>` of the UTF-8 bytes of `code`. Empty when `ok` is false. */\n readonly hash: string\n /** Byte length of `code`. */\n readonly size: number\n readonly diagnostics: readonly Diagnostic[]\n /** Host imports the module imports, sorted. These are what the host must provide to load it. */\n readonly externals: readonly string[]\n readonly compilerVersion: string\n readonly esbuildVersion: string\n}\n\n// ============================================================\n// LOADERS\n// ============================================================\n\nconst LOADERS: Readonly<Record<string, esbuild.Loader>> = {\n '.ts': 'ts',\n '.mts': 'ts',\n '.cts': 'ts',\n '.tsx': 'tsx',\n '.js': 'js',\n '.mjs': 'js',\n '.cjs': 'js',\n '.jsx': 'jsx',\n '.json': 'json',\n}\n\nconst NAMESPACE = 'pwfabric-atom'\nconst OUTFILE = 'bundle.mjs'\n\n// ============================================================\n// COMPILER\n// ============================================================\n\n/** Compile one atom. Never throws for bad input — every problem is a diagnostic. */\nexport async function compileAtom(input: CompileInput): Promise<CompileResult> {\n const diagnostics: Diagnostic[] = []\n const fail = (extra?: Diagnostic): CompileResult => {\n if (extra) diagnostics.push(extra)\n return result({ ok: false, code: '', hash: '', size: 0, diagnostics, externals: [] })\n }\n\n // ── normalise the tree ─────────────────────────────────────────\n const files = new Map<string, string | Uint8Array>()\n for (const [rawKey, content] of Object.entries(input.files)) {\n try {\n files.set(normalizeVirtualPath(rawKey), content)\n } catch (e) {\n if (e instanceof PathEscapeError) return fail(error('PATH_ESCAPE', `file key '${rawKey}' resolves outside the source tree`))\n throw e\n }\n }\n\n let entry: string\n let allowed: Set<string> | null = null\n try {\n entry = normalizeVirtualPath(input.entry)\n if (input.companions) allowed = new Set(input.companions.map(normalizeVirtualPath))\n } catch (e) {\n if (e instanceof PathEscapeError) return fail(error('PATH_ESCAPE', `${e.message}`))\n throw e\n }\n\n // ── entry wrapper, by kind ─────────────────────────────────────\n const kind: AtomKind = input.kind ?? 'block'\n const meta = atomKindMeta(kind)\n if (!meta.bundled) return fail(error('INVALID_INPUT', `Atom kind \"${kind}\" is not a bundled kind`))\n\n let esbuildEntry: string\n const ext = posix.extname(entry)\n if (meta.entry === 'identity') {\n const source = files.get(entry)\n if (source === undefined) return fail(error('INVALID_INPUT', `entry '${entry}' is not in the source tree`))\n if (source.length === 0) return fail(error('INVALID_INPUT', `Atom source for \"${entry}\" is empty`))\n const sourceBase = posix.basename(entry, ext)\n // The basename is written into the generated wrapper; it must be a plain name.\n if (!isValidSourceBase(sourceBase)) {\n return fail(error('INVALID_INPUT', `entry basename ${JSON.stringify(sourceBase)} may only contain letters, digits, '_', '-' and '.'`))\n }\n const wrapperPath = posix.join(posix.dirname(entry), `_bundle-entry${ext}`)\n if (files.has(wrapperPath)) {\n return fail(error('INVALID_INPUT', `'${wrapperPath}' is reserved for the generated entry wrapper`))\n }\n files.set(wrapperPath, buildWrapperSource(kind, { sourceBase }))\n allowed?.add(entry)\n esbuildEntry = wrapperPath\n } else if (meta.entry === 'sibling-generated') {\n if (!input.engineName) return fail(error('INVALID_INPUT', `Atom \"${entry}\" (${kind}) needs engineName`))\n // The engine name is written into the generated wrapper; it must be a plain name.\n if (!isValidEngineName(input.engineName)) {\n return fail(error('INVALID_INPUT', `engineName ${JSON.stringify(input.engineName)} may only contain letters, digits, '_' and '-'`))\n }\n if (files.has(entry)) {\n return fail(error('INVALID_INPUT', `'${entry}' is generated by the compiler for ${kind} atoms; it must not be in the source tree`))\n }\n files.set(entry, buildWrapperSource(kind, { engineName: input.engineName }))\n esbuildEntry = entry\n } else {\n return fail(error('INVALID_INPUT', `Atom kind \"${kind}\" has no bundleable entry`))\n }\n allowed?.add(esbuildEntry)\n\n // ── bundle ─────────────────────────────────────────────────────\n const hostImports = new Set(blockBundleExternals())\n const plugin = virtualTreePlugin(files, allowed, hostImports)\n\n let built: esbuild.BuildResult<{ write: false; metafile: true }>\n try {\n built = await esbuild.build({\n entryPoints: [esbuildEntry],\n outfile: OUTFILE,\n write: false,\n metafile: true,\n bundle: true,\n format: 'esm',\n platform: 'browser',\n target: input.target ?? 'es2022',\n minify: input.minify ?? true,\n treeShaking: true,\n sourcemap: input.sourcemap ? 'external' : false,\n jsx: 'automatic',\n logLevel: 'silent',\n plugins: [plugin],\n })\n } catch (e) {\n const failure = e as Partial<esbuild.BuildFailure>\n if (!Array.isArray(failure.errors)) throw e\n diagnostics.push(...failure.errors.map((m) => fromMessage(m, 'error')))\n diagnostics.push(...(failure.warnings ?? []).map((m) => fromMessage(m, 'warning')))\n return fail()\n }\n diagnostics.push(...built.warnings.map((m) => fromMessage(m, 'warning')))\n\n const out = built.outputFiles.find((f) => f.path.endsWith('.mjs'))\n const mapFile = built.outputFiles.find((f) => f.path.endsWith('.mjs.map'))\n /* c8 ignore next -- esbuild always emits the bundle when the build succeeds */\n if (!out) return fail(error('ESBUILD_FAILED', 'esbuild produced no output'))\n\n const maxBytes = input.maxBytes ?? MAX_ATOM_BUNDLE_BYTES\n if (out.contents.length > maxBytes) {\n return fail(error('BUNDLE_TOO_LARGE', `Atom \"${entry}\" bundle ${out.contents.length} bytes exceeds limit ${maxBytes}`))\n }\n\n const externals = new Set<string>()\n for (const output of Object.values(built.metafile.outputs)) {\n for (const imp of output.imports) if (imp.external) externals.add(imp.path)\n }\n\n return result({\n ok: true,\n code: out.text,\n ...(mapFile ? { map: mapFile.text } : {}),\n hash: `sha256:${createHash('sha256').update(out.contents).digest('hex')}`,\n size: out.contents.length,\n diagnostics,\n externals: [...externals].sort(),\n })\n}\n\n// ============================================================\n// THE VIRTUAL TREE\n// ============================================================\n\n/**\n * Resolves every import against the in-memory tree. Bare host imports are\n * external; every other bare import, every unresolvable or escaping relative\n * import and every undeclared companion is an error carrying its code in\n * `detail`, so all of them are reported in one pass.\n */\nfunction virtualTreePlugin(\n files: ReadonlyMap<string, string | Uint8Array>,\n allowed: ReadonlySet<string> | null,\n hostImports: ReadonlySet<string>\n): esbuild.Plugin {\n const reject = (code: DiagnosticCode, text: string): esbuild.OnResolveResult => ({\n errors: [{ text, detail: code }],\n })\n return {\n name: 'pwfabric-virtual-tree',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n const spec = args.path\n if (args.kind === 'entry-point') return { path: spec, namespace: NAMESPACE }\n\n if (spec.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(spec)) {\n return reject('PATH_ESCAPE', `absolute import '${spec}' is not allowed; import relative to the file`)\n }\n if (spec.startsWith('.')) {\n let joined: string\n try {\n joined = joinVirtual(args.importer, spec)\n } catch {\n return reject('PATH_ESCAPE', `relative import '${spec}' resolves outside the source tree`)\n }\n const hit = resolveCandidates(joined).find((c) => files.has(c))\n if (!hit) return reject('UNRESOLVED_IMPORT', `cannot resolve '${spec}' from '${args.importer}'`)\n if (allowed && !allowed.has(hit)) {\n return reject('NOT_A_COMPANION', `'${spec}' resolves to '${hit}', which is not a declared companion of this atom`)\n }\n return { path: hit, namespace: NAMESPACE }\n }\n\n if (hostImports.has(spec)) return { path: spec, external: true }\n const hostRoot = [...hostImports].find((h) => spec.startsWith(`${h}/`))\n if (hostRoot) {\n return {\n path: spec,\n external: true,\n warnings: [\n {\n text: `'${spec}' is a subpath of the host import '${hostRoot}'; it stays external, but a host import map resolves exact specifiers only, so the host must map it explicitly`,\n detail: 'HOST_SUBPATH_IMPORT',\n },\n ],\n }\n }\n return reject(\n 'NON_HOST_IMPORT',\n `'${spec}' is not a host import. A bare import must be one the host provides (${[...hostImports].sort().join(', ')}); bundle anything else as a companion file`\n )\n })\n\n build.onLoad({ filter: /.*/, namespace: NAMESPACE }, (args) => {\n const loader = LOADERS[posix.extname(args.path)]\n if (!loader) {\n return { errors: [{ text: `no loader for '${args.path}' (supported: ${Object.keys(LOADERS).join(', ')})`, detail: 'UNSUPPORTED_FILE' }] }\n }\n return { contents: files.get(args.path) as string | Uint8Array, loader }\n })\n },\n }\n}\n\n// ============================================================\n// HELPERS\n// ============================================================\n\nfunction error(code: DiagnosticCode, message: string): Diagnostic {\n return { severity: 'error', code, message }\n}\n\nconst KNOWN_CODES: ReadonlySet<string> = new Set<DiagnosticCode>([\n 'INVALID_INPUT',\n 'PATH_ESCAPE',\n 'NON_HOST_IMPORT',\n 'HOST_SUBPATH_IMPORT',\n 'UNRESOLVED_IMPORT',\n 'NOT_A_COMPANION',\n 'UNSUPPORTED_FILE',\n 'ESBUILD_FAILED',\n 'BUNDLE_TOO_LARGE',\n])\n\nfunction fromMessage(m: esbuild.Message, severity: Diagnostic['severity']): Diagnostic {\n const code: DiagnosticCode =\n typeof m.detail === 'string' && KNOWN_CODES.has(m.detail) ? (m.detail as DiagnosticCode) : 'ESBUILD_FAILED'\n const loc = m.location\n return {\n severity,\n code,\n message: m.text,\n ...(loc ? { file: loc.file.replace(`${NAMESPACE}:`, ''), line: loc.line, column: loc.column } : {}),\n }\n}\n\nfunction result(\n r: Omit<CompileResult, 'compilerVersion' | 'esbuildVersion'>\n): CompileResult {\n return { ...r, compilerVersion: COMPILER_VERSION, esbuildVersion: ESBUILD_VERSION }\n}\n"]}
@@ -0,0 +1,5 @@
1
+ import { type CompileInput, type CompileResult } from './compile.js';
2
+ /** Read a directory into a `files` map keyed by POSIX path relative to `dir`. */
3
+ export declare function readSourceTree(dir: string): Promise<Record<string, Uint8Array>>;
4
+ /** Compile the atom whose entry is `entry` (relative to `dir`) from the tree under `dir`. */
5
+ export declare function compileFolder(dir: string, entry: string, options?: Omit<CompileInput, 'files' | 'entry'>): Promise<CompileResult>;
package/dist/folder.js ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * compileFolder — a convenience for a source tree that lives on disk.
3
+ *
4
+ * Reads every file under `dir` into memory (skipping `node_modules`, `dist`
5
+ * and dot-directories), then hands the map to {@link compileAtom}. Reading is
6
+ * the only disk access; compilation itself stays in memory. A pack reader that
7
+ * already holds the tree should call `compileAtom` directly.
8
+ *
9
+ * @module @pwfabric/compiler/folder
10
+ */
11
+ import { readdir, readFile } from 'node:fs/promises';
12
+ import { join, relative, sep } from 'node:path';
13
+ import { compileAtom } from './compile.js';
14
+ const SKIP_DIRS = new Set(['node_modules', 'dist']);
15
+ /** Read a directory into a `files` map keyed by POSIX path relative to `dir`. */
16
+ export async function readSourceTree(dir) {
17
+ const files = {};
18
+ const walk = async (current) => {
19
+ const entries = await readdir(current, { withFileTypes: true });
20
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
21
+ for (const e of entries) {
22
+ const full = join(current, e.name);
23
+ if (e.isDirectory()) {
24
+ if (SKIP_DIRS.has(e.name) || e.name.startsWith('.'))
25
+ continue;
26
+ await walk(full);
27
+ }
28
+ else if (e.isFile()) {
29
+ files[relative(dir, full).split(sep).join('/')] = await readFile(full);
30
+ }
31
+ }
32
+ };
33
+ await walk(dir);
34
+ return files;
35
+ }
36
+ /** Compile the atom whose entry is `entry` (relative to `dir`) from the tree under `dir`. */
37
+ export async function compileFolder(dir, entry, options = {}) {
38
+ return compileAtom({ ...options, files: await readSourceTree(dir), entry });
39
+ }
40
+ //# sourceMappingURL=folder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"folder.js","sourceRoot":"","sources":["../src/folder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AACpD,OAAO,EAAE,IAA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AC,GAAG,CAAC,CAAC,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAA;YACxE,CAAC;QACH,CAAC;IACH,CAAC,CAAA;IACD,MAAM,IAAI,CAAC,GAAG,CAAC,CAAA;IACf,OAAO,KAAK,CAAA;AACd,CAAC;AAED,6FAA6F;AAC7F,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,GAAW,EACX,KAAa,EACb,UAAiD,EAAE;IAEnD,OAAO,WAAW,CAAC,EAAE,GAAG,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,CAAA;AAC7E,CAAC","sourcesContent":["/**\n * compileFolder — a convenience for a source tree that lives on disk.\n *\n * Reads every file under `dir` into memory (skipping `node_modules`, `dist`\n * and dot-directories), then hands the map to {@link compileAtom}. Reading is\n * the only disk access; compilation itself stays in memory. A pack reader that\n * already holds the tree should call `compileAtom` directly.\n *\n * @module @pwfabric/compiler/folder\n */\nimport { readdir, readFile } from 'node:fs/promises'\nimport { join, relative, sep } from 'node:path'\nimport { compileAtom, type CompileInput, type CompileResult } from './compile.js'\n\nconst SKIP_DIRS = new Set(['node_modules', 'dist'])\n\n/** Read a directory into a `files` map keyed by POSIX path relative to `dir`. */\nexport async function readSourceTree(dir: string): Promise<Record<string, Uint8Array>> {\n const files: Record<string, Uint8Array> = {}\n const walk = async (current: string): Promise<void> => {\n const entries = await readdir(current, { withFileTypes: true })\n entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n for (const e of entries) {\n const full = join(current, e.name)\n if (e.isDirectory()) {\n if (SKIP_DIRS.has(e.name) || e.name.startsWith('.')) continue\n await walk(full)\n } else if (e.isFile()) {\n files[relative(dir, full).split(sep).join('/')] = await readFile(full)\n }\n }\n }\n await walk(dir)\n return files\n}\n\n/** Compile the atom whose entry is `entry` (relative to `dir`) from the tree under `dir`. */\nexport async function compileFolder(\n dir: string,\n entry: string,\n options: Omit<CompileInput, 'files' | 'entry'> = {}\n): Promise<CompileResult> {\n return compileAtom({ ...options, files: await readSourceTree(dir), entry })\n}\n"]}
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @pwfabric/compiler — the atom compiler.
3
+ *
4
+ * Block / capability / connector / provider source in, one ES module out, with
5
+ * the host-provided imports left external. Pure: the caller supplies the files
6
+ * and stores the result.
7
+ *
8
+ * @module @pwfabric/compiler
9
+ */
10
+ export { compileAtom, MAX_ATOM_BUNDLE_BYTES, type CompileInput, type CompileResult, type CompileTarget, type Diagnostic, type DiagnosticCode, } from './compile.js';
11
+ export { compileFolder, readSourceTree } from './folder.js';
12
+ export { screenSource, maskSource, SCREEN_IMPORT_ALLOWLIST, screenBlockSource, BLOCK_SOURCE_IMPORT_ALLOWLIST, type ScreenOptions, type ScreenResult, } from './screen.js';
13
+ export { collectCompanions, isCompanionTarget, resolveCompanion, type CompanionScan, type ScreenFn, } from './companions.js';
14
+ export { buildWrapperSource, isValidEngineName, isValidSourceBase, type WrapperContext } from './wrappers.js';
15
+ export { COMPILER_VERSION, ESBUILD_VERSION } from './version.js';
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @pwfabric/compiler — the atom compiler.
3
+ *
4
+ * Block / capability / connector / provider source in, one ES module out, with
5
+ * the host-provided imports left external. Pure: the caller supplies the files
6
+ * and stores the result.
7
+ *
8
+ * @module @pwfabric/compiler
9
+ */
10
+ export { compileAtom, MAX_ATOM_BUNDLE_BYTES, } from './compile.js';
11
+ export { compileFolder, readSourceTree } from './folder.js';
12
+ export { screenSource, maskSource, SCREEN_IMPORT_ALLOWLIST, screenBlockSource, BLOCK_SOURCE_IMPORT_ALLOWLIST, } from './screen.js';
13
+ export { collectCompanions, isCompanionTarget, resolveCompanion, } from './companions.js';
14
+ export { buildWrapperSource, isValidEngineName, isValidSourceBase } from './wrappers.js';
15
+ export { COMPILER_VERSION, ESBUILD_VERSION } from './version.js';
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EACL,WAAW,EACX,qBAAqB,GAMtB,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAC3D,OAAO,EACL,YAAY,EACZ,UAAU,EACV,uBAAuB,EACvB,iBAAiB,EACjB,6BAA6B,GAG9B,MAAM,aAAa,CAAA;AACpB,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,GAGjB,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,iBAAiB,EAAuB,MAAM,eAAe,CAAA;AAC7G,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA","sourcesContent":["/**\n * @pwfabric/compiler — the atom compiler.\n *\n * Block / capability / connector / provider source in, one ES module out, with\n * the host-provided imports left external. Pure: the caller supplies the files\n * and stores the result.\n *\n * @module @pwfabric/compiler\n */\nexport {\n compileAtom,\n MAX_ATOM_BUNDLE_BYTES,\n type CompileInput,\n type CompileResult,\n type CompileTarget,\n type Diagnostic,\n type DiagnosticCode,\n} from './compile.js'\nexport { compileFolder, readSourceTree } from './folder.js'\nexport {\n screenSource,\n maskSource,\n SCREEN_IMPORT_ALLOWLIST,\n screenBlockSource,\n BLOCK_SOURCE_IMPORT_ALLOWLIST,\n type ScreenOptions,\n type ScreenResult,\n} from './screen.js'\nexport {\n collectCompanions,\n isCompanionTarget,\n resolveCompanion,\n type CompanionScan,\n type ScreenFn,\n} from './companions.js'\nexport { buildWrapperSource, isValidEngineName, isValidSourceBase, type WrapperContext } from './wrappers.js'\nexport { COMPILER_VERSION, ESBUILD_VERSION } from './version.js'\n"]}
@@ -0,0 +1,24 @@
1
+ /** Thrown for a path that resolves outside the virtual root. */
2
+ export declare class PathEscapeError extends Error {
3
+ readonly attempted: string;
4
+ constructor(attempted: string);
5
+ }
6
+ /**
7
+ * Normalise a caller-supplied key to the canonical virtual form: forward
8
+ * slashes, no leading `./`, no `.`/`..` segments. Throws {@link PathEscapeError}
9
+ * for an absolute path (POSIX or drive-letter), a NUL byte, an empty path, or a
10
+ * path whose `..` segments climb past the root.
11
+ */
12
+ export declare function normalizeVirtualPath(raw: string): string;
13
+ /**
14
+ * Join a relative specifier onto the directory of `fromPath` and normalise.
15
+ * Throws {@link PathEscapeError} when the result leaves the root.
16
+ */
17
+ export declare function joinVirtual(fromPath: string, spec: string): string;
18
+ /**
19
+ * The files a resolved-but-unextended path may name, in esbuild's own order:
20
+ * the exact path; for a `.js`/`.jsx`/`.mjs` spelling, the TypeScript file it
21
+ * stands for (esbuild rewrites `./x.js` to `./x.ts` the same way); the path
22
+ * plus each resolve extension; then `index.*` inside it.
23
+ */
24
+ export declare function resolveCandidates(joined: string): string[];
package/dist/paths.js ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Virtual paths. The compiler never touches a disk: every file lives in the
3
+ * caller's `files` map under a POSIX path relative to a virtual root. This
4
+ * module is the one place that decides what such a path may look like.
5
+ *
6
+ * Containment is decided by where a path RESOLVES, not by whether it spells
7
+ * `..`: `lib/../lib/x.ts` is fine, `../x.ts` is not. A relative import that
8
+ * climbs within the tree is legitimate (a block in `blocks/a/b/` reaching
9
+ * `lib/` climbs three levels); one that climbs past the root is the escape.
10
+ */
11
+ import { posix } from 'node:path';
12
+ /** Thrown for a path that resolves outside the virtual root. */
13
+ export class PathEscapeError extends Error {
14
+ attempted;
15
+ constructor(attempted) {
16
+ super(`Path resolves outside the source tree: ${attempted}`);
17
+ this.attempted = attempted;
18
+ this.name = 'PathEscapeError';
19
+ }
20
+ }
21
+ /**
22
+ * Normalise a caller-supplied key to the canonical virtual form: forward
23
+ * slashes, no leading `./`, no `.`/`..` segments. Throws {@link PathEscapeError}
24
+ * for an absolute path (POSIX or drive-letter), a NUL byte, an empty path, or a
25
+ * path whose `..` segments climb past the root.
26
+ */
27
+ export function normalizeVirtualPath(raw) {
28
+ const slashed = raw.replace(/\\/g, '/');
29
+ if (slashed.length === 0 || slashed.includes('\0'))
30
+ throw new PathEscapeError(raw);
31
+ if (slashed.startsWith('/') || /^[A-Za-z]:/.test(slashed))
32
+ throw new PathEscapeError(raw);
33
+ const normalized = posix.normalize(slashed);
34
+ if (normalized === '..' || normalized.startsWith('../') || normalized === '.' || normalized.endsWith('/')) {
35
+ throw new PathEscapeError(raw);
36
+ }
37
+ return normalized;
38
+ }
39
+ /**
40
+ * Join a relative specifier onto the directory of `fromPath` and normalise.
41
+ * Throws {@link PathEscapeError} when the result leaves the root.
42
+ */
43
+ export function joinVirtual(fromPath, spec) {
44
+ const joined = posix.normalize(posix.join(posix.dirname(fromPath), spec));
45
+ if (joined === '..' || joined.startsWith('../') || joined.startsWith('/')) {
46
+ throw new PathEscapeError(spec);
47
+ }
48
+ return joined;
49
+ }
50
+ /** esbuild's default resolve order, which the on-disk compiler relied on. */
51
+ const RESOLVE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.json'];
52
+ /**
53
+ * The files a resolved-but-unextended path may name, in esbuild's own order:
54
+ * the exact path; for a `.js`/`.jsx`/`.mjs` spelling, the TypeScript file it
55
+ * stands for (esbuild rewrites `./x.js` to `./x.ts` the same way); the path
56
+ * plus each resolve extension; then `index.*` inside it.
57
+ */
58
+ export function resolveCandidates(joined) {
59
+ const out = [joined];
60
+ const ext = posix.extname(joined);
61
+ if (ext === '.js' || ext === '.jsx') {
62
+ const base = joined.slice(0, -ext.length);
63
+ out.push(`${base}.ts`, `${base}.tsx`);
64
+ }
65
+ else if (ext === '.mjs') {
66
+ out.push(`${joined.slice(0, -4)}.mts`);
67
+ }
68
+ for (const e of RESOLVE_EXTENSIONS)
69
+ out.push(`${joined}${e}`);
70
+ for (const e of RESOLVE_EXTENSIONS)
71
+ out.push(`${joined}/index${e}`);
72
+ return out;
73
+ }
74
+ //# sourceMappingURL=paths.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G,CAAA;AACZ,CAAC","sourcesContent":["/**\n * Virtual paths. The compiler never touches a disk: every file lives in the\n * caller's `files` map under a POSIX path relative to a virtual root. This\n * module is the one place that decides what such a path may look like.\n *\n * Containment is decided by where a path RESOLVES, not by whether it spells\n * `..`: `lib/../lib/x.ts` is fine, `../x.ts` is not. A relative import that\n * climbs within the tree is legitimate (a block in `blocks/a/b/` reaching\n * `lib/` climbs three levels); one that climbs past the root is the escape.\n */\nimport { posix } from 'node:path'\n\n/** Thrown for a path that resolves outside the virtual root. */\nexport class PathEscapeError extends Error {\n constructor(readonly attempted: string) {\n super(`Path resolves outside the source tree: ${attempted}`)\n this.name = 'PathEscapeError'\n }\n}\n\n/**\n * Normalise a caller-supplied key to the canonical virtual form: forward\n * slashes, no leading `./`, no `.`/`..` segments. Throws {@link PathEscapeError}\n * for an absolute path (POSIX or drive-letter), a NUL byte, an empty path, or a\n * path whose `..` segments climb past the root.\n */\nexport function normalizeVirtualPath(raw: string): string {\n const slashed = raw.replace(/\\\\/g, '/')\n if (slashed.length === 0 || slashed.includes('\\0')) throw new PathEscapeError(raw)\n if (slashed.startsWith('/') || /^[A-Za-z]:/.test(slashed)) throw new PathEscapeError(raw)\n const normalized = posix.normalize(slashed)\n if (normalized === '..' || normalized.startsWith('../') || normalized === '.' || normalized.endsWith('/')) {\n throw new PathEscapeError(raw)\n }\n return normalized\n}\n\n/**\n * Join a relative specifier onto the directory of `fromPath` and normalise.\n * Throws {@link PathEscapeError} when the result leaves the root.\n */\nexport function joinVirtual(fromPath: string, spec: string): string {\n const joined = posix.normalize(posix.join(posix.dirname(fromPath), spec))\n if (joined === '..' || joined.startsWith('../') || joined.startsWith('/')) {\n throw new PathEscapeError(spec)\n }\n return joined\n}\n\n/** esbuild's default resolve order, which the on-disk compiler relied on. */\nconst RESOLVE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.json'] as const\n\n/**\n * The files a resolved-but-unextended path may name, in esbuild's own order:\n * the exact path; for a `.js`/`.jsx`/`.mjs` spelling, the TypeScript file it\n * stands for (esbuild rewrites `./x.js` to `./x.ts` the same way); the path\n * plus each resolve extension; then `index.*` inside it.\n */\nexport function resolveCandidates(joined: string): string[] {\n const out = [joined]\n const ext = posix.extname(joined)\n if (ext === '.js' || ext === '.jsx') {\n const base = joined.slice(0, -ext.length)\n out.push(`${base}.ts`, `${base}.tsx`)\n } else if (ext === '.mjs') {\n out.push(`${joined.slice(0, -4)}.mts`)\n }\n for (const e of RESOLVE_EXTENSIONS) out.push(`${joined}${e}`)\n for (const e of RESOLVE_EXTENSIONS) out.push(`${joined}/index${e}`)\n return out\n}\n"]}