eliscript 0.0.2 → 0.0.4
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.
- package/README.md +13 -11
- package/bootstrap/README.md +13 -8
- package/bootstrap/host/build.eli +2 -0
- package/bootstrap/host/bun.eli +2 -0
- package/bootstrap/host/check-cli-legacy.eli +2 -0
- package/bootstrap/host/evaluation-cli.eli +2 -0
- package/bootstrap/host/evaluation.eli +2 -0
- package/bootstrap/host/format-cli.eli +2 -0
- package/bootstrap/host/project-cli-legacy.eli +2 -0
- package/bootstrap/host/project-legacy.eli +2 -0
- package/bootstrap/host/watch-cli.eli +2 -0
- package/bootstrap/host/watch.eli +2 -0
- package/browser/README.md +33 -0
- package/browser/host.eli +2 -0
- package/browser/host.mjs +643 -11
- package/browser/worker.eli +2 -0
- package/browser/worker.mjs +6 -3
- package/dist/browser/host.mjs +643 -11
- package/dist/browser/worker.mjs +6 -3
- package/dist/compiler-artifact.json +1 -1
- package/dist/literal-sources/runtime/core/collection.eli +76 -16
- package/dist/literal-sources/runtime/core/metadata.eli +25 -8
- package/dist/literal-sources/runtime/core/vector.eli +7 -2
- package/dist/literal-sources/stdlib/managed-literal-protocols.eli +18 -7
- package/dist/literal-sources/stdlib/managed-literals.eli +121 -66
- package/dist/stage3-release.json +1 -1
- package/package.json +11 -2
- package/platform/README.md +33 -12
- package/platform/browser.eli +2 -0
- package/platform/http.eli +2 -0
- package/platform/worker.eli +2 -0
- package/runtime/README.md +34 -14
- package/runtime/array-text.eli +2 -0
- package/runtime/core/collection-internals.eli +2 -0
- package/runtime/core/collection.eli +2 -0
- package/runtime/core/collection.mjs +99 -17
- package/runtime/core/data-text.eli +2 -0
- package/runtime/core/data.eli +2 -0
- package/runtime/core/data.mjs +7 -5
- package/runtime/core/identifier.eli +2 -0
- package/runtime/core/lazy-sequence.eli +2 -0
- package/runtime/core/list-internals.eli +2 -0
- package/runtime/core/list.eli +2 -0
- package/runtime/core/list.mjs +3 -0
- package/runtime/core/map-internals.eli +2 -0
- package/runtime/core/map.eli +2 -0
- package/runtime/core/map.mjs +5 -0
- package/runtime/core/metadata-internals.eli +2 -0
- package/runtime/core/metadata.eli +2 -0
- package/runtime/core/metadata.mjs +14 -0
- package/runtime/core/object.eli +2 -0
- package/runtime/core/order.eli +2 -0
- package/runtime/core/order.mjs +35 -6
- package/runtime/core/persistent-kind.eli +2 -0
- package/runtime/core/persistent-kind.mjs +6 -0
- package/runtime/core/protocol-error.eli +2 -0
- package/runtime/core/protocol.eli +2 -0
- package/runtime/core/queue-internals.eli +2 -0
- package/runtime/core/queue.eli +2 -0
- package/runtime/core/queue.mjs +3 -0
- package/runtime/core/record.eli +2 -0
- package/runtime/core/regex.eli +2 -0
- package/runtime/core/sequence.eli +2 -0
- package/runtime/core/sequence.mjs +75 -13
- package/runtime/core/set-algebra.eli +2 -0
- package/runtime/core/set-internals.eli +2 -0
- package/runtime/core/set.eli +2 -0
- package/runtime/core/sorted-internals.eli +2 -0
- package/runtime/core/sorted.eli +2 -0
- package/runtime/core/text.eli +2 -0
- package/runtime/core/transducer.eli +2 -0
- package/runtime/core/transient-internals.eli +2 -0
- package/runtime/core/transient.eli +2 -0
- package/runtime/core/transient.mjs +59 -10
- package/runtime/core/truth.eli +2 -0
- package/runtime/core/type.eli +2 -0
- package/runtime/core/value-internals.eli +2 -0
- package/runtime/core/value.eli +2 -0
- package/runtime/core/vector-internals.eli +2 -0
- package/runtime/core/vector-internals.mjs +3 -6
- package/runtime/core/vector.eli +2 -0
- package/runtime/core/vector.mjs +125 -7
- package/runtime/literals.eli +2 -0
- package/runtime/number-radix.eli +2 -0
- package/runtime/source-mapping.eli +2 -0
- package/runtime/testing/list.eli +2 -0
- package/runtime/testing/map.eli +2 -0
- package/runtime/testing/queue.eli +2 -0
- package/runtime/testing/set.eli +2 -0
- package/runtime/testing/sorted.eli +2 -0
- package/runtime/testing/value.eli +2 -0
- package/runtime/testing/vector.eli +2 -0
- package/runtime/wire/http-rpc.eli +2 -0
- package/runtime/wire/markdown.eli +2 -0
- package/runtime/wire/schema.eli +2 -0
- package/runtime/worker-value-codec.eli +2 -0
- package/runtime/worker-value-stream.eli +2 -0
- package/runtime/worker.eli +2 -0
- package/stdlib/README.md +2 -2
- package/stdlib/core/order.eli +36 -10
- package/stdlib/core/seq.eli +104 -75
- package/stdlib/core/zipper.eli +274 -101
- package/stdlib/managed-literal-protocols.eli +18 -7
- package/stdlib/managed-literals.eli +121 -66
- package/stdlib/managed-runtime-collection.eli +76 -16
- package/stdlib/managed-runtime-metadata.eli +25 -8
- package/stdlib/managed-runtime-order.eli +32 -10
- package/stdlib/managed-runtime-sequence.eli +69 -28
- package/stdlib/managed-runtime-vector.eli +7 -2
- package/tools/acceptance/check.eli +13 -3
- package/tools/backends/compiler-build.mjs +140 -140
- package/tools/backends/dist/release-cli.mjs +2 -0
- package/tools/backends/dist/release-cli.mjs.map +1 -1
- package/tools/backends/stage3-targets.mjs +121 -114
- package/bootstrap/host/eliscript-cli-legacy.mjs +0 -37
package/README.md
CHANGED
|
@@ -25,8 +25,8 @@ modules, and bootstraps a compiler written in Eliscript itself.
|
|
|
25
25
|
|
|
26
26
|
Building from source needs Emacs 29 or newer and Bun 1.4 or newer. The
|
|
27
27
|
compiled compiler ships in the release tarball, so a consumer needs only Node
|
|
28
|
-
24 or Bun;
|
|
29
|
-
|
|
28
|
+
24 or Bun; releases are published to GitHub Releases and the npm registry
|
|
29
|
+
(`eliscript`).
|
|
30
30
|
|
|
31
31
|
```sh
|
|
32
32
|
bun install --frozen-lockfile
|
|
@@ -56,7 +56,7 @@ without a build server or repository files. Include `dist/browser/loader.js`
|
|
|
56
56
|
and use either `data-eliscript` or `<script type="text/eliscript">` tags:
|
|
57
57
|
|
|
58
58
|
```html
|
|
59
|
-
<script defer src="https://unpkg.com/eliscript@0.0.
|
|
59
|
+
<script defer src="https://unpkg.com/eliscript@0.0.3/dist/browser/loader.js"></script>
|
|
60
60
|
<script type="text/eliscript">
|
|
61
61
|
(module app.live
|
|
62
62
|
(print "Hello from in-browser Eliscript!"))
|
|
@@ -65,7 +65,11 @@ and use either `data-eliscript` or `<script type="text/eliscript">` tags:
|
|
|
65
65
|
|
|
66
66
|
Or import the programmatic browser SDK (`eliscript/browser`) to compile single
|
|
67
67
|
modules (`compileSource`, `runSource`), multi-file projects (`compileProject`,
|
|
68
|
-
`moduleGraphUrls`), or DOM script tags (`mountEliscriptScripts`) in memory
|
|
68
|
+
`moduleGraphUrls`), or DOM script tags (`mountEliscriptScripts`) in memory, with
|
|
69
|
+
built-in IR constant-folding/dead-branch optimization (`optimizeProgramIr`),
|
|
70
|
+
optional JavaScript compaction (`optimizeJavaScript` / `{ minify: true }`), and
|
|
71
|
+
extensionless package subpath imports (`(import "eliscript/runtime/core/order" sort)`
|
|
72
|
+
alongside explicit `.mjs`).
|
|
69
73
|
|
|
70
74
|
## What Works Today
|
|
71
75
|
|
|
@@ -82,11 +86,9 @@ modules (`compileSource`, `runSource`), multi-file projects (`compileProject`,
|
|
|
82
86
|
Experimental direct backends and the zero-import managed WASM heap are described
|
|
83
87
|
in the [backend runtime reference](tools/backends/README.md). The current delivery
|
|
84
88
|
uses a JavaScript-hosted stage0–stage3 compiler chain that emits JavaScript,
|
|
85
|
-
WASM and native programs
|
|
86
|
-
|
|
87
|
-
[active plan](docs/bootstrap-0.0.
|
|
88
|
-
Explicit functional-profile acceptance reports deferred stress cases separately
|
|
89
|
-
and does not certify full-corpus or performance acceptance.
|
|
89
|
+
WASM and native programs, with 12,000-depth persistent zipper traversal and
|
|
90
|
+
edited ascent verified across all three output targets:
|
|
91
|
+
[active plan](docs/bootstrap-0.0.4-plan.md).
|
|
90
92
|
|
|
91
93
|
## Project Status
|
|
92
94
|
|
|
@@ -105,8 +107,8 @@ Known gaps, stated rather than implied:
|
|
|
105
107
|
- The proving-ground specifications are marked `In progress`: the application is
|
|
106
108
|
exercised by its tests and published, and its own acceptance set is not
|
|
107
109
|
complete.
|
|
108
|
-
-
|
|
109
|
-
Marketplace listing
|
|
110
|
+
- Releases are published to GitHub Releases and the npm registry (`eliscript`);
|
|
111
|
+
a dedicated editor Marketplace listing is not published yet.
|
|
110
112
|
|
|
111
113
|
## Contracts
|
|
112
114
|
|
package/bootstrap/README.md
CHANGED
|
@@ -50,21 +50,26 @@ formatting behavior.
|
|
|
50
50
|
boundary, single-entry and multi-entry request identity, cycle-safe dependency
|
|
51
51
|
traversal, portable-name fixed points, and versioned build-report normalization
|
|
52
52
|
and cache-status policy.
|
|
53
|
-
`host/build.mjs` dispatches normalized operations without
|
|
54
|
-
semantics.
|
|
55
|
-
`host/project.
|
|
53
|
+
`host/build.eli` (`host/build.mjs`) dispatches normalized operations without
|
|
54
|
+
defining compiler semantics.
|
|
55
|
+
`host/project-legacy.eli` and `tools/project/project.eli` (`host/project.mjs`)
|
|
56
|
+
supply the replaceable filesystem, path, artifact, and
|
|
56
57
|
timing boundary while using those generated operations for real multi-module
|
|
57
58
|
builds.
|
|
58
|
-
`host/evaluation.mjs` owns one persistent temporary
|
|
59
|
+
`host/evaluation.eli` (`host/evaluation.mjs`) owns one persistent temporary
|
|
60
|
+
namespace, canonical value
|
|
59
61
|
printing, output framing, Source Map failure normalization, revision commits,
|
|
60
|
-
and cleanup. `host/evaluation-cli.mjs` exposes
|
|
62
|
+
and cleanup. `host/evaluation-cli.eli` (`host/evaluation-cli.mjs`) exposes
|
|
63
|
+
one-shot, NDJSON, and persistent
|
|
61
64
|
terminal REPL modes through the public `eliscript-eval` command. Terminal
|
|
62
65
|
commands and presentation remain host behavior; multiline completeness remains
|
|
63
66
|
compiler-owned reader behavior.
|
|
64
|
-
`host/watch.mjs` owns canonical content snapshots, sorted
|
|
67
|
+
`host/watch.eli` (`host/watch.mjs`) owns canonical content snapshots, sorted
|
|
68
|
+
project invalidation
|
|
65
69
|
events, polling lifecycle, and the versioned `eliscript-watch-event` boundary.
|
|
66
|
-
`host/watch-cli.mjs` exposes that boundary without a
|
|
67
|
-
development server.
|
|
70
|
+
`host/watch-cli.eli` (`host/watch-cli.mjs`) exposes that boundary without a
|
|
71
|
+
framework, bundler, or development server. All `.mjs` host artifacts are
|
|
72
|
+
materialized or compiled from `.eli` sources during `make bootstrap-backends`.
|
|
68
73
|
|
|
69
74
|
## Build
|
|
70
75
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.bootstrap.host.build
|
|
2
|
+
(js* "import { compileFile, loadCompiler } from \"./bun.mjs\";\nimport { buildProject } from \"./project.mjs\";\n\nexport async function executeBuild(options) {\n const compiler = options.compiler ?? await loadCompiler(options.moduleDirectory);\n const request = compiler.build_operation_request(options);\n if (request.mode === \"single\") {\n return compileFile({ ...request, compiler });\n }\n\n const projectOptions = {\n entry: request.entry,\n entries: request.entries,\n outDir: request.outDir,\n root: request.root,\n portableEntries: request.portableEntries,\n macroCapabilities: request.macroCapabilities,\n macroFileDependencies: request.macroFileDependencies,\n useCache: request.useCache,\n sourceOverrides: options.sourceOverrides,\n moduleDirectory: options.moduleDirectory,\n };\n if (options.compiler !== undefined) {\n projectOptions.compiler = compiler;\n projectOptions.compilerDigest = options.compilerDigest;\n }\n return buildProject(projectOptions);\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.bootstrap.host.bun
|
|
2
|
+
(js* "#!/usr/bin/env bun\n\nimport {\n lstat,\n mkdir,\n readFile,\n realpath,\n stat,\n writeFile,\n} from \"node:fs/promises\";\nimport { basename, dirname, relative, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nconst commandName = process.env.ELISCRIPT_COMMAND_NAME ?? \"eliscript-portable\";\nconst usage = `Usage: ${commandName} [OPTIONS] INPUT\n\nOptions:\n -o, --output FILE Write the generated ECMAScript module to FILE\n --source-map Write FILE.map and add a sourceMappingURL comment\n --portable NAME Emit a worker entry and its transitive dependencies\n --diagnostic-format human|json\n Select human-readable or JSON failures\n -h, --help Show this help\n`;\n\nconst diagnosticFormat = \"eliscript-diagnostic\";\nconst diagnosticVersion = 1;\n\nexport function requestedDiagnosticFormat(arguments_) {\n for (let index = 0; index < arguments_.length - 1; index += 1) {\n if (arguments_[index] === \"--diagnostic-format\" &&\n arguments_[index + 1] === \"json\") {\n return \"json\";\n }\n }\n return \"human\";\n}\n\nexport function parseArguments(arguments_) {\n const argumentsList = [...arguments_];\n if (argumentsList[0] === \"--\") argumentsList.shift();\n let input;\n let output;\n let sourceMap = false;\n let diagnosticOutput = \"human\";\n const portableEntries = [];\n\n while (argumentsList.length > 0) {\n const argument = argumentsList.shift();\n if (argument === \"-h\" || argument === \"--help\") {\n return { help: true };\n }\n if (argument === \"-o\" || argument === \"--output\") {\n if (argumentsList.length === 0) {\n throw new Error(`${argument} requires a file`);\n }\n output = argumentsList.shift();\n } else if (argument === \"--source-map\") {\n sourceMap = true;\n } else if (argument === \"--portable\") {\n if (argumentsList.length === 0) {\n throw new Error(`${argument} requires a function name`);\n }\n portableEntries.push(argumentsList.shift());\n } else if (argument === \"--diagnostic-format\") {\n if (argumentsList.length === 0) {\n throw new Error(`${argument} requires human or json`);\n }\n diagnosticOutput = argumentsList.shift();\n if (diagnosticOutput !== \"human\" && diagnosticOutput !== \"json\") {\n throw new Error(`unsupported diagnostic format: ${diagnosticOutput}`);\n }\n } else if (argument.startsWith(\"-\")) {\n throw new Error(`unknown option: ${argument}`);\n } else if (input) {\n throw new Error(\"multiple input files are not supported yet\");\n } else {\n input = argument;\n }\n }\n\n if (!input) throw new Error(\"missing input file\");\n if (sourceMap && !output) {\n throw new Error(\"--source-map requires --output\");\n }\n return {\n input,\n output,\n sourceMap,\n portableEntries,\n diagnosticFormat: diagnosticOutput,\n };\n}\n\nexport function diagnosticFromError(error) {\n if (error?.eliscriptDiagnostic?.format === diagnosticFormat &&\n error.eliscriptDiagnostic.version === diagnosticVersion) {\n return error.eliscriptDiagnostic;\n }\n return {\n format: diagnosticFormat,\n version: diagnosticVersion,\n code: \"ELI-C0001\",\n severity: \"error\",\n phase: \"cli\",\n message: error instanceof Error ? error.message : String(error),\n };\n}\n\nexport function renderDiagnostic(diagnostic) {\n const location = diagnostic?.location;\n const start = location?.start;\n if (typeof location?.file === \"string\" &&\n Number.isSafeInteger(start?.line) &&\n Number.isSafeInteger(start?.column)) {\n return `${location.file}:${start.line}:${start.column}: ${diagnostic.message}`;\n }\n return diagnostic.message;\n}\n\nexport async function loadCompiler(moduleDirectory) {\n const hostDirectory = dirname(fileURLToPath(import.meta.url));\n const directory = resolve(\n moduleDirectory ??\n process.env.ELISCRIPT_BOOTSTRAP_MODULE_DIR ??\n resolve(hostDirectory, \"../../dist/bootstrap\"),\n );\n return import(pathToFileURL(resolve(directory, \"compiler.mjs\")).href);\n}\n\nasync function physicalWritePath(path) {\n let existing = resolve(path);\n const missing = [];\n\n while (true) {\n try {\n const metadata = await lstat(existing);\n if (metadata.isSymbolicLink()) {\n try {\n const target = await realpath(existing);\n return resolve(target, ...missing.reverse());\n } catch (error) {\n if (error?.code === \"ENOENT\" || error?.code === \"ENOTDIR\") {\n throw new Error(\n `generated artifact path contains an unresolved symbolic link: ${path}`,\n );\n }\n throw error;\n }\n }\n return resolve(await realpath(existing), ...missing.reverse());\n } catch (error) {\n if (error?.code !== \"ENOENT\" && error?.code !== \"ENOTDIR\") throw error;\n const parent = dirname(existing);\n if (parent === existing) throw error;\n missing.push(basename(existing));\n existing = parent;\n }\n }\n}\n\nasync function existingFileIdentity(path) {\n try {\n const metadata = await stat(path);\n return `${metadata.dev}:${metadata.ino}`;\n } catch (error) {\n if (error?.code === \"ENOENT\" || error?.code === \"ENOTDIR\") return undefined;\n throw error;\n }\n}\n\nasync function validateFileOutputPaths(inputPath, outputPaths) {\n const inputPhysical = await realpath(inputPath);\n const inputIdentity = await existingFileIdentity(inputPath);\n const artifacts = [];\n\n for (const outputPath of outputPaths) {\n const physical = await physicalWritePath(outputPath);\n const identity = await existingFileIdentity(outputPath);\n if (physical === inputPhysical ||\n (identity !== undefined && identity === inputIdentity)) {\n throw new Error(`generated artifact must not overwrite input file: ${outputPath}`);\n }\n for (const artifact of artifacts) {\n if (physical === artifact.physical ||\n (identity !== undefined && identity === artifact.identity)) {\n throw new Error(\n `generated artifacts must be physically distinct: ${artifact.path} and ${outputPath}`,\n );\n }\n }\n artifacts.push({ path: outputPath, physical, identity });\n }\n}\n\nexport async function compileFile(options) {\n const compiler = options.compiler ?? await loadCompiler(options.moduleDirectory);\n const request = compiler.build_operation_request({\n mode: \"single\",\n input: options.input,\n output: options.output ?? null,\n sourceMap: options.sourceMap === undefined ? false : options.sourceMap,\n portableEntries: options.portableEntries ?? [],\n });\n const inputPath = resolve(request.input);\n const outputPath = request.output ? resolve(request.output) : undefined;\n if (outputPath) {\n await validateFileOutputPaths(\n inputPath,\n request.sourceMap ? [outputPath, `${outputPath}.map`] : [outputPath],\n );\n }\n const source = await readFile(inputPath, \"utf8\");\n\n if (!request.sourceMap) {\n const javascript = request.portableEntries.length > 0\n ? compiler.compile_portable_string(\n source,\n request.portableEntries,\n inputPath,\n )\n : compiler.compile_string(source, inputPath);\n if (outputPath) {\n await mkdir(dirname(outputPath), { recursive: true });\n await writeFile(outputPath, javascript);\n }\n return { javascript };\n }\n\n if (!outputPath) throw new Error(\"--source-map requires --output\");\n const mapPath = `${outputPath}.map`;\n const mapDirectory = dirname(mapPath);\n const generatedName = relative(mapDirectory, outputPath);\n const sourceName = relative(mapDirectory, inputPath);\n const emission = request.portableEntries.length > 0\n ? compiler.compile_portable_string_with_source_map(\n source,\n request.portableEntries,\n inputPath,\n generatedName,\n sourceName,\n )\n : compiler.compile_string_with_source_map(\n source,\n inputPath,\n generatedName,\n sourceName,\n );\n const mapUrl = relative(dirname(outputPath), mapPath);\n const javascript = `${emission.javascript}//# sourceMappingURL=${mapUrl}\\n`;\n\n await mkdir(mapDirectory, { recursive: true });\n await writeFile(mapPath, emission.sourceMap);\n await mkdir(dirname(outputPath), { recursive: true });\n await writeFile(outputPath, javascript);\n return { javascript, sourceMap: emission.sourceMap };\n}\n\nexport async function main(arguments_ = process.argv.slice(2)) {\n const options = parseArguments(arguments_);\n if (options.help) {\n process.stdout.write(usage);\n return;\n }\n const { executeBuild } = await import(\"./build.mjs\");\n const result = await executeBuild({ mode: \"single\", ...options });\n if (!options.output) process.stdout.write(result.javascript);\n}\n\nconst isMain = process.argv[1] !== undefined &&\n resolve(process.argv[1]) === fileURLToPath(import.meta.url);\nif (isMain) {\n const outputFormat = requestedDiagnosticFormat(process.argv.slice(2));\n main().catch((error) => {\n if (outputFormat === \"json\") {\n console.error(JSON.stringify(diagnosticFromError(error)));\n } else {\n console.error(`eliscript: ${error.message}`);\n }\n process.exitCode = 1;\n });\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.bootstrap.host.check-cli-legacy
|
|
2
|
+
(js* "#!/usr/bin/env node\n\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n diagnosticFromError,\n loadCompiler,\n renderDiagnostic,\n requestedDiagnosticFormat,\n} from \"./bun.mjs\";\nimport { checkProject } from \"./project.mjs\";\nimport { readProjectConfiguration } from \"./project-cli.mjs\";\n\nconst usage = `Usage: eliscript-check [OPTIONS] [ENTRY ...]\n\nOptions:\n --config FILE Read entries and root from a versioned project request\n --root DIR Contain local source imports below DIR\n --portable NAME Check NAME and its transitive portable closure\n --stdin-file FILE Use standard input as the current contents of FILE\n --json Print the versioned project check report\n --diagnostic-format human|json\n Select human-readable or JSON failures\n -h, --help Show this help\n`;\n\nexport function parseArguments(arguments_) {\n const argumentsList = [...arguments_];\n if (argumentsList[0] === \"--\") argumentsList.shift();\n const entries = [];\n const portableEntries = [];\n let configuration;\n let root;\n let stdinFile;\n let jsonReport = false;\n let diagnosticFormat = \"human\";\n\n while (argumentsList.length > 0) {\n const argument = argumentsList.shift();\n if (argument === \"-h\" || argument === \"--help\") return { help: true };\n if (argument === \"--config\") {\n if (argumentsList.length === 0) throw new Error(`${argument} requires a file`);\n if (configuration !== undefined) {\n throw new Error(\"multiple --config files are not supported\");\n }\n configuration = argumentsList.shift();\n } else if (argument === \"--root\") {\n if (argumentsList.length === 0) throw new Error(`${argument} requires a directory`);\n root = argumentsList.shift();\n } else if (argument === \"--portable\") {\n if (argumentsList.length === 0) throw new Error(`${argument} requires an entry name`);\n portableEntries.push(argumentsList.shift());\n } else if (argument === \"--stdin-file\") {\n if (argumentsList.length === 0) throw new Error(`${argument} requires a file`);\n if (stdinFile !== undefined) {\n throw new Error(\"multiple --stdin-file values are not supported\");\n }\n stdinFile = argumentsList.shift();\n } else if (argument === \"--json\") {\n jsonReport = true;\n } else if (argument === \"--diagnostic-format\") {\n if (argumentsList.length === 0) {\n throw new Error(`${argument} requires human or json`);\n }\n diagnosticFormat = argumentsList.shift();\n if (diagnosticFormat !== \"human\" && diagnosticFormat !== \"json\") {\n throw new Error(`unsupported diagnostic format: ${diagnosticFormat}`);\n }\n } else if (argument.startsWith(\"-\")) {\n throw new Error(`unknown option: ${argument}`);\n } else {\n entries.push(argument);\n }\n }\n\n if (configuration === undefined && entries.length === 0) {\n throw new Error(\"missing entry file\");\n }\n return {\n entry: entries.length === 1 ? entries[0] : undefined,\n entries: entries.length > 1 ? entries : undefined,\n root,\n portableEntries,\n configuration,\n stdinFile,\n jsonReport,\n diagnosticFormat,\n };\n}\n\nexport async function execute(arguments_, options = {}) {\n const parsed = parseArguments(arguments_);\n if (parsed.help) return { help: true };\n const compiler = options.compiler ?? await loadCompiler(options.moduleDirectory);\n let request;\n if (parsed.configuration !== undefined) {\n const configured = await readProjectConfiguration(parsed.configuration, compiler);\n request = {\n entry: configured.entry,\n entries: configured.entries,\n root: configured.root,\n portableEntries: configured.portableEntries,\n };\n if (parsed.entries !== undefined) {\n request.entries = parsed.entries;\n delete request.entry;\n } else if (parsed.entry !== undefined) {\n request.entry = parsed.entry;\n delete request.entries;\n }\n if (parsed.root !== undefined) request.root = parsed.root;\n if (parsed.portableEntries.length > 0) {\n request.portableEntries = parsed.portableEntries;\n }\n } else {\n request = {\n entry: parsed.entry,\n entries: parsed.entries,\n root: parsed.root,\n portableEntries: parsed.portableEntries,\n };\n }\n let sourceOverrides;\n if (parsed.stdinFile !== undefined) {\n const sourceText = options.stdinSource ?? await readFile(0, \"utf8\");\n sourceOverrides = { [resolve(parsed.stdinFile)]: sourceText };\n }\n const result = await checkProject({\n ...request,\n sourceOverrides,\n compiler,\n moduleDirectory: options.moduleDirectory,\n });\n return { result, jsonReport: parsed.jsonReport };\n}\n\nexport async function main(arguments_ = process.argv.slice(2)) {\n const execution = await execute(arguments_);\n if (execution.help) {\n process.stdout.write(usage);\n return;\n }\n process.stdout.write(execution.jsonReport\n ? `${JSON.stringify(execution.result.report)}\\n`\n : `Checked ${execution.result.report.counts.modules} modules.\\n`);\n}\n\nconst isMain = process.argv[1] !== undefined &&\n resolve(process.argv[1]) === fileURLToPath(import.meta.url);\nif (isMain) {\n const outputFormat = requestedDiagnosticFormat(process.argv.slice(2));\n main().catch((error) => {\n const diagnostic = diagnosticFromError(error);\n if (outputFormat === \"json\") {\n console.error(JSON.stringify(diagnostic));\n } else {\n console.error(`eliscript-check: ${renderDiagnostic(diagnostic)}`);\n }\n process.exitCode = 1;\n });\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.bootstrap.host.evaluation-cli
|
|
2
|
+
(js* "#!/usr/bin/env node\n\nimport { createInterface } from \"node:readline\";\nimport { resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n EvaluationSession,\n evaluationResultFormat,\n evaluationResultVersion,\n readEvaluationFile,\n} from \"./evaluation.mjs\";\n\nconst usage = `Usage: eliscript-eval [OPTIONS]\n\nOptions:\n --repl Run the persistent terminal REPL (default mode)\n --stdio Read and write one JSON record per line\n --eval SOURCE Evaluate one form\n --file FILE Load one complete Eliscript source file\n --root DIRECTORY Set the project root for REPL, --eval, or --file\n --json Print the one-shot result as JSON\n --prompt Always print the REPL banner and prompts\n --no-prompt Never print the REPL banner or prompts\n --help Show this help\n`;\n\nconst replHelp = `Commands:\n :help Show this command summary\n :load FILE Load one complete source file\n :reload Reload the last successfully loaded file\n :reset Discard the current namespace\n :quit Close the session\n`;\n\nconst replFilename = \"<repl>.eli\";\n\nfunction cliError(message) {\n const error = new Error(message);\n error.code = \"ELI-C0001\";\n return error;\n}\n\nfunction parseArguments(argv) {\n const options = {\n json: false,\n mode: null,\n root: null,\n source: null,\n file: null,\n prompt: \"auto\",\n };\n const chooseMode = (mode) => {\n if (options.mode !== null) throw cliError(\"choose exactly one evaluation mode\");\n options.mode = mode;\n };\n const choosePrompt = (prompt) => {\n if (options.prompt !== \"auto\") throw cliError(\"choose at most one prompt mode\");\n options.prompt = prompt;\n };\n for (let index = 0; index < argv.length; index += 1) {\n const argument = argv[index];\n switch (argument) {\n case \"--repl\":\n chooseMode(\"repl\");\n break;\n case \"--stdio\":\n chooseMode(\"stdio\");\n break;\n case \"--eval\":\n chooseMode(\"evaluate\");\n options.source = argv[++index];\n if (options.source === undefined) throw cliError(\"--eval requires SOURCE\");\n break;\n case \"--file\":\n chooseMode(\"load\");\n options.file = argv[++index];\n if (options.file === undefined) throw cliError(\"--file requires FILE\");\n break;\n case \"--root\":\n options.root = argv[++index];\n if (options.root === undefined) throw cliError(\"--root requires DIRECTORY\");\n break;\n case \"--json\": options.json = true; break;\n case \"--prompt\": choosePrompt(\"always\"); break;\n case \"--no-prompt\": choosePrompt(\"never\"); break;\n case \"--help\": chooseMode(\"help\"); break;\n default: throw cliError(`unknown option: ${argument}`);\n }\n }\n if (options.mode === null) options.mode = \"repl\";\n if (options.mode === \"stdio\" &&\n (options.json || options.root !== null || options.prompt !== \"auto\")) {\n throw cliError(\"--stdio accepts complete request records and no presentation options\");\n }\n if (options.mode === \"repl\" && options.json) {\n throw cliError(\"--json is available only for one-shot evaluation\");\n }\n if (options.mode !== \"repl\" && options.prompt !== \"auto\") {\n throw cliError(\"prompt options are available only in REPL mode\");\n }\n if (options.mode === \"help\" &&\n (options.json || options.root !== null || options.prompt !== \"auto\")) {\n throw cliError(\"--help does not accept evaluation or presentation options\");\n }\n return options;\n}\n\nfunction protocolFailure(message, revision) {\n return {\n format: evaluationResultFormat,\n version: evaluationResultVersion,\n id: null,\n operation: \"unknown\",\n revision,\n status: \"error\",\n diagnostic: {\n format: \"eliscript-diagnostic\",\n version: 1,\n code: \"ELI-E0001\",\n severity: \"error\",\n phase: \"evaluation-request\",\n message,\n },\n };\n}\n\nasync function runStdio() {\n const session = await EvaluationSession.create();\n const close = () => session.close();\n process.once(\"exit\", close);\n process.once(\"SIGINT\", () => {\n close();\n process.exit(130);\n });\n process.once(\"SIGTERM\", () => {\n close();\n process.exit(143);\n });\n try {\n const input = createInterface({ input: process.stdin, crlfDelay: Infinity });\n for await (const line of input) {\n if (line.trim() === \"\") continue;\n let result;\n try {\n result = await session.execute(JSON.parse(line));\n } catch (error) {\n result = protocolFailure(\n error instanceof Error ? error.message : String(error),\n session.revision,\n );\n }\n process.stdout.write(`${JSON.stringify(result)}\\n`);\n }\n } finally {\n process.removeListener(\"exit\", close);\n close();\n }\n}\n\nfunction diagnosticText(diagnostic) {\n const location = diagnostic?.location;\n const start = location?.start;\n const prefix = location?.file\n ? `${location.file}:${start?.line ?? location.line ?? 1}:` +\n `${start?.column ?? location.column ?? 1}: `\n : \"\";\n return `${prefix}${diagnostic?.message ?? \"evaluation failed\"}`;\n}\n\nfunction renderHuman(result) {\n if (result.status === \"error\") throw cliError(diagnosticText(result.diagnostic));\n if (result.kind === \"expression\" || result.kind === \"definition\") {\n return result.hasValue ? result.value : result.binding;\n }\n if (result.kind === \"module\") return `loaded ${result.bindings.length} bindings`;\n if (result.kind === \"reset\") return \"session reset\";\n if (result.kind === \"capabilities\") return \"session ready\";\n throw cliError(`unsupported evaluation result kind: ${result.kind}`);\n}\n\nfunction writeHumanResult(result, recoverable = false) {\n if (result.stdout) process.stdout.write(result.stdout);\n try {\n process.stdout.write(`${renderHuman(result)}\\n`);\n return true;\n } catch (error) {\n if (!recoverable) throw error;\n process.stdout.write(`eliscript-eval: ${error.message}\\n`);\n return false;\n }\n}\n\nfunction writeRecoverableError(error) {\n const message = error?.eliscriptDiagnostic\n ? diagnosticText(error.eliscriptDiagnostic)\n : error instanceof Error ? error.message : String(error);\n process.stdout.write(`eliscript-eval: ${message}\\n`);\n}\n\nfunction replCommand(line) {\n const match = line.trim().match(/^:([^\\s]+)(?:\\s+(.*))?$/u);\n return match ? { name: match[1], argument: match[2]?.trim() ?? \"\" } : null;\n}\n\nfunction showPrompt(_input, visible, continuation) {\n if (!visible) return;\n process.stdout.write(continuation ? \" ... \" : \"eliscript=> \");\n}\n\nasync function runTerminalCommand(command, context) {\n const { session, options } = context;\n switch (command.name) {\n case \"help\":\n if (command.argument !== \"\") throw cliError(\":help does not accept arguments\");\n process.stdout.write(replHelp);\n return false;\n case \"load\": {\n if (command.argument === \"\") throw cliError(\":load requires FILE\");\n const file = readEvaluationFile(command.argument);\n const result = await session.execute({\n id: ++context.nextId,\n operation: \"load\",\n source: file.source,\n filename: file.filename,\n root: options.root,\n });\n if (writeHumanResult(result, true)) context.lastFile = file.filename;\n return false;\n }\n case \"reload\": {\n if (command.argument !== \"\") throw cliError(\":reload does not accept arguments\");\n if (context.lastFile === null) throw cliError(\":reload requires a prior successful :load\");\n const file = readEvaluationFile(context.lastFile);\n const result = await session.execute({\n id: ++context.nextId,\n operation: \"load\",\n source: file.source,\n filename: file.filename,\n root: options.root,\n });\n if (writeHumanResult(result, true)) context.lastFile = file.filename;\n return false;\n }\n case \"reset\": {\n if (command.argument !== \"\") throw cliError(\":reset does not accept arguments\");\n writeHumanResult(await session.execute({\n id: ++context.nextId,\n operation: \"reset\",\n }), true);\n context.lastFile = null;\n return false;\n }\n case \"quit\":\n if (command.argument !== \"\") throw cliError(\":quit does not accept arguments\");\n return true;\n default:\n throw cliError(`unknown REPL command: :${command.name}`);\n }\n}\n\nasync function runRepl(options) {\n const session = await EvaluationSession.create();\n const promptVisible = options.prompt === \"always\" ||\n (options.prompt === \"auto\" && process.stdin.isTTY && process.stdout.isTTY);\n const input = createInterface({\n input: process.stdin,\n ...(promptVisible ? { output: process.stdout } : {}),\n terminal: promptVisible && Boolean(process.stdin.isTTY),\n crlfDelay: Infinity,\n });\n const context = { session, options, nextId: 0, lastFile: null };\n let source = \"\";\n let interrupted = false;\n const close = () => session.close();\n const terminate = () => {\n close();\n process.exit(143);\n };\n process.once(\"exit\", close);\n process.once(\"SIGTERM\", terminate);\n input.on(\"SIGINT\", () => {\n if (source !== \"\") {\n source = \"\";\n process.stdout.write(\"^C\\n\");\n showPrompt(input, promptVisible, false);\n } else {\n interrupted = true;\n input.close();\n }\n });\n try {\n if (promptVisible) {\n process.stdout.write(\"Eliscript REPL. Type :help for commands.\\n\");\n showPrompt(input, true, false);\n }\n for await (const line of input) {\n if (source === \"\") {\n const command = replCommand(line);\n if (command) {\n try {\n if (await runTerminalCommand(command, context)) break;\n } catch (error) {\n writeRecoverableError(error);\n }\n showPrompt(input, promptVisible, false);\n continue;\n }\n }\n source = source === \"\" ? line : `${source}\\n${line}`;\n let description;\n try {\n description = session.compiler.evaluation_input_description(\n source,\n replFilename,\n );\n } catch (error) {\n writeRecoverableError(error);\n source = \"\";\n showPrompt(input, promptVisible, false);\n continue;\n }\n if (description.status === \"incomplete\") {\n showPrompt(input, promptVisible, true);\n continue;\n }\n if (description.status === \"complete\") {\n writeHumanResult(await session.execute({\n id: ++context.nextId,\n operation: \"evaluate\",\n source,\n filename: replFilename,\n root: options.root,\n }), true);\n }\n source = \"\";\n showPrompt(input, promptVisible, false);\n }\n if (!interrupted && source !== \"\") {\n writeHumanResult(await session.execute({\n id: ++context.nextId,\n operation: \"evaluate\",\n source,\n filename: replFilename,\n root: options.root,\n }), true);\n }\n } finally {\n process.removeListener(\"exit\", close);\n process.removeListener(\"SIGTERM\", terminate);\n input.close();\n close();\n }\n}\n\nasync function runOneShot(options) {\n const session = await EvaluationSession.create();\n try {\n let request;\n if (options.mode === \"load\") {\n const file = readEvaluationFile(options.file);\n request = {\n id: 0,\n operation: \"load\",\n source: file.source,\n filename: file.filename,\n root: options.root,\n };\n } else {\n request = {\n id: 0,\n operation: \"evaluate\",\n source: options.source,\n filename: \"<command-line>.eli\",\n root: options.root,\n };\n }\n const result = await session.execute(request);\n if (options.json) process.stdout.write(`${JSON.stringify(result)}\\n`);\n else writeHumanResult(result);\n } finally {\n session.close();\n }\n}\n\nexport async function main(arguments_ = process.argv.slice(2)) {\n try {\n const options = parseArguments(arguments_);\n if (options.mode === \"help\") process.stdout.write(usage);\n else if (options.mode === \"stdio\") await runStdio();\n else if (options.mode === \"repl\") await runRepl(options);\n else await runOneShot(options);\n } catch (error) {\n process.stderr.write(`eliscript-eval: ${error.message}\\n`);\n process.exitCode = 1;\n }\n}\n\nconst isMain = process.argv[1] !== undefined &&\n resolve(process.argv[1]) === fileURLToPath(import.meta.url);\nif (isMain) await main();\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.bootstrap.host.evaluation
|
|
2
|
+
(js* "import { createHash } from \"node:crypto\";\nimport {\n existsSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n realpathSync,\n rmSync,\n symlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { SourceMap } from \"node:module\";\nimport { format } from \"node:util\";\nimport {\n basename,\n dirname,\n isAbsolute,\n join,\n relative,\n resolve,\n sep,\n} from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nimport { printValue } from \"../../runtime/core/data-text.mjs\";\nimport { loadCompiler } from \"./bun.mjs\";\nimport { buildProject } from \"./project.mjs\";\n\nexport const evaluationResultFormat = \"eliscript-evaluation-result\";\nexport const evaluationResultVersion = 1;\n\nconst projectDirectory = resolve(dirname(fileURLToPath(import.meta.url)), \"../..\");\nconst evaluationCompilerDigest = createHash(\"sha256\")\n .update(\"eliscript-evaluation-session-v1\")\n .digest(\"hex\");\n\nfunction frozen(value) {\n return Object.freeze(value);\n}\n\nfunction diagnosticError(message, filename = undefined) {\n const error = new Error(message);\n error.eliscriptDiagnostic = {\n format: \"eliscript-diagnostic\",\n version: 1,\n code: \"ELI-E0001\",\n severity: \"error\",\n phase: \"evaluation-request\",\n message,\n ...(filename ? { location: { file: filename } } : {}),\n };\n return error;\n}\n\nfunction containedPath(path, root) {\n const pathFromRoot = relative(root, path);\n return pathFromRoot === \"\" ||\n (!pathFromRoot.startsWith(`..${sep}`) && pathFromRoot !== \"..\" &&\n !isAbsolute(pathFromRoot));\n}\n\nfunction nearestProjectRoot(filename) {\n let directory = dirname(filename);\n while (true) {\n if (existsSync(join(directory, \"eliscript.json\"))) return directory;\n const parent = dirname(directory);\n if (parent === directory) return dirname(filename);\n directory = parent;\n }\n}\n\nfunction requestFilename(filename) {\n return isAbsolute(filename) ? resolve(filename) : resolve(process.cwd(), filename);\n}\n\nfunction runtimeCategory(value) {\n if (value === null) return \"nil\";\n if (value === undefined) return \"undefined\";\n return typeof value;\n}\n\nfunction stackLocation(stack) {\n if (typeof stack !== \"string\") return null;\n const match = stack.match(\n /(?:at\\s+)?(?:file:\\/\\/)?([^\\s()]+\\.eli):(\\d+):(\\d+)/u,\n );\n if (!match) return null;\n return {\n file: match[1].trim(),\n line: Number(match[2]),\n column: Number(match[3]),\n };\n}\n\nfunction generatedStackLocation(stack) {\n if (typeof stack !== \"string\") return null;\n const match = stack.match(\n /(?:at\\s+)?(?:file:\\/\\/)?([^\\s()?]+\\.mjs)(?:[?#][^\\s():]*)?:(\\d+):(\\d+)/u,\n );\n if (!match) return null;\n const generatedFile = decodeURIComponent(match[1].trim());\n const mapFile = `${generatedFile}.map`;\n if (!existsSync(mapFile)) return null;\n try {\n const sourceMap = new SourceMap(JSON.parse(readFileSync(mapFile, \"utf8\")));\n const entry = sourceMap.findEntry(Number(match[2]) - 1, Number(match[3]) - 1);\n if (!entry?.originalSource) return null;\n const originalSource = entry.originalSource.startsWith(\"file://\")\n ? fileURLToPath(entry.originalSource)\n : entry.originalSource;\n return {\n file: isAbsolute(originalSource)\n ? originalSource\n : resolve(dirname(mapFile), originalSource),\n line: entry.originalLine + 1,\n column: entry.originalColumn + 1,\n };\n } catch {\n return null;\n }\n}\n\nfunction remapPoint(point, adjustment) {\n const relativeLine = point.line - adjustment.expressionLine + 1;\n if (relativeLine < 1) return point;\n return {\n ...point,\n line: adjustment.line + relativeLine - 1,\n column: relativeLine === 1\n ? adjustment.column + Math.max(0, point.column - adjustment.expressionColumn)\n : point.column,\n };\n}\n\nfunction remapLocation(location, adjustment) {\n if (!location || !adjustment || location.file !== adjustment.syntheticFilename) {\n return location;\n }\n if (location.start && typeof location.start === \"object\") {\n return {\n ...location,\n file: adjustment.filename,\n start: remapPoint(location.start, adjustment),\n ...(location.end\n ? { end: remapPoint(location.end, adjustment) }\n : {}),\n };\n }\n return { ...remapPoint(location, adjustment), file: adjustment.filename };\n}\n\nfunction normalizeDiagnostic(error, adjustment = undefined) {\n const existing = error?.eliscriptDiagnostic;\n if (existing && typeof existing === \"object\") {\n const location = remapLocation(existing.location, adjustment);\n return frozen({\n ...existing,\n ...(location ? { location: frozen({ ...location }) } : {}),\n });\n }\n const location = remapLocation(\n stackLocation(error?.stack) ?? generatedStackLocation(error?.stack),\n adjustment,\n );\n return frozen({\n format: \"eliscript-diagnostic\",\n version: 1,\n code: \"ELI-E0002\",\n severity: \"error\",\n phase: \"evaluation-runtime\",\n message: error instanceof Error ? error.message : String(error),\n ...(location ? { location: frozen(location) } : {}),\n });\n}\n\nfunction resultBase(request, revision) {\n return {\n format: evaluationResultFormat,\n version: evaluationResultVersion,\n id: request?.id ?? null,\n operation: request?.operation ?? \"unknown\",\n revision,\n };\n}\n\nfunction success(request, revision, details) {\n return frozen({\n ...resultBase(request, revision),\n status: \"ok\",\n ...details,\n });\n}\n\nfunction appendCapturedOutput(result, stdout) {\n if (stdout === \"\") return result;\n return frozen({ ...result, stdout });\n}\n\nasync function captureStandardOutput(action) {\n const write = process.stdout.write;\n const consoleMethods = new Map();\n let stdout = \"\";\n process.stdout.write = function capture(chunk, encoding, callback) {\n stdout += Buffer.isBuffer(chunk)\n ? chunk.toString(typeof encoding === \"string\" ? encoding : \"utf8\")\n : String(chunk);\n const done = typeof encoding === \"function\" ? encoding : callback;\n if (typeof done === \"function\") queueMicrotask(done);\n return true;\n };\n for (const name of [\"debug\", \"info\", \"log\"]) {\n consoleMethods.set(name, console[name]);\n console[name] = (...values) => {\n stdout += `${format(...values)}\\n`;\n };\n }\n try {\n return { value: await action(), stdout };\n } catch (error) {\n error.eliscriptCapturedStdout = stdout;\n throw error;\n } finally {\n process.stdout.write = write;\n for (const [name, method] of consoleMethods) console[name] = method;\n }\n}\n\nfunction failure(rawRequest, request, revision, error, adjustment = undefined) {\n const rawId = rawRequest && typeof rawRequest === \"object\" ? rawRequest.id : null;\n const id = request?.id ?? (\n (typeof rawId === \"string\" && rawId.length > 0) ||\n (Number.isSafeInteger(rawId) && rawId >= 0)\n ? rawId\n : null\n );\n return frozen({\n ...resultBase({\n id,\n operation: request?.operation ?? (\n typeof rawRequest?.operation === \"string\" ? rawRequest.operation : \"unknown\"\n ),\n }, revision),\n status: \"error\",\n diagnostic: normalizeDiagnostic(error, adjustment),\n });\n}\n\nfunction namespaceSource(source, description) {\n const exported = new Set(description.exports);\n const missing = description.bindings.filter((name) => !exported.has(name));\n if (missing.length === 0) return source;\n return `${source}\\n(export ${missing.join(\" \")})\\n`;\n}\n\nfunction expressionSource(request, namespace) {\n const prelude = [...(namespace?.macroSources ?? [])];\n if (namespace?.bindings.length > 0) {\n prelude.push(`(import ${JSON.stringify(namespace.url)} ${\n namespace.bindings.join(\" \")})`);\n }\n const prefix = \"(export-default \";\n const expressionLine = prelude.reduce(\n (lines, source) => lines + source.split(\"\\n\").length,\n 1,\n );\n const syntheticFilename = `${requestFilename(request.filename)}.eval.eli`;\n return {\n source: `${prelude.length > 0 ? `${prelude.join(\"\\n\")}\\n` : \"\"}${\n prefix}${request.source}\\n)`,\n adjustment: {\n syntheticFilename,\n filename: request.filename,\n line: request.line,\n column: request.column,\n expressionLine,\n expressionColumn: prefix.length + 1,\n },\n };\n}\n\nexport class EvaluationSession {\n constructor(options) {\n this.compiler = options.compiler;\n this.directory = options.directory;\n this.revision = 0;\n this.artifact = 0;\n this.namespace = null;\n this.mode = \"empty\";\n this.definitions = new Map();\n this.definitionFilename = null;\n this.closed = false;\n }\n\n static async create(options = {}) {\n const compiler = options.compiler ?? await loadCompiler(options.moduleDirectory);\n const directory = mkdtempSync(join(tmpdir(), \"eliscript-evaluation-\"));\n try {\n mkdirSync(join(directory, \"node_modules\"), { recursive: true });\n symlinkSync(projectDirectory, join(directory, \"node_modules\", \"eliscript\"),\n \"dir\");\n return new EvaluationSession({ compiler, directory });\n } catch (error) {\n rmSync(directory, { recursive: true, force: true });\n throw error;\n }\n }\n\n ensureOpen() {\n if (this.closed) throw diagnosticError(\"evaluation session is closed\");\n }\n\n nextArtifactDirectory(label) {\n this.artifact += 1;\n const directory = join(this.directory, `${String(this.artifact).padStart(6, \"0\")}-${label}`);\n mkdirSync(directory, { recursive: true });\n return directory;\n }\n\n async compileSingle(source, filename, label) {\n const directory = this.nextArtifactDirectory(label);\n const generatedName = `${label}.mjs`;\n const modulePath = join(directory, generatedName);\n const emission = this.compiler.compile_string_with_source_map(\n source,\n filename,\n generatedName,\n filename,\n );\n writeFileSync(\n modulePath,\n `${emission.javascript}\\n`,\n \"utf8\",\n );\n writeFileSync(`${modulePath}.map`, emission.sourceMap, \"utf8\");\n const url = `${pathToFileURL(modulePath).href}?artifact=${this.artifact}`;\n return { module: await import(url), modulePath, url };\n }\n\n async compileProject(source, filename, root, label) {\n const directory = this.nextArtifactDirectory(label);\n const result = await buildProject({\n entry: filename,\n outDir: directory,\n root,\n portableEntries: [],\n useCache: false,\n sourceOverrides: new Map([[filename, source]]),\n compiler: this.compiler,\n compilerDigest: evaluationCompilerDigest,\n sourceMapReference: false,\n });\n const modulePath = result.entryOutput;\n const url = `${pathToFileURL(modulePath).href}?artifact=${this.artifact}`;\n return { module: await import(url), modulePath, url };\n }\n\n async buildNamespace(source, filename, root, label) {\n const description = this.compiler.evaluation_module_description(source, filename);\n const compiledSource = namespaceSource(source, description);\n const absoluteFilename = requestFilename(filename);\n let artifact;\n if (existsSync(absoluteFilename) && absoluteFilename.endsWith(\".eli\")) {\n const canonicalFilename = realpathSync(absoluteFilename);\n const requestedRoot = root === null ? nearestProjectRoot(canonicalFilename) : resolve(root);\n const canonicalRoot = realpathSync(requestedRoot);\n if (!containedPath(canonicalFilename, canonicalRoot)) {\n throw diagnosticError(\"evaluation file escapes project root\", filename);\n }\n artifact = await this.compileProject(\n compiledSource,\n canonicalFilename,\n canonicalRoot,\n label,\n );\n } else {\n artifact = await this.compileSingle(compiledSource, filename, label);\n }\n return frozen({\n ...artifact,\n filename,\n source,\n bindings: description.bindings,\n exports: description.exports,\n macroSources: description.macroSources,\n });\n }\n\n commitNamespace(namespace, mode) {\n this.namespace = namespace;\n this.mode = mode;\n this.revision += 1;\n }\n\n async describe(request) {\n return success(request, this.revision, {\n kind: \"capabilities\",\n capabilities: frozen({\n operations: frozen([\"describe\", \"evaluate\", \"load\", \"reset\"]),\n persistentSession: true,\n sourceMaps: true,\n valuePrinter: \"eliscript-data-text\",\n }),\n });\n }\n\n async load(request) {\n const namespace = await this.buildNamespace(\n request.source,\n request.filename,\n request.root,\n `namespace-${this.revision + 1}`,\n );\n this.definitions = new Map();\n this.definitionFilename = null;\n this.commitNamespace(namespace, \"loaded\");\n return success(request, this.revision, {\n kind: \"module\",\n bindings: namespace.bindings,\n value: null,\n valueCategory: \"module\",\n });\n }\n\n async evaluateDefinition(request, description) {\n if (this.mode === \"loaded\") {\n throw diagnosticError(\n \"evaluate a complete updated source to replace definitions from a loaded module\",\n request.filename,\n );\n }\n if (this.definitionFilename !== null &&\n this.definitionFilename !== request.filename) {\n throw diagnosticError(\n \"one definition journal cannot mix logical filenames\",\n request.filename,\n );\n }\n const definitions = new Map(this.definitions);\n definitions.set(description.name, request.source);\n const source = [...definitions.values()].join(\"\\n\");\n const namespace = await this.buildNamespace(\n source,\n request.filename,\n request.root,\n `namespace-${this.revision + 1}`,\n );\n this.definitions = definitions;\n this.definitionFilename = request.filename;\n this.commitNamespace(namespace, \"journal\");\n const hasValue = description.runtimeBinding &&\n Object.hasOwn(namespace.module, description.name);\n const value = hasValue ? namespace.module[description.name] : undefined;\n return success(request, this.revision, {\n kind: \"definition\",\n binding: description.name,\n hasValue,\n value: hasValue ? printValue(value) : null,\n valueCategory: hasValue ? runtimeCategory(value) : \"macro\",\n });\n }\n\n async evaluateExpression(request) {\n const prepared = expressionSource(request, this.namespace);\n let artifact;\n try {\n artifact = await this.compileSingle(\n prepared.source,\n prepared.adjustment.syntheticFilename,\n `expression-${this.artifact + 1}`,\n );\n } catch (error) {\n error.eliscriptEvaluationAdjustment = prepared.adjustment;\n throw error;\n }\n const value = await artifact.module.default;\n return success(request, this.revision, {\n kind: \"expression\",\n hasValue: true,\n value: printValue(value),\n valueCategory: runtimeCategory(value),\n });\n }\n\n async evaluate(request) {\n const description = this.compiler.evaluation_form_description(\n request.source,\n request.filename,\n );\n if (description.kind === \"module\") {\n throw diagnosticError(\n \"module forms require a complete-source load operation\",\n request.filename,\n );\n }\n return description.kind === \"definition\"\n ? this.evaluateDefinition(request, description)\n : this.evaluateExpression(request);\n }\n\n async reset(request) {\n this.namespace = null;\n this.mode = \"empty\";\n this.definitions = new Map();\n this.definitionFilename = null;\n this.revision += 1;\n return success(request, this.revision, {\n kind: \"reset\",\n hasValue: false,\n value: null,\n valueCategory: \"none\",\n });\n }\n\n async execute(rawRequest) {\n this.ensureOpen();\n let request;\n try {\n request = this.compiler.evaluation_operation_request(rawRequest);\n const executed = await captureStandardOutput(async () => {\n switch (request.operation) {\n case \"describe\": return this.describe(request);\n case \"evaluate\": return this.evaluate(request);\n case \"load\": return this.load(request);\n case \"reset\": return this.reset(request);\n default: throw diagnosticError(\"unsupported evaluation operation\");\n }\n });\n return appendCapturedOutput(executed.value, executed.stdout);\n } catch (error) {\n return appendCapturedOutput(failure(\n rawRequest,\n request,\n this.revision,\n error,\n error?.eliscriptEvaluationAdjustment,\n ), error?.eliscriptCapturedStdout ?? \"\");\n }\n }\n\n close() {\n if (this.closed) return;\n this.closed = true;\n rmSync(this.directory, { recursive: true, force: true });\n }\n}\n\nexport async function evaluateOnce(request, options = {}) {\n const session = await EvaluationSession.create(options);\n try {\n return await session.execute(request);\n } finally {\n session.close();\n }\n}\n\nexport function readEvaluationFile(filename) {\n const absolute = requestFilename(filename);\n return { filename: absolute, source: readFileSync(absolute, \"utf8\") };\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.bootstrap.host.format-cli
|
|
2
|
+
(js* "#!/usr/bin/env node\n\nimport { randomUUID } from \"node:crypto\";\nimport {\n readFile,\n rename,\n stat,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { basename, dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n diagnosticFromError,\n loadCompiler,\n requestedDiagnosticFormat,\n} from \"./bun.mjs\";\n\nconst usage = `Usage: eliscript-format [OPTIONS] INPUT\n\nOptions:\n --write Atomically replace INPUT when formatting changes\n --check Fail without writing when INPUT is not canonical\n --diagnostic-format human|json\n Select human-readable or JSON failures\n -h, --help Show this help\n`;\n\nexport function parseArguments(arguments_) {\n const argumentsList = [...arguments_];\n if (argumentsList[0] === \"--\") argumentsList.shift();\n let input;\n let write = false;\n let check = false;\n let diagnosticFormat = \"human\";\n\n while (argumentsList.length > 0) {\n const argument = argumentsList.shift();\n if (argument === \"-h\" || argument === \"--help\") {\n return { help: true };\n }\n if (argument === \"--write\") {\n write = true;\n } else if (argument === \"--check\") {\n check = true;\n } else if (argument === \"--diagnostic-format\") {\n if (argumentsList.length === 0) {\n throw new Error(`${argument} requires human or json`);\n }\n diagnosticFormat = argumentsList.shift();\n if (diagnosticFormat !== \"human\" && diagnosticFormat !== \"json\") {\n throw new Error(`unsupported diagnostic format: ${diagnosticFormat}`);\n }\n } else if (argument.startsWith(\"-\")) {\n throw new Error(`unknown option: ${argument}`);\n } else if (input !== undefined) {\n throw new Error(\"multiple input files are not supported\");\n } else {\n input = argument;\n }\n }\n\n if (input === undefined) throw new Error(\"missing input file\");\n if (write && check) throw new Error(\"--write and --check are mutually exclusive\");\n return { input, write, check, diagnosticFormat };\n}\n\nfunction unformattedError(filename) {\n const error = new Error(`${filename} is not formatted`);\n error.eliscriptDiagnostic = {\n format: \"eliscript-diagnostic\",\n version: 1,\n code: \"ELI-F0002\",\n severity: \"error\",\n phase: \"formatter\",\n message: \"file is not formatted\",\n location: { file: filename },\n };\n return error;\n}\n\nasync function atomicWrite(filename, source, mode) {\n const temporary = resolve(\n dirname(filename),\n `.${basename(filename)}.eliscript-format-${process.pid}-${randomUUID()}`,\n );\n try {\n await writeFile(temporary, source, { encoding: \"utf8\", mode });\n await rename(temporary, filename);\n } catch (error) {\n await unlink(temporary).catch(() => {});\n throw error;\n }\n}\n\nexport async function formatFile(options) {\n if (!options || typeof options !== \"object\") {\n throw new Error(\"formatter options must be an object\");\n }\n const filename = resolve(options.input);\n const compiler = options.compiler ?? await loadCompiler(options.moduleDirectory);\n const [source, attributes] = await Promise.all([\n readFile(filename, \"utf8\"),\n stat(filename),\n ]);\n const formatted = compiler.format_source(source, filename);\n const changed = formatted !== source;\n\n if (options.check && changed) throw unformattedError(filename);\n if (options.write && changed) {\n await atomicWrite(filename, formatted, attributes.mode);\n }\n return Object.freeze({ filename, formatted, changed });\n}\n\nexport async function main(arguments_ = process.argv.slice(2)) {\n const options = parseArguments(arguments_);\n if (options.help) {\n process.stdout.write(usage);\n return;\n }\n const result = await formatFile(options);\n if (!options.write && !options.check) process.stdout.write(result.formatted);\n}\n\nconst isMain = process.argv[1] !== undefined &&\n resolve(process.argv[1]) === fileURLToPath(import.meta.url);\nif (isMain) {\n const outputFormat = requestedDiagnosticFormat(process.argv.slice(2));\n main().catch((error) => {\n if (outputFormat === \"json\") {\n console.error(JSON.stringify(diagnosticFromError(error)));\n } else {\n console.error(`eliscript-format: ${error.message}`);\n }\n process.exitCode = 1;\n });\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.bootstrap.host.project-cli-legacy
|
|
2
|
+
(js* "#!/usr/bin/env node\n\nimport { readFile, realpath, stat } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n diagnosticFromError,\n loadCompiler,\n renderDiagnostic,\n requestedDiagnosticFormat,\n} from \"./bun.mjs\";\nimport { executeBuild } from \"./build.mjs\";\n\nconst usage = `Usage: eliscript-build [OPTIONS] [ENTRY ...]\n\nOptions:\n --out-dir DIR Write the generated module tree to DIR\n --config FILE Read a versioned project request from FILE\n --root DIR Contain local source imports below DIR\n --portable NAME Emit NAME and its transitive portable closure\n --stdin-file FILE Use standard input as the current contents of FILE\n --no-cache Disable cache reads for this build\n --json Print the versioned build decision report\n --diagnostic-format human|json\n Select human-readable or JSON failures\n -h, --help Show this help\n`;\n\nfunction configurationError(message, filename) {\n const error = new Error(message);\n error.eliscriptDiagnostic = {\n format: \"eliscript-diagnostic\",\n version: 1,\n code: \"ELI-B0002\",\n severity: \"error\",\n phase: \"project-config\",\n message,\n ...(filename ? { location: { file: filename } } : {}),\n };\n throw error;\n}\n\nfunction skipWhitespace(source, start) {\n let index = start;\n while (index < source.length && /[\\t\\n\\r ]/u.test(source[index])) index += 1;\n return index;\n}\n\nfunction scanString(source, start) {\n let index = start + 1;\n while (index < source.length) {\n if (source[index] === \"\\\\\") {\n index += 2;\n } else if (source[index] === '\"') {\n return index + 1;\n } else {\n index += 1;\n }\n }\n return source.length;\n}\n\nfunction scanValue(source, start) {\n const index = skipWhitespace(source, start);\n if (source[index] === \"{\") return scanObject(source, index);\n if (source[index] === \"[\") return scanArray(source, index);\n if (source[index] === '\"') return scanString(source, index);\n let end = index;\n while (end < source.length && !/[\\s,\\]}]/u.test(source[end])) end += 1;\n return end;\n}\n\nfunction scanObject(source, start) {\n const keys = new Set();\n let index = skipWhitespace(source, start + 1);\n if (source[index] === \"}\") return index + 1;\n while (index < source.length) {\n const keyEnd = scanString(source, index);\n const key = JSON.parse(source.slice(index, keyEnd));\n if (keys.has(key)) configurationError(`duplicate configuration key: ${key}`);\n keys.add(key);\n index = skipWhitespace(source, keyEnd);\n index = scanValue(source, skipWhitespace(source, index + 1));\n index = skipWhitespace(source, index);\n if (source[index] === \"}\") return index + 1;\n index = skipWhitespace(source, index + 1);\n }\n return index;\n}\n\nfunction scanArray(source, start) {\n let index = skipWhitespace(source, start + 1);\n if (source[index] === \"]\") return index + 1;\n while (index < source.length) {\n index = scanValue(source, index);\n index = skipWhitespace(source, index);\n if (source[index] === \"]\") return index + 1;\n index = skipWhitespace(source, index + 1);\n }\n return index;\n}\n\nexport function parseConfigurationJson(source, filename) {\n let value;\n try {\n value = JSON.parse(source);\n } catch (error) {\n configurationError(`invalid JSON: ${error.message}`, filename);\n }\n try {\n scanValue(source, 0);\n } catch (error) {\n if (error?.eliscriptDiagnostic) {\n if (filename) error.eliscriptDiagnostic.location = { file: filename };\n throw error;\n }\n throw error;\n }\n return value;\n}\n\nexport function parseArguments(arguments_) {\n const argumentsList = [...arguments_];\n if (argumentsList[0] === \"--\") argumentsList.shift();\n const portableEntries = [];\n const entries = [];\n let outDir;\n let root;\n let configuration;\n let stdinFile;\n let useCache = true;\n let jsonReport = false;\n let diagnosticFormat = \"human\";\n\n while (argumentsList.length > 0) {\n const argument = argumentsList.shift();\n if (argument === \"-h\" || argument === \"--help\") return { help: true };\n if (argument === \"--out-dir\") {\n if (argumentsList.length === 0) throw new Error(`${argument} requires a directory`);\n outDir = argumentsList.shift();\n } else if (argument === \"--config\") {\n if (argumentsList.length === 0) throw new Error(`${argument} requires a file`);\n if (configuration !== undefined) {\n throw new Error(\"multiple --config files are not supported\");\n }\n configuration = argumentsList.shift();\n } else if (argument === \"--root\") {\n if (argumentsList.length === 0) throw new Error(`${argument} requires a directory`);\n root = argumentsList.shift();\n } else if (argument === \"--portable\") {\n if (argumentsList.length === 0) throw new Error(`${argument} requires an entry name`);\n portableEntries.push(argumentsList.shift());\n } else if (argument === \"--stdin-file\") {\n if (argumentsList.length === 0) throw new Error(`${argument} requires a file`);\n if (stdinFile !== undefined) {\n throw new Error(\"multiple --stdin-file values are not supported\");\n }\n stdinFile = argumentsList.shift();\n } else if (argument === \"--no-cache\") {\n useCache = false;\n } else if (argument === \"--json\") {\n jsonReport = true;\n } else if (argument === \"--diagnostic-format\") {\n if (argumentsList.length === 0) {\n throw new Error(`${argument} requires human or json`);\n }\n diagnosticFormat = argumentsList.shift();\n if (diagnosticFormat !== \"human\" && diagnosticFormat !== \"json\") {\n throw new Error(`unsupported diagnostic format: ${diagnosticFormat}`);\n }\n } else if (argument.startsWith(\"-\")) {\n throw new Error(`unknown option: ${argument}`);\n } else {\n entries.push(argument);\n }\n }\n\n if (configuration === undefined) {\n if (entries.length === 0) throw new Error(\"missing entry file\");\n if (outDir === undefined) throw new Error(\"missing --out-dir\");\n }\n return {\n entry: entries.length === 1 ? entries[0] : undefined,\n entries: entries.length > 1 ? entries : undefined,\n outDir,\n root,\n portableEntries,\n useCache,\n jsonReport,\n diagnosticFormat,\n configuration,\n stdinFile,\n };\n}\n\nexport async function readProjectConfiguration(filename, compiler) {\n const expanded = resolve(filename);\n let canonical;\n try {\n if (!(await stat(expanded)).isFile()) throw new Error(\"not a file\");\n canonical = await realpath(expanded);\n } catch {\n configurationError(\"configuration file does not exist\", expanded);\n }\n const source = await readFile(canonical, \"utf8\");\n const parsed = parseConfigurationJson(source, canonical);\n const configuration = compiler.project_configuration(parsed, canonical);\n const directory = dirname(canonical);\n const root = resolve(directory, configuration.sourceRoot);\n return {\n ...(configuration.version === 2\n ? { entries: configuration.entries.map((entry) => resolve(root, entry)) }\n : { entry: resolve(root, configuration.entry) }),\n outDir: resolve(directory, configuration.outDir),\n root,\n portableEntries: [...configuration.portableEntries],\n macroCapabilities: [...configuration.macroCapabilities],\n macroFileDependencies: [...configuration.macroFileDependencies],\n useCache: configuration.cache,\n configuration: canonical,\n };\n}\n\nexport async function execute(arguments_, options = {}) {\n const parsed = parseArguments(arguments_);\n if (parsed.help) return { help: true };\n let request;\n if (parsed.configuration !== undefined) {\n const compiler = await loadCompiler(options.moduleDirectory);\n request = await readProjectConfiguration(parsed.configuration, compiler);\n if (parsed.entries !== undefined) {\n request.entries = parsed.entries;\n delete request.entry;\n } else if (parsed.entry !== undefined) {\n request.entry = parsed.entry;\n delete request.entries;\n }\n if (parsed.outDir !== undefined) request.outDir = parsed.outDir;\n if (parsed.root !== undefined) request.root = parsed.root;\n if (parsed.portableEntries.length > 0) {\n request.portableEntries = parsed.portableEntries;\n }\n if (!parsed.useCache) request.useCache = false;\n } else {\n request = {\n entry: parsed.entry,\n entries: parsed.entries,\n outDir: parsed.outDir,\n root: parsed.root,\n portableEntries: parsed.portableEntries,\n macroCapabilities: [],\n macroFileDependencies: [],\n useCache: parsed.useCache,\n };\n }\n let sourceOverrides;\n if (parsed.stdinFile !== undefined) {\n const sourceText = options.stdinSource ?? await readFile(0, \"utf8\");\n sourceOverrides = { [resolve(parsed.stdinFile)]: sourceText };\n }\n const result = await executeBuild({\n mode: \"project\",\n ...request,\n sourceOverrides,\n moduleDirectory: options.moduleDirectory,\n });\n return { result, jsonReport: parsed.jsonReport };\n}\n\nexport async function main(arguments_ = process.argv.slice(2)) {\n const execution = await execute(arguments_);\n if (execution.help) {\n process.stdout.write(usage);\n return;\n }\n process.stdout.write(execution.jsonReport\n ? `${JSON.stringify(execution.result.report)}\\n`\n : `${execution.result.entryOutputs.join(\"\\n\")}\\n`);\n}\n\nconst isMain = process.argv[1] !== undefined &&\n resolve(process.argv[1]) === fileURLToPath(import.meta.url);\nif (isMain) {\n const outputFormat = requestedDiagnosticFormat(process.argv.slice(2));\n main().catch((error) => {\n const diagnostic = diagnosticFromError(error);\n if (outputFormat === \"json\") {\n console.error(JSON.stringify(diagnostic));\n } else {\n console.error(`eliscript-build: ${renderDiagnostic(diagnostic)}`);\n }\n process.exitCode = 1;\n });\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.bootstrap.host.project-legacy
|
|
2
|
+
(js* "import { createHash } from \"node:crypto\";\nimport {\n lstatSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n realpathSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport {\n basename,\n dirname,\n isAbsolute,\n relative,\n resolve,\n sep,\n} from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { loadCompiler } from \"./bun.mjs\";\n\nconst manifestFilename = \"eliscript-project.json\";\nconst cacheFormat = \"eliscript-project-cache\";\nconst cacheVersion = 2;\nconst hostDirectory = dirname(fileURLToPath(import.meta.url));\n\nfunction projectError(message, filename) {\n const error = new Error(message);\n error.eliscriptDiagnostic = {\n format: \"eliscript-diagnostic\",\n version: 1,\n code: \"ELI-B0001\",\n severity: \"error\",\n phase: \"project-build\",\n message,\n ...(filename ? { location: { file: filename } } : {}),\n };\n throw error;\n}\n\nfunction canonicalDirectory(path, label) {\n const expanded = resolve(path);\n let attributes;\n try {\n attributes = statSync(expanded);\n } catch {\n projectError(`${label} is not a directory`, expanded);\n }\n if (!attributes.isDirectory()) {\n projectError(`${label} is not a directory`, expanded);\n }\n return realpathSync(expanded);\n}\n\nfunction pathOption(value, label) {\n if (typeof value !== \"string\" || value.length === 0) {\n projectError(`${label} must be a non-empty path`);\n }\n return value;\n}\n\nfunction insideRoot(root, candidate) {\n const path = relative(root, candidate);\n return path === \"\" || (!isAbsolute(path) && path !== \"..\" &&\n !path.startsWith(`..${sep}`));\n}\n\nfunction canonicalSource(path, root, importer) {\n const expanded = resolve(path);\n let attributes;\n try {\n attributes = statSync(expanded);\n } catch {\n projectError(`local Eliscript module does not exist: ${path}`, importer);\n }\n if (!attributes.isFile()) {\n projectError(`local Eliscript module does not exist: ${path}`, importer);\n }\n const canonical = realpathSync(expanded);\n if (!insideRoot(root, canonical)) {\n projectError(`local Eliscript module escapes project root: ${path}`, importer);\n }\n return canonical;\n}\n\nfunction macroDependency(specifier, root, importer) {\n const expanded = resolve(root, specifier);\n let attributes;\n try {\n attributes = statSync(expanded);\n } catch {\n projectError(`macro file dependency does not exist: ${specifier}`, importer);\n }\n if (!attributes.isFile()) {\n projectError(`macro file dependency does not exist: ${specifier}`, importer);\n }\n const source = realpathSync(expanded);\n if (!insideRoot(root, source)) {\n projectError(\n `macro file dependency escapes project root: ${specifier}`,\n importer,\n );\n }\n const bytes = readFileSync(source);\n return {\n specifier,\n source,\n digest: createHash(\"sha256\").update(bytes).digest(\"hex\"),\n content: (() => {\n try {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n projectError(\n `macro file dependency is not valid UTF-8: ${specifier}`,\n importer,\n );\n }\n })(),\n };\n}\n\nfunction macroInputs(request, root, importer) {\n const dependencies = [...request.macroFileDependencies]\n .map((specifier) => macroDependency(specifier, root, importer));\n const canonical = new Set(dependencies.map(({ source }) => source));\n if (canonical.size !== dependencies.length) {\n projectError(\"macro file dependencies resolve to duplicates\", importer);\n }\n return {\n dependencies,\n context: {\n capabilities: new Set(request.macroCapabilities),\n files: new Map(dependencies.map(({ specifier, content }) =>\n [specifier, content])),\n },\n };\n}\n\nfunction macroDependencyRecords(dependencies, root) {\n return dependencies.map(({ source, digest }) => ({\n path: relative(root, source),\n digest,\n }));\n}\n\nfunction outputFor(source, root, outDir) {\n const sourcePath = relative(root, source);\n return resolve(outDir, `${sourcePath.slice(0, -4)}.mjs`);\n}\n\nfunction physicalWritePath(path) {\n const expanded = resolve(path);\n const suffix = [];\n let cursor = expanded;\n while (true) {\n try {\n lstatSync(cursor);\n let canonical;\n try {\n canonical = realpathSync(cursor);\n } catch {\n projectError(`generated artifact contains an unresolved symlink: ${expanded}`);\n }\n return resolve(canonical, ...suffix.reverse());\n } catch (error) {\n if (error?.eliscriptDiagnostic) throw error;\n if (error?.code !== \"ENOENT\") {\n projectError(`generated artifact path cannot be resolved: ${expanded}`);\n }\n const parent = dirname(cursor);\n if (parent === cursor) {\n projectError(`generated artifact path cannot be resolved: ${expanded}`);\n }\n suffix.push(basename(cursor));\n cursor = parent;\n }\n }\n}\n\nfunction existingFileIdentity(path) {\n try {\n const attributes = statSync(path);\n return attributes.isFile() ? `${attributes.dev}:${attributes.ino}` : null;\n } catch {\n return null;\n }\n}\n\nfunction validateOutputIsolation({ sources, macroDependencies, root, outDir }) {\n const protectedPaths = [\n ...sources,\n ...macroDependencies.map(({ source }) => source),\n ];\n const protectedCanonical = new Set(protectedPaths.map((path) =>\n realpathSync(path)));\n const protectedIdentities = new Set(protectedPaths\n .map(existingFileIdentity)\n .filter((identity) => identity !== null));\n const artifacts = [\n ...sources.flatMap((source) => {\n const output = outputFor(source, root, outDir);\n return [output, `${output}.map`];\n }),\n resolve(outDir, manifestFilename),\n ];\n const artifactCanonical = new Set();\n const artifactIdentities = new Set();\n for (const artifact of artifacts) {\n const physical = physicalWritePath(artifact);\n const identity = existingFileIdentity(artifact);\n if (!insideRoot(outDir, physical)) {\n projectError(`generated artifact escapes output directory: ${artifact}`);\n }\n if (protectedCanonical.has(physical) ||\n (identity !== null && protectedIdentities.has(identity))) {\n projectError(`generated artifact would overwrite an input: ${artifact}`);\n }\n if (artifactCanonical.has(physical) ||\n (identity !== null && artifactIdentities.has(identity))) {\n projectError(`generated artifacts resolve to the same file: ${artifact}`);\n }\n artifactCanonical.add(physical);\n if (identity !== null) artifactIdentities.add(identity);\n }\n}\n\nfunction localSourceImport(specifier) {\n return specifier.endsWith(\".eli\") &&\n (specifier.startsWith(\"./\") || specifier.startsWith(\"../\"));\n}\n\nfunction relativeImport(target, importer) {\n const path = relative(dirname(importer), target);\n return path.startsWith(\"./\") || path.startsWith(\"../\") ? path : `./${path}`;\n}\n\nfunction walkProgram(program, visit) {\n const pending = [...program.body];\n while (pending.length > 0) {\n const node = pending.pop();\n visit(node);\n for (let index = node.children.length - 1; index >= 0; index -= 1) {\n pending.push(node.children[index]);\n }\n }\n}\n\nfunction projectImports(program, source, root, portable) {\n const imports = [];\n walkProgram(program, (node) => {\n if (node.kind !== \"import-declaration\") return;\n const specifier = node.value;\n if (portable && node.properties?.portable !== true) {\n projectError(\"portable project contains a non-portable import\", source);\n }\n if (!localSourceImport(specifier)) {\n if (portable || specifier.endsWith(\".eli\")) {\n const kind = portable ? \"portable import\" : \"Eliscript source import\";\n projectError(`${kind} must be a relative .eli module: ${specifier}`, source);\n }\n return;\n }\n const dependency = canonicalSource(\n resolve(dirname(source), specifier),\n root,\n source,\n );\n imports.push({\n dependency,\n entries: node.children\n .filter((child) => child.kind === \"import-named\")\n .map((child) => child.value),\n node,\n });\n });\n return imports;\n}\n\nfunction rewriteLocalImports(program, source, root, outDir) {\n const outputPath = outputFor(source, root, outDir);\n walkProgram(program, (node) => {\n if (node.kind !== \"import-declaration\" || !localSourceImport(node.value)) {\n return;\n }\n const dependency = canonicalSource(\n resolve(dirname(source), node.value),\n root,\n source,\n );\n node.value = relativeImport(outputFor(dependency, root, outDir), outputPath);\n });\n}\n\nfunction digestBytes(bytes) {\n return createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\nfunction digestFile(filename) {\n return digestBytes(readFileSync(filename));\n}\n\nfunction regularFile(filename) {\n try {\n return statSync(filename).isFile();\n } catch (error) {\n if (error?.code === \"ENOENT\") return false;\n throw error;\n }\n}\n\nfunction compilerModuleDirectory(moduleDirectory) {\n return resolve(\n moduleDirectory ??\n process.env.ELISCRIPT_BOOTSTRAP_MODULE_DIR ??\n resolve(hostDirectory, \"../../dist/bootstrap\"),\n );\n}\n\nfunction compilerDirectoryDigest(directory) {\n const filenames = readdirSync(directory, { withFileTypes: true })\n .filter((entry) => entry.isFile() &&\n (entry.name.endsWith(\".mjs\") || entry.name.endsWith(\".mjs.map\")))\n .map((entry) => entry.name)\n .sort();\n if (!filenames.includes(\"compiler.mjs\")) {\n projectError(\"generated compiler directory is incomplete\", directory);\n }\n const hash = createHash(\"sha256\");\n for (const filename of filenames) {\n hash.update(filename);\n hash.update(\"\\0\");\n hash.update(readFileSync(resolve(directory, filename)));\n hash.update(\"\\0\");\n }\n return hash.digest(\"hex\");\n}\n\nfunction compilerDigestOption(value) {\n if (typeof value !== \"string\" || !/^[0-9a-f]{64}$/u.test(value)) {\n projectError(\"injected compiler requires a lowercase SHA-256 compilerDigest\");\n }\n return value;\n}\n\nfunction writeModule({\n compiler,\n program,\n source,\n sourceText,\n root,\n outDir,\n dependencies,\n macroDependencies,\n portableEntries,\n reason,\n sourceMapReference,\n}) {\n const output = outputFor(source, root, outDir);\n const sourceMap = `${output}.map`;\n rewriteLocalImports(program, source, root, outDir);\n const emission = compiler.emit_ir_string_with_source_map(\n program,\n sourceText,\n basename(output),\n relative(dirname(sourceMap), source),\n );\n const javascript = sourceMapReference\n ? `${emission.javascript}//# sourceMappingURL=${basename(sourceMap)}\\n`\n : emission.javascript;\n mkdirSync(dirname(output), { recursive: true });\n writeFileSync(sourceMap, emission.sourceMap);\n writeFileSync(output, javascript);\n return {\n source,\n output,\n sourceMap,\n sourceDigest: digestBytes(sourceText),\n outputDigest: digestFile(output),\n sourceMapDigest: digestFile(sourceMap),\n dependencies,\n macroDependencies,\n portableEntries,\n reused: false,\n reason,\n };\n}\n\nfunction reportModule(module, root, outDir) {\n return {\n source: relative(root, module.source),\n output: relative(outDir, module.output),\n sourceMap: relative(outDir, module.sourceMap),\n status: module.reused ? \"reused\" : \"compiled\",\n reason: module.reason,\n dependencies: module.dependencies.map((dependency) => relative(root, dependency)),\n ...(module.macroDependencies.length > 0\n ? { macroDependencies: macroDependencyRecords(module.macroDependencies, root) }\n : {}),\n portableEntries: [...module.portableEntries],\n };\n}\n\nfunction manifestRecord(module, root, outDir) {\n return {\n source: relative(root, module.source),\n output: relative(outDir, module.output),\n sourceMap: relative(outDir, module.sourceMap),\n sourceDigest: module.sourceDigest,\n outputDigest: module.outputDigest,\n sourceMapDigest: module.sourceMapDigest,\n ...(module.macroDependencies.length > 0\n ? { macroDependencies: macroDependencyRecords(module.macroDependencies, root) }\n : {}),\n };\n}\n\nfunction cacheMetadataRecord(module, root) {\n return {\n source: relative(root, module.source),\n dependencies: module.dependencies.map((dependency) => relative(root, dependency)),\n ...(module.macroDependencies.length > 0\n ? { macroDependencies: macroDependencyRecords(module.macroDependencies, root) }\n : {}),\n portableEntries: [...module.portableEntries],\n };\n}\n\nfunction cacheIdentityModule(record) {\n return {\n source: record.source,\n dependencies: record.dependencies,\n ...(record.macroDependencies === undefined\n ? {}\n : { macroDependencies: record.macroDependencies }),\n portableEntries: record.portableEntries,\n };\n}\n\nfunction cacheIdentity(value) {\n if (!value || !Array.isArray(value.modules)) return undefined;\n const modules = value.modules.map(cacheIdentityModule);\n if (value.format === undefined && value.version === 1) {\n return {\n version: 1,\n compilerDigest: value.compilerDigest,\n mode: value.mode,\n portableEntries: value.portableEntries,\n modules,\n };\n }\n return {\n format: value.format,\n version: value.version,\n compilerDigest: value.compilerDigest,\n mode: value.mode,\n portableEntries: value.portableEntries,\n modules,\n };\n}\n\nfunction writeManifest(\n entryOutputs,\n modules,\n root,\n outDir,\n mode,\n portableEntries,\n compilerDigest,\n) {\n const outputEntries = entryOutputs.map((entryOutput) =>\n relative(outDir, entryOutput));\n const identity = outputEntries.length === 1\n ? {\n format: \"eliscript-project\",\n version: 1,\n entry: outputEntries[0],\n modules: modules.map((module) => manifestRecord(module, root, outDir)),\n }\n : {\n format: \"eliscript-project\",\n version: 2,\n entries: outputEntries,\n modules: modules.map((module) => manifestRecord(module, root, outDir)),\n };\n const digest = digestBytes(JSON.stringify(identity));\n const cache = {\n format: cacheFormat,\n version: cacheVersion,\n compilerDigest,\n mode,\n portableEntries,\n modules: modules.map((module) => cacheMetadataRecord(module, root)),\n };\n const cacheDigest = digestBytes(JSON.stringify(cache));\n const manifest = resolve(outDir, manifestFilename);\n mkdirSync(outDir, { recursive: true });\n writeFileSync(manifest, `${JSON.stringify({\n ...identity,\n digest,\n cache: { ...cache, digest: cacheDigest },\n })}\\n`);\n return { manifest: realpathSync(manifest), digest };\n}\n\nfunction readCache({\n compiler,\n enabled,\n outDir,\n entryOutputs,\n mode,\n portableEntries,\n compilerDigest,\n}) {\n const manifestPath = resolve(outDir, manifestFilename);\n if (!enabled) {\n return compiler.project_cache_lookup({\n enabled: false,\n manifestStatus: \"missing\",\n });\n }\n if (!regularFile(manifestPath)) {\n return compiler.project_cache_lookup({\n enabled: true,\n manifestStatus: \"missing\",\n });\n }\n try {\n const manifest = JSON.parse(readFileSync(manifestPath, \"utf8\"));\n const graphIdentity = manifest?.version === 2\n ? {\n format: manifest?.format,\n version: manifest?.version,\n entries: manifest?.entries,\n modules: manifest?.modules,\n }\n : {\n format: manifest?.format,\n version: manifest?.version,\n entry: manifest?.entry,\n modules: manifest?.modules,\n };\n const privateIdentity = cacheIdentity(manifest?.cache);\n return compiler.project_cache_lookup({\n enabled: true,\n manifestStatus: \"readable\",\n manifest,\n expectedEntry: entryOutputs.length === 1\n ? relative(outDir, entryOutputs[0])\n : undefined,\n expectedEntries: entryOutputs.map((entryOutput) =>\n relative(outDir, entryOutput)),\n graphDigestValid: manifest?.digest ===\n digestBytes(JSON.stringify(graphIdentity)),\n cacheDigestValid: privateIdentity !== undefined &&\n manifest.cache?.digest === digestBytes(JSON.stringify(privateIdentity)),\n compilerDigest,\n mode,\n portableEntries,\n });\n } catch {\n return compiler.project_cache_lookup({\n enabled: true,\n manifestStatus: \"unreadable\",\n });\n }\n}\n\nfunction cachedRecords(lookup) {\n return new Map((lookup.cache?.records ?? []).map((record) =>\n [record.source, record]));\n}\n\nfunction cachedModule({\n compiler,\n source,\n root,\n outDir,\n record,\n expectedPortableEntries,\n expectedMacroDependencies = [],\n}) {\n const output = outputFor(source, root, outDir);\n const sourceMap = `${output}.map`;\n let sourceDigest;\n let outputDigest;\n let sourceMapDigest;\n let outputExists = false;\n let sourceMapExists = false;\n let artifactFailure;\n try {\n sourceDigest = digestFile(source);\n outputExists = regularFile(output);\n sourceMapExists = regularFile(sourceMap);\n if (outputExists) outputDigest = digestFile(output);\n if (sourceMapExists) sourceMapDigest = digestFile(sourceMap);\n } catch {\n artifactFailure = \"artifact-unreadable\";\n }\n let dependencies = [];\n let dependenciesValid = true;\n const expectedMacroRecords = macroDependencyRecords(\n expectedMacroDependencies,\n root,\n );\n let macroDependenciesMatch = false;\n try {\n if (!Array.isArray(record?.metadata?.dependencies) ||\n !Array.isArray(record?.metadata?.portableEntries)) {\n throw new TypeError(\"cache module metadata is invalid\");\n }\n dependencies = record.metadata.dependencies.map((dependency) =>\n canonicalSource(resolve(root, dependency), root, source));\n const recordedMacroDependencies = record.metadata.macroDependencies ?? [];\n macroDependenciesMatch =\n JSON.stringify(recordedMacroDependencies) ===\n JSON.stringify(expectedMacroRecords);\n } catch {\n dependenciesValid = false;\n }\n const decision = compiler.project_cache_decision({\n record,\n output: relative(outDir, output),\n sourceMap: relative(outDir, sourceMap),\n expectedPortableEntries,\n macroDependenciesMatch,\n sourceDigest,\n outputExists,\n sourceMapExists,\n outputDigest,\n sourceMapDigest,\n dependenciesValid,\n artifactFailure,\n });\n return {\n decision,\n module: decision.reused\n ? {\n source,\n output,\n sourceMap,\n sourceDigest,\n outputDigest,\n sourceMapDigest,\n dependencies,\n macroDependencies: expectedMacroDependencies,\n portableEntries: [...record.metadata.portableEntries],\n reused: true,\n reason: \"verified\",\n }\n : undefined,\n };\n}\n\nfunction standardPlan(\n compiler,\n entries,\n root,\n outDir,\n sourceCache,\n programCache,\n records,\n decisions,\n sourceOverrides,\n macroContext,\n macroDependencies,\n) {\n return compiler.project_plan(entries, (source) => {\n const cached = cachedModule({\n compiler,\n source,\n root,\n outDir,\n record: records.get(relative(root, source)),\n expectedPortableEntries: [],\n expectedMacroDependencies: macroDependencies,\n });\n decisions.set(source, cached);\n if (cached.module !== undefined) return cached.module.dependencies;\n const sourceText = sourceOverrides.get(source) ?? readFileSync(source, \"utf8\");\n const program = compiler.compile_ir_string(sourceText, source, macroContext);\n sourceCache.set(source, sourceText);\n programCache.set(source, program);\n return projectImports(program, source, root, false)\n .map(({ dependency }) => dependency);\n });\n}\n\nfunction portablePlan(\n compiler,\n entry,\n entries,\n root,\n sourceCache,\n programCache,\n sourceOverrides,\n macroContext,\n) {\n return compiler.portable_project_plan([{ id: entry, entries }],\n (source, requestedEntries) => {\n const sourceText = sourceOverrides.get(source) ?? readFileSync(source, \"utf8\");\n const program = compiler.compile_project_portable_ir_string(\n sourceText,\n requestedEntries,\n source,\n macroContext,\n );\n sourceCache.set(source, sourceText);\n programCache.set(source, program);\n return projectImports(program, source, root, true).map((dependency) => ({\n id: dependency.dependency,\n entries: dependency.entries,\n }));\n });\n}\n\nfunction sourceOverridesOption(values, root) {\n if (values === undefined) return new Map();\n const entries = values instanceof Map\n ? [...values.entries()]\n : Object.entries(values);\n const overrides = new Map();\n for (const [filename, sourceText] of entries) {\n if (typeof sourceText !== \"string\") {\n projectError(\"project source override must be a string\", filename);\n }\n const source = canonicalSource(\n pathOption(filename, \"project source override\"),\n root,\n filename,\n );\n if (overrides.has(source)) {\n projectError(\"project source overrides resolve to duplicates\", source);\n }\n overrides.set(source, sourceText);\n }\n return overrides;\n}\n\nfunction validateSourceOverrides(sourceOverrides, plan) {\n const plannedSources = new Set(plan.modules.map((record) => record.id));\n for (const source of sourceOverrides.keys()) {\n if (!plannedSources.has(source)) {\n projectError(\"project source override is outside the project graph\", source);\n }\n }\n}\n\nfunction checkStandardPlan(\n compiler,\n entries,\n root,\n sourceOverrides,\n macroContext,\n) {\n return compiler.project_plan(entries, (source) => {\n const sourceText = sourceOverrides.get(source) ?? readFileSync(source, \"utf8\");\n const program = compiler.compile_ir_string(sourceText, source, macroContext);\n return projectImports(program, source, root, false)\n .map(({ dependency }) => dependency);\n });\n}\n\nfunction checkPortablePlan(\n compiler,\n entry,\n entries,\n root,\n sourceOverrides,\n macroContext,\n) {\n return compiler.portable_project_plan([{ id: entry, entries }],\n (source, requestedEntries) => {\n const sourceText = sourceOverrides.get(source) ?? readFileSync(source, \"utf8\");\n const program = compiler.compile_project_portable_ir_string(\n sourceText,\n requestedEntries,\n source,\n macroContext,\n );\n return projectImports(program, source, root, true).map((dependency) => ({\n id: dependency.dependency,\n entries: dependency.entries,\n }));\n });\n}\n\nexport async function checkProject(options) {\n if (!options || typeof options !== \"object\") {\n projectError(\"project check options must be an object\");\n }\n if (options.entry === undefined && options.entries === undefined) {\n projectError(\"project check requires entry or entries\");\n }\n const moduleDirectory = compilerModuleDirectory(options.moduleDirectory);\n const compiler = options.compiler ?? await loadCompiler(moduleDirectory);\n const request = compiler.check_operation_request({\n entry: options.entry,\n entries: options.entries,\n root: options.root ?? null,\n portableEntries: options.portableEntries ?? [],\n macroCapabilities: options.macroCapabilities ?? [],\n macroFileDependencies: options.macroFileDependencies ?? [],\n });\n const entryPaths = request.entries.map((entry) =>\n resolve(pathOption(entry, \"entry\")));\n if (entryPaths.length > 1 && request.root === null) {\n projectError(\"multi-entry project checks require an explicit project root\");\n }\n const root = canonicalDirectory(\n request.root === null\n ? dirname(entryPaths[0])\n : pathOption(request.root, \"project root\"),\n \"project root\",\n );\n const entries = entryPaths.map((entryPath) => {\n const entry = canonicalSource(entryPath, root, entryPath);\n if (!entry.endsWith(\".eli\")) {\n projectError(\"entry file must use the .eli extension\", entry);\n }\n return entry;\n }).sort();\n if (new Set(entries).size !== entries.length) {\n projectError(\"project entries resolve to duplicate sources\");\n }\n const macro = macroInputs(request, root, entries[0]);\n const sourceOverrides = sourceOverridesOption(options.sourceOverrides, root);\n const portableEntries = [...request.portableEntries];\n const plan = portableEntries.length > 0\n ? checkPortablePlan(\n compiler,\n entries[0],\n portableEntries,\n root,\n sourceOverrides,\n macro.context,\n )\n : checkStandardPlan(\n compiler,\n entries,\n root,\n sourceOverrides,\n macro.context,\n );\n validateSourceOverrides(sourceOverrides, plan);\n const mode = plan.mode;\n const modules = plan.modules.map((record) => ({\n source: relative(root, record.id),\n dependencies: record.dependencies.map((dependency) =>\n relative(root, typeof dependency === \"string\" ? dependency : dependency.id)),\n portableEntries: record.entries === undefined ? [] : [...record.entries],\n }));\n const report = compiler.project_check_report({\n mode,\n root,\n entries: entries.map((entry) => relative(root, entry)),\n portableEntries,\n modules,\n });\n return Object.freeze({\n format: \"eliscript-project-check\",\n version: 1,\n root,\n entries: Object.freeze(entries),\n mode,\n portableEntries: Object.freeze(portableEntries),\n macroCapabilities: request.macroCapabilities,\n macroFileDependencies: Object.freeze(macro.dependencies),\n report,\n plan,\n });\n}\n\nexport async function buildProject(options) {\n const startedAt = performance.now();\n if (!options || typeof options !== \"object\") {\n projectError(\"project build options must be an object\");\n }\n if ((options.entry === undefined && options.entries === undefined) ||\n options.outDir === undefined) {\n projectError(\"project build requires entry or entries and outDir\");\n }\n const moduleDirectory = compilerModuleDirectory(options.moduleDirectory);\n const compiler = options.compiler ?? await loadCompiler(moduleDirectory);\n const request = compiler.build_operation_request({\n mode: \"project\",\n entry: options.entry,\n entries: options.entries,\n outDir: options.outDir,\n root: options.root ?? null,\n portableEntries: options.portableEntries ?? [],\n macroCapabilities: options.macroCapabilities ?? [],\n macroFileDependencies: options.macroFileDependencies ?? [],\n useCache: options.useCache === undefined ? true : options.useCache,\n });\n const requestedEntries = request.version === 2\n ? [...request.entries]\n : [request.entry];\n if (requestedEntries.length > 1 && request.root === null) {\n projectError(\"multi-entry project builds require an explicit project root\");\n }\n const entryPaths = requestedEntries.map((entry) =>\n resolve(pathOption(entry, \"entry\")));\n const root = canonicalDirectory(\n request.root === null\n ? dirname(entryPaths[0])\n : pathOption(request.root, \"project root\"),\n \"project root\",\n );\n const entries = entryPaths.map((entryPath) => {\n const entry = canonicalSource(entryPath, root, entryPath);\n if (!entry.endsWith(\".eli\")) {\n projectError(\"entry file must use the .eli extension\", entry);\n }\n return entry;\n }).sort();\n if (new Set(entries).size !== entries.length) {\n projectError(\"project entries resolve to duplicate sources\");\n }\n const macro = macroInputs(request, root, entries[0]);\n const sourceOverrides = sourceOverridesOption(options.sourceOverrides, root);\n const requestedOutDir = resolve(pathOption(request.outDir, \"output\"));\n try {\n const attributes = statSync(requestedOutDir);\n if (!attributes.isDirectory()) {\n projectError(\"output path is not a directory\", requestedOutDir);\n }\n } catch (error) {\n if (error?.eliscriptDiagnostic) throw error;\n mkdirSync(requestedOutDir, { recursive: true });\n }\n const outDir = realpathSync(requestedOutDir);\n const sourceMapReference = options.sourceMapReference !== false;\n const useCache = request.useCache && sourceOverrides.size === 0 &&\n sourceMapReference;\n const compilerDigest = options.compiler === undefined\n ? compilerDirectoryDigest(moduleDirectory)\n : compilerDigestOption(options.compilerDigest);\n const requestedPortableEntries = [...request.portableEntries];\n const mode = requestedPortableEntries.length > 0 ? \"portable\" : \"standard\";\n const entryOutputs = entries.map((entry) => outputFor(entry, root, outDir));\n const cacheStartedAt = performance.now();\n const cacheLookup = readCache({\n compiler,\n enabled: useCache,\n outDir,\n entryOutputs,\n mode,\n portableEntries: requestedPortableEntries,\n compilerDigest,\n });\n const cacheReadMs = performance.now() - cacheStartedAt;\n const records = cachedRecords(cacheLookup);\n const sourceCache = new Map();\n const programCache = new Map();\n const decisions = new Map();\n const plan = mode === \"portable\"\n ? portablePlan(\n compiler,\n entries[0],\n requestedPortableEntries,\n root,\n sourceCache,\n programCache,\n sourceOverrides,\n macro.context,\n )\n : standardPlan(\n compiler,\n entries,\n root,\n outDir,\n sourceCache,\n programCache,\n records,\n decisions,\n sourceOverrides,\n macro.context,\n macro.dependencies,\n );\n validateSourceOverrides(sourceOverrides, plan);\n validateOutputIsolation({\n sources: plan.modules.map(({ id }) => id),\n macroDependencies: macro.dependencies,\n root,\n outDir,\n });\n const normalizedPortableEntries = plan.mode === \"portable\"\n ? [...plan.entries[0].entries]\n : [];\n const modules = plan.modules.map((record) => {\n const dependencies = record.dependencies.map((dependency) =>\n typeof dependency === \"string\" ? dependency : dependency.id);\n const modulePortableEntries = record.entries === undefined\n ? []\n : [...record.entries];\n const cached = plan.mode === \"standard\"\n ? decisions.get(record.id)\n : cachedModule({\n compiler,\n source: record.id,\n root,\n outDir,\n record: records.get(relative(root, record.id)),\n expectedPortableEntries: modulePortableEntries,\n expectedMacroDependencies: macro.dependencies,\n });\n if (cached?.module !== undefined) return cached.module;\n return writeModule({\n compiler,\n program: programCache.get(record.id),\n source: record.id,\n sourceText: sourceCache.get(record.id),\n root,\n outDir,\n dependencies,\n macroDependencies: macro.dependencies,\n portableEntries: modulePortableEntries,\n reason: cacheLookup.cache === null\n ? cacheLookup.reason\n : cached.decision.reason,\n sourceMapReference,\n });\n });\n const workFinishedAt = performance.now();\n const manifestData = writeManifest(\n entryOutputs,\n modules,\n root,\n outDir,\n plan.mode,\n normalizedPortableEntries,\n compilerDigest,\n );\n const manifestFinishedAt = performance.now();\n const reportInput = {\n mode: plan.mode,\n root,\n outDir,\n manifest: relative(outDir, manifestData.manifest),\n digest: manifestData.digest,\n portableEntries: normalizedPortableEntries,\n cache: { enabled: useCache, reason: cacheLookup.reason },\n timings: {\n cacheReadMs,\n workMs: Math.max(0, workFinishedAt - startedAt - cacheReadMs),\n manifestWriteMs: manifestFinishedAt - workFinishedAt,\n totalMs: manifestFinishedAt - startedAt,\n },\n modules: modules.map((module) => reportModule(module, root, outDir)),\n };\n if (entries.length === 1) {\n reportInput.entry = relative(root, entries[0]);\n reportInput.entryOutput = relative(outDir, entryOutputs[0]);\n } else {\n reportInput.entries = entries.map((entry) => relative(root, entry));\n reportInput.entryOutputs = entryOutputs.map((entryOutput) =>\n relative(outDir, entryOutput));\n }\n const report = compiler.project_build_report(reportInput);\n return Object.freeze({\n format: \"eliscript-project-build\",\n version: entries.length === 1 ? 1 : 2,\n root,\n outDir,\n entry: entries.length === 1 ? entries[0] : undefined,\n entryOutput: entries.length === 1 ? entryOutputs[0] : undefined,\n entries: Object.freeze(entries),\n entryOutputs: Object.freeze(entryOutputs),\n mode: plan.mode,\n portableEntries: Object.freeze(normalizedPortableEntries),\n macroCapabilities: request.macroCapabilities,\n macroFileDependencies: Object.freeze(macro.dependencies),\n modules: Object.freeze(modules.map((module) => Object.freeze(module))),\n manifest: manifestData.manifest,\n digest: manifestData.digest,\n report,\n plan,\n });\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.bootstrap.host.watch-cli
|
|
2
|
+
(js* "#!/usr/bin/env node\n\nimport { resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n diagnosticFromError,\n loadCompiler,\n renderDiagnostic,\n} from \"./bun.mjs\";\nimport { readProjectConfiguration } from \"./project-cli.mjs\";\nimport {\n defaultWatchInterval,\n maximumWatchInterval,\n minimumWatchInterval,\n ProjectWatcher,\n} from \"./watch.mjs\";\n\nconst usage = `Usage: eliscript-watch (--root DIRECTORY | --config FILE) [OPTIONS]\n\nOptions:\n --root DIRECTORY Observe regular .eli files below DIRECTORY\n --config FILE Resolve and observe a versioned project configuration\n --interval MS Poll every ${defaultWatchInterval} ms by default (${minimumWatchInterval}-${maximumWatchInterval})\n --json Emit one versioned JSON event per line\n -h, --help Show this help\n`;\n\nexport function parseArguments(arguments_) {\n const argumentsList = [...arguments_];\n let root;\n let configuration;\n let interval = defaultWatchInterval;\n let json = false;\n while (argumentsList.length > 0) {\n const argument = argumentsList.shift();\n if (argument === \"-h\" || argument === \"--help\") return { help: true };\n if (argument === \"--root\") {\n if (argumentsList.length === 0) throw new Error(\"--root requires a directory\");\n root = argumentsList.shift();\n } else if (argument === \"--config\") {\n if (argumentsList.length === 0) throw new Error(\"--config requires a file\");\n configuration = argumentsList.shift();\n } else if (argument === \"--interval\") {\n if (argumentsList.length === 0) throw new Error(\"--interval requires milliseconds\");\n const text = argumentsList.shift();\n if (!/^[0-9]+$/u.test(text)) throw new Error(\"--interval requires an integer\");\n interval = Number(text);\n } else if (argument === \"--json\") {\n json = true;\n } else {\n throw new Error(`unknown option: ${argument}`);\n }\n }\n if ((root === undefined) === (configuration === undefined)) {\n throw new Error(\"choose exactly one of --root or --config\");\n }\n return { root, configuration, interval, json };\n}\n\nfunction writeEvent(event, json) {\n if (json) {\n process.stdout.write(`${JSON.stringify(event)}\\n`);\n return;\n }\n if (event.event === \"ready\") {\n process.stdout.write(`watching ${event.root}\\n`);\n } else if (event.event === \"error\") {\n process.stdout.write(`watch error: ${renderDiagnostic(event.diagnostic)}\\n`);\n } else {\n for (const change of event.changes) {\n process.stdout.write(`${change.kind} ${change.path ?? change.file}\\n`);\n }\n }\n}\n\nasync function watchOptions(parsed, options) {\n if (parsed.configuration === undefined) {\n return { root: parsed.root, configuration: null, interval: parsed.interval };\n }\n const compiler = await loadCompiler(options.moduleDirectory);\n const request = await readProjectConfiguration(parsed.configuration, compiler);\n return {\n root: request.root,\n configuration: request.configuration,\n interval: parsed.interval,\n };\n}\n\nexport async function execute(arguments_, options = {}) {\n const parsed = parseArguments(arguments_);\n if (parsed.help) return { help: true };\n const watcher = await ProjectWatcher.create(await watchOptions(parsed, options));\n return { watcher, json: parsed.json };\n}\n\nexport async function main(arguments_ = process.argv.slice(2)) {\n const execution = await execute(arguments_);\n if (execution.help) {\n process.stdout.write(usage);\n return;\n }\n const { watcher, json } = execution;\n let stop;\n const stopped = new Promise((resolveStopped) => {\n stop = resolveStopped;\n });\n const handleSignal = () => stop();\n process.once(\"SIGINT\", handleSignal);\n process.once(\"SIGTERM\", handleSignal);\n try {\n watcher.start((event) => writeEvent(event, json));\n await stopped;\n } finally {\n process.removeListener(\"SIGINT\", handleSignal);\n process.removeListener(\"SIGTERM\", handleSignal);\n await watcher.close();\n }\n}\n\nconst isMain = process.argv[1] !== undefined &&\n resolve(process.argv[1]) === fileURLToPath(import.meta.url);\nif (isMain) {\n main().catch((error) => {\n const diagnostic = diagnosticFromError(error);\n console.error(`eliscript-watch: ${renderDiagnostic(diagnostic)}`);\n process.exitCode = 1;\n });\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.bootstrap.host.watch
|
|
2
|
+
(js* "import { createHash } from \"node:crypto\";\nimport { readdir, readFile, realpath, stat } from \"node:fs/promises\";\nimport { isAbsolute, join, relative, resolve, sep } from \"node:path\";\n\nexport const watchEventFormat = \"eliscript-watch-event\";\nexport const watchEventVersion = 1;\nexport const defaultWatchInterval = 250;\nexport const minimumWatchInterval = 25;\nexport const maximumWatchInterval = 60_000;\n\nfunction freeze(value) {\n return Object.freeze(value);\n}\n\nfunction watchError(message, filename = undefined) {\n const error = new Error(message);\n error.eliscriptDiagnostic = {\n format: \"eliscript-diagnostic\",\n version: 1,\n code: \"ELI-W0001\",\n severity: \"error\",\n phase: \"project-watch\",\n message,\n ...(filename ? { location: { file: filename } } : {}),\n };\n return error;\n}\n\nfunction containedPath(file, root) {\n const fromRoot = relative(root, file);\n return fromRoot === \"\" ||\n (fromRoot !== \"..\" && !fromRoot.startsWith(`..${sep}`) &&\n !isAbsolute(fromRoot));\n}\n\nfunction digestBytes(value) {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction snapshotDigest(files) {\n const hash = createHash(\"sha256\");\n for (const [file, digest] of [...files].sort(([left], [right]) =>\n left.localeCompare(right))) {\n hash.update(file);\n hash.update(\"\\0\");\n hash.update(digest);\n hash.update(\"\\0\");\n }\n return hash.digest(\"hex\");\n}\n\nasync function canonicalDirectory(directory) {\n const expanded = resolve(directory);\n try {\n if (!(await stat(expanded)).isDirectory()) {\n throw watchError(\"watch root is not a directory\", expanded);\n }\n return await realpath(expanded);\n } catch (error) {\n if (error?.eliscriptDiagnostic) throw error;\n throw watchError(\"watch root does not exist\", expanded);\n }\n}\n\nasync function canonicalConfiguration(filename) {\n if (filename === null || filename === undefined) return null;\n const expanded = resolve(filename);\n try {\n if (!(await stat(expanded)).isFile()) {\n throw watchError(\"watch configuration is not a file\", expanded);\n }\n return await realpath(expanded);\n } catch (error) {\n if (error?.eliscriptDiagnostic) throw error;\n throw watchError(\"watch configuration does not exist\", expanded);\n }\n}\n\nfunction watchInterval(value) {\n const interval = value ?? defaultWatchInterval;\n if (!Number.isSafeInteger(interval) || interval < minimumWatchInterval ||\n interval > maximumWatchInterval) {\n throw watchError(\n `watch interval must be an integer between ${minimumWatchInterval} and ` +\n `${maximumWatchInterval} milliseconds`,\n );\n }\n return interval;\n}\n\nasync function readDigest(filename) {\n try {\n return digestBytes(await readFile(filename));\n } catch (error) {\n if (error?.code === \"ENOENT\" || error?.code === \"ENOTDIR\") return null;\n throw error;\n }\n}\n\nasync function collectSources(directory, files) {\n let entries;\n try {\n entries = await readdir(directory, { withFileTypes: true });\n } catch (error) {\n if (error?.code === \"ENOENT\" || error?.code === \"ENOTDIR\") return;\n throw error;\n }\n entries.sort((left, right) => left.name.localeCompare(right.name));\n for (const entry of entries) {\n if (entry.isSymbolicLink()) continue;\n const filename = join(directory, entry.name);\n if (entry.isDirectory()) {\n await collectSources(filename, files);\n } else if (entry.isFile() && entry.name.endsWith(\".eli\")) {\n const digest = await readDigest(filename);\n if (digest !== null) files.set(filename, digest);\n }\n }\n}\n\nasync function projectSnapshot(root, configuration) {\n const files = new Map();\n await collectSources(root, files);\n if (configuration !== null && !files.has(configuration)) {\n const digest = await readDigest(configuration);\n if (digest !== null) files.set(configuration, digest);\n }\n return freeze({ files, digest: snapshotDigest(files) });\n}\n\nfunction changesBetween(previous, current, root) {\n const files = new Set([...previous.files.keys(), ...current.files.keys()]);\n return [...files].sort().flatMap((file) => {\n const before = previous.files.get(file);\n const after = current.files.get(file);\n if (before === after) return [];\n const kind = before === undefined\n ? \"create\"\n : after === undefined ? \"delete\" : \"modify\";\n return [freeze({\n file,\n ...(containedPath(file, root) ? { path: relative(root, file) } : {}),\n kind,\n })];\n });\n}\n\nfunction eventRecord(sequence, event, root, fields = {}) {\n return freeze({\n format: watchEventFormat,\n version: watchEventVersion,\n sequence,\n event,\n root,\n ...fields,\n });\n}\n\nexport class ProjectWatcher {\n static async create(options = {}) {\n if (!options || typeof options !== \"object\") {\n throw watchError(\"watch options must be an object\");\n }\n if (typeof options.root !== \"string\" || options.root.length === 0) {\n throw watchError(\"watch root must be a non-empty string\");\n }\n const root = await canonicalDirectory(options.root);\n const configuration = await canonicalConfiguration(options.configuration);\n const interval = watchInterval(options.interval);\n const snapshot = await projectSnapshot(root, configuration);\n return new ProjectWatcher(root, configuration, interval, snapshot);\n }\n\n constructor(root, configuration, interval, snapshot) {\n this.root = root;\n this.configuration = configuration;\n this.interval = interval;\n this.snapshot = snapshot;\n this.sequence = 0;\n this.timer = null;\n this.scanning = false;\n this.scanPromise = null;\n this.closed = false;\n }\n\n ready() {\n return eventRecord(0, \"ready\", this.root, {\n changes: freeze([]),\n digest: this.snapshot.digest,\n });\n }\n\n async scan() {\n if (this.closed) throw watchError(\"watch session is closed\", this.root);\n const next = await projectSnapshot(this.root, this.configuration);\n const changes = changesBetween(this.snapshot, next, this.root);\n this.snapshot = next;\n if (changes.length === 0) return null;\n this.sequence += 1;\n return eventRecord(this.sequence, \"change\", this.root, {\n changes: freeze(changes),\n digest: next.digest,\n });\n }\n\n error(error) {\n this.sequence += 1;\n const diagnostic = error?.eliscriptDiagnostic ?? {\n format: \"eliscript-diagnostic\",\n version: 1,\n code: \"ELI-W0002\",\n severity: \"error\",\n phase: \"project-watch\",\n message: error instanceof Error ? error.message : String(error),\n location: { file: this.root },\n };\n return eventRecord(this.sequence, \"error\", this.root, {\n diagnostic: freeze(diagnostic),\n });\n }\n\n start(onEvent) {\n if (typeof onEvent !== \"function\") {\n throw watchError(\"watch event handler must be a function\");\n }\n if (this.closed) throw watchError(\"watch session is closed\", this.root);\n if (this.timer !== null) return this;\n this.timer = setInterval(async () => {\n if (this.scanning || this.closed) return;\n this.scanning = true;\n this.scanPromise = this.scan();\n try {\n const event = await this.scanPromise;\n if (!this.closed && event !== null) onEvent(event);\n } catch (error) {\n if (!this.closed) onEvent(this.error(error));\n } finally {\n this.scanning = false;\n this.scanPromise = null;\n }\n }, this.interval);\n onEvent(this.ready());\n return this;\n }\n\n async close() {\n if (this.timer !== null) clearInterval(this.timer);\n this.timer = null;\n this.closed = true;\n if (this.scanPromise !== null) {\n try {\n await this.scanPromise;\n } catch {\n // A closing watcher suppresses the final recoverable scan failure.\n }\n }\n }\n}\n\nexport async function snapshotProject(options) {\n const watcher = await ProjectWatcher.create(options);\n try {\n return watcher.ready();\n } finally {\n await watcher.close();\n }\n}\n"))
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Browser Compiler Host & Worker
|
|
2
|
+
|
|
3
|
+
[Project README](../README.md) | [Getting started](../docs/getting-started.md) |
|
|
4
|
+
[Platform packages](../platform/README.md)
|
|
5
|
+
|
|
6
|
+
This directory contains the in-memory browser compiler SDK (`host.eli`) and its
|
|
7
|
+
Web Worker transport (`worker.eli`). During `make bootstrap-backends` and
|
|
8
|
+
`bun run build:browser`, these `.eli` sources are materialized and bundled into
|
|
9
|
+
`dist/browser/` (`compiler.js`, `loader.js`, `host.mjs`, and `worker.mjs`).
|
|
10
|
+
|
|
11
|
+
## Live Browser `<script type="text/eliscript">` Loader
|
|
12
|
+
|
|
13
|
+
Include `dist/browser/loader.js` on any static page to compile, execute, and
|
|
14
|
+
hot-reload `<script type="text/eliscript">` tags (inline or `src="..."`) or
|
|
15
|
+
`data-eliscript` entry points directly in the browser without a backend server:
|
|
16
|
+
|
|
17
|
+
```html
|
|
18
|
+
<script defer src="https://unpkg.com/eliscript@0.0.4/dist/browser/loader.js"></script>
|
|
19
|
+
<script type="text/eliscript">
|
|
20
|
+
(module app.live
|
|
21
|
+
(import "eliscript/runtime/core/order" sort)
|
|
22
|
+
(print "Sorted:" (sort [4 1 3 2])))
|
|
23
|
+
</script>
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Programmatic Browser SDK (`eliscript/browser`)
|
|
27
|
+
|
|
28
|
+
Import `eliscript/browser` to compile single modules (`compileSource`,
|
|
29
|
+
`runSource`), multi-file in-memory projects (`compileProject`,
|
|
30
|
+
`moduleGraphUrls`), or DOM script tags (`mountEliscriptScripts`), with built-in
|
|
31
|
+
Closure-style IR optimization (`optimizeProgramIr`), optional JavaScript
|
|
32
|
+
compaction (`optimizeJavaScript` / `{ minify: true }`), and extensionless
|
|
33
|
+
`eliscript/*` package subpath resolution.
|
package/browser/host.eli
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.browser.host
|
|
2
|
+
(js* "// In-memory compile host for browsers and workers.\n//\n// The command-line host in `bootstrap/host/project.mjs` answers the project\n// planner from the filesystem. This host answers the same questions from a map\n// of sources, so a project compiles without a server process, and it rewrites\n// every specifier the emitted modules carry so they can run from blob URLs.\n//\n// Every import in this file is relative. A worker has no document and therefore\n// no import map, so this module and the compiler bundle it loads must never\n// depend on one.\n\nimport {\n compile_ir_string,\n emit_ir_string_with_source_map,\n project_plan,\n} from \"../dist/browser/compiler.js\";\n\nconst SOURCE_EXTENSION = \".eli\";\nconst OUTPUT_EXTENSION = \".mjs\";\n\n/* ------------------------------------------------------------------ paths */\n\nfunction splitPath(path) {\n return path.split(\"/\").filter((part) => part !== \"\" && part !== \".\");\n}\n\nexport function normalizePath(path) {\n const parts = [];\n for (const part of splitPath(path)) {\n if (part === \"..\") {\n if (parts.length === 0) {\n throw new Error(`path escapes the project root: ${path}`);\n }\n parts.pop();\n } else {\n parts.push(part);\n }\n }\n return parts.join(\"/\");\n}\n\nexport function dirname(path) {\n const parts = splitPath(path);\n parts.pop();\n return parts.join(\"/\");\n}\n\nexport function resolvePath(importer, specifier) {\n const base = dirname(importer);\n return normalizePath(base === \"\" ? specifier : `${base}/${specifier}`);\n}\n\nexport function outputPathFor(source) {\n if (!source.endsWith(SOURCE_EXTENSION)) {\n throw new Error(`source module must end with ${SOURCE_EXTENSION}: ${source}`);\n }\n return `${source.slice(0, -SOURCE_EXTENSION.length)}${OUTPUT_EXTENSION}`;\n}\n\nexport function relativePath(from, to) {\n const fromParts = splitPath(dirname(from));\n const toParts = splitPath(to);\n let common = 0;\n while (common < fromParts.length && common < toParts.length &&\n fromParts[common] === toParts[common]) {\n common += 1;\n }\n const parts = [\n ...fromParts.slice(common).map(() => \"..\"),\n ...toParts.slice(common),\n ];\n const joined = parts.join(\"/\");\n return joined.startsWith(\".\") ? joined : `./${joined}`;\n}\n\n/* ------------------------------------------------------------------ graph */\n\n// The planner hands back discovery order, but a module's imports must exist\n// before it does, so execution needs a dependency-first order.\nexport function dependencyOrder(modules) {\n const byId = new Map(modules.map((module) => [module.id, module]));\n const order = [];\n const state = new Map();\n for (const module of modules) visit(module.id);\n return order;\n\n function visit(id) {\n const seen = state.get(id);\n if (seen === \"done\") return;\n if (seen === \"visiting\") throw new Error(`import cycle through ${id}`);\n state.set(id, \"visiting\");\n for (const dependency of byId.get(id)?.dependencies ?? []) visit(dependency);\n state.set(id, \"done\");\n order.push(id);\n }\n}\n\nfunction walkProgram(program, visit) {\n const pending = [...program.body];\n while (pending.length > 0) {\n const node = pending.pop();\n visit(node);\n const children = node.children;\n if (children === undefined || children === null) continue;\n for (let index = children.length - 1; index >= 0; index -= 1) {\n pending.push(children[index]);\n }\n }\n}\n\nfunction isPlainLiteralNode(node) {\n return (\n node !== null &&\n typeof node === \"object\" &&\n node.kind === \"literal\" &&\n node.properties?.literalKind === undefined\n );\n}\n\nfunction isConstantLiteralNode(node) {\n if (node === null || typeof node !== \"object\" || node.kind !== \"literal\") {\n return false;\n }\n const literalKind = node.properties?.literalKind;\n return (\n literalKind === undefined ||\n literalKind === \"undefined\" ||\n literalKind === \"keyword\"\n );\n}\n\nfunction cloneLiteralNode(literal, span) {\n return {\n kind: \"literal\",\n span: span ?? literal.span,\n value: literal.value,\n children: [],\n ...(literal.properties ? { properties: { ...literal.properties } } : {}),\n };\n}\n\nfunction literalRuntimeValue(node) {\n const literalKind = node.properties?.literalKind;\n if (literalKind === \"undefined\") return undefined;\n if (literalKind === \"keyword\") return `:${node.value}`;\n return node.value;\n}\n\nfunction literalTruthiness(node) {\n if (!isConstantLiteralNode(node)) {\n return null;\n }\n const literalKind = node.properties?.literalKind;\n if (literalKind === \"undefined\") return false;\n if (literalKind === \"keyword\") return true;\n return node.value !== false && node.value !== null && node.value !== undefined;\n}\n\nfunction collectMutatedNames(program) {\n const mutated = new Set();\n walkProgram(program, (node) => {\n if (node.kind === \"assignment\") {\n for (const pair of node.children ?? []) {\n if (typeof pair?.value === \"string\") mutated.add(pair.value);\n }\n } else if (\n node.kind === \"variable-declaration\" &&\n node.properties?.mutable === true &&\n typeof node.value === \"string\"\n ) {\n mutated.add(node.value);\n }\n });\n return mutated;\n}\n\nfunction foldIrNode(node, env = new Map(), mutated = new Set()) {\n if (node === null || typeof node !== \"object\") return node;\n if (node.kind === \"export-declaration\" || node.kind === \"import-declaration\") {\n return node;\n }\n\n if (node.kind === \"reference\" && typeof node.value === \"string\") {\n if (!mutated.has(node.value) && env.has(node.value)) {\n return cloneLiteralNode(env.get(node.value), node.span);\n }\n return node;\n }\n\n if (node.kind === \"module-declaration\" && Array.isArray(node.children)) {\n const scope = new Map(env);\n let changed = false;\n const nextChildren = node.children.map((child) => {\n const next = foldIrNode(child, scope, mutated);\n if (next !== child) changed = true;\n if (\n next.kind === \"variable-declaration\" &&\n next.properties?.mutable !== true &&\n typeof next.value === \"string\" &&\n !mutated.has(next.value) &&\n Array.isArray(next.children) &&\n next.children.length === 1 &&\n isConstantLiteralNode(next.children[0])\n ) {\n scope.set(next.value, next.children[0]);\n }\n return next;\n });\n return changed ? { ...node, children: nextChildren } : node;\n }\n\n if (\n (node.kind === \"function-declaration\" || node.kind === \"function-expression\") &&\n Array.isArray(node.children)\n ) {\n const paramCount = node.properties?.parameterCount ?? 0;\n const scope = new Map(env);\n for (let index = 0; index < paramCount; index += 1) {\n const param = node.children[index];\n if (typeof param?.value === \"string\") scope.delete(param.value);\n }\n let changed = false;\n const nextChildren = node.children.map((child, index) => {\n if (index < paramCount) return child;\n const next = foldIrNode(child, scope, mutated);\n if (next !== child) changed = true;\n return next;\n });\n return changed ? { ...node, children: nextChildren } : node;\n }\n\n if (node.kind === \"lexical-bindings\" && Array.isArray(node.children)) {\n const bindingCount = node.properties?.bindingCount ?? 0;\n const sequential = node.properties?.sequential === true;\n const outerScope = new Map(env);\n const bodyScope = new Map(env);\n let changed = false;\n const nextChildren = node.children.map((child, index) => {\n if (index < bindingCount && child.kind === \"lexical-binding\") {\n const initScope = sequential ? bodyScope : outerScope;\n let nextBinding = child;\n if (Array.isArray(child.children) && child.children.length > 0) {\n let bindingChanged = false;\n const nextBindingChildren = child.children.map((expr) => {\n const folded = foldIrNode(expr, initScope, mutated);\n if (folded !== expr) bindingChanged = true;\n return folded;\n });\n if (bindingChanged) {\n changed = true;\n nextBinding = { ...child, children: nextBindingChildren };\n }\n }\n if (\n typeof nextBinding.value === \"string\" &&\n nextBinding.properties?.pattern !== true\n ) {\n if (\n !mutated.has(nextBinding.value) &&\n Array.isArray(nextBinding.children) &&\n nextBinding.children.length === 1 &&\n isConstantLiteralNode(nextBinding.children[0])\n ) {\n bodyScope.set(nextBinding.value, nextBinding.children[0]);\n } else {\n bodyScope.delete(nextBinding.value);\n }\n }\n return nextBinding;\n }\n const next = foldIrNode(child, bodyScope, mutated);\n if (next !== child) changed = true;\n return next;\n });\n const updated = changed ? { ...node, children: nextChildren } : node;\n const bodyNodes = updated.children.slice(bindingCount);\n if (bodyNodes.length === 1 && isConstantLiteralNode(bodyNodes[0])) {\n const allBindingsPureConstants = updated.children\n .slice(0, bindingCount)\n .every(\n (binding) =>\n binding.kind === \"lexical-binding\" &&\n binding.properties?.pattern !== true &&\n Array.isArray(binding.children) &&\n binding.children.length === 1 &&\n isConstantLiteralNode(binding.children[0]),\n );\n if (allBindingsPureConstants) {\n return bodyNodes[0];\n }\n }\n return updated;\n }\n\n if (Array.isArray(node.children) && node.children.length > 0) {\n let changed = false;\n const optimizedChildren = node.children.map((child) => {\n const next = foldIrNode(child, env, mutated);\n if (next !== child) changed = true;\n return next;\n });\n if (changed) {\n node = { ...node, children: optimizedChildren };\n }\n }\n\n const children = node.children ?? [];\n if (node.kind === \"conditional\" && children.length >= 2) {\n const truthy = literalTruthiness(children[0]);\n if (truthy === true) return children[1];\n if (truthy === false) {\n return (\n children[2] ?? {\n kind: \"literal\",\n span: node.span,\n value: null,\n children: [],\n }\n );\n }\n }\n\n if (node.kind === \"short-circuit\" && children.length > 0) {\n if (node.value === \"and\") {\n const remaining = [];\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n const truthy = literalTruthiness(child);\n if (truthy === false && remaining.length === 0) {\n return child;\n }\n if (truthy === true && index < children.length - 1) {\n continue;\n }\n remaining.push(child);\n }\n if (remaining.length === 1) return remaining[0];\n if (remaining.length !== children.length) {\n return { ...node, children: remaining };\n }\n } else if (node.value === \"or\") {\n const remaining = [];\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n const truthy = literalTruthiness(child);\n if (truthy === true && remaining.length === 0) {\n return child;\n }\n if (truthy === false && index < children.length - 1) {\n continue;\n }\n remaining.push(child);\n }\n if (remaining.length === 1) return remaining[0];\n if (remaining.length !== children.length) {\n return { ...node, children: remaining };\n }\n }\n }\n\n if (node.kind === \"intrinsic\") {\n if (node.value === \"not\" && children.length === 1) {\n const truthy = literalTruthiness(children[0]);\n if (truthy !== null) {\n return {\n kind: \"literal\",\n span: node.span,\n value: !truthy,\n children: [],\n };\n }\n }\n\n if (\n (node.value === \"null\" ||\n node.value === \"nil?\" ||\n node.value === \"undefined?\" ||\n node.value === \"nullish?\") &&\n children.length === 1 &&\n isConstantLiteralNode(children[0])\n ) {\n const raw = literalRuntimeValue(children[0]);\n const result =\n node.value === \"undefined?\"\n ? raw === undefined\n : node.value === \"nullish?\"\n ? raw === null || raw === undefined\n : raw === null;\n return {\n kind: \"literal\",\n span: node.span,\n value: result,\n children: [],\n };\n }\n\n if (\n (node.value === \"=\" ||\n node.value === \"/=\" ||\n node.value === \"not=\" ||\n node.value === \"eq\" ||\n node.value === \"equal\") &&\n children.length === 2 &&\n isConstantLiteralNode(children[0]) &&\n isConstantLiteralNode(children[1])\n ) {\n const left = literalRuntimeValue(children[0]);\n const right = literalRuntimeValue(children[1]);\n const same = left === right;\n return {\n kind: \"literal\",\n span: node.span,\n value: node.value === \"/=\" || node.value === \"not=\" ? !same : same,\n children: [],\n };\n }\n\n if (\n (node.value === \"<\" ||\n node.value === \"<=\" ||\n node.value === \">\" ||\n node.value === \">=\") &&\n children.length === 2 &&\n isPlainLiteralNode(children[0]) &&\n isPlainLiteralNode(children[1]) &&\n typeof children[0].value === \"number\" &&\n typeof children[1].value === \"number\"\n ) {\n const left = children[0].value;\n const right = children[1].value;\n const compared =\n node.value === \"<\"\n ? left < right\n : node.value === \"<=\"\n ? left <= right\n : node.value === \">\"\n ? left > right\n : left >= right;\n return {\n kind: \"literal\",\n span: node.span,\n value: compared,\n children: [],\n };\n }\n\n if (\n children.every(\n (child) => isPlainLiteralNode(child) && typeof child.value === \"number\",\n )\n ) {\n const values = children.map((child) => child.value);\n let folded;\n switch (node.value) {\n case \"+\":\n folded = values.reduce((sum, item) => sum + item, 0);\n break;\n case \"*\":\n folded = values.reduce((product, item) => product * item, 1);\n break;\n case \"-\":\n if (values.length === 1) folded = -values[0];\n else if (values.length >= 2) {\n folded = values.slice(1).reduce((acc, item) => acc - item, values[0]);\n }\n break;\n case \"/\":\n if (values.length === 2 && values[1] !== 0) {\n folded = values[0] / values[1];\n }\n break;\n case \"%\":\n if (values.length === 2 && values[1] !== 0) {\n folded = values[0] % values[1];\n }\n break;\n case \"1+\":\n if (values.length === 1) folded = values[0] + 1;\n break;\n case \"1-\":\n if (values.length === 1) folded = values[0] - 1;\n break;\n default:\n break;\n }\n if (typeof folded === \"number\" && Number.isFinite(folded)) {\n return {\n kind: \"literal\",\n span: node.span,\n value: folded,\n children: [],\n };\n }\n }\n\n if (node.value === \"+\" && children.length >= 2) {\n const nonZero = children.filter(\n (child) => !(isPlainLiteralNode(child) && child.value === 0),\n );\n if (nonZero.length > 0 && nonZero.length < children.length) {\n return nonZero.length === 1\n ? nonZero[0]\n : { ...node, children: nonZero };\n }\n }\n\n if (node.value === \"*\" && children.length >= 2) {\n const nonOne = children.filter(\n (child) => !(isPlainLiteralNode(child) && child.value === 1),\n );\n if (nonOne.length > 0 && nonOne.length < children.length) {\n return nonOne.length === 1 ? nonOne[0] : { ...node, children: nonOne };\n }\n }\n }\n\n if (\n node.kind === \"string-concat\" &&\n children.every(\n (child) =>\n isPlainLiteralNode(child) &&\n (typeof child.value === \"string\" ||\n typeof child.value === \"number\" ||\n typeof child.value === \"boolean\" ||\n child.value === null),\n )\n ) {\n return {\n kind: \"literal\",\n span: node.span,\n value: children\n .map((child) => (child.value === null ? \"\" : String(child.value)))\n .join(\"\"),\n children: [],\n };\n }\n\n return node;\n}\n\n/**\n * Performs a Closure-style IR optimization pass (constant propagation,\n * constant folding, algebraic identity simplification, and dead conditional\n * branch elimination) over a compiled Eliscript IR program.\n */\nexport function optimizeProgramIr(program) {\n if (program === null || typeof program !== \"object\" || !Array.isArray(program.body)) {\n return program;\n }\n const mutated = collectMutatedNames(program);\n const topScope = new Map();\n program.body = program.body.map((node) => {\n const next = foldIrNode(node, topScope, mutated);\n if (\n next.kind === \"variable-declaration\" &&\n next.properties?.mutable !== true &&\n typeof next.value === \"string\" &&\n !mutated.has(next.value) &&\n Array.isArray(next.children) &&\n next.children.length === 1 &&\n isConstantLiteralNode(next.children[0])\n ) {\n topScope.set(next.value, next.children[0]);\n }\n return next;\n });\n return program;\n}\n\nfunction isIdentifierChar(ch) {\n if (!ch) return false;\n const code = ch.charCodeAt(0);\n return (\n (code >= 48 && code <= 57) ||\n (code >= 65 && code <= 90) ||\n (code >= 97 && code <= 122) ||\n code === 36 ||\n code === 95 ||\n code > 127\n );\n}\n\nfunction compactLineWhitespace(line) {\n if (line.startsWith(\"//# sourceMappingURL=\")) return line;\n let result = \"\";\n let index = 0;\n const length = line.length;\n while (index < length) {\n const ch = line[index];\n if (ch === '\"' || ch === \"'\" || ch === \"`\") {\n const quote = ch;\n result += ch;\n index += 1;\n while (index < length) {\n const cur = line[index];\n result += cur;\n index += 1;\n if (cur === \"\\\\\" && index < length) {\n result += line[index];\n index += 1;\n continue;\n }\n if (cur === quote) break;\n }\n continue;\n }\n if (ch === \" \" || ch === \"\\t\") {\n while (index < length && (line[index] === \" \" || line[index] === \"\\t\")) {\n index += 1;\n }\n const prev = result[result.length - 1] ?? \"\";\n const next = line[index] ?? \"\";\n if (\n (isIdentifierChar(prev) && isIdentifierChar(next)) ||\n (prev === \"+\" && next === \"+\") ||\n (prev === \"-\" && next === \"-\") ||\n (prev === \"/\" && (next === \"/\" || next === \"*\"))\n ) {\n result += \" \";\n }\n continue;\n }\n result += ch;\n index += 1;\n }\n return result;\n}\n\n/**\n * Strips comments and compacts whitespace in emitted JavaScript while\n * preserving string/template literals and sourceMappingURL directives.\n */\nexport function optimizeJavaScript(code) {\n if (typeof code !== \"string\" || code.length === 0) return code;\n let out = \"\";\n let index = 0;\n const length = code.length;\n\n while (index < length) {\n const ch = code[index];\n const next = code[index + 1];\n\n if (ch === '\"' || ch === \"'\" || ch === \"`\") {\n const quote = ch;\n out += ch;\n index += 1;\n while (index < length) {\n const current = code[index];\n out += current;\n index += 1;\n if (current === \"\\\\\" && index < length) {\n out += code[index];\n index += 1;\n continue;\n }\n if (current === quote) break;\n }\n continue;\n }\n\n if (ch === \"/\" && next === \"/\") {\n const lineEnd = code.indexOf(\"\\n\", index + 2);\n const comment = lineEnd < 0 ? code.slice(index) : code.slice(index, lineEnd);\n if (comment.startsWith(\"//# sourceMappingURL=\")) {\n out += comment;\n }\n index = lineEnd < 0 ? length : lineEnd;\n continue;\n }\n\n if (ch === \"/\" && next === \"*\") {\n const closeIndex = code.indexOf(\"*/\", index + 2);\n if (closeIndex < 0) break;\n const block = code.slice(index + 2, closeIndex);\n out += block.includes(\"\\n\") ? \"\\n\" : \" \";\n index = closeIndex + 2;\n continue;\n }\n\n out += ch;\n index += 1;\n }\n\n const lines = out\n .split(\"\\n\")\n .map((line) => compactLineWhitespace(line.trim()))\n .filter((line) => line.length > 0);\n return lines.length === 0 ? \"\" : `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction applyPostCompileOptimization(javascript, sourceMap, meta, options = {}) {\n let code =\n options.minify === true || options.optimize === \"compact\"\n ? optimizeJavaScript(javascript)\n : javascript;\n let map = sourceMap;\n if (typeof options.closureCompiler === \"function\") {\n const transformed = options.closureCompiler(code, {\n ...meta,\n sourceMap: map,\n });\n if (typeof transformed === \"string\") {\n code = transformed;\n } else if (transformed !== null && typeof transformed === \"object\") {\n if (typeof transformed.javascript === \"string\") code = transformed.javascript;\n if (typeof transformed.sourceMap === \"string\") map = transformed.sourceMap;\n }\n }\n return { javascript: code, sourceMap: map };\n}\n\nfunction localSourceSpecifier(specifier) {\n return specifier.startsWith(\".\") && specifier.endsWith(SOURCE_EXTENSION);\n}\n\nfunction importSpecifiers(program) {\n const specifiers = [];\n walkProgram(program, (node) => {\n if (node.kind === \"import-declaration\") specifiers.push(node);\n });\n return specifiers;\n}\n\n// A source map names its source relative to the map beside it, which is a bare\n// relative path rather than an import specifier.\nfunction mapSourcePath(output, source) {\n const path = relativePath(`${output}.map`, source);\n return path.startsWith(\"./\") ? path.slice(2) : path;\n}\n\n// The emitter injects runtime imports of its own for literals, collection\n// helpers, list operations, and value equality. Those are not import nodes in\n// the program, so they survive the IR rewrite above and must be resolved in the\n// emitted text or every module that uses a vector keeps a bare specifier.\nfunction rewriteEmittedExternals(code, source, resolveExternal) {\n if (resolveExternal === undefined) return code;\n const rewrite = (whole, prefix, quoted) => {\n const specifier = quoted.slice(1, -1);\n if (specifier.startsWith(\".\") || specifier.startsWith(\"/\") ||\n specifier.includes(\"://\")) {\n return whole;\n }\n const external = resolveExternal(specifier, source);\n return typeof external === \"string\" && external.length > 0\n ? `${prefix}\"${external}\"`\n : whole;\n };\n return code\n .replace(/(\\bfrom\\s+)(\"[^\"]+\")/gu, rewrite)\n .replace(/(\\bimport\\s+)(\"[^\"]+\")/gu, rewrite);\n}\n\nfunction diagnosticOf(error, filename) {\n return error?.eliscriptDiagnostic ?? {\n format: \"eliscript-diagnostic\",\n version: 1,\n code: \"ELI-BROWSER-0001\",\n severity: \"error\",\n phase: \"browser-host\",\n message: error?.message ?? String(error),\n location: { file: filename },\n };\n}\n\nexport class BrowserCompileError extends Error {\n constructor(diagnostics) {\n super(diagnostics.map((diagnostic) => diagnostic.message).join(\"; \"));\n this.name = \"BrowserCompileError\";\n this.diagnostics = diagnostics;\n }\n}\n\nfunction failure(code, message, filename) {\n return new BrowserCompileError([{\n format: \"eliscript-diagnostic\",\n version: 1,\n code,\n severity: \"error\",\n phase: \"browser-host\",\n message,\n location: { file: filename },\n }]);\n}\n\n/* ---------------------------------------------------------------- compile */\n\n// Rewrites every specifier an emitted module carries:\n// - a local `.eli` import becomes the relative path of its emitted module;\n// - a bare specifier is offered to `resolveExternal`, so an application can\n// point the runtime at a served directory without an import map;\n// - anything `resolveExternal` declines stays as written, which is what a\n// third-party package import needs.\nfunction normalizePackageSubpath(specifier) {\n if (\n /^eliscript\\/(?:runtime|platform|dist\\/stdlib|stdlib)\\//u.test(specifier) &&\n !/\\.[a-z0-9]+$/iu.test(specifier)\n ) {\n return `${specifier}${OUTPUT_EXTENSION}`;\n }\n return specifier;\n}\n\nfunction rewriteSpecifiers(program, source, resolveExternal) {\n for (const node of importSpecifiers(program)) {\n const specifier = node.value;\n if (localSourceSpecifier(specifier)) {\n node.value = relativePath(\n outputPathFor(source),\n outputPathFor(resolvePath(source, specifier)),\n );\n continue;\n }\n if (specifier.startsWith(\".\") || specifier.startsWith(\"/\")) continue;\n const normalized = normalizePackageSubpath(specifier);\n node.value = normalized;\n const external = resolveExternal?.(normalized, source);\n if (typeof external === \"string\" && external.length > 0) node.value = external;\n }\n}\n\n/**\n * Compiles one module.\n *\n * @returns {{ javascript: string, sourceMap: object }}\n */\nexport function compileSource(\n source,\n filename = `module${SOURCE_EXTENSION}`,\n options = {},\n) {\n const program = compile_ir_string(source, filename, options.macroContext ?? null);\n if (options.optimize !== false) {\n optimizeProgramIr(program);\n }\n rewriteSpecifiers(program, filename, options.resolveExternal);\n const output = outputPathFor(filename);\n const emission = emit_ir_string_with_source_map(\n program,\n source,\n output,\n mapSourcePath(output, filename),\n );\n const rewritten = rewriteEmittedExternals(\n emission.javascript,\n filename,\n options.resolveExternal,\n );\n return applyPostCompileOptimization(\n rewritten,\n emission.sourceMap,\n { filename, output },\n options,\n );\n}\n\n/**\n * Compiles a whole project from a map of sources.\n *\n * @param {object} request\n * @param {Record<string, string>} request.files relative `.eli` path to source\n * @param {string} request.entry relative `.eli` path to compile from\n * @returns {{ plan: object, modules: Record<string, object> }}\n */\nexport function compileProject({\n files,\n entry,\n macroContext = null,\n resolveExternal,\n optimize = true,\n minify = false,\n closureCompiler,\n}) {\n for (const path of Object.keys(files)) outputPathFor(path);\n if (files[entry] === undefined) {\n throw failure(\"ELI-BROWSER-0002\", `entry is not in the project: ${entry}`, entry);\n }\n\n const programs = new Map();\n const programFor = (id) => {\n if (programs.has(id)) return programs.get(id);\n if (files[id] === undefined) {\n throw failure(\"ELI-BROWSER-0003\", `missing source for import: ${id}`, id);\n }\n let program;\n try {\n program = compile_ir_string(files[id], id, macroContext);\n if (optimize !== false) {\n optimizeProgramIr(program);\n }\n } catch (error) {\n throw new BrowserCompileError([diagnosticOf(error, id)]);\n }\n programs.set(id, program);\n return program;\n };\n\n const plan = project_plan([entry], (id) => importSpecifiers(programFor(id))\n .filter((node) => localSourceSpecifier(node.value))\n .map((node) => resolvePath(id, node.value)));\n\n const modules = {};\n for (const id of dependencyOrder(plan.modules)) {\n const output = outputPathFor(id);\n const program = programFor(id);\n rewriteSpecifiers(program, id, resolveExternal);\n const emission = emit_ir_string_with_source_map(\n program,\n files[id],\n output,\n mapSourcePath(output, id),\n );\n const rewritten = rewriteEmittedExternals(emission.javascript, id, resolveExternal);\n const optimized = applyPostCompileOptimization(\n rewritten,\n emission.sourceMap,\n { filename: id, output },\n { optimize, minify, closureCompiler },\n );\n modules[output] = {\n id,\n source: files[id],\n javascript: optimized.javascript,\n sourceMap: optimized.sourceMap,\n };\n }\n return { plan, modules };\n}\n\n/* ---------------------------------------------------------------- execute */\n\n/**\n * Turns compiled modules into importable blob URLs, dependencies first.\n *\n * A blob module has no directory, so its relative imports cannot resolve. Each\n * local specifier was therefore rewritten to a relative path during compilation\n * and is replaced here by the blob URL of the module it names. Only import\n * specifiers are touched, never a string literal that resembles one.\n *\n * @returns {{ entryUrl: string, urls: Record<string, string>, release: () => void }}\n */\nexport function moduleGraphUrls(modules, entry) {\n const urls = {};\n const created = [];\n const outputs = Object.keys(modules);\n\n const targetOf = (from, specifier) => {\n const parts = splitPath(dirname(from));\n for (const part of specifier.split(\"/\")) {\n if (part === \"\" || part === \".\") continue;\n if (part === \"..\") parts.pop();\n else parts.push(part);\n }\n return parts.join(\"/\");\n };\n const rewritePattern = (code, from, pattern) => code.replace(\n pattern,\n (whole, prefix, quoted) => {\n const specifier = quoted.slice(1, -1);\n if (!specifier.startsWith(\".\")) return whole;\n const url = urls[targetOf(from, specifier)];\n return url === undefined ? whole : `${prefix}\"${url}\"`;\n },\n );\n\n for (const outputPath of outputs) {\n let code = modules[outputPath].javascript;\n code = rewritePattern(code, outputPath, /(\\bfrom\\s+)(\"[^\"]+\")/gu);\n code = rewritePattern(code, outputPath, /(\\bimport\\s+)(\"[^\"]+\")/gu);\n urls[outputPath] = URL.createObjectURL(\n new Blob([code], { type: \"text/javascript\" }),\n );\n created.push(urls[outputPath]);\n }\n\n const entryUrl = urls[outputPathFor(entry)];\n if (entryUrl === undefined) {\n for (const url of created) URL.revokeObjectURL(url);\n throw failure(\"ELI-BROWSER-0004\", `compiled entry is missing: ${entry}`, entry);\n }\n const release = () => {\n for (const url of created) URL.revokeObjectURL(url);\n };\n return { entryUrl, urls, release };\n}\n\n/**\n * Compiles one Eliscript module in memory and executes it immediately via a\n * temporary Blob URL.\n *\n * @param {string} source Eliscript source text\n * @param {string} [filename=\"module.eli\"] virtual filename for diagnostics/maps\n * @param {object} [options={}] compilation options (e.g., resolveExternal)\n * @returns {Promise<{ module: object, javascript: string, sourceMap: string }>}\n */\nexport async function runSource(\n source,\n filename = `module${SOURCE_EXTENSION}`,\n options = {},\n) {\n const compiled = compileSource(source, filename, options);\n const url = URL.createObjectURL(\n new Blob([compiled.javascript], { type: \"text/javascript\" }),\n );\n try {\n const module = await import(url);\n return {\n module,\n javascript: compiled.javascript,\n sourceMap: compiled.sourceMap,\n };\n } finally {\n URL.revokeObjectURL(url);\n }\n}\n\nfunction scriptFilename(script, index) {\n const explicit = script?.getAttribute?.(\"data-filename\") || script?.dataset?.filename;\n if (typeof explicit === \"string\" && explicit.trim().length > 0) {\n const name = explicit.trim();\n return name.endsWith(SOURCE_EXTENSION) ? name : `${name}${SOURCE_EXTENSION}`;\n }\n if (typeof script?.src === \"string\" && script.src.length > 0) {\n try {\n const url = new URL(script.src, globalThis.location?.href ?? \"http://localhost/\");\n const tail = url.pathname.split(\"/\").filter(Boolean).pop();\n if (tail && tail.endsWith(SOURCE_EXTENSION)) return tail;\n } catch {}\n }\n return `inline-${index + 1}${SOURCE_EXTENSION}`;\n}\n\n/**\n * Scans a DOM root for `<script type=\"text/eliscript\">` elements (both inline\n * and external `src=\"...\"`) and compiles + executes each one in document order.\n *\n * @param {ParentNode} [root=globalThis.document]\n * @param {object} [options={}]\n * @returns {Promise<Array<{ script: Element, filename: string, module: object, javascript: string, sourceMap: string }>>}\n */\nexport async function mountEliscriptScripts(\n root = globalThis.document,\n options = {},\n) {\n if (!root || typeof root.querySelectorAll !== \"function\") return [];\n const fetchImpl = options.fetch ?? globalThis.fetch;\n const scripts = Array.from(root.querySelectorAll('script[type=\"text/eliscript\"]'));\n const mounted = [];\n for (let index = 0; index < scripts.length; index += 1) {\n const script = scripts[index];\n if (script.dataset?.eliscriptMounted === \"true\") continue;\n if (script.dataset) script.dataset.eliscriptMounted = \"true\";\n const filename = scriptFilename(script, index);\n let source = script.textContent ?? \"\";\n if (typeof script.src === \"string\" && script.src.length > 0) {\n const response = await fetchImpl(script.src);\n if (!response.ok) {\n throw failure(\n \"ELI-BROWSER-0005\",\n `failed to fetch ${script.src}: ${response.status}`,\n filename,\n );\n }\n source = await response.text();\n }\n const executed = await runSource(source, filename, options);\n mounted.push({\n script,\n filename,\n ...executed,\n });\n }\n return mounted;\n}\n\nexport const browserHostSurface = Object.freeze({\n sourceExtension: SOURCE_EXTENSION,\n outputExtension: OUTPUT_EXTENSION,\n});\n"))
|