@oseo/host 0.0.0-stage → 0.1.0-canary.370

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 CHANGED
@@ -1,3 +1,77 @@
1
- # Temporary Holding Version
1
+ @oseo/host
2
+ ==========
2
3
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
4
+ `@oseo/host` supplies the [Oseo compiler] with filesystem, temporary-directory,
5
+ and subprocess operations on Node.js and Deno. Use `createNodeHost()` on
6
+ Node.js or `createDenoHost()` on Deno. If you use only the Oseo CLI, you do
7
+ not need to install this adapter separately.
8
+
9
+ Install with `npm install @oseo/host` or `deno add jsr:@oseo/host`, then
10
+ import from `@oseo/host`.
11
+
12
+ [Oseo compiler]: https://github.com/dahlia/oseo/tree/main/packages/compiler
13
+
14
+
15
+ Load a module graph
16
+ -------------------
17
+
18
+ Pair `createFileModuleLoader()` with `fileModuleResolver` to load a file
19
+ entry point and follow relative imports. The resolver does not use Node.js
20
+ or Deno package resolution. The loader classifies paths ending in `.json`
21
+ as JSON modules; the compiler checks their import attributes and contents.
22
+
23
+ Add `@oseo/compiler` and `@oseo/parser-babel` to your project to run this
24
+ example. Save it as *inspect.mjs* beside the *main.js* you want to load.
25
+ On Deno, use `createDenoHost()` and grant read access to the source files.
26
+
27
+ ~~~~ js
28
+ import { buildModuleGraph } from "@oseo/compiler";
29
+ import {
30
+ createFileModuleLoader,
31
+ createNodeHost,
32
+ fileModuleResolver,
33
+ } from "@oseo/host";
34
+ import { babelModuleFrontend } from "@oseo/parser-babel";
35
+
36
+ const host = createNodeHost();
37
+ const { diagnostics, graph } = await buildModuleGraph(
38
+ babelModuleFrontend,
39
+ createFileModuleLoader(host),
40
+ fileModuleResolver,
41
+ new URL("./main.js", import.meta.url).href,
42
+ );
43
+
44
+ if (graph === undefined) {
45
+ throw new Error(JSON.stringify(diagnostics));
46
+ }
47
+ console.log(`Loaded ${graph.modules.length} modules`);
48
+ ~~~~
49
+
50
+
51
+ Native builds
52
+ -------------
53
+
54
+ The adapters report normalized operating-system and architecture names
55
+ so callers can check whether a native target can run on the current host.
56
+ The optional persistent cache uses `XDG_CACHE_HOME` or *~/.cache* on Linux
57
+ and *~/Library/Caches* on macOS. Oseo does not prune cached archives. If you
58
+ remove them, the next native build recreates the archives it needs.
59
+
60
+ On Node.js, use `createNodeHost({ delegateSpawns: true })` to run subprocesses
61
+ through a reusable helper. Call `await host.close()` to drain accepted
62
+ requests and shut down the helper.
63
+
64
+
65
+ Publish an executable
66
+ ---------------------
67
+
68
+ To retain a linked executable, use `createExecutablePublisher()` on either
69
+ host. Call `inspect(destination, protectedPaths)` before building, with the
70
+ entry source and graph sources in `protectedPaths`. Pass the returned
71
+ destination record to `publish(linkedPath, inspectedDestination)` after a
72
+ successful link. Publication stages the file beside its destination so
73
+ readers do not see partial bytes; it does not guarantee crash durability.
74
+ See the [publication contract] and the [host implementation notes].
75
+
76
+ [publication contract]: https://github.com/dahlia/oseo/blob/main/docs/adr/0037-retained-native-executables.md
77
+ [host implementation notes]: https://github.com/dahlia/oseo/blob/main/docs/development/package-host.md
@@ -0,0 +1,35 @@
1
+ //#region src/cache-files.d.ts
2
+ interface DenoExistingTextFileWriter {
3
+ writeTextFile(path: string, contents: string, options: {
4
+ readonly create: false;
5
+ }): Promise<void>;
6
+ }
7
+ interface CacheLockDirectoryRenameOptions {
8
+ readonly deadlineMilliseconds: number;
9
+ readonly retryPermissionErrors: boolean;
10
+ }
11
+ /**
12
+ * Rename a claimed cache-lock directory across host sharing semantics.
13
+ *
14
+ * Windows can reject a directory rename while another waiter briefly
15
+ * enumerates it. The claimed state file remains the ownership fence while
16
+ * retrying, so no other caller can publish through the same lease.
17
+ */
18
+ declare function renameClaimedCacheLockDirectory(rename: (fromPath: string, toPath: string) => Promise<void>, fromPath: string, toPath: string, options: CacheLockDirectoryRenameOptions): Promise<void>;
19
+ /**
20
+ * Overwrite an existing Node.js cache state file without recreating it.
21
+ *
22
+ * A missing path means that another process replaced the cache lock directory,
23
+ * so recreating the state file would let a stale owner join the replacement.
24
+ */
25
+ declare function overwriteExistingNodeTextFile(path: string, contents: string): Promise<void>;
26
+ /**
27
+ * Overwrite an existing Deno cache state file without recreating it.
28
+ *
29
+ * This mirrors the Node.js claim rule while keeping Deno filesystem behavior
30
+ * behind the host adapter's narrow runtime interface.
31
+ */
32
+ declare function overwriteExistingDenoTextFile(runtime: DenoExistingTextFileWriter, path: string, contents: string): Promise<void>;
33
+ //#endregion
34
+ export { overwriteExistingDenoTextFile, overwriteExistingNodeTextFile, renameClaimedCacheLockDirectory };
35
+ //# sourceMappingURL=cache-files.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-files.d.ts","names":[],"sources":["../src/cache-files.ts"],"mappings":";UAkBU;EACR,cACE,cACA,kBACA;aAAoB;MACnB;;UAmBK;WACC;WACA;;;;;;;;;iBAUW,gCACpB,SAAS,kBAAkB,mBAAmB,eAC9C,kBACA,gBACA,SAAS,kCACR;;;;;;;iBA8BmB,8BACpB,cACA,mBACC;;;;;;;iBAiBmB,8BACpB,SAAS,4BACT,cACA,mBACC"}
@@ -0,0 +1,50 @@
1
+ //#region src/cache-files.ts
2
+ const cacheLockRenameRetryMilliseconds = 5;
3
+ function isTransientDirectoryRenameError(cause, retryPermissionErrors) {
4
+ return cause instanceof Error && "code" in cause && (retryPermissionErrors && (cause.code === "EACCES" || cause.code === "EPERM") || cause.code === "EBUSY" || cause.code === "ENOTEMPTY");
5
+ }
6
+ /**
7
+ * Rename a claimed cache-lock directory across host sharing semantics.
8
+ *
9
+ * Windows can reject a directory rename while another waiter briefly
10
+ * enumerates it. The claimed state file remains the ownership fence while
11
+ * retrying, so no other caller can publish through the same lease.
12
+ */
13
+ async function renameClaimedCacheLockDirectory(rename, fromPath, toPath, options) {
14
+ while (true) try {
15
+ await rename(fromPath, toPath);
16
+ return;
17
+ } catch (error) {
18
+ if (!isTransientDirectoryRenameError(error, options.retryPermissionErrors) || Date.now() >= options.deadlineMilliseconds) throw error;
19
+ await new Promise((resolve) => setTimeout(resolve, cacheLockRenameRetryMilliseconds));
20
+ }
21
+ }
22
+ /**
23
+ * Overwrite an existing Node.js cache state file without recreating it.
24
+ *
25
+ * A missing path means that another process replaced the cache lock directory,
26
+ * so recreating the state file would let a stale owner join the replacement.
27
+ */
28
+ async function overwriteExistingNodeTextFile(path, contents) {
29
+ const { open } = await import("node:fs/promises");
30
+ const file = await open(path, "r+");
31
+ try {
32
+ await file.truncate(0);
33
+ await file.writeFile(contents);
34
+ } finally {
35
+ await file.close();
36
+ }
37
+ }
38
+ /**
39
+ * Overwrite an existing Deno cache state file without recreating it.
40
+ *
41
+ * This mirrors the Node.js claim rule while keeping Deno filesystem behavior
42
+ * behind the host adapter's narrow runtime interface.
43
+ */
44
+ async function overwriteExistingDenoTextFile(runtime, path, contents) {
45
+ await runtime.writeTextFile(path, contents, { create: false });
46
+ }
47
+
48
+ //#endregion
49
+ export { overwriteExistingDenoTextFile, overwriteExistingNodeTextFile, renameClaimedCacheLockDirectory };
50
+ //# sourceMappingURL=cache-files.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-files.js","names":[],"sources":["../src/cache-files.ts"],"sourcesContent":["/*\n * Oseo, an ahead-of-time compiler for JavaScript and TypeScript.\n * Copyright (C) 2026 Hong Minhee <https://hongminhee.org/>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n */\n\ninterface DenoExistingTextFileWriter {\n writeTextFile(\n path: string,\n contents: string,\n options: { readonly create: false },\n ): Promise<void>;\n}\n\nconst cacheLockRenameRetryMilliseconds = 5;\n\nfunction isTransientDirectoryRenameError(\n cause: unknown,\n retryPermissionErrors: boolean,\n): boolean {\n return (\n cause instanceof Error &&\n \"code\" in cause &&\n ((retryPermissionErrors &&\n (cause.code === \"EACCES\" || cause.code === \"EPERM\")) ||\n cause.code === \"EBUSY\" ||\n cause.code === \"ENOTEMPTY\")\n );\n}\n\ninterface CacheLockDirectoryRenameOptions {\n readonly deadlineMilliseconds: number;\n readonly retryPermissionErrors: boolean;\n}\n\n/**\n * Rename a claimed cache-lock directory across host sharing semantics.\n *\n * Windows can reject a directory rename while another waiter briefly\n * enumerates it. The claimed state file remains the ownership fence while\n * retrying, so no other caller can publish through the same lease.\n */\nexport async function renameClaimedCacheLockDirectory(\n rename: (fromPath: string, toPath: string) => Promise<void>,\n fromPath: string,\n toPath: string,\n options: CacheLockDirectoryRenameOptions,\n): Promise<void> {\n /* eslint-disable no-await-in-loop -- Rename attempts retain one claim. */\n while (true) {\n try {\n await rename(fromPath, toPath);\n return;\n } catch (error) {\n if (\n !isTransientDirectoryRenameError(\n error,\n options.retryPermissionErrors,\n ) ||\n Date.now() >= options.deadlineMilliseconds\n ) {\n throw error;\n }\n await new Promise((resolve) =>\n setTimeout(resolve, cacheLockRenameRetryMilliseconds),\n );\n }\n }\n /* eslint-enable no-await-in-loop */\n}\n\n/**\n * Overwrite an existing Node.js cache state file without recreating it.\n *\n * A missing path means that another process replaced the cache lock directory,\n * so recreating the state file would let a stale owner join the replacement.\n */\nexport async function overwriteExistingNodeTextFile(\n path: string,\n contents: string,\n): Promise<void> {\n const { open } = await import(\"node:fs/promises\");\n const file = await open(path, \"r+\");\n try {\n await file.truncate(0);\n await file.writeFile(contents);\n } finally {\n await file.close();\n }\n}\n\n/**\n * Overwrite an existing Deno cache state file without recreating it.\n *\n * This mirrors the Node.js claim rule while keeping Deno filesystem behavior\n * behind the host adapter's narrow runtime interface.\n */\nexport async function overwriteExistingDenoTextFile(\n runtime: DenoExistingTextFileWriter,\n path: string,\n contents: string,\n): Promise<void> {\n await runtime.writeTextFile(path, contents, { create: false });\n}\n"],"mappings":";AA0BA,MAAM,mCAAmC;AAEzC,SAAS,gCACP,OACA,uBACS;CACT,OACE,iBAAiB,SACjB,UAAU,UACR,0BACC,MAAM,SAAS,YAAY,MAAM,SAAS,YAC3C,MAAM,SAAS,WACf,MAAM,SAAS;AAErB;;;;;;;;AAcA,eAAsB,gCACpB,QACA,UACA,QACA,SACe;CAEf,OAAO,MACL,IAAI;EACF,MAAM,OAAO,UAAU,MAAM;EAC7B;CACF,SAAS,OAAO;EACd,IACE,CAAC,gCACC,OACA,QAAQ,qBACV,KACA,KAAK,IAAI,KAAK,QAAQ,sBAEtB,MAAM;EAER,MAAM,IAAI,SAAS,YACjB,WAAW,SAAS,gCAAgC,CACtD;CACF;AAGJ;;;;;;;AAQA,eAAsB,8BACpB,MACA,UACe;CACf,MAAM,EAAE,SAAS,MAAM,OAAO;CAC9B,MAAM,OAAO,MAAM,KAAK,MAAM,IAAI;CAClC,IAAI;EACF,MAAM,KAAK,SAAS,CAAC;EACrB,MAAM,KAAK,UAAU,QAAQ;CAC/B,UAAU;EACR,MAAM,KAAK,MAAM;CACnB;AACF;;;;;;;AAQA,eAAsB,8BACpB,SACA,MACA,UACe;CACf,MAAM,QAAQ,cAAc,MAAM,UAAU,EAAE,QAAQ,MAAM,CAAC;AAC/D"}
@@ -0,0 +1,35 @@
1
+ import { chmod, copyFile, link, rename, unlink } from "node:fs/promises";
2
+ //#region src/executable-publication.d.ts
3
+ /** Identity retained between destination inspection and publication. */
4
+ interface ExecutableDestination {
5
+ readonly path: string;
6
+ readonly protectedPaths: readonly string[];
7
+ readonly existing?: {
8
+ readonly device: bigint;
9
+ readonly inode: bigint;
10
+ };
11
+ }
12
+ /** Filesystem publication boundary shared by both compiler hosts. */
13
+ interface ExecutablePublisher {
14
+ /** Validate the parent, replacement kind, and source graph before linking. */
15
+ inspect(destination: string, protectedPaths: readonly string[]): Promise<ExecutableDestination>;
16
+ /** Publish unchanged linker bytes under ADR 0037's replacement rules. */
17
+ publish(linkedPath: string, destination: ExecutableDestination): Promise<void>;
18
+ }
19
+ /**
20
+ * Create ADR 0037 publication operations using Node.js-compatible filesystem
21
+ * APIs, supported unchanged by Node.js and Deno. CompilerHost stays narrow.
22
+ */
23
+ declare function createExecutablePublisher(): ExecutablePublisher;
24
+ interface PublicationFiles {
25
+ readonly chmod: typeof chmod;
26
+ readonly copyFile: typeof copyFile;
27
+ readonly link: typeof link;
28
+ readonly rename: typeof rename;
29
+ readonly unlink: typeof unlink;
30
+ }
31
+ /** Internal fault-injection boundary for publication failure tests. */
32
+ declare function createPublicationWithFiles(overrides?: Partial<PublicationFiles>): ExecutablePublisher;
33
+ //#endregion
34
+ export { ExecutableDestination, ExecutablePublisher, createExecutablePublisher, createPublicationWithFiles };
35
+ //# sourceMappingURL=executable-publication.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executable-publication.d.ts","names":[],"sources":["../src/executable-publication.ts"],"mappings":";;;UAkCiB;WACN;WACA;WACA;aACE;aACA;;;;UAKI;;EAEf,QACE,qBACA,oCACC,QAAQ;;EAEX,QACE,oBACA,aAAa,wBACZ;;;;;;iBA4GW,6BAA6B;UAInC;WACC,cAAc;WACd,iBAAiB;WACjB,aAAa;WACb,eAAe;WACf,eAAe;;;iBAIV,2BACd,YAAW,QAAQ,oBAClB"}
@@ -0,0 +1,133 @@
1
+ import { chmod, copyFile, link, lstat, open, realpath, rename, stat, unlink } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { basename, dirname, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ //#region src/executable-publication.ts
7
+ function errorCode(error) {
8
+ if (!("code" in error)) return void 0;
9
+ const code = error.code;
10
+ return code === "ENOENT" || code === "EPERM" || code === "ENOTSUP" ? code : void 0;
11
+ }
12
+ function filesystemPath(path) {
13
+ return /^file:/iu.test(path) ? fileURLToPath(path) : path;
14
+ }
15
+ function refusal(path, reason) {
16
+ return /* @__PURE__ */ new Error(`Cannot publish '${path}': ${reason}; choose --output.`);
17
+ }
18
+ async function inspectDestination(destination, protectedPaths) {
19
+ const path = resolve(destination);
20
+ if (!(await stat(dirname(path))).isDirectory()) throw refusal(path, "the parent is not a directory");
21
+ let existing;
22
+ try {
23
+ existing = await lstat(path, { bigint: true });
24
+ } catch (error) {
25
+ if (!(error instanceof Error) || errorCode(error) !== "ENOENT") throw error;
26
+ }
27
+ if (existing == null) return {
28
+ path,
29
+ protectedPaths
30
+ };
31
+ if (!existing.isFile()) throw refusal(path, "the destination is not a regular file");
32
+ const canonicalPath = await realpath(path);
33
+ for (const protectedPath of protectedPaths) {
34
+ let canonicalProtectedPath;
35
+ try {
36
+ canonicalProtectedPath = await realpath(filesystemPath(protectedPath));
37
+ } catch (error) {
38
+ if (!(error instanceof Error) || errorCode(error) !== "ENOENT") throw error;
39
+ canonicalProtectedPath = resolve(filesystemPath(protectedPath));
40
+ }
41
+ if (canonicalPath === canonicalProtectedPath) throw refusal(path, "the destination is a source in the build graph");
42
+ }
43
+ const file = await open(path, "r");
44
+ const bytes = /* @__PURE__ */ new Uint8Array(4);
45
+ try {
46
+ await file.read(bytes, 0, 4, 0);
47
+ } finally {
48
+ await file.close();
49
+ }
50
+ const magic = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
51
+ if (![
52
+ "7f454c46",
53
+ "feedface",
54
+ "cefaedfe",
55
+ "feedfacf",
56
+ "cffaedfe",
57
+ "cafebabe",
58
+ "bebafeca",
59
+ "cafebabf",
60
+ "bfbafeca"
61
+ ].includes(magic)) throw refusal(path, "the destination is not an ELF or Mach-O file");
62
+ return {
63
+ existing: {
64
+ device: existing.dev,
65
+ inode: existing.ino
66
+ },
67
+ path,
68
+ protectedPaths
69
+ };
70
+ }
71
+ async function requireUnchangedDestination(destination) {
72
+ const current = await inspectDestination(destination.path, destination.protectedPaths);
73
+ if (current.existing?.device !== destination.existing?.device || current.existing?.inode !== destination.existing?.inode) throw refusal(destination.path, "the destination changed during the build");
74
+ }
75
+ /**
76
+ * Create ADR 0037 publication operations using Node.js-compatible filesystem
77
+ * APIs, supported unchanged by Node.js and Deno. CompilerHost stays narrow.
78
+ */
79
+ function createExecutablePublisher() {
80
+ return createPublicationWithFiles();
81
+ }
82
+ /** Internal fault-injection boundary for publication failure tests. */
83
+ function createPublicationWithFiles(overrides = {}) {
84
+ const files = {
85
+ chmod,
86
+ copyFile,
87
+ link,
88
+ rename,
89
+ unlink,
90
+ ...overrides
91
+ };
92
+ return {
93
+ inspect: inspectDestination,
94
+ async publish(linkedPath, destination) {
95
+ const temporaryPath = resolve(dirname(destination.path), `.${basename(destination.path)}.oseo-${randomUUID()}.tmp`);
96
+ let copied = false;
97
+ let failure;
98
+ try {
99
+ const reserved = await open(temporaryPath, "wx");
100
+ copied = true;
101
+ await reserved.close();
102
+ await files.copyFile(linkedPath, temporaryPath);
103
+ await files.chmod(temporaryPath, (await stat(linkedPath)).mode & 4095);
104
+ await requireUnchangedDestination(destination);
105
+ if (destination.existing != null) {
106
+ await files.rename(temporaryPath, destination.path);
107
+ copied = false;
108
+ } else try {
109
+ await files.link(temporaryPath, destination.path);
110
+ } catch (error) {
111
+ const code = error instanceof Error ? errorCode(error) : void 0;
112
+ if (code !== "EPERM" && code !== "ENOTSUP") throw error;
113
+ await requireUnchangedDestination(destination);
114
+ await files.rename(temporaryPath, destination.path);
115
+ copied = false;
116
+ }
117
+ } catch (error) {
118
+ failure = error;
119
+ }
120
+ if (copied) try {
121
+ await files.unlink(temporaryPath);
122
+ } catch (error) {
123
+ if (failure != null) throw new AggregateError([failure, error], `${String(failure)}; temporary file cleanup failed: ${error}`, { cause: error });
124
+ throw error;
125
+ }
126
+ if (failure != null) throw failure;
127
+ }
128
+ };
129
+ }
130
+
131
+ //#endregion
132
+ export { createExecutablePublisher, createPublicationWithFiles };
133
+ //# sourceMappingURL=executable-publication.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executable-publication.js","names":[],"sources":["../src/executable-publication.ts"],"sourcesContent":["/*\n * Oseo, an ahead-of-time compiler for JavaScript and TypeScript.\n * Copyright (C) 2026 Hong Minhee <https://hongminhee.org/>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n */\n\nimport {\n chmod,\n copyFile,\n link,\n lstat,\n open,\n realpath,\n rename,\n stat,\n unlink,\n} from \"node:fs/promises\";\nimport { randomUUID } from \"node:crypto\";\nimport { basename, dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/** Identity retained between destination inspection and publication. */\nexport interface ExecutableDestination {\n readonly path: string;\n readonly protectedPaths: readonly string[];\n readonly existing?: {\n readonly device: bigint;\n readonly inode: bigint;\n };\n}\n\n/** Filesystem publication boundary shared by both compiler hosts. */\nexport interface ExecutablePublisher {\n /** Validate the parent, replacement kind, and source graph before linking. */\n inspect(\n destination: string,\n protectedPaths: readonly string[],\n ): Promise<ExecutableDestination>;\n /** Publish unchanged linker bytes under ADR 0037's replacement rules. */\n publish(\n linkedPath: string,\n destination: ExecutableDestination,\n ): Promise<void>;\n}\n\ntype PublicationErrorCode = \"ENOENT\" | \"EPERM\" | \"ENOTSUP\";\n\nfunction errorCode(error: Error): PublicationErrorCode | undefined {\n if (!(\"code\" in error)) return undefined;\n const code = error.code;\n return code === \"ENOENT\" || code === \"EPERM\" || code === \"ENOTSUP\"\n ? code\n : undefined;\n}\n\nfunction filesystemPath(path: string): string {\n return /^file:/iu.test(path) ? fileURLToPath(path) : path;\n}\n\nfunction refusal(path: string, reason: string): Error {\n return new Error(`Cannot publish '${path}': ${reason}; choose --output.`);\n}\n\nasync function inspectDestination(\n destination: string,\n protectedPaths: readonly string[],\n): Promise<ExecutableDestination> {\n const path = resolve(destination);\n if (!(await stat(dirname(path))).isDirectory()) {\n throw refusal(path, \"the parent is not a directory\");\n }\n let existing;\n try {\n existing = await lstat(path, { bigint: true });\n } catch (error) {\n if (!(error instanceof Error) || errorCode(error) !== \"ENOENT\") {\n throw error;\n }\n }\n if (existing == null) return { path, protectedPaths };\n if (!existing.isFile()) {\n throw refusal(path, \"the destination is not a regular file\");\n }\n const canonicalPath = await realpath(path);\n for (const protectedPath of protectedPaths) {\n let canonicalProtectedPath: string;\n try {\n // eslint-disable-next-line no-await-in-loop -- Ordered graph validation.\n canonicalProtectedPath = await realpath(filesystemPath(protectedPath));\n } catch (error) {\n if (!(error instanceof Error) || errorCode(error) !== \"ENOENT\") {\n throw error;\n }\n canonicalProtectedPath = resolve(filesystemPath(protectedPath));\n }\n if (canonicalPath === canonicalProtectedPath) {\n throw refusal(path, \"the destination is a source in the build graph\");\n }\n }\n const file = await open(path, \"r\");\n const bytes = new Uint8Array(4);\n try {\n await file.read(bytes, 0, 4, 0);\n } finally {\n await file.close();\n }\n const magic = Array.from(bytes, (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n if (\n ![\n \"7f454c46\", // ELF\n \"feedface\",\n \"cefaedfe\",\n \"feedfacf\",\n \"cffaedfe\", // Mach-O\n \"cafebabe\",\n \"bebafeca\",\n \"cafebabf\",\n \"bfbafeca\", // Universal Mach-O\n ].includes(magic)\n ) {\n throw refusal(path, \"the destination is not an ELF or Mach-O file\");\n }\n return {\n existing: { device: existing.dev, inode: existing.ino },\n path,\n protectedPaths,\n };\n}\n\nasync function requireUnchangedDestination(\n destination: ExecutableDestination,\n): Promise<void> {\n const current = await inspectDestination(\n destination.path,\n destination.protectedPaths,\n );\n if (\n current.existing?.device !== destination.existing?.device ||\n current.existing?.inode !== destination.existing?.inode\n ) {\n throw refusal(destination.path, \"the destination changed during the build\");\n }\n}\n\n/**\n * Create ADR 0037 publication operations using Node.js-compatible filesystem\n * APIs, supported unchanged by Node.js and Deno. CompilerHost stays narrow.\n */\nexport function createExecutablePublisher(): ExecutablePublisher {\n return createPublicationWithFiles();\n}\n\ninterface PublicationFiles {\n readonly chmod: typeof chmod;\n readonly copyFile: typeof copyFile;\n readonly link: typeof link;\n readonly rename: typeof rename;\n readonly unlink: typeof unlink;\n}\n\n/** Internal fault-injection boundary for publication failure tests. */\nexport function createPublicationWithFiles(\n overrides: Partial<PublicationFiles> = {},\n): ExecutablePublisher {\n const files = { chmod, copyFile, link, rename, unlink, ...overrides };\n return {\n inspect: inspectDestination,\n async publish(linkedPath, destination) {\n const temporaryPath = resolve(\n dirname(destination.path),\n `.${basename(destination.path)}.oseo-${randomUUID()}.tmp`,\n );\n let copied = false;\n let failure: unknown;\n try {\n const reserved = await open(temporaryPath, \"wx\");\n copied = true;\n await reserved.close();\n await files.copyFile(linkedPath, temporaryPath);\n await files.chmod(\n temporaryPath,\n (await stat(linkedPath)).mode & 0o7777,\n );\n await requireUnchangedDestination(destination);\n if (destination.existing != null) {\n await files.rename(temporaryPath, destination.path);\n copied = false;\n } else {\n try {\n await files.link(temporaryPath, destination.path);\n } catch (error) {\n const code = error instanceof Error ? errorCode(error) : undefined;\n if (code !== \"EPERM\" && code !== \"ENOTSUP\") throw error;\n await requireUnchangedDestination(destination);\n await files.rename(temporaryPath, destination.path);\n copied = false;\n }\n }\n } catch (error) {\n failure = error;\n }\n if (copied) {\n try {\n await files.unlink(temporaryPath);\n } catch (error) {\n if (failure != null) {\n throw new AggregateError(\n [failure, error],\n `${String(failure)}; temporary file cleanup failed: ${error}`,\n { cause: error },\n );\n }\n throw error;\n }\n }\n if (failure != null) throw failure;\n },\n };\n}\n"],"mappings":";;;;;;AA2DA,SAAS,UAAU,OAAgD;CACjE,IAAI,EAAE,UAAU,QAAQ,OAAO;CAC/B,MAAM,OAAO,MAAM;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,MAAM,OAAO,iBAAiB,QAAQ,UAAU,KAAK,IAAI;KACzD,IAAI,SAAS,WAAW,SAAS,WAAW,MAAM;KAClD,MAAM,4BAA4B,WAAW;KAC7C,MAAM,MAAM,OAAO,eAAe,YAAY,IAAI;KAClD,SAAS;IACX;GAEJ,SAAS,OAAO;IACd,UAAU;GACZ;GACA,IAAI,QACF,IAAI;IACF,MAAM,MAAM,OAAO,aAAa;GAClC,SAAS,OAAO;IACd,IAAI,WAAW,MACb,MAAM,IAAI,eACR,CAAC,SAAS,KAAK,GACf,GAAG,OAAO,OAAO,EAAE,mCAAmC,SACtD,EAAE,OAAO,MAAM,CACjB;IAEF,MAAM;GACR;GAEF,IAAI,WAAW,MAAM,MAAM;EAC7B;CACF;AACF"}
@@ -0,0 +1,30 @@
1
+ import { ExecutableDestination, ExecutablePublisher, createExecutablePublisher } from "./executable-publication.js";
2
+ import { CompilerHost, ExecutionHostDescription, ModuleLoader, ModuleResolver } from "@oseo/compiler";
3
+ //#region src/index.d.ts
4
+ /** Normalize Node.js or Deno platform facts at the concrete host boundary. */
5
+ declare function normalizeExecutionHost(reportedOperatingSystem: string, reportedArchitecture: string): ExecutionHostDescription;
6
+ /** Normalize one file URL to the canonical module identity spelling. */
7
+ declare function canonicalizeFileModuleUrl(url: URL): string;
8
+ /** Produce the stable content identity recorded in a module graph. */
9
+ declare function hashModuleSource(source: string): string;
10
+ /** Load canonical file URLs through one explicit compiler host. */
11
+ declare function createFileModuleLoader(host: CompilerHost, runtimeAbiVersion?: string): ModuleLoader;
12
+ /** Resolve the relative file specifiers frozen by the M4 profile. */
13
+ declare const fileModuleResolver: ModuleResolver;
14
+ /** Optional execution services for long-running Node.js compiler hosts. */
15
+ interface NodeHostOptions {
16
+ /** Spawn through a small reusable process instead of the compiler heap. */
17
+ readonly delegateSpawns?: boolean;
18
+ }
19
+ /** A Node host can explicitly drain and close its optional spawn service. */
20
+ interface NodeHost extends CompilerHost {
21
+ /** Stop accepting delegated work, drain pending requests, and close IPC. */
22
+ close(): Promise<void>;
23
+ }
24
+ /** Create the Node.js implementation of compiler host operations. */
25
+ declare function createNodeHost(options?: NodeHostOptions): NodeHost;
26
+ /** Create the Deno implementation of compiler host operations. */
27
+ declare function createDenoHost(): CompilerHost;
28
+ //#endregion
29
+ export { type ExecutableDestination, type ExecutablePublisher, NodeHost, NodeHostOptions, canonicalizeFileModuleUrl, createDenoHost, createExecutablePublisher, createFileModuleLoader, createNodeHost, fileModuleResolver, hashModuleSource, normalizeExecutionHost };
30
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;iBAyDgB,uBACd,iCACA,+BACC;;iBAy2Ba,0BAA0B,KAAK;;iBAY/B,iBAAiB;;iBAUjB,uBACd,MAAM,cACN,6BACC;;cAoFU,oBAAoB;;UAsDhB;;WAEN;;;UAIM,iBAAiB;;EAEhC,SAAS;;;iBAIK,eAAe,UAAS,kBAAuB;;iBAkI/C,kBAAkB"}