@dual-os/cli 0.0.0-stage → 0.11.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +15 -2
  3. package/dist/_virtual/_rolldown/runtime.js +13 -0
  4. package/dist/auth/credentials.d.ts +17 -0
  5. package/dist/auth/credentials.d.ts.map +1 -0
  6. package/dist/auth/credentials.js +57 -0
  7. package/dist/auth/credentials.js.map +1 -0
  8. package/dist/auth/destination.d.ts +22 -0
  9. package/dist/auth/destination.d.ts.map +1 -0
  10. package/dist/auth/destination.js +49 -0
  11. package/dist/auth/destination.js.map +1 -0
  12. package/dist/auth/http.d.ts +12 -0
  13. package/dist/auth/http.d.ts.map +1 -0
  14. package/dist/auth/http.js +34 -0
  15. package/dist/auth/http.js.map +1 -0
  16. package/dist/auth/login.d.ts +22 -0
  17. package/dist/auth/login.d.ts.map +1 -0
  18. package/dist/auth/login.js +98 -0
  19. package/dist/auth/login.js.map +1 -0
  20. package/dist/auth/protocol.d.ts +26 -0
  21. package/dist/auth/protocol.d.ts.map +1 -0
  22. package/dist/auth/protocol.js +31 -0
  23. package/dist/auth/protocol.js.map +1 -0
  24. package/dist/baseline.d.ts +18 -0
  25. package/dist/baseline.d.ts.map +1 -0
  26. package/dist/baseline.js +22 -0
  27. package/dist/baseline.js.map +1 -0
  28. package/dist/bin.d.ts +1 -0
  29. package/dist/bin.js +7 -0
  30. package/dist/bin.js.map +1 -0
  31. package/dist/cli.d.ts +19 -0
  32. package/dist/cli.d.ts.map +1 -0
  33. package/dist/cli.js +492 -0
  34. package/dist/cli.js.map +1 -0
  35. package/dist/create/choices.d.ts +58 -0
  36. package/dist/create/choices.d.ts.map +1 -0
  37. package/dist/create/choices.js +121 -0
  38. package/dist/create/choices.js.map +1 -0
  39. package/dist/create/deployment.d.ts +48 -0
  40. package/dist/create/deployment.d.ts.map +1 -0
  41. package/dist/create/deployment.js +66 -0
  42. package/dist/create/deployment.js.map +1 -0
  43. package/dist/create/scaffold.d.ts +57 -0
  44. package/dist/create/scaffold.d.ts.map +1 -0
  45. package/dist/create/scaffold.js +198 -0
  46. package/dist/create/scaffold.js.map +1 -0
  47. package/dist/create/source-reference.d.ts +39 -0
  48. package/dist/create/source-reference.d.ts.map +1 -0
  49. package/dist/create/source-reference.js +185 -0
  50. package/dist/create/source-reference.js.map +1 -0
  51. package/dist/create/template.d.ts +116 -0
  52. package/dist/create/template.d.ts.map +1 -0
  53. package/dist/create/template.js +211 -0
  54. package/dist/create/template.js.map +1 -0
  55. package/dist/diagnostics.d.ts +6 -0
  56. package/dist/diagnostics.d.ts.map +1 -0
  57. package/dist/diagnostics.js +18 -0
  58. package/dist/diagnostics.js.map +1 -0
  59. package/dist/help.d.ts +16 -0
  60. package/dist/help.d.ts.map +1 -0
  61. package/dist/help.js +73 -0
  62. package/dist/help.js.map +1 -0
  63. package/dist/openapi/bundle.d.ts +18 -0
  64. package/dist/openapi/bundle.d.ts.map +1 -0
  65. package/dist/openapi/bundle.js +201 -0
  66. package/dist/openapi/bundle.js.map +1 -0
  67. package/dist/openapi/discovery.d.ts +30 -0
  68. package/dist/openapi/discovery.d.ts.map +1 -0
  69. package/dist/openapi/discovery.js +325 -0
  70. package/dist/openapi/discovery.js.map +1 -0
  71. package/dist/openapi/emit.d.ts +52 -0
  72. package/dist/openapi/emit.d.ts.map +1 -0
  73. package/dist/openapi/emit.js +596 -0
  74. package/dist/openapi/emit.js.map +1 -0
  75. package/dist/openapi/graphql.d.ts +102 -0
  76. package/dist/openapi/graphql.d.ts.map +1 -0
  77. package/dist/openapi/graphql.js +294 -0
  78. package/dist/openapi/graphql.js.map +1 -0
  79. package/dist/openapi/identity.d.ts +88 -0
  80. package/dist/openapi/identity.d.ts.map +1 -0
  81. package/dist/openapi/identity.js +98 -0
  82. package/dist/openapi/identity.js.map +1 -0
  83. package/dist/openapi/mcp.d.ts +21 -0
  84. package/dist/openapi/mcp.d.ts.map +1 -0
  85. package/dist/openapi/mcp.js +133 -0
  86. package/dist/openapi/mcp.js.map +1 -0
  87. package/dist/openapi/operations.d.ts +165 -0
  88. package/dist/openapi/operations.d.ts.map +1 -0
  89. package/dist/openapi/operations.js +361 -0
  90. package/dist/openapi/operations.js.map +1 -0
  91. package/dist/openapi/overlay.d.ts +23 -0
  92. package/dist/openapi/overlay.d.ts.map +1 -0
  93. package/dist/openapi/overlay.js +115 -0
  94. package/dist/openapi/overlay.js.map +1 -0
  95. package/dist/openapi/plugin.d.ts +83 -0
  96. package/dist/openapi/plugin.d.ts.map +1 -0
  97. package/dist/openapi/plugin.js +468 -0
  98. package/dist/openapi/plugin.js.map +1 -0
  99. package/dist/openapi/polymorphism.d.ts +21 -0
  100. package/dist/openapi/polymorphism.d.ts.map +1 -0
  101. package/dist/openapi/polymorphism.js +96 -0
  102. package/dist/openapi/polymorphism.js.map +1 -0
  103. package/dist/openapi/postman.d.ts +21 -0
  104. package/dist/openapi/postman.d.ts.map +1 -0
  105. package/dist/openapi/postman.js +286 -0
  106. package/dist/openapi/postman.js.map +1 -0
  107. package/dist/openapi/schema.d.ts +178 -0
  108. package/dist/openapi/schema.d.ts.map +1 -0
  109. package/dist/openapi/schema.js +1234 -0
  110. package/dist/openapi/schema.js.map +1 -0
  111. package/dist/openapi/select.d.ts +22 -0
  112. package/dist/openapi/select.d.ts.map +1 -0
  113. package/dist/openapi/select.js +79 -0
  114. package/dist/openapi/select.js.map +1 -0
  115. package/dist/openapi/spec.d.ts +147 -0
  116. package/dist/openapi/spec.d.ts.map +1 -0
  117. package/dist/openapi/spec.js +263 -0
  118. package/dist/openapi/spec.js.map +1 -0
  119. package/dist/openapi/swagger.d.ts +166 -0
  120. package/dist/openapi/swagger.d.ts.map +1 -0
  121. package/dist/openapi/swagger.js +298 -0
  122. package/dist/openapi/swagger.js.map +1 -0
  123. package/dist/openapi/versions.d.ts +52 -0
  124. package/dist/openapi/versions.d.ts.map +1 -0
  125. package/dist/openapi/versions.js +120 -0
  126. package/dist/openapi/versions.js.map +1 -0
  127. package/dist/plugin/archive.d.ts +27 -0
  128. package/dist/plugin/archive.d.ts.map +1 -0
  129. package/dist/plugin/archive.js +170 -0
  130. package/dist/plugin/archive.js.map +1 -0
  131. package/dist/plugin/bundle.d.ts +27 -0
  132. package/dist/plugin/bundle.d.ts.map +1 -0
  133. package/dist/plugin/bundle.js +328 -0
  134. package/dist/plugin/bundle.js.map +1 -0
  135. package/dist/plugin/init.d.ts +18 -0
  136. package/dist/plugin/init.d.ts.map +1 -0
  137. package/dist/plugin/init.js +121 -0
  138. package/dist/plugin/init.js.map +1 -0
  139. package/dist/plugin/inspection.d.ts +24 -0
  140. package/dist/plugin/inspection.d.ts.map +1 -0
  141. package/dist/plugin/inspection.js +24 -0
  142. package/dist/plugin/inspection.js.map +1 -0
  143. package/dist/plugin/package.d.ts +26 -0
  144. package/dist/plugin/package.d.ts.map +1 -0
  145. package/dist/plugin/package.js +73 -0
  146. package/dist/plugin/package.js.map +1 -0
  147. package/dist/plugin/publication.d.ts +29 -0
  148. package/dist/plugin/publication.d.ts.map +1 -0
  149. package/dist/plugin/publication.js +65 -0
  150. package/dist/plugin/publication.js.map +1 -0
  151. package/dist/plugin/validation.d.ts +15 -0
  152. package/dist/plugin/validation.d.ts.map +1 -0
  153. package/dist/plugin/validation.js +119 -0
  154. package/dist/plugin/validation.js.map +1 -0
  155. package/dist/release/archives.d.ts +33 -0
  156. package/dist/release/archives.d.ts.map +1 -0
  157. package/dist/release/archives.js +81 -0
  158. package/dist/release/archives.js.map +1 -0
  159. package/dist/release/release-manifest.d.ts +182 -0
  160. package/dist/release/release-manifest.d.ts.map +1 -0
  161. package/dist/release/release-manifest.js +79 -0
  162. package/dist/release/release-manifest.js.map +1 -0
  163. package/dist/release/releases.d.ts +36 -0
  164. package/dist/release/releases.d.ts.map +1 -0
  165. package/dist/release/releases.js +122 -0
  166. package/dist/release/releases.js.map +1 -0
  167. package/dist/skills.d.ts +35 -0
  168. package/dist/skills.d.ts.map +1 -0
  169. package/dist/skills.js +257 -0
  170. package/dist/skills.js.map +1 -0
  171. package/package.json +73 -4
  172. package/skills/dual-fde/SKILL.md +38 -0
  173. package/skills/dual-fde/references/access.md +62 -0
  174. package/skills/dual-fde/references/author-plugins.md +54 -0
  175. package/skills/dual-fde/references/cli.md +97 -0
  176. package/skills/dual-fde/references/manage-plugins.md +78 -0
  177. package/skills/dual-fde/references/migrations-deployment.md +84 -0
  178. package/skills/dual-fde/references/openapi-plugins.md +47 -0
  179. package/skills/dual-fde/references/sdk-docs.md +56 -0
  180. package/skills/dual-fde/references/upgrades.md +115 -0
  181. package/skills/dual-fde/references/working-context.md +69 -0
  182. package/src/auth/credentials.ts +84 -0
  183. package/src/auth/destination.ts +83 -0
  184. package/src/auth/http.ts +39 -0
  185. package/src/auth/login.ts +177 -0
  186. package/src/auth/protocol.ts +37 -0
  187. package/src/baseline.ts +15 -0
  188. package/src/bin.ts +4 -0
  189. package/src/cli.ts +969 -0
  190. package/src/create/choices.ts +177 -0
  191. package/src/create/deployment.ts +96 -0
  192. package/src/create/scaffold.ts +334 -0
  193. package/src/create/source-reference.ts +212 -0
  194. package/src/create/template.ts +300 -0
  195. package/src/diagnostics.ts +8 -0
  196. package/src/help.ts +142 -0
  197. package/src/openapi/bundle.ts +290 -0
  198. package/src/openapi/discovery.ts +438 -0
  199. package/src/openapi/emit.ts +1031 -0
  200. package/src/openapi/graphql.ts +375 -0
  201. package/src/openapi/identity.ts +153 -0
  202. package/src/openapi/mcp.ts +165 -0
  203. package/src/openapi/operations.ts +781 -0
  204. package/src/openapi/overlay.ts +195 -0
  205. package/src/openapi/plugin.ts +856 -0
  206. package/src/openapi/polymorphism.ts +207 -0
  207. package/src/openapi/postman.ts +403 -0
  208. package/src/openapi/schema.ts +2138 -0
  209. package/src/openapi/select.ts +113 -0
  210. package/src/openapi/spec.ts +401 -0
  211. package/src/openapi/swagger.ts +422 -0
  212. package/src/openapi/versions.ts +174 -0
  213. package/src/plugin/archive.ts +244 -0
  214. package/src/plugin/bundle.ts +572 -0
  215. package/src/plugin/init.ts +178 -0
  216. package/src/plugin/inspection.ts +19 -0
  217. package/src/plugin/package.ts +140 -0
  218. package/src/plugin/publication.ts +128 -0
  219. package/src/plugin/validation.ts +213 -0
  220. package/src/release/archives.ts +133 -0
  221. package/src/release/release-manifest.ts +79 -0
  222. package/src/release/releases.ts +210 -0
  223. package/src/skills.ts +434 -0
  224. package/templates/compose/.env.compose.example.hbs +3 -0
  225. package/templates/compose/.env.host.example.hbs +4 -0
  226. package/templates/compose/Dockerfile.hbs +12 -0
  227. package/templates/compose/OPERATIONS.md.hbs +159 -0
  228. package/templates/compose/_dockerignore +14 -0
  229. package/templates/compose/compose.external.yaml +7 -0
  230. package/templates/compose/compose.host-linux.yaml +5 -0
  231. package/templates/compose/compose.host.yaml.hbs +15 -0
  232. package/templates/compose/compose.yaml.hbs +85 -0
  233. package/templates/compose/release.env.hbs +2 -0
  234. package/templates/default/.env.example.hbs +79 -0
  235. package/templates/default/README.md.hbs +150 -0
  236. package/templates/default/_gitignore +11 -0
  237. package/templates/default/packages/customer-plugin/src/Customer.ts.hbs +17 -0
  238. package/templates/default/packages/customer-plugin/tsconfig.json +15 -0
  239. package/templates/default/packages/execution-layer/src/App.ts.hbs +7 -0
  240. package/templates/default/packages/execution-layer/src/Host.ts.hbs +31 -0
  241. package/templates/default/packages/execution-layer/src/Telemetry.ts.hbs +23 -0
  242. package/templates/default/packages/execution-layer/src/api.ts.hbs +21 -0
  243. package/templates/default/packages/execution-layer/src/bootstrap.ts +22 -0
  244. package/templates/default/packages/execution-layer/src/migrate.ts +11 -0
  245. package/templates/default/packages/execution-layer/src/registry-check.ts +29 -0
  246. package/templates/default/packages/execution-layer/src/registry-sync.ts +14 -0
  247. package/templates/default/packages/execution-layer/src/worker.ts.hbs +16 -0
  248. package/templates/default/packages/execution-layer/test/app.host-test.ts.hbs +58 -0
  249. package/templates/default/packages/execution-layer/test/app.test.ts.hbs +16 -0
  250. package/templates/default/tsconfig.json +5 -0
  251. package/templates/default/vitest.config.ts +5 -0
  252. package/templates/default/vitest.host.config.ts +6 -0
  253. package/templates/opensandbox/OPEN-SANDBOX.md +25 -0
  254. package/templates/opensandbox/docker/agent-sandbox.Dockerfile +41 -0
@@ -0,0 +1,170 @@
1
+ import { __exportAll } from "../_virtual/_rolldown/runtime.js";
2
+ import { PackageError, Service as Service$1, fromCause } from "./package.js";
3
+ import { make } from "./bundle.js";
4
+ import { Result as Result$1 } from "./inspection.js";
5
+ import { Service as Service$2 } from "./validation.js";
6
+ import "./archive.js";
7
+ import { Array, Context, DateTime, Effect, FileSystem, Layer, MutableList, Order, Path, Schema } from "effect";
8
+ import { Digest } from "effect/crypto";
9
+ import { Hex } from "effect/encoding";
10
+ import { ChildProcess, ChildProcessSpawner } from "effect/process";
11
+ import * as tar from "tar";
12
+ // src/plugin/archive.ts
13
+ var archive_exports = /* @__PURE__ */ __exportAll({
14
+ Artifact: () => Artifact,
15
+ PluginArchive: () => archive_exports,
16
+ Service: () => Service,
17
+ layer: () => layer
18
+ });
19
+ const Manifest = Schema.Struct({ scripts: Schema.Record(Schema.String, Schema.String) });
20
+ const Artifact = Schema.Struct({
21
+ activated: Schema.Literal(false),
22
+ digest: Schema.String,
23
+ file: Schema.String,
24
+ plugin: Schema.String,
25
+ published: Schema.Literal(false),
26
+ size: Schema.Finite,
27
+ version: Schema.String
28
+ });
29
+ var Service = class extends Context.Service()("@dual-os/cli/plugin/archive/Service") {};
30
+ const layer = Layer.effect(Service, Effect.gen(function* () {
31
+ const fs = yield* FileSystem.FileSystem;
32
+ const path = yield* Path.Path;
33
+ const crypto = yield* Digest.Digest;
34
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
35
+ const packages = yield* Service$1;
36
+ const validation = yield* Service$2;
37
+ const buildBundle = yield* make;
38
+ const executable = (yield* spawner.string(ChildProcess.make("which", ["bun"]))).trim();
39
+ return Service.of({ build: Effect.fn("PluginArchive.build")(function* (directory, output) {
40
+ const root = yield* fs.realPath(path.resolve(directory));
41
+ const lockRoot = Effect.fnUntraced(function* (current) {
42
+ if (yield* fs.exists(path.join(current, "bun.lock"))) return current;
43
+ const parent = path.dirname(current);
44
+ if (parent === current) return yield* PackageError.make({ message: "A frozen bun.lock is required to build a plugin" });
45
+ return yield* lockRoot(parent);
46
+ });
47
+ const locked = yield* lockRoot(root);
48
+ const command = Effect.fnUntraced(function* (executable, args, cwd) {
49
+ if ((yield* spawner.exitCode(ChildProcess.make(executable, args, {
50
+ cwd,
51
+ stdin: "ignore",
52
+ stdout: "ignore",
53
+ stderr: "inherit"
54
+ }))) !== 0) return yield* PackageError.make({ message: `Plugin build failed: ${executable} ${Array.join(args, " ")}` });
55
+ });
56
+ const bun = (yield* spawner.string(ChildProcess.make("bun", ["--version"]))).trim();
57
+ if (bun !== "1.4.2") return yield* PackageError.make({ message: "Plugin builds require Bun 1.4.2" });
58
+ yield* command("bun", [
59
+ "install",
60
+ "--frozen-lockfile",
61
+ "--ignore-scripts",
62
+ "--no-env-file"
63
+ ], locked);
64
+ const manifest = yield* Schema.decodeEffect(Schema.fromJsonString(Manifest))(yield* fs.readFileString(path.join(root, "package.json")));
65
+ const build = manifest.scripts["build"] ? "build" : "prepack";
66
+ if (!manifest.scripts[build]) return yield* PackageError.make({ message: "Declare scripts.build or scripts.prepack before building a plugin" });
67
+ yield* command("bun", [
68
+ "run",
69
+ "--no-env-file",
70
+ build
71
+ ], root);
72
+ const prepared = yield* packages.inspect(root);
73
+ const original = yield* validation.validate(root);
74
+ const compiled = yield* buildBundle(root, prepared);
75
+ const declaration = {
76
+ entrypoint: compiled.entrypoint.replaceAll("\\", "/"),
77
+ export: prepared.export,
78
+ format: 2,
79
+ plugin: original.plugin,
80
+ runner: compiled.runner,
81
+ sdk_version: compiled.sdkVersion,
82
+ version: original.version
83
+ };
84
+ const write = (name, value) => Effect.flatMap(Schema.encodeEffect(Schema.fromJsonString(Schema.Json))(value), (text) => fs.writeFileString(path.join(compiled.output, name), text));
85
+ yield* write("package.json", {
86
+ ...compiled.manifest,
87
+ dependencies: {},
88
+ devDependencies: {},
89
+ peerDependencies: {},
90
+ optionalDependencies: {},
91
+ scripts: {},
92
+ files: ["**/*"],
93
+ dual: { plugin: {
94
+ ...declaration,
95
+ assets: compiled.assets
96
+ } }
97
+ });
98
+ yield* write("dual-plugin.json", declaration);
99
+ yield* write("bundle-inventory.json", {
100
+ format: 1,
101
+ toolchain: {
102
+ bun,
103
+ lockfile_sha512: Hex.encode(yield* crypto.digest(Digest.sha512, yield* fs.readFile(path.join(locked, "bun.lock"))))
104
+ },
105
+ packages: compiled.packages
106
+ });
107
+ const names = Array.sort(yield* fs.glob("**/*", { root: compiled.output }), Order.String);
108
+ const files = MutableList.make();
109
+ for (const name of names) if ((yield* fs.stat(path.join(compiled.output, name))).type === "File") MutableList.append(files, name);
110
+ const staged = yield* fs.makeTempDirectoryScoped({ prefix: "dual-plugin-tarball-" });
111
+ const archive = path.join(staged, "plugin.tgz");
112
+ yield* Effect.tryPromise(() => tar.create({
113
+ cwd: compiled.output,
114
+ file: archive,
115
+ gzip: true,
116
+ portable: true,
117
+ mtime: DateTime.toDateUtc(DateTime.makeUnsafe("1980-01-01T00:00:00Z")),
118
+ prefix: "package"
119
+ }, MutableList.toArray(files)));
120
+ const isolated = path.join(staged, "isolated");
121
+ yield* fs.makeDirectory(isolated);
122
+ yield* Effect.tryPromise(() => tar.extract({
123
+ cwd: isolated,
124
+ file: archive,
125
+ strip: 1,
126
+ strict: true
127
+ }));
128
+ const inspected = yield* validation.validate(isolated);
129
+ const publicExports = Effect.fnUntraced(function* (directory, entries) {
130
+ const output = yield* spawner.string(ChildProcess.make(executable, [
131
+ "--no-env-file",
132
+ "--no-install",
133
+ "--eval",
134
+ "import { pathToFileURL } from \"node:url\"; const result = {}; for (const [source,file] of JSON.parse(process.argv[1])) result[source] = Object.keys(await import(pathToFileURL(process.cwd()+\"/\"+file).href)).sort(); console.log(JSON.stringify(result));",
135
+ JSON.stringify(entries)
136
+ ], {
137
+ cwd: directory,
138
+ env: {},
139
+ stdin: "ignore"
140
+ }));
141
+ return yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Record(Schema.String, Schema.Array(Schema.String))))(output.trim());
142
+ });
143
+ const originalExports = yield* publicExports(root, Array.map(compiled.publicJavaScript, (entry) => [entry.source, entry.source]));
144
+ const finalExports = yield* publicExports(isolated, Array.map(compiled.publicJavaScript, (entry) => [entry.source, entry.output]));
145
+ if (JSON.stringify(originalExports) !== JSON.stringify(finalExports)) return yield* PackageError.make({ message: "The final tarball changed public JavaScript exports; no archive was written" });
146
+ const encode = Schema.encodeEffect(Schema.fromJsonString(Result$1));
147
+ if ((yield* encode(original)) !== (yield* encode(inspected))) return yield* PackageError.make({ message: "The packaged plugin identity or contracts differ from the project inspection; no archive was written" });
148
+ const bytes = yield* fs.readFile(archive);
149
+ const file = path.resolve(output);
150
+ yield* fs.makeDirectory(path.dirname(file), { recursive: true });
151
+ const temporary = yield* fs.makeTempFileScoped({
152
+ directory: path.dirname(file),
153
+ prefix: ".dual-plugin-"
154
+ });
155
+ yield* fs.writeFile(temporary, bytes);
156
+ yield* fs.rename(temporary, file);
157
+ return {
158
+ activated: false,
159
+ digest: Hex.encode(yield* crypto.digest(Digest.sha512, bytes)),
160
+ file,
161
+ plugin: original.plugin,
162
+ published: false,
163
+ size: bytes.length,
164
+ version: original.version
165
+ };
166
+ }, Effect.scoped, Effect.mapError((cause) => Schema.is(PackageError)(cause) ? cause : fromCause(cause))) });
167
+ }));
168
+ export { Artifact, archive_exports as PluginArchive, Service, layer };
169
+
170
+ //# sourceMappingURL=archive.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"archive.js","names":["PluginPackage.Service","PluginValidation.Service","makeBundle","PluginInspection.Result","PluginPackage.PackageError","PluginPackage.fromCause"],"sources":["../../src/plugin/archive.ts"],"sourcesContent":["import type { PlatformError } from \"effect\";\nimport {\n Array,\n Context,\n DateTime,\n Effect,\n FileSystem,\n Layer,\n MutableList,\n Order,\n Path,\n Schema,\n} from \"effect\";\n\nimport { Digest } from \"effect/crypto\";\nimport { Hex } from \"effect/encoding\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\nimport * as tar from \"tar\";\n\nimport { make as makeBundle } from \"./bundle.ts\";\nimport { PluginInspection } from \"./inspection.ts\";\nimport { PluginPackage } from \"./package.ts\";\nimport { PluginValidation } from \"./validation.ts\";\n\nconst Manifest = Schema.Struct({ scripts: Schema.Record(Schema.String, Schema.String) });\nexport type Artifact = typeof Artifact.Type;\nexport const Artifact = Schema.Struct({\n activated: Schema.Literal(false),\n digest: Schema.String,\n file: Schema.String,\n plugin: Schema.String,\n published: Schema.Literal(false),\n size: Schema.Finite,\n version: Schema.String,\n});\nexport type Interface = {\n readonly build: (\n directory: string,\n output: string,\n ) => Effect.Effect<Artifact, PluginPackage.PackageError>;\n};\nexport class Service extends Context.Service<Service, Interface>()(\n \"@dual-os/cli/plugin/archive/Service\",\n) {}\n\nexport const layer = Layer.effect(\n Service,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const crypto = yield* Digest.Digest;\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n const packages = yield* PluginPackage.Service;\n const validation = yield* PluginValidation.Service;\n const buildBundle = yield* makeBundle;\n const executable = (yield* spawner.string(ChildProcess.make(\"which\", [\"bun\"]))).trim();\n return Service.of({\n build: Effect.fn(\"PluginArchive.build\")(\n function* (directory, output) {\n const root = yield* fs.realPath(path.resolve(directory));\n const lockRoot = Effect.fnUntraced(function* (\n current: string,\n ): Effect.fn.Return<string, PlatformError.PlatformError | PluginPackage.PackageError> {\n if (yield* fs.exists(path.join(current, \"bun.lock\"))) return current;\n const parent = path.dirname(current);\n if (parent === current)\n return yield* PluginPackage.PackageError.make({\n message: \"A frozen bun.lock is required to build a plugin\",\n });\n return yield* lockRoot(parent);\n });\n const locked = yield* lockRoot(root);\n const command = Effect.fnUntraced(function* (\n executable: string,\n args: string[],\n cwd: string,\n ) {\n const code = yield* spawner.exitCode(\n ChildProcess.make(executable, args, {\n cwd,\n stdin: \"ignore\",\n stdout: \"ignore\",\n stderr: \"inherit\",\n }),\n );\n if (code !== 0)\n return yield* PluginPackage.PackageError.make({\n message: `Plugin build failed: ${executable} ${Array.join(args, \" \")}`,\n });\n });\n const bun = (yield* spawner.string(ChildProcess.make(\"bun\", [\"--version\"]))).trim();\n if (bun !== \"1.4.2\")\n return yield* PluginPackage.PackageError.make({\n message: \"Plugin builds require Bun 1.4.2\",\n });\n yield* command(\n \"bun\",\n [\"install\", \"--frozen-lockfile\", \"--ignore-scripts\", \"--no-env-file\"],\n locked,\n );\n const manifest = yield* Schema.decodeEffect(Schema.fromJsonString(Manifest))(\n yield* fs.readFileString(path.join(root, \"package.json\")),\n );\n const build = manifest.scripts[\"build\"] ? \"build\" : \"prepack\";\n if (!manifest.scripts[build])\n return yield* PluginPackage.PackageError.make({\n message: \"Declare scripts.build or scripts.prepack before building a plugin\",\n });\n yield* command(\"bun\", [\"run\", \"--no-env-file\", build], root);\n const prepared = yield* packages.inspect(root);\n const original = yield* validation.validate(root);\n const compiled = yield* buildBundle(root, prepared);\n const declaration = {\n entrypoint: compiled.entrypoint.replaceAll(\"\\\\\", \"/\"),\n export: prepared.export,\n format: 2,\n plugin: original.plugin,\n runner: compiled.runner,\n sdk_version: compiled.sdkVersion,\n version: original.version,\n };\n const write = (name: string, value: Schema.Json) =>\n Effect.flatMap(Schema.encodeEffect(Schema.fromJsonString(Schema.Json))(value), text =>\n fs.writeFileString(path.join(compiled.output, name), text),\n );\n yield* write(\"package.json\", {\n ...compiled.manifest,\n dependencies: {},\n devDependencies: {},\n peerDependencies: {},\n optionalDependencies: {},\n scripts: {},\n files: [\"**/*\"],\n dual: { plugin: { ...declaration, assets: compiled.assets } },\n });\n yield* write(\"dual-plugin.json\", declaration);\n yield* write(\"bundle-inventory.json\", {\n format: 1,\n toolchain: {\n bun,\n lockfile_sha512: Hex.encode(\n yield* crypto.digest(\n Digest.sha512,\n yield* fs.readFile(path.join(locked, \"bun.lock\")),\n ),\n ),\n },\n packages: compiled.packages,\n });\n const names = Array.sort(yield* fs.glob(\"**/*\", { root: compiled.output }), Order.String);\n const files = MutableList.make<string>();\n for (const name of names)\n if ((yield* fs.stat(path.join(compiled.output, name))).type === \"File\")\n MutableList.append(files, name);\n const staged = yield* fs.makeTempDirectoryScoped({ prefix: \"dual-plugin-tarball-\" });\n const archive = path.join(staged, \"plugin.tgz\");\n yield* Effect.tryPromise(() =>\n tar.create(\n {\n cwd: compiled.output,\n file: archive,\n gzip: true,\n portable: true,\n mtime: DateTime.toDateUtc(DateTime.makeUnsafe(\"1980-01-01T00:00:00Z\")),\n prefix: \"package\",\n },\n MutableList.toArray(files),\n ),\n );\n const isolated = path.join(staged, \"isolated\");\n yield* fs.makeDirectory(isolated);\n yield* Effect.tryPromise(() =>\n tar.extract({ cwd: isolated, file: archive, strip: 1, strict: true }),\n );\n const inspected = yield* validation.validate(isolated);\n const publicExports = Effect.fnUntraced(function* (\n directory: string,\n entries: (readonly [string, string])[],\n ) {\n const output = yield* spawner.string(\n ChildProcess.make(\n executable,\n [\n \"--no-env-file\",\n \"--no-install\",\n \"--eval\",\n 'import { pathToFileURL } from \"node:url\"; const result = {}; for (const [source,file] of JSON.parse(process.argv[1])) result[source] = Object.keys(await import(pathToFileURL(process.cwd()+\"/\"+file).href)).sort(); console.log(JSON.stringify(result));',\n JSON.stringify(entries),\n ],\n { cwd: directory, env: {}, stdin: \"ignore\" },\n ),\n );\n return yield* Schema.decodeEffect(\n Schema.fromJsonString(Schema.Record(Schema.String, Schema.Array(Schema.String))),\n )(output.trim());\n });\n const originalExports = yield* publicExports(\n root,\n Array.map(compiled.publicJavaScript, entry => [entry.source, entry.source] as const),\n );\n const finalExports = yield* publicExports(\n isolated,\n Array.map(compiled.publicJavaScript, entry => [entry.source, entry.output] as const),\n );\n if (JSON.stringify(originalExports) !== JSON.stringify(finalExports))\n return yield* PluginPackage.PackageError.make({\n message:\n \"The final tarball changed public JavaScript exports; no archive was written\",\n });\n const encode = Schema.encodeEffect(Schema.fromJsonString(PluginInspection.Result));\n if ((yield* encode(original)) !== (yield* encode(inspected)))\n return yield* PluginPackage.PackageError.make({\n message:\n \"The packaged plugin identity or contracts differ from the project inspection; no archive was written\",\n });\n const bytes = yield* fs.readFile(archive);\n const file = path.resolve(output);\n yield* fs.makeDirectory(path.dirname(file), { recursive: true });\n const temporary = yield* fs.makeTempFileScoped({\n directory: path.dirname(file),\n prefix: \".dual-plugin-\",\n });\n yield* fs.writeFile(temporary, bytes);\n yield* fs.rename(temporary, file);\n return {\n activated: false,\n digest: Hex.encode(yield* crypto.digest(Digest.sha512, bytes)),\n file,\n plugin: original.plugin,\n published: false,\n size: bytes.length,\n version: original.version,\n } satisfies Artifact;\n },\n Effect.scoped,\n Effect.mapError(cause =>\n Schema.is(PluginPackage.PackageError)(cause) ? cause : PluginPackage.fromCause(cause),\n ),\n ),\n });\n }),\n);\n\nexport * as PluginArchive from \"./archive.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwBA,MAAM,WAAW,OAAO,OAAO,EAAE,SAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,MAAM,EAAE,CAAC;AAEvF,MAAa,WAAW,OAAO,OAAO;CACpC,WAAW,OAAO,QAAQ,KAAK;CAC/B,QAAQ,OAAO;CACf,MAAM,OAAO;CACb,QAAQ,OAAO;CACf,WAAW,OAAO,QAAQ,KAAK;CAC/B,MAAM,OAAO;CACb,SAAS,OAAO;AAClB,CAAC;AAOD,IAAa,UAAb,cAA6B,QAAQ,QAA4B,CAAC,CAChE,qCACF,CAAC,CAAC,CAAC;AAEH,MAAa,QAAQ,MAAM,OACzB,SACA,OAAO,IAAI,aAAa;CACtB,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,SAAS,OAAO,OAA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AS,CAAC,MAAM,QAAQ,MAAM,MAAM,CAAU,CACrF;EACA,MAAM,eAAe,OAAO,cAC1B,UACA,MAAM,IAAI,SAAS,mBAAkB,UAAS,CAAC,MAAM,QAAQ,MAAM,MAAM,CAAU,CACrF;EACA,IAAI,KAAK,UAAU,eAAe,MAAM,KAAK,UAAU,YAAY,GACjE,OAAO,OAAA,aAAkC,KAAK,EAC5C,SACE,8EACJ,CAAC;EACH,MAAM,SAAS,OAAO,aAAa,OAAO,eAAeC,QAAuB,CAAC;EACjF,KAAK,OAAO,OAAO,QAAQ,QAAQ,OAAO,OAAO,SAAS,IACxD,OAAO,OAAA,aAAkC,KAAK,EAC5C,SACE,uGACJ,CAAC;EACH,MAAM,QAAQ,OAAO,GAAG,SAAS,OAAO;EACxC,MAAM,OAAO,KAAK,QAAQ,MAAM;EAChC,OAAO,GAAG,cAAc,KAAK,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;EAC/D,MAAM,YAAY,OAAO,GAAG,mBAAmB;GAC7C,WAAW,KAAK,QAAQ,IAAI;GAC5B,QAAQ;EACV,CAAC;EACD,OAAO,GAAG,UAAU,WAAW,KAAK;EACpC,OAAO,GAAG,OAAO,WAAW,IAAI;EAChC,OAAO;GACL,WAAW;GACX,QAAQ,IAAI,OAAO,OAAO,OAAO,OAAO,OAAO,QAAQ,KAAK,CAAC;GAC7D;GACA,QAAQ,SAAS;GACjB,WAAW;GACX,MAAM,MAAM;GACZ,SAAS,SAAS;EACpB;CACF,GACA,OAAO,QACP,OAAO,UAAS,UACd,OAAO,GAAGC,YAA0B,CAAC,CAAC,KAAK,IAAI,QAAQC,UAAwB,KAAK,CACtF,CACF,EACF,CAAC;AACH,CAAC,CACH"}
@@ -0,0 +1,27 @@
1
+ import { PackageError, Prepared } from "./package.js";
2
+ import { Effect, FileSystem, Path, PlatformError, Schema } from "effect";
3
+ import { ChildProcessSpawner } from "effect/process";
4
+ export declare const make: Effect.Effect<(root: string, prepared: Prepared) => Effect.Effect<{
5
+ output: string;
6
+ sdkVersion: string;
7
+ runner: string;
8
+ manifest: {
9
+ name?: string;
10
+ version: string;
11
+ license?: string;
12
+ exports: Schema.Json;
13
+ };
14
+ entrypoint: string;
15
+ assets: string[];
16
+ publicJavaScript: {
17
+ source: string;
18
+ output: string;
19
+ }[];
20
+ packages: {
21
+ name: string;
22
+ version: string;
23
+ license: string;
24
+ licenses: string[];
25
+ }[];
26
+ }, PackageError | PlatformError.PlatformError | Schema.SchemaError | import("effect/Cause").UnknownError, never>, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path>;
27
+ //# sourceMappingURL=bundle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundle.d.ts","names":["PluginPackage.Prepared","PluginPackage.PackageError"],"sources":["../../src/plugin/bundle.ts"],"mappings":";;;qBAsMa,MAAI,OAAA,QAAA,cAAA,UAAAA,aAAA,OAAA;;;;;;;;;;;;;;;;;IAmMH;IAAiB;IAAiB;IAAkB;;GAkLhEC,eAAA,cAAA,gBAAA,OAAA,qCAAA,6BAAA,oBAAA,sBAAA,WAAA,aAAA,KAAA"}
@@ -0,0 +1,328 @@
1
+ import { PackageError } from "./package.js";
2
+ import { createRequire, isBuiltin } from "node:module";
3
+ import { Array, Effect, FileSystem, MutableHashMap, MutableList, Order, Path, Predicate, Record, Schema } from "effect";
4
+ import { ChildProcess, ChildProcessSpawner } from "effect/process";
5
+ import * as acorn from "acorn";
6
+ import { ReleaseManifest } from "#release/release-manifest";
7
+ // src/plugin/bundle.ts
8
+ const Import = Schema.Struct({
9
+ path: Schema.String,
10
+ external: Schema.optionalKey(Schema.Boolean)
11
+ });
12
+ const Metafile = Schema.Struct({
13
+ inputs: Schema.Record(Schema.String, Schema.Struct({ imports: Schema.Array(Import) })),
14
+ outputs: Schema.Record(Schema.String, Schema.Struct({
15
+ imports: Schema.Array(Import),
16
+ inputs: Schema.Record(Schema.String, Schema.Struct({ bytesInOutput: Schema.Number })),
17
+ entryPoint: Schema.optionalKey(Schema.String)
18
+ }))
19
+ });
20
+ const Metadata = Schema.StructWithRest(Schema.Struct({
21
+ name: Schema.optionalKey(Schema.String),
22
+ version: ReleaseManifest.ExactVersion,
23
+ license: Schema.optionalKey(Schema.String),
24
+ exports: Schema.optionalKey(Schema.Json)
25
+ }), [Schema.Record(Schema.String, Schema.Json)]);
26
+ function targets(value) {
27
+ if (typeof value === "string") return [value];
28
+ if (value === null) return [];
29
+ if (typeof value !== "object") throw PackageError.make({ message: "Unsupported package exports" });
30
+ return Array.flatMap(Object.values(value), targets);
31
+ }
32
+ function pattern(expression) {
33
+ if (expression.type === "Literal" && typeof expression.value === "string") return expression.value;
34
+ if (expression.type === "BinaryExpression" && expression.operator === "+" && expression.left.type !== "PrivateIdentifier") return pattern(expression.left) + pattern(expression.right);
35
+ if (expression.type === "TemplateLiteral") return Array.join(Array.map(expression.quasis, (part) => part.value.cooked ?? part.value.raw), "*");
36
+ return "*";
37
+ }
38
+ function isNode(value) {
39
+ return Predicate.isObject(value) && Predicate.isString(value["type"]) && Predicate.isNumber(value["start"]) && Predicate.isNumber(value["end"]);
40
+ }
41
+ function references(code) {
42
+ const tree = acorn.parse(code, {
43
+ ecmaVersion: "latest",
44
+ sourceType: "module",
45
+ allowReturnOutsideFunction: true
46
+ });
47
+ const found = MutableList.make();
48
+ const visit = (expression, parent, grandparent) => {
49
+ if (expression.type === "ImportExpression") MutableList.append(found, {
50
+ kind: "import",
51
+ path: pattern(expression.source)
52
+ });
53
+ if (expression.type === "CallExpression" && expression.callee.type === "Identifier" && Array.contains(["require", "__require"], expression.callee.name) && expression.arguments[0]) MutableList.append(found, {
54
+ kind: "require",
55
+ path: pattern(expression.arguments[0])
56
+ });
57
+ if (expression.type === "CallExpression" && expression.callee.type === "MemberExpression" && expression.callee.object.type === "MetaProperty" && expression.callee.object.meta.name === "import" && expression.callee.property.type === "Identifier" && Array.contains(["resolve", "require"], expression.callee.property.name) && expression.arguments[0]) MutableList.append(found, {
58
+ kind: "resolve",
59
+ path: pattern(expression.arguments[0])
60
+ });
61
+ if (expression.type === "ImportSpecifier" && expression.imported.type === "Identifier" && expression.imported.name === "createRequire" && parent?.type === "ImportDeclaration" && Array.contains(["node:module", "module"], parent.source.value)) MutableList.append(found, {
62
+ kind: "resolve",
63
+ path: "createRequire"
64
+ });
65
+ if ((expression.type === "ImportNamespaceSpecifier" || expression.type === "ImportDefaultSpecifier") && parent?.type === "ImportDeclaration" && Array.contains(["node:module", "module"], parent.source.value) || expression.type === "ImportExpression" && Array.contains(["node:module", "module"], pattern(expression.source)) || expression.type === "CallExpression" && expression.callee.type === "Identifier" && Array.contains(["require", "__require"], expression.callee.name) && expression.arguments[0] && Array.contains(["node:module", "module"], pattern(expression.arguments[0]))) MutableList.append(found, {
66
+ kind: "resolve",
67
+ path: "module namespace"
68
+ });
69
+ if (expression.type === "NewExpression") {
70
+ const base = expression.arguments[1];
71
+ if (expression.callee.type === "Identifier" && expression.callee.name === "URL" && base?.type === "MemberExpression" && base.object.type === "MetaProperty" && base.object.meta.name === "import" && base.object.property.name === "meta" && base.property.type === "Identifier" && base.property.name === "url" && expression.arguments[0]) {
72
+ const receiver = parent?.type === "MemberExpression" ? parent : expression;
73
+ const call = receiver === parent ? grandparent : parent;
74
+ const method = call?.type === "CallExpression" ? call.callee : void 0;
75
+ const name = method?.type === "Identifier" ? method.name : method?.type === "MemberExpression" && method.property.type === "Identifier" ? method.property.name : "";
76
+ if (!(call?.type === "CallExpression" && call.arguments[0] === receiver && Array.contains([
77
+ "writeFile",
78
+ "writeFileSync",
79
+ "writeFileString",
80
+ "appendFile",
81
+ "appendFileSync",
82
+ "makeDirectory",
83
+ "mkdir",
84
+ "mkdirSync"
85
+ ], name))) MutableList.append(found, {
86
+ kind: "asset",
87
+ path: pattern(expression.arguments[0])
88
+ });
89
+ }
90
+ }
91
+ const fields = Object.values(expression);
92
+ for (const field of fields) if (isNode(field)) visit(field, expression, parent);
93
+ else if (Array.isArray(field)) {
94
+ for (const child of field) if (isNode(child)) visit(child, expression, parent);
95
+ }
96
+ };
97
+ visit(tree);
98
+ return MutableList.toArray(found);
99
+ }
100
+ const make = Effect.gen(function* () {
101
+ const fs = yield* FileSystem.FileSystem;
102
+ const path = yield* Path.Path;
103
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
104
+ return Effect.fn("PluginBundle.build")(function* (root, prepared) {
105
+ const json = Effect.fnUntraced(function* (file) {
106
+ return yield* Schema.decodeEffect(Schema.fromJsonString(Metadata))(yield* fs.readFileString(file));
107
+ });
108
+ const manifest = yield* json(path.join(root, "package.json"));
109
+ const require = createRequire(prepared.entrypoint);
110
+ const sdkRoot = path.dirname(require.resolve("@dual-os/sdk/package.json"));
111
+ const sdk = yield* json(path.join(sdkRoot, "package.json"));
112
+ const sdkRunner = yield* fs.realPath(require.resolve("@dual-os/sdk/Runner"));
113
+ const input = path.join(root, ".dual/bundle-input");
114
+ const output = path.join(root, ".dual/bundle-output");
115
+ for (const directory of [input, output]) {
116
+ if (yield* fs.exists(directory)) yield* fs.remove(directory, { recursive: true });
117
+ yield* fs.makeDirectory(directory, { recursive: true });
118
+ }
119
+ const safe = Effect.fnUntraced(function* (name) {
120
+ const relative = path.relative(root, path.resolve(root, name));
121
+ if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative) || Array.some(relative.split(path.sep), (part) => [
122
+ "node_modules",
123
+ ".dual",
124
+ ".env",
125
+ ".npmrc",
126
+ ".netrc"
127
+ ].includes(part) || part.startsWith(".env."))) return yield* PackageError.make({ message: `Unsafe bundle path: ${name}` });
128
+ const source = path.resolve(root, name);
129
+ if (!(yield* fs.realPath(source)).startsWith(`${root}${path.sep}`)) return yield* PackageError.make({ message: `Bundle file escapes the package: ${name}` });
130
+ return {
131
+ source,
132
+ relative
133
+ };
134
+ });
135
+ const copy = Effect.fnUntraced(function* (name, destination) {
136
+ const file = yield* safe(name);
137
+ if ((yield* fs.stat(file.source)).type !== "File") return yield* PackageError.make({ message: `Bundle export must be a file: ${name}` });
138
+ const bytes = yield* fs.readFile(file.source);
139
+ if (/\.[cm]?tsx?$/u.test(name) && !/\.d\.[cm]?ts$/u.test(name)) return yield* PackageError.make({ message: `Source exports/assets cannot be shipped in a JavaScript bundle: ${name}` });
140
+ const prefix = Buffer.from(bytes.subarray(0, 4));
141
+ if (/\.(?:node|dll|dylib|exe|so(?:\.[0-9.]+)?)$|(?:^|\/)binding\.gyp$/iu.test(name) || prefix.length === 4 && [
142
+ 2135247942,
143
+ 4277009102,
144
+ 3472551422,
145
+ 4277009103,
146
+ 3489328638,
147
+ 3405691582,
148
+ 3199925962
149
+ ].includes(prefix.readUInt32BE(0)) || prefix.length >= 2 && prefix.readUInt16BE(0) === 19802) return yield* PackageError.make({ message: `Native bundle content is unsupported: ${name}` });
150
+ yield* fs.makeDirectory(path.dirname(path.join(destination, file.relative)), { recursive: true });
151
+ yield* fs.copyFile(file.source, path.join(destination, file.relative));
152
+ });
153
+ const publicFiles = MutableList.make();
154
+ for (const target of yield* Effect.try(() => targets(manifest.exports ?? {}))) {
155
+ const matches = yield* fs.glob(target, { root });
156
+ if (Array.isArrayEmpty(matches)) return yield* PackageError.make({ message: `Missing public export: ${target}` });
157
+ MutableList.appendAll(publicFiles, matches);
158
+ }
159
+ const declared = Array.dedupe([
160
+ ...MutableList.toArray(publicFiles),
161
+ path.relative(root, prepared.entrypoint),
162
+ ...Array.map(prepared.assets, (file) => path.relative(root, file))
163
+ ]);
164
+ const declarations = MutableList.make();
165
+ for (const file of yield* fs.glob("**/*", {
166
+ root,
167
+ exclude: [
168
+ "node_modules/**",
169
+ ".dual/**",
170
+ ".git/**"
171
+ ]
172
+ })) {
173
+ const source = path.join(root, file);
174
+ if ((yield* fs.stat(source)).type !== "File") continue;
175
+ if (/\.d\.[cm]?ts(?:\.map)?$/u.test(file)) {
176
+ yield* copy(file, output);
177
+ MutableList.append(declarations, file);
178
+ }
179
+ if (/\.(?:[cm]?js|json|map)$/.test(file) && !Array.some(file.split("/"), (part) => part.startsWith("."))) yield* copy(path.relative(root, source), input);
180
+ }
181
+ for (const file of declared) {
182
+ yield* copy(file, input);
183
+ if (!/\.(?:[cm]?js)$/.test(file)) yield* copy(file, output);
184
+ }
185
+ for (const file of [
186
+ "README.md",
187
+ "LICENSE",
188
+ "LICENSE.md",
189
+ "LICENSE.txt"
190
+ ]) if (yield* fs.exists(path.join(root, file))) yield* copy(file, output);
191
+ yield* fs.writeFileString(path.join(input, "package.json"), yield* fs.readFileString(path.join(root, "package.json")));
192
+ const modules = Effect.fnUntraced(function* (directory) {
193
+ if (yield* fs.exists(path.join(directory, "node_modules"))) return path.join(directory, "node_modules");
194
+ const parent = path.dirname(directory);
195
+ if (parent === directory) return yield* PackageError.make({ message: "Install build dependencies from a frozen lockfile first" });
196
+ return yield* modules(parent);
197
+ });
198
+ yield* fs.symlink(yield* modules(root), path.join(input, "node_modules"));
199
+ const runnerName = Effect.fnUntraced(function* (index) {
200
+ const name = index === 0 ? "Runner.js" : `Runner-${index}.js`;
201
+ return (yield* fs.exists(path.join(input, name))) ? yield* runnerName(index + 1) : name;
202
+ });
203
+ const runner = yield* runnerName(0);
204
+ yield* fs.writeFileString(path.join(input, runner), "import \"@dual-os/sdk/Runner\";\n");
205
+ const entries = Array.dedupe([...Array.filter(declared, (file) => /\.(?:[cm]?js)$/.test(file)), runner]);
206
+ const metaPath = path.join(root, ".dual/bundle-metafile.json");
207
+ if ((yield* spawner.exitCode(ChildProcess.make("bun", [
208
+ "build",
209
+ "--no-env-file",
210
+ "--target=bun",
211
+ "--format=esm",
212
+ "--splitting",
213
+ "--keep-names",
214
+ "--sourcemap=linked",
215
+ `--metafile=${metaPath}`,
216
+ "--root",
217
+ input,
218
+ "--outdir",
219
+ output,
220
+ ...Array.map(entries, (file) => path.resolve(input, file))
221
+ ], {
222
+ cwd: input,
223
+ stdin: "ignore",
224
+ stdout: "ignore",
225
+ stderr: "inherit"
226
+ }))) !== 0) return yield* PackageError.make({ message: "Self-contained plugin compilation failed; no installation fallback is available" });
227
+ const meta = yield* Schema.decodeEffect(Schema.fromJsonString(Metafile))(yield* fs.readFileString(metaPath));
228
+ const emitted = Record.fromEntries(Array.flatMap(Object.entries(meta.outputs), (entry) => entry[1].entryPoint ? [[path.relative(input, path.resolve(input, entry[1].entryPoint)), entry[0].replace(/^\.\//u, "")]] : []));
229
+ const rewrite = (value) => {
230
+ if (typeof value === "string") return emitted[path.normalize(value)] ? `./${emitted[path.normalize(value)]}` : value.replace(/\.[cm]js$/u, ".js");
231
+ if (value === null || typeof value !== "object") return value;
232
+ if (Array.isArray(value)) return Array.map(value, rewrite);
233
+ return Record.map(value, rewrite);
234
+ };
235
+ const packages = MutableHashMap.empty();
236
+ const contributing = Array.dedupe(Array.flatMap(Object.values(meta.outputs), (result) => Array.map(Array.filter(Object.entries(result.inputs), (entry) => entry[1].bytesInOutput > 0), (entry) => entry[0])));
237
+ for (const file of contributing) {
238
+ const source = yield* fs.realPath(path.resolve(input, file));
239
+ const body = yield* fs.readFileString(source);
240
+ for (const reference of /\.[cm]?js$/.test(source) ? yield* Effect.try(() => references(body)) : []) {
241
+ if (reference.kind === "resolve" && Array.contains(["createRequire", "module namespace"], reference.path)) continue;
242
+ if (reference.kind === "import" && source === sdkRunner) continue;
243
+ if (isBuiltin(reference.path) || reference.path.startsWith("bun:")) continue;
244
+ if (reference.kind === "asset" && /^(?!file:)[a-z][a-z\d+.-]*:/iu.test(reference.path)) continue;
245
+ if (reference.kind === "resolve") return yield* PackageError.make({ message: `Runtime package resolution cannot be bundled in ${file}: ${reference.path}; use an import instead` });
246
+ if (reference.kind !== "asset" && !reference.path.includes("*")) continue;
247
+ if (reference.kind === "require") return yield* PackageError.make({ message: `Unresolved computed require in ${file}; use finite imports and declare dual.plugin.assets` });
248
+ if (!reference.path.startsWith(".")) return yield* PackageError.make({ message: `Unresolved dynamic import/resource in ${file}: ${reference.path}. Declare finite relative files in dual.plugin.assets.` });
249
+ const matches = yield* fs.glob(reference.path, { root: path.dirname(source) });
250
+ if (Array.isArrayEmpty(matches)) return yield* PackageError.make({ message: `Missing dynamic import/resource in ${file}: ${reference.path}` });
251
+ if (reference.path.includes("*")) for (const match of matches) {
252
+ const relative = path.relative(input, path.resolve(path.dirname(source), match));
253
+ if (!Array.some(declared, (name) => path.normalize(name) === relative)) return yield* PackageError.make({ message: `Declare dynamic file in dual.plugin.assets: ${relative}` });
254
+ }
255
+ }
256
+ if (source.startsWith(`${input}${path.sep}`)) continue;
257
+ const owner = Effect.fnUntraced(function* (directory) {
258
+ if (yield* fs.exists(path.join(directory, "package.json"))) return directory;
259
+ const parent = path.dirname(directory);
260
+ if (parent === directory) return yield* PackageError.make({ message: `Dependency has no package manifest: ${source}` });
261
+ return yield* owner(parent);
262
+ });
263
+ const directory = yield* owner(path.dirname(source));
264
+ if (MutableHashMap.has(packages, directory)) continue;
265
+ const pkg = yield* json(path.join(directory, "package.json"));
266
+ if (!pkg.name || !pkg.license) return yield* PackageError.make({ message: `Dependency lacks name/license metadata: ${directory}` });
267
+ const licenseFiles = (yield* fs.glob("{LICENSE,LICENCE,COPYING,NOTICE}{,.md,.txt}", { root: directory })).sort();
268
+ if (Array.isArrayEmpty(licenseFiles)) return yield* PackageError.make({ message: `Dependency attribution missing: ${pkg.name}@${pkg.version}` });
269
+ const licenses = MutableList.make();
270
+ for (const license of licenseFiles) {
271
+ if ((yield* fs.stat(path.join(directory, license))).size === 0n) return yield* PackageError.make({ message: `Empty dependency attribution: ${pkg.name}@${pkg.version}: ${license}` });
272
+ const target = `licenses/${pkg.name.replaceAll("/", "_")}@${pkg.version}/${license}`;
273
+ yield* fs.makeDirectory(path.dirname(path.join(output, target)), { recursive: true });
274
+ yield* fs.copyFile(path.join(directory, license), path.join(output, target));
275
+ MutableList.append(licenses, target);
276
+ }
277
+ MutableHashMap.set(packages, directory, {
278
+ name: pkg.name,
279
+ version: pkg.version,
280
+ license: pkg.license,
281
+ licenses: MutableList.toArray(licenses)
282
+ });
283
+ }
284
+ for (const [file, metadata] of Object.entries(meta.outputs)) {
285
+ for (const imported of metadata.imports) {
286
+ if (isBuiltin(imported.path) || imported.path.startsWith("bun:")) continue;
287
+ if (imported.external || !imported.path.startsWith(".") || !(yield* fs.exists(path.resolve(output, imported.path)))) return yield* PackageError.make({ message: `Unbundled dependency in ${file}: ${imported.path}` });
288
+ }
289
+ if (!/\.[cm]?js$/.test(file)) continue;
290
+ const outputCode = yield* fs.readFileString(path.resolve(output, file));
291
+ for (const reference of yield* Effect.try(() => references(outputCode))) {
292
+ if (reference.kind === "resolve" && Array.contains(["createRequire", "module namespace"], reference.path)) return yield* PackageError.make({ message: `Runtime package resolution cannot be bundled in ${file}: ${reference.path}; use static named imports instead` });
293
+ if (reference.kind === "require" && !isBuiltin(reference.path) && !reference.path.startsWith("bun:")) return yield* PackageError.make({ message: `Unbundled require in ${file}: ${reference.path}; no installation fallback is available` });
294
+ if (reference.kind === "import" && reference.path.startsWith(".") && reference.path.includes("*") && Array.isArrayEmpty(yield* fs.glob(reference.path, { root: path.resolve(output, path.dirname(file)) }))) return yield* PackageError.make({ message: `Bundle dynamic import is missing after splitting: ${file}: ${reference.path}` });
295
+ if (reference.kind !== "asset") continue;
296
+ if (/^(?!file:)[a-z][a-z\d+.-]*:/iu.test(reference.path)) continue;
297
+ if (!(yield* fs.exists(path.resolve(output, path.dirname(file), reference.path)))) return yield* PackageError.make({ message: `Bundle resource is missing after splitting: ${file}: ${reference.path}` });
298
+ }
299
+ }
300
+ return {
301
+ output,
302
+ sdkVersion: sdk.version,
303
+ runner: emitted[runner] ?? runner,
304
+ manifest: {
305
+ ...manifest,
306
+ exports: rewrite(manifest.exports ?? {})
307
+ },
308
+ entrypoint: emitted[path.relative(root, prepared.entrypoint)] ?? path.relative(root, prepared.entrypoint),
309
+ assets: Array.dedupe([
310
+ ...Array.map(prepared.assets, (file) => {
311
+ const relative = path.relative(root, file);
312
+ return emitted[relative] ?? relative;
313
+ }),
314
+ ...MutableList.toArray(declarations),
315
+ ...Array.filter(MutableList.toArray(publicFiles), (file) => !/\.[cm]?js$/u.test(file)),
316
+ ...Array.map(Array.filter(Object.keys(meta.outputs), (file) => !/\.[cm]?js$/u.test(file)), (file) => file.replace(/^\.\//u, ""))
317
+ ]),
318
+ publicJavaScript: Array.map(Array.filter(MutableList.toArray(publicFiles), (file) => /\.[cm]?js$/u.test(file)), (source) => ({
319
+ source,
320
+ output: emitted[path.normalize(source)] ?? source
321
+ })),
322
+ packages: Array.sort(Array.fromIterable(MutableHashMap.values(packages)), Order.mapInput(Order.String, (pkg) => `${pkg.name}@${pkg.version}`))
323
+ };
324
+ });
325
+ });
326
+ export { make };
327
+
328
+ //# sourceMappingURL=bundle.js.map