@vultro/runtime-cloud 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # `@vultro/runtime-cloud`
2
2
 
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.
3
+ 基于 [`cloudflare/workerd`](https://github.com/cloudflare/workerd) 的极简 Cloud 运行时。
4
+
5
+ 定位上相当于一个 **极度精简的 `@cloudflare/vite-plugin` 替代品**:不依赖 Wrangler 或 Miniflare,也不引入 `esbuild`,直接复用 Vite 打包 Worker(含原生 `.wasm` 分离)、生成最小 `workerd.capnp`,并由 Vite dev server 或生产脚本拉起 `workerd` 执行 `VultroDO` / `VultroSyncDO`。
6
+
7
+ ## 导出结构
8
+
9
+ - `@vultro/runtime-cloud`:`bundleCloudWorker`、`renderWorkerdCapnp`、`startWorkerd`、`resolveWorkerdBinary`
10
+ - `@vultro/runtime-cloud/worker`:`createRuntime`、`createRuntimeWorker`、`defineWorker`(运行在 `workerd` 沙箱内)
11
+ - `@vultro/runtime-cloud/capnp`:纯 Cap'n Proto 配置渲染
12
+
13
+ ## 使用自定义 `workerd` 二进制
14
+
15
+ 通过环境变量 `VULTRO_WORKERD_BIN=/path/to/workerd` 或在 `vultro.config.ts` 中设置 `cloud.workerdBin` 即可切换到你二次开发的 `workerd` 分支。
@@ -0,0 +1,102 @@
1
+ // \0vite/preload-helper.js
2
+ var scriptRel = /* @__PURE__ */ (function detectScriptRel() {
3
+ const relList = typeof document < "u" && document.createElement("link").relList;
4
+ return relList && relList.supports && relList.supports("modulepreload") ? "modulepreload" : "preload";
5
+ })();
6
+ var assetsURL = function(dep) {
7
+ return "/" + dep;
8
+ };
9
+ var seen = {};
10
+ var failedCssLinks = {};
11
+ var isCssPreloadUrl = function isCssPreloadUrl(url) {
12
+ return url.pathname.endsWith(".css");
13
+ };
14
+ var preloadOnce = function preloadOnce(seen, href, preload) {
15
+ if (href in seen) return seen[href];
16
+ const promise = preload();
17
+ if (!promise) {
18
+ seen[href] = void 0;
19
+ return;
20
+ }
21
+ const preloadPromise = promise.then(() => {
22
+ seen[href] = void 0;
23
+ }, (err) => {
24
+ delete seen[href];
25
+ throw err;
26
+ });
27
+ seen[href] = preloadPromise;
28
+ return preloadPromise;
29
+ };
30
+ var __vitePreload = function preload(baseModule, deps, importerUrl) {
31
+ let promise = Promise.resolve();
32
+ if (deps && deps.length > 0) {
33
+ let allSettled = function(promises) {
34
+ return Promise.all(promises.map((p) => Promise.resolve(p).then((value) => ({
35
+ status: "fulfilled",
36
+ value
37
+ }), (reason) => ({
38
+ status: "rejected",
39
+ reason
40
+ }))));
41
+ }, importMetaResolve = function(specifier) {
42
+ if (import.meta.resolve) return new URL(import.meta.resolve(specifier));
43
+ return new URL(specifier, import.meta.url);
44
+ }, preloadedHrefs;
45
+ const cspNonceMeta = document.querySelector("meta[property=csp-nonce]"), cspNonce = cspNonceMeta?.nonce || cspNonceMeta?.getAttribute("nonce");
46
+ promise = allSettled(deps.map((depString) => {
47
+ depString = assetsURL(depString, importerUrl);
48
+ const dep = importMetaResolve(depString), isCss = isCssPreloadUrl(dep);
49
+ return preloadOnce(seen, dep.href, () => {
50
+ if (preloadedHrefs === void 0) {
51
+ preloadedHrefs = {
52
+ all: /* @__PURE__ */ new Set(),
53
+ styles: /* @__PURE__ */ new Set()
54
+ };
55
+ const links = document.getElementsByTagName("link");
56
+ for (let i = links.length - 1; i >= 0; i--) {
57
+ const link = links[i];
58
+ preloadedHrefs.all.add(link.href);
59
+ if (link.rel === "stylesheet") preloadedHrefs.styles.add(link.href);
60
+ }
61
+ }
62
+ const preloadedHrefSet = isCss ? preloadedHrefs.styles : preloadedHrefs.all, failedCssLink = isCss ? failedCssLinks[dep.href] : void 0;
63
+ if (!failedCssLink && preloadedHrefSet.has(dep.href)) return;
64
+ const link = document.createElement("link");
65
+ link.rel = isCss ? "stylesheet" : scriptRel;
66
+ if (!isCss) link.as = "script";
67
+ link.crossOrigin = "";
68
+ link.href = dep.href;
69
+ if (cspNonce) link.setAttribute("nonce", cspNonce);
70
+ if (failedCssLink) delete failedCssLinks[dep.href];
71
+ if (failedCssLink?.isConnected) failedCssLink.replaceWith(link);
72
+ else document.head.appendChild(link);
73
+ if (isCss) return new Promise((res, rej) => {
74
+ const handleSettle = (e) => {
75
+ link.removeEventListener("load", handleSettle);
76
+ link.removeEventListener("error", handleSettle);
77
+ if (e.type === "error") {
78
+ failedCssLinks[dep.href] = link;
79
+ rej(Error(`Unable to preload CSS for ${dep}`));
80
+ } else res(e);
81
+ };
82
+ link.addEventListener("load", handleSettle);
83
+ link.addEventListener("error", handleSettle);
84
+ });
85
+ });
86
+ }).filter((p) => p !== void 0));
87
+ }
88
+ function handlePreloadError(err) {
89
+ const e = new Event("vite:preloadError", { cancelable: !0 });
90
+ e.payload = err;
91
+ window.dispatchEvent(e);
92
+ if (!e.defaultPrevented) throw err;
93
+ }
94
+ return promise.then((res) => {
95
+ for (const item of res || []) {
96
+ if (item.status !== "rejected") continue;
97
+ handlePreloadError(item.reason);
98
+ }
99
+ return baseModule().catch(handlePreloadError);
100
+ });
101
+ };
102
+ export { __vitePreload };
@@ -0,0 +1,60 @@
1
+ import type { WorkerdModuleSpec } from "./capnp.js";
2
+ /**
3
+ * ============================================================================
4
+ * Cloud Worker 打包器(基于 Vite)
5
+ * ============================================================================
6
+ *
7
+ * 直接复用 Vite(Vite 8 内置 Rolldown)把 Vultro 入口、`convex/` 业务函数与
8
+ * 组件打成 `workerd` 可加载的 ESM + 原生 `.wasm` 模块列表,不再额外依赖 `esbuild`。
9
+ *
10
+ * 为什么不能沿用 Bun / Node 的 `wasmModulePlugin`(base64 + `new WebAssembly.Module`):
11
+ * - `workerd` 安全策略禁止在运行时动态编译 Wasm(`Wasm code generation disallowed`);
12
+ * - 必须把 `.wasm` 作为独立二进制资产输出,保留 `import mod from "./xxx.wasm"`
13
+ * 外部引用,并在 `workerd.capnp` 中声明 `(name = "...", wasm = embed "...")`,
14
+ * 由 `workerd` 在加载阶段预编译。
15
+ */
16
+ /** `bundleCloudWorker` 的输入选项。 */
17
+ export interface BundleCloudWorkerOptions {
18
+ /** 项目根目录。 */
19
+ rootDir: string;
20
+ /** 打包输出目录(`worker.mjs` 与 `.wasm` 资源写到这里)。 */
21
+ outDir: string;
22
+ /** `.capnp` 文件所在目录,用于计算 `embedPath` 相对路径;默认等于 `outDir`。 */
23
+ capnpDir?: string;
24
+ /** 入口文件路径;与 `entryCode` 二选一。 */
25
+ entryFile?: string;
26
+ /** 内存中的入口源码;与 `entryFile` 二选一。 */
27
+ entryCode?: string;
28
+ /** 使用 `entryCode` 时的模块解析基准目录,默认 `rootDir`。 */
29
+ resolveDir?: string;
30
+ /** 额外保持 external 的模块匹配。 */
31
+ external?: string[];
32
+ /** 额外 `node_modules` 搜索路径(用于入口位于独立临时目录时解析依赖)。 */
33
+ nodePaths?: string[];
34
+ /** 输出主入口文件名,默认 `"worker.mjs"`。 */
35
+ entryFileName?: string;
36
+ /** 是否开启代码压缩,默认 `false`(开发与排障更清晰)。 */
37
+ minify?: boolean;
38
+ /** 是否生成 sourcemap,默认 `true`。 */
39
+ sourcemap?: boolean;
40
+ /** 每次构建前是否清空 `outDir`,默认 `true`(避免残留过期 `.wasm` hash 文件)。 */
41
+ cleanOutDir?: boolean;
42
+ /** Vite 构建日志级别,默认 `"silent"`。 */
43
+ logLevel?: "info" | "warn" | "error" | "silent";
44
+ }
45
+ /** `bundleCloudWorker` 的输出产物描述。 */
46
+ export interface BundleCloudWorkerResult {
47
+ /** 主 Worker 文件绝对路径(`outDir/worker.mjs`)。 */
48
+ entryPath: string;
49
+ /** 可直接传给 `buildVultroCapnpConfig({ modules })` 的模块清单。 */
50
+ modules: WorkerdModuleSpec[];
51
+ /** 提取出的所有 `.wasm` 文件绝对路径。 */
52
+ wasmFiles: string[];
53
+ /** 构建耗时(毫秒)。 */
54
+ durationMs: number;
55
+ }
56
+ /**
57
+ * 使用 Vite 把 Cloud Worker 入口及其依赖打包到 `outDir`,
58
+ * 返回 `workerd.capnp` 所需的模块清单。
59
+ */
60
+ export declare function bundleCloudWorker(options: BundleCloudWorkerOptions): Promise<BundleCloudWorkerResult>;
package/dist/bundle.js ADDED
@@ -0,0 +1,241 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync } from "node:fs";
3
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { __vitePreload } from "./_virtual/_vite/preload-helper.js";
6
+ // src/bundle.ts
7
+ var VIRTUAL_ASSET_PREFIX = "\0vultro-cloud-asset:";
8
+ var TEXT_ASSET_EXTENSIONS = /* @__PURE__ */ new Set([
9
+ ".txt",
10
+ ".html",
11
+ ".sql"
12
+ ]);
13
+ /**
14
+ * 使用 Vite 把 Cloud Worker 入口及其依赖打包到 `outDir`,
15
+ * 返回 `workerd.capnp` 所需的模块清单。
16
+ */
17
+ async function bundleCloudWorker(options) {
18
+ if (!options.entryFile && options.entryCode === void 0) throw new Error("bundleCloudWorker 需要提供 entryFile 或 entryCode。");
19
+ let viteBuild;
20
+ try {
21
+ ({build: viteBuild} = await __vitePreload(() => import("vite"), []));
22
+ } catch (error) {
23
+ throw new Error(`bundleCloudWorker 需要 Vite,请确认已安装 vite 依赖:${error instanceof Error ? error.message : String(error)}`);
24
+ }
25
+ const startedAt = Date.now();
26
+ const rootDir = resolve(options.rootDir);
27
+ const outDir = resolve(options.outDir);
28
+ const capnpDir = resolve(options.capnpDir ?? outDir);
29
+ const resolveDir = resolve(options.resolveDir ?? rootDir);
30
+ if (options.cleanOutDir !== false && existsSync(outDir)) {
31
+ const lexicalOutDir = resolve(outDir);
32
+ const canonicalOutDir = canonicalPath(outDir);
33
+ const entryPathAbs = options.entryFile ? resolve(rootDir, options.entryFile) : void 0;
34
+ const protectedDirs = [
35
+ rootDir,
36
+ resolveDir,
37
+ ...entryPathAbs ? [dirname(entryPathAbs), entryPathAbs] : []
38
+ ];
39
+ for (const protectedDir of protectedDirs) for (const protectedVariant of [resolve(protectedDir), canonicalPath(protectedDir)]) for (const outDirVariant of [lexicalOutDir, canonicalOutDir]) if (isSameOrParentDir(outDirVariant, protectedVariant)) throw new Error(`bundleCloudWorker 拒绝清空 outDir(${outDir}),因为它包含或等于受保护目录(${protectedDir})。`);
40
+ rmSync(outDir, {
41
+ recursive: true,
42
+ force: true
43
+ });
44
+ }
45
+ mkdirSync(outDir, { recursive: true });
46
+ const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
47
+ const fallbackNodeModules = join(packageRoot, "node_modules");
48
+ const moduleFile = fileURLToPath(import.meta.url);
49
+ const workerEntryAbs = join(dirname(moduleFile), `worker${extname(moduleFile)}`);
50
+ const nodePaths = [...options.nodePaths ?? [], fallbackNodeModules];
51
+ const entryFileName = options.entryFileName ?? "worker.mjs";
52
+ const wasmImportPrefix = entryFileName.includes("/") ? `${toPosix(relative(dirname(entryFileName), "."))}/` : "./";
53
+ const entryTarget = options.entryFile ? resolve(rootDir, options.entryFile) : join(resolveDir, "__vultro_cloud_entry__.ts");
54
+ const isVirtualEntry = !options.entryFile;
55
+ const externalMatchers = [
56
+ /^node:/,
57
+ /^cloudflare:/,
58
+ /^workerd:/,
59
+ ...(options.external ?? []).map(toExternalMatcher)
60
+ ];
61
+ const wasmAssets = /* @__PURE__ */ new Map();
62
+ const inlineAssets = /* @__PURE__ */ new Map();
63
+ let nextInlineAssetId = 0;
64
+ const rawOutput = await viteBuild({
65
+ configFile: false,
66
+ root: rootDir,
67
+ logLevel: options.logLevel ?? "silent",
68
+ plugins: [{
69
+ name: "vultro:cloud-worker",
70
+ enforce: "pre",
71
+ async resolveId(source, importer) {
72
+ if (isVirtualEntry && source === entryTarget) return entryTarget;
73
+ const [cleanSource, query] = splitQuery(source);
74
+ if (cleanSource.endsWith(".wasm") && !query) {
75
+ const resolved = await resolveWithFallback(source, importer, nodePaths, (src, imp) => this.resolve(src, imp, { skipSelf: true }));
76
+ if (!resolved?.id) return null;
77
+ const absPath = splitQuery(resolved.id)[0];
78
+ let asset = wasmAssets.get(absPath);
79
+ if (!asset) {
80
+ const bytes = readFileSync(absPath);
81
+ const hash = createHash("sha256").update(bytes).digest("hex").slice(0, 8);
82
+ asset = {
83
+ fileName: `${basename(absPath, ".wasm")}-${hash}.wasm`,
84
+ bytes
85
+ };
86
+ wasmAssets.set(absPath, asset);
87
+ }
88
+ return {
89
+ id: `${wasmImportPrefix}${asset.fileName}`,
90
+ external: true
91
+ };
92
+ }
93
+ const ext = extensionOf(cleanSource);
94
+ if (!query && (TEXT_ASSET_EXTENSIONS.has(ext) || ext === ".bin")) {
95
+ const resolved = await resolveWithFallback(source, importer, nodePaths, (src, imp) => this.resolve(src, imp, { skipSelf: true }));
96
+ if (!resolved?.id) return null;
97
+ const absPath = splitQuery(resolved.id)[0];
98
+ const virtualId = `${VIRTUAL_ASSET_PREFIX}${nextInlineAssetId++}.mjs`;
99
+ inlineAssets.set(virtualId, absPath);
100
+ return virtualId;
101
+ }
102
+ if (isBareSpecifier(cleanSource) && !matchesExternal(cleanSource, externalMatchers)) {
103
+ const direct = await this.resolve(source, importer, { skipSelf: true });
104
+ if (direct) return direct;
105
+ return await resolveInNodePaths(source, nodePaths, (src, imp) => this.resolve(src, imp, { skipSelf: true }));
106
+ }
107
+ return null;
108
+ },
109
+ load(id) {
110
+ if (isVirtualEntry && id === entryTarget) return options.entryCode ?? "";
111
+ const filePath = inlineAssets.get(id);
112
+ if (filePath) {
113
+ this.addWatchFile(filePath);
114
+ if (extensionOf(filePath) === ".bin") {
115
+ const base64 = readFileSync(filePath).toString("base64");
116
+ return [`const bytes = Uint8Array.from(atob(${JSON.stringify(base64)}), (c) => c.charCodeAt(0));`, "export default bytes;"].join("\n");
117
+ }
118
+ return `export default ${JSON.stringify(readFileSync(filePath, "utf8"))};`;
119
+ }
120
+ return null;
121
+ },
122
+ generateBundle() {
123
+ for (const { fileName, bytes } of wasmAssets.values()) this.emitFile({
124
+ type: "asset",
125
+ fileName,
126
+ source: bytes
127
+ });
128
+ }
129
+ }],
130
+ resolve: { alias: { "@vultro/runtime-cloud/worker": workerEntryAbs } },
131
+ define: { "process.env.NODE_ENV": JSON.stringify(options.minify ? "production" : "development") },
132
+ ssr: {
133
+ target: "webworker",
134
+ noExternal: true,
135
+ resolve: {
136
+ conditions: [
137
+ "workerd",
138
+ "worker",
139
+ "browser"
140
+ ],
141
+ mainFields: [
142
+ "browser",
143
+ "module",
144
+ "main"
145
+ ]
146
+ }
147
+ },
148
+ build: {
149
+ ssr: entryTarget,
150
+ ssrEmitAssets: true,
151
+ outDir,
152
+ emptyOutDir: false,
153
+ target: "esnext",
154
+ minify: options.minify ?? false,
155
+ sourcemap: options.sourcemap ?? true,
156
+ rollupOptions: {
157
+ external: externalMatchers,
158
+ output: {
159
+ format: "esm",
160
+ entryFileNames: entryFileName
161
+ }
162
+ }
163
+ }
164
+ });
165
+ const outputs = (Array.isArray(rawOutput) ? rawOutput : [rawOutput]).flatMap((item) => "output" in item ? item.output : []);
166
+ const emittedChunks = outputs.filter((item) => item.type === "chunk");
167
+ const entryChunk = emittedChunks.find((item) => item.isEntry) ?? emittedChunks.find((item) => item.fileName === entryFileName);
168
+ if (!entryChunk) throw new Error(`bundleCloudWorker 未能在构建产物中找到入口 chunk(${entryFileName})。`);
169
+ const entryPath = join(outDir, entryChunk.fileName);
170
+ const orderedChunks = [entryPath, ...emittedChunks.filter((item) => /\.(?:m?js|cjs)$/.test(item.fileName)).map((item) => join(outDir, item.fileName)).filter((file) => file !== entryPath)];
171
+ const wasmFiles = outputs.filter((item) => item.type === "asset" && item.fileName.endsWith(".wasm")).map((item) => join(outDir, item.fileName));
172
+ return {
173
+ entryPath,
174
+ modules: [...orderedChunks.map((chunkPath) => ({
175
+ name: toPosix(relative(outDir, chunkPath)),
176
+ type: "esModule",
177
+ embedPath: toCapnpEmbedPath(capnpDir, chunkPath)
178
+ })), ...wasmFiles.map((wasmPath) => ({
179
+ name: toPosix(relative(outDir, wasmPath)),
180
+ type: "wasm",
181
+ embedPath: toCapnpEmbedPath(capnpDir, wasmPath)
182
+ }))],
183
+ wasmFiles,
184
+ durationMs: Date.now() - startedAt
185
+ };
186
+ }
187
+ async function resolveWithFallback(source, importer, nodePaths, resolver) {
188
+ const direct = await resolver(source, importer);
189
+ if (direct) return direct;
190
+ if (!isBareSpecifier(splitQuery(source)[0])) return null;
191
+ return await resolveInNodePaths(source, nodePaths, resolver);
192
+ }
193
+ async function resolveInNodePaths(source, nodePaths, resolver) {
194
+ for (const nodePath of nodePaths) {
195
+ const resolved = await resolver(source, join(dirname(nodePath), "__vultro_anchor__.js"));
196
+ if (resolved) return resolved;
197
+ }
198
+ return null;
199
+ }
200
+ function splitQuery(id) {
201
+ const idx = id.indexOf("?");
202
+ if (idx === -1) return [id, ""];
203
+ return [id.slice(0, idx), id.slice(idx)];
204
+ }
205
+ function extensionOf(filePath) {
206
+ const name = basename(filePath);
207
+ const dot = name.lastIndexOf(".");
208
+ return dot === -1 ? "" : name.slice(dot).toLowerCase();
209
+ }
210
+ function isBareSpecifier(source) {
211
+ return !source.startsWith(".") && !source.startsWith("/") && !source.startsWith("\0") && !source.includes(":");
212
+ }
213
+ function toExternalMatcher(pattern) {
214
+ if (!pattern.includes("*")) return pattern;
215
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
216
+ return new RegExp(`^${escaped}$`);
217
+ }
218
+ function matchesExternal(id, matchers) {
219
+ return matchers.some((matcher) => typeof matcher === "string" ? id === matcher || id.startsWith(`${matcher}/`) : matcher.test(id));
220
+ }
221
+ function canonicalPath(targetPath) {
222
+ try {
223
+ return existsSync(targetPath) ? realpathSync(targetPath) : resolve(targetPath);
224
+ } catch {
225
+ return resolve(targetPath);
226
+ }
227
+ }
228
+ function isSameOrParentDir(candidate, target) {
229
+ const rel = relative(candidate, target);
230
+ if (rel === "") return true;
231
+ if (isAbsolute(rel)) return false;
232
+ return rel !== ".." && !rel.startsWith(`..${sep}`);
233
+ }
234
+ function toPosix(value) {
235
+ return value.split(sep).join("/");
236
+ }
237
+ function toCapnpEmbedPath(fromDir, targetFile) {
238
+ const rel = toPosix(relative(fromDir, targetFile));
239
+ return rel.startsWith(".") ? rel : `./${rel}`;
240
+ }
241
+ export { bundleCloudWorker };
@@ -0,0 +1,53 @@
1
+ /**
2
+ * ============================================================================
3
+ * workerd 极简 Cap'n Proto 配置生成
4
+ * ============================================================================
5
+ *
6
+ * 绕开 `wrangler.json` 与 `@cloudflare/vite-plugin` 的整套重量级包装,
7
+ * 直接为 Vultro Worker + Durable Objects(`VultroDO` / `VultroSyncDO`)
8
+ * 生成 `workerd` 原生 `.capnp` 配置文件。
9
+ */
10
+ /** Worker 模块定义(ESM 主文件或伴随的原生 `.wasm` 资产)。 */
11
+ export interface WorkerdModuleSpec {
12
+ /** 模块引用名(相对输出目录,例如 `"worker.mjs"` 或 `"argon2-xxx.wasm"`)。 */
13
+ name: string;
14
+ /** 模块类型;`workerd` 禁止运行时动态编译 Wasm,`.wasm` 必须用 `"wasm"` 预编译嵌入。 */
15
+ type: "esModule" | "wasm" | "text" | "json" | "data";
16
+ /** 文件路径(生成 `embed "<path>"`)。 */
17
+ embedPath: string;
18
+ }
19
+ /** 构造 Vultro `workerd.capnp` 的精简选项。 */
20
+ export interface WorkerdCapnpOptions {
21
+ /** 部署名(用作 DO `uniqueKey` 前缀与 R2 桶标识),默认 `"vultro"`。 */
22
+ name?: string;
23
+ /** 打包后的模块清单(至少包含主入口 `worker.mjs`)。 */
24
+ modules: WorkerdModuleSpec[];
25
+ /** workerd compatibilityDate,默认 `"2026-11-29"`。 */
26
+ compatibilityDate?: string;
27
+ /** 额外 compatibilityFlags;`compatibilityDate < "2026-08-04"` 时默认包含 `"nodejs_compat"`。 */
28
+ compatibilityFlags?: string[];
29
+ /** HTTP 监听地址,默认 `"127.0.0.1:0"`(由 `--control-fd` 分配随机可用端口)。 */
30
+ listenAddress?: string;
31
+ /** DO SQLite 本地磁盘目录;省略或传 `"inMemory"` 时仅存内存。 */
32
+ doStorageDir?: string | "inMemory";
33
+ /**
34
+ * 启用本地 R2(`workerd` 内置 `ClusterBucket` + `/workerd/r2.js`)。
35
+ * 传字符串表示本地磁盘目录;传 `false` 关闭(文件字节仅存 DO SQLite)。
36
+ */
37
+ r2Dir?: string | false;
38
+ /** 静态资源目录(生产构建由 `workerd` 内置 `AssetsService` 直接托管 SPA)。 */
39
+ assets?: {
40
+ dir: string;
41
+ runWorkerFirst?: string[];
42
+ };
43
+ /** 注入给 Worker `env` 的文本环境变量(如 `VULTRO_TRUST_LOCALHOST`)。 */
44
+ vars?: Record<string, string>;
45
+ /** 从宿主环境变量透传给 Worker `env` 的变量名(如 `VULTRO_ADMIN_TOKEN`)。 */
46
+ fromEnvironment?: string[];
47
+ }
48
+ /** Cap'n Proto 双引号字符串转义。 */
49
+ export declare function escapeCapnpText(value: string): string;
50
+ /**
51
+ * 渲染极简 `workerd.capnp` 配置文本。
52
+ */
53
+ export declare function renderWorkerdCapnp(options: WorkerdCapnpOptions): string;
package/dist/capnp.js ADDED
@@ -0,0 +1,81 @@
1
+ // src/capnp.ts
2
+ /** Cap'n Proto 双引号字符串转义。 */
3
+ function escapeCapnpText(value) {
4
+ return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
5
+ }
6
+ function capnpStr(value) {
7
+ return `"${escapeCapnpText(value)}"`;
8
+ }
9
+ /**
10
+ * 渲染极简 `workerd.capnp` 配置文本。
11
+ */
12
+ function renderWorkerdCapnp(options) {
13
+ if (options.modules.length === 0) throw new Error("renderWorkerdCapnp 至少需要一个 Worker 模块。");
14
+ const firstModule = options.modules[0];
15
+ if (!firstModule) throw new Error("renderWorkerdCapnp 至少需要一个 Worker 模块。");
16
+ if (firstModule.type !== "esModule") throw new Error("renderWorkerdCapnp 要求 modules[0] 必须是 Worker 入口(esModule 类型)。");
17
+ const name = options.name ?? "vultro";
18
+ const compatDate = options.compatibilityDate ?? "2026-11-29";
19
+ const builtinNodejsCompat = compatDate >= "2026-08-04";
20
+ const userFlags = (options.compatibilityFlags ?? []).filter((flag) => !builtinNodejsCompat || flag !== "nodejs_compat" && flag !== "nodejs_compat_v2");
21
+ const compatFlags = [...builtinNodejsCompat ? [] : ["nodejs_compat"], ...userFlags];
22
+ const uniqueCompatFlags = [...new Set(compatFlags)];
23
+ const listenAddress = options.listenAddress ?? "127.0.0.1:0";
24
+ const useMemoryDo = !options.doStorageDir || options.doStorageDir === "inMemory";
25
+ const useR2 = typeof options.r2Dir === "string" && options.r2Dir.length > 0;
26
+ const reservedBindings = /* @__PURE__ */ new Set(["VULTRO_DO", "VULTRO_SYNC_DO"]);
27
+ if (useR2) reservedBindings.add("VULTRO_R2");
28
+ const bindings = [`(name = "VULTRO_DO", durableObjectNamespace = "VultroDO")`, `(name = "VULTRO_SYNC_DO", durableObjectNamespace = "VultroSyncDO")`];
29
+ if (useR2) bindings.push(`(name = "VULTRO_R2", r2Bucket = (name = "r2-worker", props = (json = ${capnpStr(JSON.stringify({ bucket: `${name}-blobs` }))})))`);
30
+ for (const [key, value] of Object.entries(options.vars ?? {})) {
31
+ if (reservedBindings.has(key)) throw new Error(`vars 不能使用保留绑定名 "${key}"。`);
32
+ bindings.push(`(name = ${capnpStr(key)}, text = ${capnpStr(value)})`);
33
+ }
34
+ for (const envVar of options.fromEnvironment ?? []) {
35
+ if (reservedBindings.has(envVar)) throw new Error(`fromEnvironment 不能使用保留绑定名 "${envVar}"。`);
36
+ bindings.push(`(name = ${capnpStr(envVar)}, fromEnvironment = ${capnpStr(envVar)})`);
37
+ }
38
+ const modulesCapnp = options.modules.map((mod) => ` (name = ${capnpStr(mod.name)}, ${mod.type} = embed ${capnpStr(mod.embedPath)}),`).join("\n");
39
+ const extraServices = [];
40
+ if (!useMemoryDo) extraServices.push(` (name = "do-storage", disk = (path = ${capnpStr(options.doStorageDir)}, writable = true)),`);
41
+ if (useR2) extraServices.push(` (name = "blob-disk", disk = (path = ${capnpStr(options.r2Dir)}, writable = true)),`, ` (name = "r2-bucket", bucket = (path = ${capnpStr(`${name}/r2`)}, localDisk = "blob-disk")),`, ` (name = "r2-worker", worker = (`, ` modules = [(name = "r2", bundled = "/workerd/r2.js")],`, ` compatibilityDate = ${capnpStr(compatDate)},`, ` bindings = [(name = "BLOBS", service = "r2-bucket")],`, ` )),`);
42
+ let entryService = "main";
43
+ if (options.assets) {
44
+ const assetsConfig = JSON.stringify({
45
+ html_handling: "auto-trailing-slash",
46
+ not_found_handling: "single-page-application",
47
+ ...options.assets.runWorkerFirst ? { run_worker_first: options.assets.runWorkerFirst } : {}
48
+ });
49
+ extraServices.push(` (name = "assets", assets = (`, ` path = ${capnpStr(options.assets.dir)},`, ` config = ${capnpStr(assetsConfig)},`, ` userWorker = "main",`, ` )),`);
50
+ entryService = "assets";
51
+ }
52
+ const doStorageLine = useMemoryDo ? ` durableObjectStorage = (inMemory = void),` : ` durableObjectStorage = (localDisk = "do-storage"),`;
53
+ return [
54
+ "# 由 @vultro/runtime-cloud 自动生成",
55
+ "using Workerd = import \"/workerd/workerd.capnp\";",
56
+ "",
57
+ "const config :Workerd.Config = (",
58
+ " services = [",
59
+ " (name = \"main\", worker = (",
60
+ " modules = [",
61
+ modulesCapnp,
62
+ " ],",
63
+ ` compatibilityDate = ${capnpStr(compatDate)},`,
64
+ ...uniqueCompatFlags.length > 0 ? [` compatibilityFlags = [${uniqueCompatFlags.map(capnpStr).join(", ")}],`] : [],
65
+ " bindings = [",
66
+ ...bindings.map((line) => ` ${line},`),
67
+ " ],",
68
+ " durableObjectNamespaces = [",
69
+ ` (className = "VultroDO", uniqueKey = ${capnpStr(`${name}-VultroDO`)}, enableSql = true),`,
70
+ ` (className = "VultroSyncDO", uniqueKey = ${capnpStr(`${name}-VultroSyncDO`)}, enableSql = true),`,
71
+ " ],",
72
+ doStorageLine,
73
+ " )),",
74
+ ...extraServices,
75
+ " ],",
76
+ ` sockets = [(name = "http", address = ${capnpStr(listenAddress)}, http = (), service = ${capnpStr(entryService)})],`,
77
+ ");",
78
+ ""
79
+ ].join("\n");
80
+ }
81
+ export { escapeCapnpText, renderWorkerdCapnp };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * ============================================================================
3
+ * @vultro/runtime-cloud
4
+ * ============================================================================
5
+ *
6
+ * 基于 `cloudflare/workerd` 的极简自托管 Cloud 运行时(类似 `@cloudflare/vite-plugin`
7
+ * 的轻量替代,无 Miniflare / Wrangler 依赖)。
8
+ *
9
+ * 只包含三部分:
10
+ * 1. `bundleCloudWorker`:直接用 Vite 打出 `worker.mjs` 与原生 `.wasm` 资产;
11
+ * 2. `renderWorkerdCapnp`:生成最小 `workerd.capnp`(DO SQLite、R2 桶、静态资源);
12
+ * 3. `startWorkerd`:启动并托管 `workerd` 子进程(支持通过 `VULTRO_WORKERD_BIN`
13
+ * 或参数切换成自定义二次开发的 `workerd` 二进制)。
14
+ *
15
+ * 运行在 `workerd` 内部的代码请导入 `@vultro/runtime-cloud/worker`。
16
+ */
17
+ export { escapeCapnpText, renderWorkerdCapnp, type WorkerdCapnpOptions, type WorkerdModuleSpec, } from "./capnp.js";
18
+ export { bundleCloudWorker, type BundleCloudWorkerOptions, type BundleCloudWorkerResult, } from "./bundle.js";
19
+ export { resolveWorkerdBinary, startWorkerd, type StartWorkerdOptions, type WorkerdInstance, } from "./workerd.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ import { escapeCapnpText, renderWorkerdCapnp } from "./capnp.js";
2
+ import { bundleCloudWorker } from "./bundle.js";
3
+ import { resolveWorkerdBinary, startWorkerd } from "./workerd.js";
4
+ export { bundleCloudWorker, escapeCapnpText, renderWorkerdCapnp, resolveWorkerdBinary, startWorkerd };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * ============================================================================
3
+ * @vultro/runtime-cloud/worker
4
+ * ============================================================================
5
+ *
6
+ * 运行在 `workerd` 沙箱内部的极简 Vultro Worker 入口。
7
+ *
8
+ * 复用 `@vultro/runtime-cf` 的 `VultroDO` / `VultroSyncDO` 与路由分发,
9
+ * 不包含任何 Node / 宿主侧打包或进程依赖,确保 Vite 打进 `workerd` 时
10
+ * 产物体积最小、结构清晰。
11
+ */
12
+ export { createRuntime, createRuntimeWorker, defineWorker, type DefineWorkerOptions, type RuntimeEnv, type WorkerComposition, } from "@vultro/runtime-cf";
package/dist/worker.js ADDED
@@ -0,0 +1 @@
1
+ export { createRuntime, createRuntimeWorker, defineWorker } from "@vultro/runtime-cf";
@@ -0,0 +1,43 @@
1
+ import { type WorkerdCapnpOptions } from "./capnp.js";
2
+ /**
3
+ * ============================================================================
4
+ * workerd 进程启动与二进制解析
5
+ * ============================================================================
6
+ */
7
+ /** 启动 `workerd` 的选项。 */
8
+ export interface StartWorkerdOptions {
9
+ /** 写入 `workerd.capnp` 的路径。 */
10
+ capnpPath: string;
11
+ /** Cap'n Proto 配置选项;提供后会自动渲染并写入 `capnpPath`。 */
12
+ capnp?: WorkerdCapnpOptions;
13
+ /** 可选自定义 `workerd` 二进制路径(默认解析 `VULTRO_WORKERD_BIN` 或内置 `workerd`)。 */
14
+ binaryPath?: string;
15
+ /** 子进程工作目录,默认 `.capnp` 所在目录。 */
16
+ cwd?: string;
17
+ /** 附加环境变量。 */
18
+ env?: Record<string, string>;
19
+ /** 启动超时(毫秒),默认 15000。 */
20
+ startupTimeoutMs?: number;
21
+ /** 日志回调(默认静默,避免测试输出噪音)。 */
22
+ onLog?: (stream: "stdout" | "stderr", line: string) => void;
23
+ }
24
+ /** 运行中的 `workerd` 实例句柄。 */
25
+ export interface WorkerdInstance {
26
+ readonly port: number;
27
+ readonly url: string;
28
+ readonly pid: number;
29
+ readonly capnpPath: string;
30
+ readonly binaryPath: string;
31
+ readonly exited: Promise<number | null>;
32
+ stop(): Promise<void>;
33
+ }
34
+ /**
35
+ * 解析 `workerd` 可执行文件路径。
36
+ *
37
+ * 顺序:显式 `binaryPath` → `VULTRO_WORKERD_BIN` → npm 包 `workerd` → `PATH`。
38
+ */
39
+ export declare function resolveWorkerdBinary(binaryPath?: string, cwd?: string): string;
40
+ /**
41
+ * 启动 `workerd serve`,通过 `--control-fd=3` 获取真实监听端口后返回句柄。
42
+ */
43
+ export declare function startWorkerd(options: StartWorkerdOptions): Promise<WorkerdInstance>;
@@ -0,0 +1,332 @@
1
+ import { spawn } from "node:child_process";
2
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { connect, createServer } from "node:net";
5
+ import { delimiter, dirname, join, resolve } from "node:path";
6
+ import { renderWorkerdCapnp } from "./capnp.js";
7
+ // src/workerd.ts
8
+ /**
9
+ * 解析 `workerd` 可执行文件路径。
10
+ *
11
+ * 顺序:显式 `binaryPath` → `VULTRO_WORKERD_BIN` → npm 包 `workerd` → `PATH`。
12
+ */
13
+ function resolveWorkerdBinary(binaryPath, cwd = process.cwd()) {
14
+ const baseDir = resolve(cwd);
15
+ if (binaryPath) {
16
+ const resolved = resolve(baseDir, binaryPath);
17
+ if (!existsSync(resolved)) throw new Error(`指定的 workerd 二进制不存在:${resolved}`);
18
+ return resolved;
19
+ }
20
+ const envBin = {}.VULTRO_WORKERD_BIN?.trim();
21
+ if (envBin) {
22
+ const resolved = resolve(baseDir, envBin);
23
+ if (!existsSync(resolved)) throw new Error(`VULTRO_WORKERD_BIN 指向的文件不存在:${resolved}`);
24
+ return resolved;
25
+ }
26
+ for (const anchor of [join(baseDir, "package.json"), import.meta.url]) try {
27
+ const loaded = createRequire(anchor)("workerd");
28
+ const bin = typeof loaded === "string" ? loaded : loaded?.default;
29
+ if (bin && existsSync(bin)) return bin;
30
+ } catch {}
31
+ const exe = process.platform === "win32" ? "workerd.exe" : "workerd";
32
+ for (const dir of ({}.PATH ?? "").split(delimiter)) {
33
+ if (!dir) continue;
34
+ const candidate = resolve(dir, exe);
35
+ try {
36
+ if (!statSync(candidate).isFile()) continue;
37
+ accessSync(candidate, constants.X_OK);
38
+ return candidate;
39
+ } catch {
40
+ continue;
41
+ }
42
+ }
43
+ throw new Error("未找到 workerd 可执行文件;请确认已安装 workerd 依赖或设置 VULTRO_WORKERD_BIN。");
44
+ }
45
+ /**
46
+ * 启动 `workerd serve`,通过 `--control-fd=3` 获取真实监听端口后返回句柄。
47
+ */
48
+ async function startWorkerd(options) {
49
+ const capnpPath = resolve(options.capnpPath);
50
+ const binaryPath = resolveWorkerdBinary(options.binaryPath, options.cwd);
51
+ const useControlFd = process.platform !== "win32";
52
+ let effectiveCapnp = options.capnp;
53
+ let explicitHost = "127.0.0.1";
54
+ let explicitPort;
55
+ if (!useControlFd) {
56
+ if (effectiveCapnp) {
57
+ explicitHost = extractHost(effectiveCapnp.listenAddress) ?? "127.0.0.1";
58
+ explicitPort = inferPort(effectiveCapnp.listenAddress);
59
+ if (!explicitPort) {
60
+ explicitPort = await allocateFreePort(explicitHost);
61
+ effectiveCapnp = {
62
+ ...effectiveCapnp,
63
+ listenAddress: `${explicitHost}:${explicitPort}`
64
+ };
65
+ }
66
+ } else {
67
+ const fromFile = inferAddressFromCapnpFile(capnpPath);
68
+ if (!fromFile?.port) throw new Error("当前平台不支持 --control-fd;使用已有 workerd.capnp 时请显式配置非 0 监听端口,或通过 capnp 选项传入配置。");
69
+ explicitHost = fromFile.host ?? "127.0.0.1";
70
+ explicitPort = fromFile.port;
71
+ }
72
+ }
73
+ if (effectiveCapnp) {
74
+ mkdirSync(dirname(capnpPath), { recursive: true });
75
+ writeFileSync(capnpPath, renderWorkerdCapnp(effectiveCapnp), "utf8");
76
+ }
77
+ const args = [
78
+ "serve",
79
+ "--experimental",
80
+ ...useControlFd ? ["--control-fd=3"] : [],
81
+ capnpPath,
82
+ "config"
83
+ ];
84
+ const proc = spawn(binaryPath, args, {
85
+ cwd: options.cwd ?? dirname(capnpPath),
86
+ stdio: useControlFd ? [
87
+ "ignore",
88
+ "pipe",
89
+ "pipe",
90
+ "pipe"
91
+ ] : [
92
+ "ignore",
93
+ "pipe",
94
+ "pipe"
95
+ ],
96
+ env: { ...options.env ?? {} }
97
+ });
98
+ const stderrLines = [];
99
+ const pushStderrLine = (line) => {
100
+ if (!line) return;
101
+ stderrLines.push(line);
102
+ if (stderrLines.length > 30) stderrLines.shift();
103
+ };
104
+ proc.on("error", (error) => {
105
+ const message = formatProcessError(error, binaryPath);
106
+ pushStderrLine(message);
107
+ options.onLog?.("stderr", message);
108
+ });
109
+ const pipeLogs = (stream, readable) => {
110
+ if (!readable) return;
111
+ let buf = "";
112
+ readable.on("data", (chunk) => {
113
+ buf += chunk.toString("utf8");
114
+ let nl = buf.indexOf("\n");
115
+ while (nl !== -1) {
116
+ const line = buf.slice(0, nl).replace(/\r$/, "");
117
+ buf = buf.slice(nl + 1);
118
+ if (stream === "stderr") pushStderrLine(line);
119
+ options.onLog?.(stream, line);
120
+ nl = buf.indexOf("\n");
121
+ }
122
+ });
123
+ };
124
+ pipeLogs("stdout", proc.stdout);
125
+ pipeLogs("stderr", proc.stderr);
126
+ const exited = new Promise((resolveExit) => {
127
+ proc.once("exit", (code) => resolveExit(code));
128
+ });
129
+ const timeoutMs = options.startupTimeoutMs ?? 15e3;
130
+ let port;
131
+ try {
132
+ if (useControlFd && proc.stdio[3]) port = await waitControlListen(proc.stdio[3], proc, timeoutMs, stderrLines);
133
+ else {
134
+ port = explicitPort;
135
+ await waitTcpListen(explicitHost, port, proc, timeoutMs, stderrLines, binaryPath);
136
+ }
137
+ } catch (error) {
138
+ try {
139
+ await killProc(proc);
140
+ } catch {}
141
+ throw error;
142
+ }
143
+ const listenHost = (effectiveCapnp ? extractHost(effectiveCapnp.listenAddress) : void 0) ?? explicitHost;
144
+ let stopPromise;
145
+ const exitHook = () => {
146
+ try {
147
+ proc.kill("SIGKILL");
148
+ } catch {}
149
+ };
150
+ process.once("exit", exitHook);
151
+ proc.once("exit", () => process.off("exit", exitHook));
152
+ return {
153
+ port,
154
+ url: `http://${formatUrlHost(listenHost)}:${port}`,
155
+ pid: proc.pid ?? 0,
156
+ capnpPath,
157
+ binaryPath,
158
+ exited,
159
+ async stop() {
160
+ if (!stopPromise) stopPromise = killProc(proc);
161
+ await stopPromise;
162
+ }
163
+ };
164
+ }
165
+ function inferPort(address) {
166
+ if (!address) return void 0;
167
+ const match = /:(\d+)$/.exec(address);
168
+ if (!match?.[1]) return void 0;
169
+ const num = Number(match[1]);
170
+ return num > 0 ? num : void 0;
171
+ }
172
+ function extractHost(address) {
173
+ if (!address) return void 0;
174
+ return /^(.*):(\d+)$/.exec(address)?.[1] || void 0;
175
+ }
176
+ /** 把监听 host 转成可访问的 URL host:IPv6 加方括号,通配监听回退回环。 */
177
+ function formatUrlHost(host) {
178
+ const value = host?.trim();
179
+ if (!value) return "127.0.0.1";
180
+ if (value === "0.0.0.0" || value === "::") return "127.0.0.1";
181
+ return value.includes(":") ? `[${value}]` : value;
182
+ }
183
+ function inferAddressFromCapnpFile(capnpPath) {
184
+ try {
185
+ const content = readFileSync(capnpPath, "utf8").split("\n").filter((line) => !/^\s*#/.test(line)).join("\n");
186
+ const match = /\baddress\s*=\s*"([^"]+)"/.exec(content);
187
+ if (!match?.[1]) return void 0;
188
+ return {
189
+ host: extractHost(match[1]),
190
+ port: inferPort(match[1])
191
+ };
192
+ } catch {
193
+ return;
194
+ }
195
+ }
196
+ function allocateFreePort(host) {
197
+ return new Promise((resolvePort, rejectPort) => {
198
+ const server = createServer();
199
+ server.unref();
200
+ server.once("error", rejectPort);
201
+ server.listen(0, host, () => {
202
+ const addr = server.address();
203
+ const port = addr && typeof addr === "object" ? addr.port : 0;
204
+ server.close((err) => {
205
+ if (err) rejectPort(err);
206
+ else if (port > 0) resolvePort(port);
207
+ else rejectPort(/* @__PURE__ */ new Error("无法分配可用监听端口"));
208
+ });
209
+ });
210
+ });
211
+ }
212
+ function formatProcessError(error, binaryPath) {
213
+ const code = error.code;
214
+ if (code === "ENOENT") return `workerd 未安装或路径不存在(${binaryPath}):${error.message}`;
215
+ if (code === "EACCES" || code === "EPERM") return `workerd 无执行权限(${binaryPath},${code}):${error.message}`;
216
+ return `workerd 进程错误(${binaryPath}):${error.message}`;
217
+ }
218
+ function waitControlListen(stream, proc, timeoutMs, stderrLines) {
219
+ return new Promise((resolvePort, rejectPort) => {
220
+ let buffer = "";
221
+ let settled = false;
222
+ const finish = (err, port) => {
223
+ if (settled) return;
224
+ settled = true;
225
+ clearTimeout(timer);
226
+ stream.off("data", onData);
227
+ proc.off("exit", onExit);
228
+ proc.off("error", onError);
229
+ if (err) rejectPort(err);
230
+ else resolvePort(port);
231
+ };
232
+ const timer = setTimeout(() => {
233
+ finish(/* @__PURE__ */ new Error(`workerd 启动超时(${timeoutMs}ms)${stderrLines.length ? `:\n${stderrLines.join("\n")}` : ""}`));
234
+ }, timeoutMs);
235
+ const onExit = (code) => {
236
+ finish(/* @__PURE__ */ new Error(`workerd 意外退出(退出码 ${code ?? "unknown"})${stderrLines.length ? `:\n${stderrLines.join("\n")}` : ""}`));
237
+ };
238
+ const onError = (err) => finish(err);
239
+ const onData = (chunk) => {
240
+ buffer += chunk.toString("utf8");
241
+ let nl = buffer.indexOf("\n");
242
+ while (nl !== -1) {
243
+ const line = buffer.slice(0, nl).trim();
244
+ buffer = buffer.slice(nl + 1);
245
+ if (line) try {
246
+ const event = JSON.parse(line);
247
+ if (event.event === "listen" && typeof event.port === "number") {
248
+ finish(void 0, event.port);
249
+ return;
250
+ }
251
+ } catch {}
252
+ nl = buffer.indexOf("\n");
253
+ }
254
+ };
255
+ stream.on("data", onData);
256
+ proc.once("exit", onExit);
257
+ proc.once("error", onError);
258
+ });
259
+ }
260
+ function waitTcpListen(host, port, proc, timeoutMs, stderrLines, binaryPath) {
261
+ const connectHost = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
262
+ return new Promise((resolveReady, rejectReady) => {
263
+ let settled = false;
264
+ let probeTimer;
265
+ let activeSocket;
266
+ const finish = (err) => {
267
+ if (settled) return;
268
+ settled = true;
269
+ clearTimeout(deadline);
270
+ if (probeTimer) clearTimeout(probeTimer);
271
+ activeSocket?.destroy();
272
+ proc.off("exit", onExit);
273
+ proc.off("error", onError);
274
+ if (err) rejectReady(err);
275
+ else resolveReady();
276
+ };
277
+ const deadline = setTimeout(() => {
278
+ finish(/* @__PURE__ */ new Error(`workerd 启动超时(${timeoutMs}ms)${stderrLines.length ? `:\n${stderrLines.join("\n")}` : ""}`));
279
+ }, timeoutMs);
280
+ const onExit = (code) => {
281
+ finish(/* @__PURE__ */ new Error(`workerd 启动失败(退出码 ${code ?? "unknown"})${stderrLines.length ? `:\n${stderrLines.join("\n")}` : ""}`));
282
+ };
283
+ const onError = (error) => {
284
+ finish(new Error(formatProcessError(error, binaryPath)));
285
+ };
286
+ const probe = () => {
287
+ if (settled) return;
288
+ if (proc.exitCode !== null || proc.signalCode !== null) return;
289
+ const socket = connect({
290
+ host: connectHost,
291
+ port
292
+ });
293
+ activeSocket = socket;
294
+ socket.once("connect", () => {
295
+ socket.destroy();
296
+ probeTimer = setTimeout(() => {
297
+ if (settled) return;
298
+ if (proc.exitCode === null && proc.signalCode === null) finish();
299
+ else probeTimer = setTimeout(probe, 50);
300
+ }, 200);
301
+ });
302
+ socket.once("error", () => {
303
+ socket.destroy();
304
+ if (!settled) probeTimer = setTimeout(probe, 50);
305
+ });
306
+ };
307
+ proc.once("exit", onExit);
308
+ proc.once("error", onError);
309
+ probe();
310
+ });
311
+ }
312
+ async function killProc(proc) {
313
+ if (proc.exitCode !== null || proc.signalCode !== null) return;
314
+ if (proc.pid === void 0) return;
315
+ if (!proc.killed) try {
316
+ proc.kill("SIGTERM");
317
+ } catch {
318
+ return;
319
+ }
320
+ const exited = new Promise((resolveExit) => {
321
+ proc.once("exit", () => resolveExit());
322
+ });
323
+ const timedOut = () => new Promise((resolveTimeout) => setTimeout(() => resolveTimeout(false), 3e3));
324
+ if (await Promise.race([exited.then(() => true), timedOut()])) return;
325
+ try {
326
+ proc.kill("SIGKILL");
327
+ } catch {
328
+ return;
329
+ }
330
+ if (!await Promise.race([exited.then(() => true), timedOut()])) throw new Error(`workerd(pid=${proc.pid})在 SIGTERM + SIGKILL 后仍未退出,无法确认端口已释放`);
331
+ }
332
+ export { resolveWorkerdBinary, startWorkerd };
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@vultro/runtime-cloud",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "description": "Self-hosted cloud runtime adapter for @vultro/core built on top of cloudflare/workerd",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./worker": {
13
+ "types": "./dist/worker.d.ts",
14
+ "import": "./dist/worker.js",
15
+ "default": "./dist/worker.js"
16
+ },
17
+ "./capnp": {
18
+ "types": "./dist/capnp.d.ts",
19
+ "import": "./dist/capnp.js",
20
+ "default": "./dist/capnp.js"
21
+ }
22
+ },
23
+ "dependencies": {
24
+ "@vultro/runtime-cf": "0.0.1",
25
+ "workerd": "1.20261129.1"
26
+ },
27
+ "peerDependencies": {
28
+ "vite": "^7.0.0 || ^8.0.0"
29
+ },
30
+ "peerDependenciesMeta": {
31
+ "vite": {
32
+ "optional": true
33
+ }
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "types": "./dist/index.d.ts"
39
+ }