@guren/plugin-cloudflare 0.2.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.
- package/dist/chunk-76ERVQJ3.js +340 -0
- package/dist/commands.d.ts +16 -0
- package/dist/commands.js +34 -0
- package/dist/index.d.ts +75 -0
- package/dist/index.js +62 -0
- package/package.json +53 -0
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
// src/build.ts
|
|
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";
|
|
5
|
+
async function buildCloudflareOutput(options = {}) {
|
|
6
|
+
const root = resolvePathLike(options.rootDir ?? process.cwd());
|
|
7
|
+
const out = resolvePathLike(options.outputDir ?? resolve(root, ".cloudflare"));
|
|
8
|
+
const appEntry = resolvePathLike(options.appEntry ?? resolve(root, "src/app.ts"));
|
|
9
|
+
const publicDir = resolvePathLike(options.publicDir ?? resolve(root, "public"));
|
|
10
|
+
const ssrDir = resolvePathLike(options.ssrDir ?? resolve(root, ".guren/ssr"));
|
|
11
|
+
const clientEntryKey = options.clientEntryKey ?? "resources/js/app.tsx";
|
|
12
|
+
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
|
+
}
|
|
18
|
+
const packageJson = readPackageJson(root);
|
|
19
|
+
if (!options.skipAppBuild) {
|
|
20
|
+
runAppBuild(root, packageJson.scripts ?? {});
|
|
21
|
+
}
|
|
22
|
+
if (!existsSync(appEntry)) {
|
|
23
|
+
throw new Error(`Cloudflare build: app entry not found at ${appEntry}. Pass "appEntry" if your Application lives elsewhere.`);
|
|
24
|
+
}
|
|
25
|
+
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
|
+
}
|
|
42
|
+
writeFileSync(resolve(out, "worker.js"), renderWorkerModule({ out, appEntry, ssrImport, assetEnv }));
|
|
43
|
+
flattenD1Migrations(resolve(root, "db/migrations"), resolve(out, "d1-migrations"));
|
|
44
|
+
writeDevOnlyStubs(out);
|
|
45
|
+
scaffoldWranglerConfig(root, out, packageJson.name);
|
|
46
|
+
}
|
|
47
|
+
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
|
+
}
|
|
85
|
+
};
|
|
86
|
+
function writeDevOnlyStubs(out) {
|
|
87
|
+
for (const stub of Object.values(DEV_ONLY_STUBS)) {
|
|
88
|
+
writeFileSync(resolve(out, stub.file), stub.source);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function devOnlyAliases(outRelative) {
|
|
92
|
+
return Object.fromEntries(
|
|
93
|
+
Object.entries(DEV_ONLY_STUBS).map(([specifier, stub]) => [
|
|
94
|
+
specifier,
|
|
95
|
+
`./${outRelative}/${stub.file}`
|
|
96
|
+
])
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
function flattenD1Migrations(migrationsDir, outDir) {
|
|
100
|
+
if (!existsSync(migrationsDir)) {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
const entries = readdirSync(migrationsDir, { withFileTypes: true });
|
|
104
|
+
const copies = [];
|
|
105
|
+
for (const entry of entries) {
|
|
106
|
+
if (entry.isFile() && entry.name.endsWith(".sql")) {
|
|
107
|
+
copies.push({ from: resolve(migrationsDir, entry.name), to: entry.name });
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (entry.isDirectory() && entry.name !== "meta") {
|
|
111
|
+
const nested = resolve(migrationsDir, entry.name, "migration.sql");
|
|
112
|
+
if (existsSync(nested)) {
|
|
113
|
+
copies.push({ from: nested, to: `${entry.name}.sql` });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const seen = /* @__PURE__ */ new Map();
|
|
118
|
+
for (const copy of copies) {
|
|
119
|
+
const clash = seen.get(copy.to);
|
|
120
|
+
if (clash) {
|
|
121
|
+
throw new Error(
|
|
122
|
+
`Cloudflare build: migrations "${clash}" and "${copy.from}" both flatten to "${copy.to}". Rename one so wrangler sees a stable order.`
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
seen.set(copy.to, copy.from);
|
|
126
|
+
}
|
|
127
|
+
if (existsSync(outDir)) {
|
|
128
|
+
rmSync(outDir, { recursive: true, force: true });
|
|
129
|
+
}
|
|
130
|
+
if (copies.length === 0) {
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
mkdirSync(outDir, { recursive: true });
|
|
134
|
+
for (const copy of copies) {
|
|
135
|
+
cpSync(copy.from, resolve(outDir, copy.to));
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function readPackageJson(root) {
|
|
139
|
+
const packageJsonPath = resolve(root, "package.json");
|
|
140
|
+
if (!existsSync(packageJsonPath)) {
|
|
141
|
+
return {};
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
return JSON.parse(readFileSync(packageJsonPath, "utf8"));
|
|
145
|
+
} catch {
|
|
146
|
+
return {};
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function runAppBuild(root, scripts) {
|
|
150
|
+
if (!scripts.build) {
|
|
151
|
+
throw new Error(
|
|
152
|
+
'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.'
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
const result = Bun.spawnSync({
|
|
156
|
+
cmd: ["bun", "run", "build"],
|
|
157
|
+
cwd: root,
|
|
158
|
+
stdout: "inherit",
|
|
159
|
+
stderr: "inherit"
|
|
160
|
+
});
|
|
161
|
+
if (result.exitCode !== 0) {
|
|
162
|
+
throw new Error('Cloudflare build: the app "build" script failed.');
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
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) {
|
|
172
|
+
console.warn(
|
|
173
|
+
`Cloudflare build: no SSR manifest entry for "${ssrEntryKey}" under ${ssrDir}; generating a CSR-only worker.`
|
|
174
|
+
);
|
|
175
|
+
return void 0;
|
|
176
|
+
}
|
|
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
|
+
const module = await import(pathToFileURL(file).href);
|
|
187
|
+
const renderer = module.render ?? module.default;
|
|
188
|
+
if (typeof renderer !== "function") {
|
|
189
|
+
throw new Error(
|
|
190
|
+
`Cloudflare build: SSR entry ${file} does not export a renderer (expected a named "render" or default export).`
|
|
191
|
+
);
|
|
192
|
+
}
|
|
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
|
+
};
|
|
211
|
+
}
|
|
212
|
+
function renderWorkerModule(input) {
|
|
213
|
+
const lines = [
|
|
214
|
+
"// Generated by `guren cloudflare:build`. Do not edit \u2014 regenerate instead.",
|
|
215
|
+
"import { createWorkersHandler } from '@guren/plugin-cloudflare'"
|
|
216
|
+
];
|
|
217
|
+
if (input.ssrImport) {
|
|
218
|
+
lines.push(
|
|
219
|
+
"import { setInertiaSsrRenderer } from '@guren/core'",
|
|
220
|
+
`import * as ssrModule from ${JSON.stringify(importSpecifier(input.out, input.ssrImport.file))}`
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
lines.push(`import app from ${JSON.stringify(importSpecifier(input.out, input.appEntry))}`, "");
|
|
224
|
+
if (input.assetEnv.entry) {
|
|
225
|
+
lines.push(`process.env.GUREN_INERTIA_ENTRY = ${JSON.stringify(input.assetEnv.entry)}`);
|
|
226
|
+
}
|
|
227
|
+
if (input.assetEnv.styles) {
|
|
228
|
+
lines.push(`process.env.GUREN_INERTIA_STYLES = ${JSON.stringify(input.assetEnv.styles)}`);
|
|
229
|
+
}
|
|
230
|
+
if (input.assetEnv.entry || input.assetEnv.styles) {
|
|
231
|
+
lines.push("");
|
|
232
|
+
}
|
|
233
|
+
if (input.ssrImport) {
|
|
234
|
+
lines.push("setInertiaSsrRenderer(ssrModule.render ?? ssrModule.default)", "");
|
|
235
|
+
}
|
|
236
|
+
lines.push("export default createWorkersHandler(app)", "");
|
|
237
|
+
return lines.join("\n");
|
|
238
|
+
}
|
|
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
|
+
function scaffoldWranglerConfig(root, out, packageName) {
|
|
250
|
+
const configPath = resolve(root, "wrangler.jsonc");
|
|
251
|
+
if (existsSync(configPath)) {
|
|
252
|
+
warnMissingBuildOwnedKeys(configPath, relative(root, out).split(sep).join("/"));
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
const appName = (packageName ?? "guren-app").replace(/^@[^/]+\//, "");
|
|
256
|
+
const outRelative = relative(root, out).split(sep).join("/");
|
|
257
|
+
const config = {
|
|
258
|
+
name: appName,
|
|
259
|
+
main: `${outRelative}/worker.js`,
|
|
260
|
+
compatibility_date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
|
|
261
|
+
compatibility_flags: ["nodejs_compat"],
|
|
262
|
+
alias: devOnlyAliases(outRelative),
|
|
263
|
+
define: {
|
|
264
|
+
// Statements in the generated worker cannot beat ESM import hoisting,
|
|
265
|
+
// and wrangler `vars` are not guaranteed to reach `process.env` before
|
|
266
|
+
// the app's module graph evaluates — framework and app code branch on
|
|
267
|
+
// NODE_ENV at module scope, so it is substituted at build time (the
|
|
268
|
+
// same approach the Vercel plugin takes).
|
|
269
|
+
"process.env.NODE_ENV": '"production"',
|
|
270
|
+
// workerd leaves `import.meta.url` undefined. Two things break on it:
|
|
271
|
+
// Vite's SSR bundle initializes `createRequire(import.meta.url)`, and
|
|
272
|
+
// scaffolded config resolves paths with `new URL(..., import.meta.url)`
|
|
273
|
+
// — both at module scope, so the worker dies before serving anything.
|
|
274
|
+
// Substituting a literal is safe precisely because Workers has no
|
|
275
|
+
// filesystem: every such path is already meaningless there.
|
|
276
|
+
"import.meta.url": '"file:///worker.js"'
|
|
277
|
+
},
|
|
278
|
+
assets: { directory: `${outRelative}/assets` },
|
|
279
|
+
d1_databases: [
|
|
280
|
+
{
|
|
281
|
+
binding: "DB",
|
|
282
|
+
database_name: appName,
|
|
283
|
+
database_id: "TODO: wrangler d1 create",
|
|
284
|
+
migrations_dir: `${outRelative}/d1-migrations`
|
|
285
|
+
}
|
|
286
|
+
],
|
|
287
|
+
vars: { NODE_ENV: "production" }
|
|
288
|
+
};
|
|
289
|
+
writeFileSync(configPath, `${JSON.stringify(config, null, 2)}
|
|
290
|
+
`);
|
|
291
|
+
console.log(`Cloudflare build: scaffolded ${configPath} \u2014 fill in d1_databases[0].database_id before deploying.`);
|
|
292
|
+
}
|
|
293
|
+
function warnMissingBuildOwnedKeys(configPath, outRelative) {
|
|
294
|
+
let config;
|
|
295
|
+
try {
|
|
296
|
+
config = JSON.parse(readFileSync(configPath, "utf8"));
|
|
297
|
+
} catch {
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
const missing = [];
|
|
301
|
+
const alias = config.alias;
|
|
302
|
+
if (!alias || Object.keys(devOnlyAliases(outRelative)).some((key) => !(key in alias))) {
|
|
303
|
+
missing.push(`"alias": ${JSON.stringify(devOnlyAliases(outRelative))}`);
|
|
304
|
+
}
|
|
305
|
+
const define = config.define;
|
|
306
|
+
if (!define?.["process.env.NODE_ENV"]) {
|
|
307
|
+
missing.push('"define": { "process.env.NODE_ENV": "\\"production\\"" }');
|
|
308
|
+
}
|
|
309
|
+
const d1 = config.d1_databases?.[0];
|
|
310
|
+
if (d1 && d1.migrations_dir !== `${outRelative}/d1-migrations`) {
|
|
311
|
+
missing.push(`"migrations_dir": "${outRelative}/d1-migrations" (inside d1_databases[0])`);
|
|
312
|
+
}
|
|
313
|
+
if (missing.length > 0) {
|
|
314
|
+
console.warn(
|
|
315
|
+
`Cloudflare build: ${configPath} predates this plugin version. Add the following or the worker will fail to start or skip migrations:
|
|
316
|
+
${missing.join("\n ")}`
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
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
|
+
|
|
337
|
+
export {
|
|
338
|
+
buildCloudflareOutput,
|
|
339
|
+
flattenD1Migrations
|
|
340
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import * as citty from 'citty';
|
|
2
|
+
|
|
3
|
+
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
|
+
}>;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export { _default as default };
|
package/dist/commands.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import {
|
|
2
|
+
buildCloudflareOutput
|
|
3
|
+
} from "./chunk-76ERVQJ3.js";
|
|
4
|
+
|
|
5
|
+
// src/commands.ts
|
|
6
|
+
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
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { ServiceProviderConstructor } from '@guren/core';
|
|
2
|
+
|
|
3
|
+
/** First call wins; later calls are ignored (never overwrite a live env). */
|
|
4
|
+
declare function captureWorkersEnv(env: unknown): void;
|
|
5
|
+
/** Throws with a clear message if called before the first request captured env. */
|
|
6
|
+
declare function getWorkersEnv<E = unknown>(): E;
|
|
7
|
+
/** Clears the holder. Used by createWorkersHandler on boot failure and by tests. */
|
|
8
|
+
declare function resetWorkersEnv(): void;
|
|
9
|
+
|
|
10
|
+
interface WorkersExecutionContext {
|
|
11
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
12
|
+
passThroughOnException?(): void;
|
|
13
|
+
}
|
|
14
|
+
interface WorkersAppLike {
|
|
15
|
+
boot(): Promise<void>;
|
|
16
|
+
fetch(request: Request, env?: unknown, executionCtx?: unknown): Response | Promise<Response>;
|
|
17
|
+
}
|
|
18
|
+
interface WorkersHandler {
|
|
19
|
+
fetch(request: Request, env: unknown, ctx: WorkersExecutionContext): Promise<Response>;
|
|
20
|
+
}
|
|
21
|
+
declare function createWorkersHandler(app: WorkersAppLike): WorkersHandler;
|
|
22
|
+
|
|
23
|
+
type PathLike = string | URL;
|
|
24
|
+
interface BuildCloudflareOutputOptions {
|
|
25
|
+
/** App root directory. Defaults to the current working directory. */
|
|
26
|
+
rootDir?: PathLike;
|
|
27
|
+
/** Output directory for the assembled worker. Defaults to `<root>/.cloudflare`. */
|
|
28
|
+
outputDir?: PathLike;
|
|
29
|
+
/** Module that default-exports the Guren Application. Defaults to `<root>/src/app.ts`. */
|
|
30
|
+
appEntry?: PathLike;
|
|
31
|
+
/** Static files directory copied into Workers Static Assets. Defaults to `<root>/public`. */
|
|
32
|
+
publicDir?: PathLike;
|
|
33
|
+
/** Vite SSR build output. Defaults to `<root>/.guren/ssr`. */
|
|
34
|
+
ssrDir?: PathLike;
|
|
35
|
+
/** Client manifest key for the frontend entry. Defaults to `resources/js/app.tsx`. */
|
|
36
|
+
clientEntryKey?: string;
|
|
37
|
+
/** SSR manifest key for the server entry. Defaults to `resources/js/ssr.tsx`. */
|
|
38
|
+
ssrEntryKey?: string;
|
|
39
|
+
/** Skip running the app's `build` script before assembling output. */
|
|
40
|
+
skipAppBuild?: boolean;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Assemble a deployable Cloudflare Workers directory (`.cloudflare/`) from a
|
|
44
|
+
* built Guren app: a generated worker entry that statically wires the SSR
|
|
45
|
+
* bundle, static assets for Workers Static Assets, and a one-time
|
|
46
|
+
* `wrangler.jsonc` scaffold. Deploy with `wrangler deploy`.
|
|
47
|
+
*/
|
|
48
|
+
declare function buildCloudflareOutput(options?: BuildCloudflareOutputOptions): Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* Wrangler's `migrations_dir` only discovers flat `*.sql` files, but
|
|
51
|
+
* drizzle-kit (1.x) emits one `<timestamp>_<name>/migration.sql` folder per
|
|
52
|
+
* migration. Flatten each folder into `<folder-name>.sql` (plain `*.sql`
|
|
53
|
+
* files pass through unchanged, `meta/` bookkeeping is skipped) so
|
|
54
|
+
* `wrangler d1 migrations apply` sees them in filename order. Regenerated on
|
|
55
|
+
* every build — run `cloudflare:build` after adding a migration.
|
|
56
|
+
*/
|
|
57
|
+
declare function flattenD1Migrations(migrationsDir: string, outDir: string): void;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Configuration for the Cloudflare plugin. Currently empty — reserved for
|
|
61
|
+
* upcoming RFC 0003 parts (session/OAuth-state store wiring on Workers).
|
|
62
|
+
*/
|
|
63
|
+
interface CloudflarePluginConfig {
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Register the Cloudflare plugin.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```typescript
|
|
70
|
+
* createApp({ providers: [cloudflarePlugin()] })
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
declare function cloudflarePlugin(config?: CloudflarePluginConfig): ServiceProviderConstructor;
|
|
74
|
+
|
|
75
|
+
export { type BuildCloudflareOutputOptions, type CloudflarePluginConfig, type WorkersAppLike, type WorkersExecutionContext, type WorkersHandler, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, resetWorkersEnv };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import {
|
|
2
|
+
buildCloudflareOutput,
|
|
3
|
+
flattenD1Migrations
|
|
4
|
+
} from "./chunk-76ERVQJ3.js";
|
|
5
|
+
|
|
6
|
+
// src/index.ts
|
|
7
|
+
import { definePlugin } from "@guren/core";
|
|
8
|
+
|
|
9
|
+
// src/env.ts
|
|
10
|
+
var holder;
|
|
11
|
+
function captureWorkersEnv(env) {
|
|
12
|
+
holder ??= { env };
|
|
13
|
+
}
|
|
14
|
+
function getWorkersEnv() {
|
|
15
|
+
if (!holder) {
|
|
16
|
+
throw new Error(
|
|
17
|
+
"getWorkersEnv() was called before the first request captured the Workers env. Defer access behind a closure instead of reading it at module scope, e.g. binding: () => getWorkersEnv<Env>().DB"
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
return holder.env;
|
|
21
|
+
}
|
|
22
|
+
function resetWorkersEnv() {
|
|
23
|
+
holder = void 0;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// src/handler.ts
|
|
27
|
+
function createWorkersHandler(app) {
|
|
28
|
+
let bootPromise;
|
|
29
|
+
return {
|
|
30
|
+
async fetch(request, env, ctx) {
|
|
31
|
+
captureWorkersEnv(env);
|
|
32
|
+
bootPromise ??= app.boot();
|
|
33
|
+
try {
|
|
34
|
+
await bootPromise;
|
|
35
|
+
} catch (error) {
|
|
36
|
+
bootPromise = void 0;
|
|
37
|
+
resetWorkersEnv();
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
return app.fetch(request, env, ctx);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// src/index.ts
|
|
46
|
+
var factory = definePlugin({
|
|
47
|
+
name: "cloudflare",
|
|
48
|
+
register() {
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
function cloudflarePlugin(config = {}) {
|
|
52
|
+
return factory(config);
|
|
53
|
+
}
|
|
54
|
+
export {
|
|
55
|
+
buildCloudflareOutput,
|
|
56
|
+
captureWorkersEnv,
|
|
57
|
+
cloudflarePlugin,
|
|
58
|
+
createWorkersHandler,
|
|
59
|
+
flattenD1Migrations,
|
|
60
|
+
getWorkersEnv,
|
|
61
|
+
resetWorkersEnv
|
|
62
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@guren/plugin-cloudflare",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/gurenjs/guren",
|
|
9
|
+
"directory": "packages/plugin-cloudflare"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/gurenjs/guren#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/gurenjs/guren/issues"
|
|
14
|
+
},
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public"
|
|
17
|
+
},
|
|
18
|
+
"gurenPlugin": {
|
|
19
|
+
"compatibility": ">=1.0.0 <2.0.0",
|
|
20
|
+
"commands": {
|
|
21
|
+
"entry": "./dist/commands.js",
|
|
22
|
+
"names": [
|
|
23
|
+
"cloudflare:build"
|
|
24
|
+
]
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"dist"
|
|
29
|
+
],
|
|
30
|
+
"main": "dist/index.js",
|
|
31
|
+
"types": "dist/index.d.ts",
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"types": "./dist/index.d.ts",
|
|
35
|
+
"default": "./dist/index.js"
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "tsup",
|
|
40
|
+
"test": "bun test",
|
|
41
|
+
"typecheck": "tsc --noEmit"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"@guren/core": "^1.3.0",
|
|
45
|
+
"citty": "^0.1.6"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@cloudflare/workers-types": "^4.20260702.1",
|
|
49
|
+
"@types/node": "^20.14.10",
|
|
50
|
+
"tsup": "^8.5.0",
|
|
51
|
+
"typescript": "^5.4.0"
|
|
52
|
+
}
|
|
53
|
+
}
|