@guren/plugin-cloudflare 0.2.0 → 0.2.2

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 ADDED
@@ -0,0 +1,51 @@
1
+ # @guren/plugin-cloudflare
2
+
3
+ Deploy a [Guren](https://guren.dev/) application to Cloudflare Workers, with D1 as the database.
4
+
5
+ ```bash
6
+ bunx guren plugin @guren/plugin-cloudflare
7
+ bun add @guren/plugin-cloudflare
8
+ ```
9
+
10
+ Installing registers a `cloudflare:build` command and scaffolds `wrangler.jsonc` on the first build.
11
+
12
+ ## Build and deploy
13
+
14
+ ```bash
15
+ bunx guren cloudflare:build
16
+ bunx wrangler deploy
17
+ ```
18
+
19
+ `cloudflare:build` runs your app's `build` script, then assembles a `.cloudflare/` directory containing the worker entry, static assets for Workers Static Assets, and flattened D1 migrations. It is generated output — add it to `.gitignore` and rebuild before every deploy.
20
+
21
+ ## API
22
+
23
+ - **`createWorkersHandler(app)`** — wraps a Guren `Application` in a Workers module handler. Boot is lazy and deduplicated on the first request, because `boot()` performs I/O that workerd forbids in global scope. The handler deduplicates boot itself, so boot-once holds for anything matching `WorkersAppLike`, not only Guren's `Application`.
24
+ - **`getWorkersEnv<Env>()`** — exposes the first request's bindings to boot-time config through a write-once holder. workerd can also expose bindings at module scope via `cloudflare:workers`, but importing that from shared config would break every other runtime (Bun, Lambda, Vercel) — the holder keeps `config/*.ts` portable. Use it to hand a D1 binding to the ORM:
25
+
26
+ ```typescript
27
+ import { createD1Database } from '@guren/core'
28
+ import { getWorkersEnv } from '@guren/plugin-cloudflare'
29
+
30
+ const database = createD1Database({
31
+ binding: () => getWorkersEnv<{ DB: unknown }>().DB,
32
+ })
33
+ ```
34
+
35
+ The binding is a resolver, not a value — it must be read lazily.
36
+
37
+ - **`cloudflarePlugin()`** — the service provider factory, registered automatically by `guren plugin`.
38
+
39
+ ## Things Workers changes
40
+
41
+ Workers has no filesystem and shares no memory between requests, so a few defaults do not apply:
42
+
43
+ - **Sessions and OAuth state must be database-backed.** Each request may land on a different isolate. The in-memory defaults work locally and then drop every session in production. Use `DatabaseSessionStore` and `DatabaseOAuthStateStore`.
44
+ - **Migrations are applied out of band.** `wrangler d1 migrations apply` owns the lifecycle; the app never migrates itself.
45
+ - **`APP_KEY` is required.** Sessions and CSRF are signed with it, and the worker throws at startup without it.
46
+
47
+ See the [Cloudflare Workers deployment guide](https://guren.dev/docs/guides/cloudflare) for the full path from an empty account to a deployed app, including D1 setup, secrets, free-plan limits, and local development.
48
+
49
+ ## License
50
+
51
+ MIT
@@ -1,7 +1,18 @@
1
1
  // src/build.ts
2
2
  import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "fs";
3
- import { isAbsolute, relative, resolve, sep } from "path";
4
- import { fileURLToPath, pathToFileURL } from "url";
3
+ import { relative, resolve, sep } from "path";
4
+ import { pathToFileURL } from "url";
5
+ import {
6
+ DEV_ONLY_MODULES,
7
+ importSpecifier,
8
+ renderDevOnlyStub,
9
+ assertOutputDirOutsideRoot,
10
+ resetOutputDir,
11
+ resolveClientAssetEnv,
12
+ resolvePathLike,
13
+ resolveSsrEntryFile,
14
+ stageStaticAssets
15
+ } from "@guren/core/internal/deploy-build";
5
16
  async function buildCloudflareOutput(options = {}) {
6
17
  const root = resolvePathLike(options.rootDir ?? process.cwd());
7
18
  const out = resolvePathLike(options.outputDir ?? resolve(root, ".cloudflare"));
@@ -10,11 +21,7 @@ async function buildCloudflareOutput(options = {}) {
10
21
  const ssrDir = resolvePathLike(options.ssrDir ?? resolve(root, ".guren/ssr"));
11
22
  const clientEntryKey = options.clientEntryKey ?? "resources/js/app.tsx";
12
23
  const ssrEntryKey = options.ssrEntryKey ?? "resources/js/ssr.tsx";
13
- if (out === root || root.startsWith(out + sep)) {
14
- throw new Error(
15
- `Cloudflare build: outputDir (${out}) must be a directory outside or below the app root, never the root itself \u2014 it is deleted on every build.`
16
- );
17
- }
24
+ assertOutputDirOutsideRoot(out, root, "Cloudflare build");
18
25
  const packageJson = readPackageJson(root);
19
26
  if (!options.skipAppBuild) {
20
27
  runAppBuild(root, packageJson.scripts ?? {});
@@ -23,76 +30,40 @@ async function buildCloudflareOutput(options = {}) {
23
30
  throw new Error(`Cloudflare build: app entry not found at ${appEntry}. Pass "appEntry" if your Application lives elsewhere.`);
24
31
  }
25
32
  const ssrImport = await resolveSsrImport(ssrDir, ssrEntryKey);
26
- const assetEnv = resolveClientAssetEnv(root, clientEntryKey);
27
- if (existsSync(out)) {
28
- rmSync(out, { recursive: true, force: true });
29
- }
30
- mkdirSync(resolve(out, "assets"), { recursive: true });
31
- if (existsSync(publicDir)) {
32
- cpSync(publicDir, resolve(out, "assets"), { recursive: true });
33
- }
34
- const shadowingIndex = resolve(out, "assets/index.html");
35
- if (existsSync(shadowingIndex)) {
36
- rmSync(shadowingIndex);
37
- }
38
- const clientAssetsDir = resolve(publicDir, "assets");
39
- if (existsSync(clientAssetsDir)) {
40
- cpSync(clientAssetsDir, resolve(out, "assets/public/assets"), { recursive: true });
41
- }
33
+ const assetEnv = resolveClientAssetEnv(publicDir, clientEntryKey, "Cloudflare build");
34
+ resetOutputDir(out, root, "Cloudflare build");
35
+ stageStaticAssets(publicDir, resolve(out, "assets"));
42
36
  writeFileSync(resolve(out, "worker.js"), renderWorkerModule({ out, appEntry, ssrImport, assetEnv }));
43
37
  flattenD1Migrations(resolve(root, "db/migrations"), resolve(out, "d1-migrations"));
44
38
  writeDevOnlyStubs(out);
45
39
  scaffoldWranglerConfig(root, out, packageJson.name);
46
40
  }
47
41
  var MCP_UNAVAILABLE = "The MCP endpoint is unavailable on Cloudflare Workers \u2014 it generates files on disk.";
48
- function mcpStub(exportNames) {
49
- const throwing = exportNames.map((name) => `export class ${name} { constructor() { throw new Error(${JSON.stringify(MCP_UNAVAILABLE)}) } }`).join("\n");
50
- return `${throwing}
51
- export default {}
52
- `;
53
- }
54
- var DEV_ONLY_STUBS = {
55
- "bun:sqlite": {
56
- file: "stub-bun-sqlite.js",
57
- source: 'export const Database = class { constructor() { throw new Error("bun:sqlite is unavailable on Cloudflare Workers \u2014 use createD1Database().") } }\nexport default { Database }\n'
58
- },
59
- vite: {
60
- file: "stub-vite.js",
61
- source: 'export function createServer() { throw new Error("The Vite dev server is unavailable on Cloudflare Workers \u2014 assets are served by Workers Static Assets.") }\nexport default { createServer }\n'
62
- },
63
- // The opt-in MCP endpoint's lazy imports still drag the CLI generators
64
- // (and Babel) plus the MCP SDK into the bundle. `@guren/cli` is imported
65
- // bare, but the SDK is only ever reached through subpaths — and an alias
66
- // on a package name does not cover them, so each subpath is listed.
67
- // `@guren/cli` is imported bare and only read through namespace property
68
- // access, so an empty module suffices; the SDK subpaths are destructured
69
- // and need their names present. A package-name alias does not cover
70
- // subpaths, so each is listed.
71
- "@guren/cli": {
72
- file: "stub-guren-cli.js",
73
- source: `// ${MCP_UNAVAILABLE}
74
- export {}
75
- `
76
- },
77
- "@modelcontextprotocol/sdk/server/mcp.js": {
78
- file: "stub-mcp-server.js",
79
- source: mcpStub(["McpServer", "ResourceTemplate"])
80
- },
81
- "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js": {
82
- file: "stub-mcp-transport.js",
83
- source: mcpStub(["WebStandardStreamableHTTPServerTransport"])
84
- }
42
+ var UNAVAILABLE_ON_WORKERS = {
43
+ sqlite: "bun:sqlite is unavailable on Cloudflare Workers \u2014 use createD1Database().",
44
+ vite: "The Vite dev server is unavailable on Cloudflare Workers \u2014 assets are served by Workers Static Assets.",
45
+ mcp: MCP_UNAVAILABLE
46
+ };
47
+ var STUB_FILES = {
48
+ "bun:sqlite": "stub-bun-sqlite.js",
49
+ vite: "stub-vite.js",
50
+ "@guren/cli": "stub-guren-cli.js",
51
+ "@modelcontextprotocol/sdk/server/mcp.js": "stub-mcp-server.js",
52
+ "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js": "stub-mcp-transport.js"
85
53
  };
86
54
  function writeDevOnlyStubs(out) {
87
- for (const stub of Object.values(DEV_ONLY_STUBS)) {
88
- writeFileSync(resolve(out, stub.file), stub.source);
55
+ for (const module of DEV_ONLY_MODULES) {
56
+ writeFileSync(
57
+ resolve(out, STUB_FILES[module.specifier]),
58
+ renderDevOnlyStub(module, UNAVAILABLE_ON_WORKERS[module.kind])
59
+ );
89
60
  }
90
61
  }
91
62
  function devOnlyAliases(outRelative) {
92
63
  return Object.fromEntries(
93
- Object.entries(DEV_ONLY_STUBS).map(([specifier, stub]) => [
94
- specifier,
95
- `./${outRelative}/${stub.file}`
64
+ DEV_ONLY_MODULES.map((module) => [
65
+ module.specifier,
66
+ `./${outRelative}/${STUB_FILES[module.specifier]}`
96
67
  ])
97
68
  );
98
69
  }
@@ -163,51 +134,23 @@ function runAppBuild(root, scripts) {
163
134
  }
164
135
  }
165
136
  async function resolveSsrImport(ssrDir, ssrEntryKey) {
166
- const manifest = loadManifest(
167
- resolve(ssrDir, ".vite/manifest.json"),
168
- resolve(ssrDir, "manifest.json")
169
- );
170
- const entryFile = manifest?.[ssrEntryKey]?.file;
171
- if (!entryFile) {
137
+ const file = resolveSsrEntryFile(ssrDir, ssrEntryKey, "Cloudflare build");
138
+ if (!file) {
172
139
  console.warn(
173
140
  `Cloudflare build: no SSR manifest entry for "${ssrEntryKey}" under ${ssrDir}; generating a CSR-only worker.`
174
141
  );
175
142
  return void 0;
176
143
  }
177
- const file = resolve(ssrDir, entryFile);
178
- if (!file.startsWith(ssrDir + sep)) {
179
- throw new Error(
180
- `Cloudflare build: SSR manifest entry "${entryFile}" escapes the SSR output directory ${ssrDir}.`
181
- );
182
- }
183
- if (!existsSync(file)) {
184
- throw new Error(`Cloudflare build: SSR manifest points at ${file}, but the file does not exist.`);
185
- }
186
144
  const module = await import(pathToFileURL(file).href);
187
- const renderer = module.render ?? module.default;
188
- if (typeof renderer !== "function") {
145
+ const rendererExport = ["render", "default"].find(
146
+ (name) => typeof module[name] === "function"
147
+ );
148
+ if (!rendererExport) {
189
149
  throw new Error(
190
150
  `Cloudflare build: SSR entry ${file} does not export a renderer (expected a named "render" or default export).`
191
151
  );
192
152
  }
193
- return { file };
194
- }
195
- function resolveClientAssetEnv(root, clientEntryKey) {
196
- const manifest = loadManifest(
197
- resolve(root, "public/assets/.vite/manifest.json"),
198
- resolve(root, "public/assets/manifest.json")
199
- );
200
- const entry = manifest?.[clientEntryKey];
201
- if (!entry?.file) {
202
- console.warn(
203
- `Cloudflare build: no client manifest entry for "${clientEntryKey}"; GUREN_INERTIA_ENTRY will not be set.`
204
- );
205
- return {};
206
- }
207
- return {
208
- entry: `/assets/${entry.file}`,
209
- styles: entry.css?.length ? entry.css.map((file) => `/assets/${file}`).join(",") : void 0
210
- };
153
+ return { file, rendererExport };
211
154
  }
212
155
  function renderWorkerModule(input) {
213
156
  const lines = [
@@ -217,10 +160,10 @@ function renderWorkerModule(input) {
217
160
  if (input.ssrImport) {
218
161
  lines.push(
219
162
  "import { setInertiaSsrRenderer } from '@guren/core'",
220
- `import * as ssrModule from ${JSON.stringify(importSpecifier(input.out, input.ssrImport.file))}`
163
+ `import * as ssrModule from ${JSON.stringify(importSpecifier(input.out, input.ssrImport.file, "Cloudflare build"))}`
221
164
  );
222
165
  }
223
- lines.push(`import app from ${JSON.stringify(importSpecifier(input.out, input.appEntry))}`, "");
166
+ lines.push(`import app from ${JSON.stringify(importSpecifier(input.out, input.appEntry, "Cloudflare build"))}`, "");
224
167
  if (input.assetEnv.entry) {
225
168
  lines.push(`process.env.GUREN_INERTIA_ENTRY = ${JSON.stringify(input.assetEnv.entry)}`);
226
169
  }
@@ -231,27 +174,13 @@ function renderWorkerModule(input) {
231
174
  lines.push("");
232
175
  }
233
176
  if (input.ssrImport) {
234
- lines.push("setInertiaSsrRenderer(ssrModule.render ?? ssrModule.default)", "");
177
+ lines.push(`setInertiaSsrRenderer(ssrModule.${input.ssrImport.rendererExport})`, "");
235
178
  }
236
179
  lines.push("export default createWorkersHandler(app)", "");
237
180
  return lines.join("\n");
238
181
  }
239
- function importSpecifier(fromDir, target) {
240
- const rel = relative(fromDir, target);
241
- if (isAbsolute(rel)) {
242
- throw new Error(
243
- `Cloudflare build: ${target} cannot be imported relative to ${fromDir} (different drive or root?). Keep the app, SSR output, and outputDir on the same volume.`
244
- );
245
- }
246
- const specifier = rel.split(sep).join("/");
247
- return specifier.startsWith(".") ? specifier : `./${specifier}`;
248
- }
249
182
  function scaffoldWranglerConfig(root, out, packageName) {
250
183
  const configPath = resolve(root, "wrangler.jsonc");
251
- if (existsSync(configPath)) {
252
- warnMissingBuildOwnedKeys(configPath, relative(root, out).split(sep).join("/"));
253
- return;
254
- }
255
184
  const appName = (packageName ?? "guren-app").replace(/^@[^/]+\//, "");
256
185
  const outRelative = relative(root, out).split(sep).join("/");
257
186
  const config = {
@@ -286,8 +215,16 @@ function scaffoldWranglerConfig(root, out, packageName) {
286
215
  ],
287
216
  vars: { NODE_ENV: "production" }
288
217
  };
289
- writeFileSync(configPath, `${JSON.stringify(config, null, 2)}
290
- `);
218
+ try {
219
+ writeFileSync(configPath, `${JSON.stringify(config, null, 2)}
220
+ `, { flag: "wx" });
221
+ } catch (error) {
222
+ if (error.code === "EEXIST") {
223
+ warnMissingBuildOwnedKeys(configPath, outRelative);
224
+ return;
225
+ }
226
+ throw error;
227
+ }
291
228
  console.log(`Cloudflare build: scaffolded ${configPath} \u2014 fill in d1_databases[0].database_id before deploying.`);
292
229
  }
293
230
  function warnMissingBuildOwnedKeys(configPath, outRelative) {
@@ -299,8 +236,9 @@ function warnMissingBuildOwnedKeys(configPath, outRelative) {
299
236
  }
300
237
  const missing = [];
301
238
  const alias = config.alias;
302
- if (!alias || Object.keys(devOnlyAliases(outRelative)).some((key) => !(key in alias))) {
303
- missing.push(`"alias": ${JSON.stringify(devOnlyAliases(outRelative))}`);
239
+ const expectedAliases = devOnlyAliases(outRelative);
240
+ if (!alias || Object.keys(expectedAliases).some((key) => !(key in alias))) {
241
+ missing.push(`"alias": ${JSON.stringify(expectedAliases)}`);
304
242
  }
305
243
  const define = config.define;
306
244
  if (!define?.["process.env.NODE_ENV"]) {
@@ -317,22 +255,6 @@ function warnMissingBuildOwnedKeys(configPath, outRelative) {
317
255
  );
318
256
  }
319
257
  }
320
- function resolvePathLike(value) {
321
- return value instanceof URL ? fileURLToPath(value) : resolve(String(value));
322
- }
323
- function loadManifest(...paths) {
324
- for (const path of paths) {
325
- if (!existsSync(path)) {
326
- continue;
327
- }
328
- try {
329
- return JSON.parse(readFileSync(path, "utf8"));
330
- } catch {
331
- continue;
332
- }
333
- }
334
- return void 0;
335
- }
336
258
 
337
259
  export {
338
260
  buildCloudflareOutput,
package/dist/commands.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  buildCloudflareOutput
3
- } from "./chunk-76ERVQJ3.js";
3
+ } from "./chunk-32YY6FCY.js";
4
4
 
5
5
  // src/commands.ts
6
6
  import { defineCommand } from "citty";
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ServiceProviderConstructor } from '@guren/core';
2
+ import { PathLike } from '@guren/core/internal/deploy-build';
2
3
 
3
4
  /** First call wins; later calls are ignored (never overwrite a live env). */
4
5
  declare function captureWorkersEnv(env: unknown): void;
@@ -11,6 +12,11 @@ interface WorkersExecutionContext {
11
12
  waitUntil(promise: Promise<unknown>): void;
12
13
  passThroughOnException?(): void;
13
14
  }
15
+ /**
16
+ * The shape `createWorkersHandler` needs from an app. Structural rather than
17
+ * `Application` itself, so `boot()` is not assumed to be idempotent — each
18
+ * handler dedupes boot across its own requests for anything conforming here.
19
+ */
14
20
  interface WorkersAppLike {
15
21
  boot(): Promise<void>;
16
22
  fetch(request: Request, env?: unknown, executionCtx?: unknown): Response | Promise<Response>;
@@ -20,7 +26,6 @@ interface WorkersHandler {
20
26
  }
21
27
  declare function createWorkersHandler(app: WorkersAppLike): WorkersHandler;
22
28
 
23
- type PathLike = string | URL;
24
29
  interface BuildCloudflareOutputOptions {
25
30
  /** App root directory. Defaults to the current working directory. */
26
31
  rootDir?: PathLike;
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  buildCloudflareOutput,
3
3
  flattenD1Migrations
4
- } from "./chunk-76ERVQJ3.js";
4
+ } from "./chunk-32YY6FCY.js";
5
5
 
6
6
  // src/index.ts
7
7
  import { definePlugin } from "@guren/core";
@@ -29,12 +29,15 @@ function createWorkersHandler(app) {
29
29
  return {
30
30
  async fetch(request, env, ctx) {
31
31
  captureWorkersEnv(env);
32
- bootPromise ??= app.boot();
32
+ let attempt;
33
33
  try {
34
- await bootPromise;
34
+ attempt = bootPromise ??= app.boot();
35
+ await attempt;
35
36
  } catch (error) {
36
- bootPromise = void 0;
37
- resetWorkersEnv();
37
+ if (bootPromise === attempt) {
38
+ bootPromise = void 0;
39
+ resetWorkersEnv();
40
+ }
38
41
  throw error;
39
42
  }
40
43
  return app.fetch(request, env, ctx);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/plugin-cloudflare",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -41,7 +41,7 @@
41
41
  "typecheck": "tsc --noEmit"
42
42
  },
43
43
  "dependencies": {
44
- "@guren/core": "^1.3.0",
44
+ "@guren/core": "^1.5.2",
45
45
  "citty": "^0.1.6"
46
46
  },
47
47
  "devDependencies": {