@guren/plugin-cloudflare 0.3.1 → 0.4.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.
@@ -0,0 +1,321 @@
1
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { relative, resolve, sep } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { DEV_ONLY_MODULES, SQL_CLIENT_MODULES, assertOutputDirOutsideRoot, clientManifestJson, importSpecifier, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, stageStaticAssets } from "@guren/core/internal/deploy-build";
5
+ //#region src/build.ts
6
+ /**
7
+ * Assemble a deployable Cloudflare Workers directory (`.cloudflare/`) from a
8
+ * built Guren app: a generated worker entry that statically wires the SSR
9
+ * bundle, static assets for Workers Static Assets, and a one-time
10
+ * `wrangler.jsonc` scaffold. Deploy with `wrangler deploy`.
11
+ */
12
+ async function buildCloudflareOutput(options = {}) {
13
+ const root = resolvePathLike(options.rootDir ?? process.cwd());
14
+ const out = resolvePathLike(options.outputDir ?? resolve(root, ".cloudflare"));
15
+ const appEntry = resolvePathLike(options.appEntry ?? resolve(root, "src/app.ts"));
16
+ const publicDir = resolvePathLike(options.publicDir ?? resolve(root, "public"));
17
+ const ssrDir = resolvePathLike(options.ssrDir ?? resolve(root, ".guren/ssr"));
18
+ const clientEntryKey = options.clientEntryKey ?? "resources/js/app.tsx";
19
+ const ssrEntryKey = options.ssrEntryKey ?? "resources/js/ssr.tsx";
20
+ assertOutputDirOutsideRoot(out, root, "Cloudflare build");
21
+ const packageJson = readPackageJson(root);
22
+ if (!options.skipAppBuild) runAppBuild(root, packageJson.scripts ?? {});
23
+ if (!existsSync(appEntry)) throw new Error(`Cloudflare build: app entry not found at ${appEntry}. Pass "appEntry" if your Application lives elsewhere.`);
24
+ const ssrImport = await resolveSsrImport(ssrDir, ssrEntryKey);
25
+ const assetEnv = resolveClientAssetEnv(publicDir, clientEntryKey, "Cloudflare build");
26
+ const viteManifest = clientManifestJson(publicDir);
27
+ resetOutputDir(out, root, "Cloudflare build");
28
+ stageStaticAssets(publicDir, resolve(out, "assets"));
29
+ const workerEnv = renderWorkerEnvModule({
30
+ assetEnv,
31
+ viteManifest
32
+ });
33
+ if (workerEnv) writeFileSync(resolve(out, "worker-env.js"), workerEnv);
34
+ writeFileSync(resolve(out, "worker.js"), renderWorkerModule({
35
+ out,
36
+ appEntry,
37
+ ssrImport,
38
+ hasEnvModule: workerEnv !== void 0
39
+ }));
40
+ flattenD1Migrations(resolve(root, "db/migrations"), resolve(out, "d1-migrations"));
41
+ writeDevOnlyStubs(out);
42
+ scaffoldWranglerConfig(root, out, packageJson.name);
43
+ }
44
+ const MCP_UNAVAILABLE = "The MCP endpoint is unavailable on Cloudflare Workers — it generates files on disk.";
45
+ /**
46
+ * Why the dev-only modules in `DEV_ONLY_MODULES` cannot run here, worded for
47
+ * this platform: each names the Workers-appropriate replacement.
48
+ */
49
+ /**
50
+ * Both lists: on Workers the SQL clients are as unreachable as the dev-only
51
+ * modules, because D1 is the only database the platform has.
52
+ */
53
+ const STUBBED_MODULES = [...DEV_ONLY_MODULES, ...SQL_CLIENT_MODULES];
54
+ const UNAVAILABLE_ON_WORKERS = {
55
+ sqlite: "bun:sqlite is unavailable on Cloudflare Workers — use createD1Database().",
56
+ vite: "The Vite dev server is unavailable on Cloudflare Workers — assets are served by Workers Static Assets.",
57
+ mcp: MCP_UNAVAILABLE,
58
+ "sql-driver": "This database client is unavailable on Cloudflare Workers — use createD1Database(). It is stubbed because @guren/orm names it in a dynamic import that bundlers follow even when the branch cannot be taken."
59
+ };
60
+ /**
61
+ * Wrangler resolves an `alias` to a path on disk, so unlike a bundler plugin
62
+ * each stub needs a file of its own. The names are deliberately hand-written
63
+ * rather than derived: they are baked into every app's committed
64
+ * `wrangler.jsonc`, which the scaffold never overwrites, so deriving them
65
+ * would rename files out from under existing apps for no benefit.
66
+ *
67
+ * Keyed on `DevOnlySpecifier`, so adding an entry to `DEV_ONLY_MODULES` is a
68
+ * compile error here until it gets a filename — the drift a derived name would
69
+ * have prevented, caught by the type system instead.
70
+ */
71
+ const STUB_FILES = {
72
+ "bun:sqlite": "stub-bun-sqlite.js",
73
+ vite: "stub-vite.js",
74
+ "@guren/cli": "stub-guren-cli.js",
75
+ "@modelcontextprotocol/sdk/server/mcp.js": "stub-mcp-server.js",
76
+ "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js": "stub-mcp-transport.js",
77
+ postgres: "stub-postgres.js",
78
+ mysql2: "stub-mysql2.js",
79
+ "mysql2/promise": "stub-mysql2-promise.js",
80
+ "@aws-sdk/client-rds-data": "stub-rds-data.js"
81
+ };
82
+ function writeDevOnlyStubs(out) {
83
+ for (const module of STUBBED_MODULES) writeFileSync(resolve(out, STUB_FILES[module.specifier]), renderDevOnlyStub(module, UNAVAILABLE_ON_WORKERS[module.kind]));
84
+ }
85
+ /**
86
+ * A package-name alias does not cover subpaths, so every stubbed specifier —
87
+ * including each MCP SDK subpath — needs its own entry. Unlike the Lambda
88
+ * plugin's bundler hook, wrangler cannot match a prefix, so an SDK subpath
89
+ * added upstream needs a new `DEV_ONLY_MODULES` entry to stay stubbed here.
90
+ */
91
+ function devOnlyAliases(outRelative) {
92
+ return Object.fromEntries(STUBBED_MODULES.map((module) => [module.specifier, `./${outRelative}/${STUB_FILES[module.specifier]}`]));
93
+ }
94
+ /**
95
+ * Wrangler's `migrations_dir` only discovers flat `*.sql` files, but
96
+ * drizzle-kit (1.x) emits one `<timestamp>_<name>/migration.sql` folder per
97
+ * migration. Flatten each folder into `<folder-name>.sql` (plain `*.sql`
98
+ * files pass through unchanged, `meta/` bookkeeping is skipped) so
99
+ * `wrangler d1 migrations apply` sees them in filename order. Regenerated on
100
+ * every build — run `cloudflare:build` after adding a migration.
101
+ */
102
+ function flattenD1Migrations(migrationsDir, outDir) {
103
+ if (!existsSync(migrationsDir)) return;
104
+ const entries = readdirSync(migrationsDir, { withFileTypes: true });
105
+ const copies = [];
106
+ for (const entry of entries) {
107
+ if (entry.isFile() && entry.name.endsWith(".sql")) {
108
+ copies.push({
109
+ from: resolve(migrationsDir, entry.name),
110
+ to: entry.name
111
+ });
112
+ continue;
113
+ }
114
+ if (entry.isDirectory() && entry.name !== "meta") {
115
+ const nested = resolve(migrationsDir, entry.name, "migration.sql");
116
+ if (existsSync(nested)) copies.push({
117
+ from: nested,
118
+ to: `${entry.name}.sql`
119
+ });
120
+ }
121
+ }
122
+ const seen = /* @__PURE__ */ new Map();
123
+ for (const copy of copies) {
124
+ const clash = seen.get(copy.to);
125
+ if (clash) throw new Error(`Cloudflare build: migrations "${clash}" and "${copy.from}" both flatten to "${copy.to}". Rename one so wrangler sees a stable order.`);
126
+ seen.set(copy.to, copy.from);
127
+ }
128
+ if (existsSync(outDir)) rmSync(outDir, {
129
+ recursive: true,
130
+ force: true
131
+ });
132
+ if (copies.length === 0) return;
133
+ mkdirSync(outDir, { recursive: true });
134
+ for (const copy of copies) cpSync(copy.from, resolve(outDir, copy.to));
135
+ }
136
+ function readPackageJson(root) {
137
+ const packageJsonPath = resolve(root, "package.json");
138
+ if (!existsSync(packageJsonPath)) return {};
139
+ try {
140
+ return JSON.parse(readFileSync(packageJsonPath, "utf8"));
141
+ } catch {
142
+ return {};
143
+ }
144
+ }
145
+ function runAppBuild(root, scripts) {
146
+ if (!scripts.build) throw new Error("Cloudflare build: no \"build\" script found in package.json. Add one (codegen + vite build + vite build --ssr) or pass --skip-app-build after building manually.");
147
+ if (Bun.spawnSync({
148
+ cmd: [
149
+ "bun",
150
+ "run",
151
+ "build"
152
+ ],
153
+ cwd: root,
154
+ stdout: "inherit",
155
+ stderr: "inherit"
156
+ }).exitCode !== 0) throw new Error("Cloudflare build: the app \"build\" script failed.");
157
+ }
158
+ async function resolveSsrImport(ssrDir, ssrEntryKey) {
159
+ const file = resolveSsrEntryFile(ssrDir, ssrEntryKey, "Cloudflare build");
160
+ if (!file) {
161
+ console.warn(`Cloudflare build: no SSR manifest entry for "${ssrEntryKey}" under ${ssrDir}; generating a CSR-only worker.`);
162
+ return;
163
+ }
164
+ const module = await import(pathToFileURL(file).href);
165
+ const rendererExport = ["render", "default"].find((name) => typeof module[name] === "function");
166
+ if (!rendererExport) throw new Error(`Cloudflare build: SSR entry ${file} does not export a renderer (expected a named "render" or default export).`);
167
+ return {
168
+ file,
169
+ rendererExport
170
+ };
171
+ }
172
+ /**
173
+ * Statements assigning the build-derived environment, emitted as a module of
174
+ * their own rather than as lines in worker.js: worker.js imports this module
175
+ * *first*, which is the only ordering ESM import hoisting cannot defeat. A
176
+ * statement in the worker body runs after the app's module graph has already
177
+ * evaluated, so a module-scope `viteAsset()` call in the app would see no
178
+ * manifest and throw before the worker could start. (The Lambda wrapper
179
+ * solves the same hazard by assigning env before dynamically importing the
180
+ * app.)
181
+ */
182
+ function renderWorkerEnvModule(input) {
183
+ const lines = [];
184
+ if (input.assetEnv.entry) lines.push(`process.env.GUREN_INERTIA_ENTRY = ${JSON.stringify(input.assetEnv.entry)}`);
185
+ if (input.assetEnv.styles) lines.push(`process.env.GUREN_INERTIA_STYLES = ${JSON.stringify(input.assetEnv.styles)}`);
186
+ if (input.viteManifest) lines.push(`process.env.GUREN_VITE_MANIFEST = ${JSON.stringify(input.viteManifest)}`);
187
+ if (lines.length === 0) return;
188
+ return [
189
+ "// Generated by `guren cloudflare:build`. Do not edit — regenerate instead.",
190
+ ...lines,
191
+ ""
192
+ ].join("\n");
193
+ }
194
+ function renderWorkerModule(input) {
195
+ const lines = ["// Generated by `guren cloudflare:build`. Do not edit — regenerate instead."];
196
+ if (input.hasEnvModule) lines.push("import './worker-env.js'");
197
+ lines.push("import { createWorkersHandler } from '@guren/plugin-cloudflare'");
198
+ if (input.ssrImport) lines.push("import { setInertiaSsrRenderer } from '@guren/core'", `import * as ssrModule from ${JSON.stringify(importSpecifier(input.out, input.ssrImport.file, "Cloudflare build"))}`);
199
+ lines.push(`import app from ${JSON.stringify(importSpecifier(input.out, input.appEntry, "Cloudflare build"))}`, "");
200
+ if (input.ssrImport) lines.push(`setInertiaSsrRenderer(ssrModule.${input.ssrImport.rendererExport})`, "");
201
+ lines.push("export default createWorkersHandler(app)", "");
202
+ return lines.join("\n");
203
+ }
204
+ function scaffoldWranglerConfig(root, out, packageName) {
205
+ const configPath = resolve(root, "wrangler.jsonc");
206
+ const appName = (packageName ?? "guren-app").replace(/^@[^/]+\//, "");
207
+ const outRelative = relative(root, out).split(sep).join("/");
208
+ const config = {
209
+ name: appName,
210
+ main: `${outRelative}/worker.js`,
211
+ compatibility_date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
212
+ compatibility_flags: ["nodejs_compat"],
213
+ alias: devOnlyAliases(outRelative),
214
+ define: {
215
+ "process.env.NODE_ENV": "\"production\"",
216
+ "import.meta.url": "\"file:///worker.js\""
217
+ },
218
+ assets: { directory: `${outRelative}/assets` },
219
+ d1_databases: [{
220
+ binding: "DB",
221
+ database_name: appName,
222
+ database_id: "TODO: wrangler d1 create",
223
+ migrations_dir: `${outRelative}/d1-migrations`
224
+ }],
225
+ vars: { NODE_ENV: "production" }
226
+ };
227
+ try {
228
+ writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, { flag: "wx" });
229
+ } catch (error) {
230
+ if (error.code === "EEXIST") {
231
+ warnMissingBuildOwnedKeys(configPath, outRelative);
232
+ return;
233
+ }
234
+ throw error;
235
+ }
236
+ console.log(`Cloudflare build: scaffolded ${configPath} — fill in d1_databases[0].database_id before deploying.`);
237
+ }
238
+ /**
239
+ * `wrangler.jsonc` is JSONC by name and by habit — the scaffold writes plain
240
+ * JSON, but every app that has touched the file since has comments in it, and
241
+ * `JSON.parse` rejects the first one. Reading it with `JSON.parse` meant the
242
+ * upgrade warning below could not fire for the population it was written for.
243
+ *
244
+ * Only comments and trailing commas are stripped, which is the whole of what
245
+ * wrangler accepts beyond JSON. The scan tracks string literals rather than
246
+ * pattern-matching, because a config carries both hazards for real: `define`
247
+ * holds `"\"file:///worker.js\""`, where the `//` is inside a string and the
248
+ * quotes around it are escaped.
249
+ */
250
+ function parseJsonc(text) {
251
+ const out = [];
252
+ let index = 0;
253
+ while (index < text.length) {
254
+ const char = text[index];
255
+ if (char === "\"") {
256
+ const start = index;
257
+ index += 1;
258
+ while (index < text.length) {
259
+ if (text[index] === "\\") {
260
+ index += 2;
261
+ continue;
262
+ }
263
+ if (text[index] === "\"") {
264
+ index += 1;
265
+ break;
266
+ }
267
+ index += 1;
268
+ }
269
+ out.push(text.slice(start, index));
270
+ continue;
271
+ }
272
+ if (char === "/" && text[index + 1] === "/") {
273
+ while (index < text.length && text[index] !== "\n") index += 1;
274
+ continue;
275
+ }
276
+ if (char === "/" && text[index + 1] === "*") {
277
+ const end = text.indexOf("*/", index + 2);
278
+ index = end === -1 ? text.length : end + 2;
279
+ continue;
280
+ }
281
+ if (char === "}" || char === "]") {
282
+ let back = out.length - 1;
283
+ while (back >= 0 && /^\s+$/.test(out[back])) back -= 1;
284
+ if (back >= 0 && out[back] === ",") out.splice(back, 1);
285
+ }
286
+ out.push(char);
287
+ index += 1;
288
+ }
289
+ return JSON.parse(out.join(""));
290
+ }
291
+ /**
292
+ * The scaffold never overwrites an existing config, but `alias`, `define`,
293
+ * and `migrations_dir` are build-owned invariants pointing into the output
294
+ * directory — an app scaffolded before they existed deploys a worker that
295
+ * cannot resolve `bun:sqlite` or never applies its migrations. Name exactly
296
+ * what is missing rather than failing the build.
297
+ *
298
+ * Individual entries, never a whole `"alias"` or `"define"` object: apps keep
299
+ * their own entries under both keys — a `shiki` stub, a pinned `@guren/orm`,
300
+ * an extra `define` — and a suggestion shaped like a complete object reads as
301
+ * one to paste over what is there, which would drop them.
302
+ */
303
+ function warnMissingBuildOwnedKeys(configPath, outRelative) {
304
+ let config;
305
+ try {
306
+ config = parseJsonc(readFileSync(configPath, "utf8"));
307
+ } catch {
308
+ console.warn(`Cloudflare build: could not parse ${configPath}, so its build-owned keys went unchecked. Fix the file, or compare it against a config scaffolded in an empty directory.`);
309
+ return;
310
+ }
311
+ const missing = [];
312
+ const configAlias = config.alias;
313
+ const alias = typeof configAlias === "object" && configAlias !== null ? configAlias : {};
314
+ for (const [specifier, target] of Object.entries(devOnlyAliases(outRelative))) if (!(specifier in alias)) missing.push(`${JSON.stringify(specifier)}: ${JSON.stringify(target)} (inside "alias")`);
315
+ if (!config.define?.["process.env.NODE_ENV"]) missing.push("\"process.env.NODE_ENV\": \"\\\"production\\\"\" (inside \"define\")");
316
+ const d1 = config.d1_databases?.[0];
317
+ if (d1 && d1.migrations_dir !== `${outRelative}/d1-migrations`) missing.push(`"migrations_dir": "${outRelative}/d1-migrations" (inside d1_databases[0])`);
318
+ if (missing.length > 0) console.warn(`Cloudflare build: ${configPath} predates this plugin version. Add these entries, alongside whatever the file already has under the same keys, or the worker will fail to start or skip migrations:\n ${missing.join("\n ")}`);
319
+ }
320
+ //#endregion
321
+ export { flattenD1Migrations as n, buildCloudflareOutput as t };
@@ -1,16 +1,15 @@
1
- import * as citty from 'citty';
2
-
1
+ //#region src/commands.d.ts
3
2
  declare const _default: {
4
- 'cloudflare:build': citty.CommandDef<{
5
- root: {
6
- type: "string";
7
- description: string;
8
- };
9
- 'skip-app-build': {
10
- type: "boolean";
11
- description: string;
12
- };
13
- }>;
3
+ 'cloudflare:build': import("citty").CommandDef<{
4
+ root: {
5
+ type: "string";
6
+ description: string;
7
+ };
8
+ 'skip-app-build': {
9
+ type: "boolean";
10
+ description: string;
11
+ };
12
+ }>;
14
13
  };
15
-
16
- export { _default as default };
14
+ //#endregion
15
+ export { _default as default };
package/dist/commands.js CHANGED
@@ -1,34 +1,26 @@
1
- import {
2
- buildCloudflareOutput
3
- } from "./chunk-6DV73MBR.js";
4
-
5
- // src/commands.ts
1
+ import { t as buildCloudflareOutput } from "./build-B7zQ13ai.js";
6
2
  import { defineCommand } from "citty";
7
- var cloudflareBuild = defineCommand({
8
- meta: {
9
- name: "cloudflare:build",
10
- description: "Assemble a Cloudflare Workers deployment (.cloudflare/) from the app build"
11
- },
12
- args: {
13
- root: {
14
- type: "string",
15
- description: "App root directory (defaults to the current working directory)"
16
- },
17
- "skip-app-build": {
18
- type: "boolean",
19
- description: "Skip running the app's build script before assembling output"
20
- }
21
- },
22
- async run({ args }) {
23
- await buildCloudflareOutput({
24
- rootDir: args.root || process.cwd(),
25
- skipAppBuild: Boolean(args["skip-app-build"])
26
- });
27
- }
28
- });
29
- var commands_default = {
30
- "cloudflare:build": cloudflareBuild
31
- };
32
- export {
33
- commands_default as default
34
- };
3
+ var commands_default = { "cloudflare:build": defineCommand({
4
+ meta: {
5
+ name: "cloudflare:build",
6
+ description: "Assemble a Cloudflare Workers deployment (.cloudflare/) from the app build"
7
+ },
8
+ args: {
9
+ root: {
10
+ type: "string",
11
+ description: "App root directory (defaults to the current working directory)"
12
+ },
13
+ "skip-app-build": {
14
+ type: "boolean",
15
+ description: "Skip running the app's build script before assembling output"
16
+ }
17
+ },
18
+ async run({ args }) {
19
+ await buildCloudflareOutput({
20
+ rootDir: args.root || process.cwd(),
21
+ skipAppBuild: Boolean(args["skip-app-build"])
22
+ });
23
+ }
24
+ }) };
25
+ //#endregion
26
+ export { commands_default as default };