@guren/plugin-cloudflare 0.5.0 → 0.6.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/build-B2fIb1lu.js +867 -0
- package/dist/commands.d.ts +8 -0
- package/dist/commands.js +12 -2
- package/dist/env.d.ts +26 -0
- package/dist/env.js +34 -0
- package/dist/index.d.ts +25 -8
- package/dist/index.js +2 -17
- package/package.json +10 -3
- package/templates/mcp-oauth/app/Http/Controllers/McpOAuthController.ts +286 -0
- package/templates/mcp-oauth/app/View/McpOAuthConsentPage.tsx +142 -0
- package/templates/mcp-oauth/app/View/McpOAuthErrorPage.tsx +57 -0
- package/templates/mcp-oauth/routes/mcp-oauth.ts +35 -0
- package/dist/build-B7zQ13ai.js +0 -321
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** @jsxImportSource @guren/core */
|
|
2
|
+
import type { FC } from '@guren/core'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The page a visitor gets when the authorize request itself is unusable —
|
|
6
|
+
* scaffolded once by `guren cloudflare:build --mcp-oauth` and yours to edit.
|
|
7
|
+
*
|
|
8
|
+
* These arrivals are routine, not application faults: a query that is
|
|
9
|
+
* malformed, truncated, tampered with, or simply stale, and a consent form
|
|
10
|
+
* submitted after its CSRF token expired. Left to the exception handler they
|
|
11
|
+
* would surface as a 500 with a stack trace in it — alarming, and useless to
|
|
12
|
+
* the person reading it, because the fix is never anything they can do on this
|
|
13
|
+
* page. It is to start again from the client that sent them.
|
|
14
|
+
*
|
|
15
|
+
* **Nothing derived from the request is rendered here.** No provider message,
|
|
16
|
+
* no query parameter, no exception text: all of it is attacker-controllable,
|
|
17
|
+
* and this page is reached by a browser. `title` and `advice` are the
|
|
18
|
+
* caller's own fixed strings.
|
|
19
|
+
*
|
|
20
|
+
* A file of its own rather than a second export beside the consent screen: it
|
|
21
|
+
* is a different document with different styling and no form, and a developer
|
|
22
|
+
* editing the consent screen should not have to scroll past it.
|
|
23
|
+
*
|
|
24
|
+
* See `McpOAuthConsentPage.tsx` for why the `@jsxImportSource` pragma on line
|
|
25
|
+
* 1 is what lets this compile in an app whose `tsconfig` points
|
|
26
|
+
* `jsx: "react-jsx"` at React. Keep it on the first line.
|
|
27
|
+
*/
|
|
28
|
+
export interface McpOAuthErrorPageProps {
|
|
29
|
+
/** What went wrong, in the visitor's terms. A fixed string, never echoed input. */
|
|
30
|
+
title: string
|
|
31
|
+
/** What to do about it. Also fixed. */
|
|
32
|
+
advice: string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const STYLES = `
|
|
36
|
+
:root { color-scheme: light dark; font-family: system-ui, sans-serif; }
|
|
37
|
+
body { margin: 0 auto; max-width: 32rem; padding: 3rem 1rem; line-height: 1.5; }
|
|
38
|
+
h1 { font-size: 1.25rem; }
|
|
39
|
+
p { opacity: .8; }
|
|
40
|
+
`
|
|
41
|
+
|
|
42
|
+
export const McpOAuthErrorPage: FC<McpOAuthErrorPageProps> = ({ title, advice }) => (
|
|
43
|
+
<html lang="en">
|
|
44
|
+
<head>
|
|
45
|
+
<meta charset="utf-8" />
|
|
46
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
47
|
+
<title>{title}</title>
|
|
48
|
+
<style>{STYLES}</style>
|
|
49
|
+
</head>
|
|
50
|
+
<body>
|
|
51
|
+
<h1>{title}</h1>
|
|
52
|
+
<p>{advice}</p>
|
|
53
|
+
</body>
|
|
54
|
+
</html>
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
export default McpOAuthErrorPage
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The OAuth authorize/consent routes for the App MCP endpoint, scaffolded once
|
|
3
|
+
* by `guren cloudflare:build --mcp-oauth` and yours to edit from here.
|
|
4
|
+
*
|
|
5
|
+
* `@cloudflare/workers-oauth-provider` owns `/oauth/token` and
|
|
6
|
+
* `/oauth/register` itself — it answers them before the request ever reaches
|
|
7
|
+
* this application. `/oauth/authorize` is the one endpoint the provider hands
|
|
8
|
+
* back, because only the application can say who is signed in and render a
|
|
9
|
+
* consent screen that means anything.
|
|
10
|
+
*
|
|
11
|
+
* **Wire this into your routes entry**, or nothing mounts it:
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* // routes/web.ts
|
|
15
|
+
* import { registerMcpOAuthRoutes } from './mcp-oauth'
|
|
16
|
+
*
|
|
17
|
+
* export function registerWebRoutes(router: Router): void {
|
|
18
|
+
* registerMcpOAuthRoutes(router)
|
|
19
|
+
* // …your own routes
|
|
20
|
+
* }
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* These routes are deliberately **not** `.agent()`-exposed: they are the gate
|
|
24
|
+
* an agent passes through, not something an agent may call.
|
|
25
|
+
*/
|
|
26
|
+
import type { Router } from '@guren/core'
|
|
27
|
+
|
|
28
|
+
import McpOAuthController from '../app/Http/Controllers/McpOAuthController.js'
|
|
29
|
+
|
|
30
|
+
export function registerMcpOAuthRoutes(router: Router): void {
|
|
31
|
+
router.get('/oauth/authorize', [McpOAuthController, 'show']).name('mcp-oauth.authorize')
|
|
32
|
+
router.post('/oauth/authorize', [McpOAuthController, 'approve']).name('mcp-oauth.approve')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export default registerMcpOAuthRoutes
|
package/dist/build-B7zQ13ai.js
DELETED
|
@@ -1,321 +0,0 @@
|
|
|
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 };
|