@guren/core 1.8.0 → 1.9.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.
@@ -1,243 +1,501 @@
1
- // src/internal/deploy-build.ts
2
- import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync } from "fs";
3
- import { basename, dirname, isAbsolute, relative, resolve, sep } from "path";
4
- import { fileURLToPath } from "url";
1
+ import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync } from "node:fs";
2
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ //#region src/internal/deploy-build.ts
5
+ /**
6
+ * Build-time helpers shared by the deploy plugins (`@guren/plugin-cloudflare`,
7
+ * `@guren/plugin-lambda`, `@guren/plugin-vercel`).
8
+ *
9
+ * Internal by the rules in `contributing/api-stability.md`: reachable only
10
+ * through a deep import under `internal/`, never re-exported from
11
+ * `@guren/core`'s index. No stability guarantee — it exists so the three
12
+ * plugins stop carrying three copies of the same knowledge, not as a public
13
+ * extension point.
14
+ *
15
+ * Deliberately imports nothing from the framework itself: a plugin's build
16
+ * step should not drag the runtime into a developer's build process. Only
17
+ * `node:` builtins belong here, and `deploy-build.test.ts` asserts it of the
18
+ * built artifact — the property would otherwise break silently the day the bundler
19
+ * splits a shared chunk out of this entry.
20
+ *
21
+ * What does *not* belong here: anything a platform legitimately decides for
22
+ * itself. The message naming a platform and its replacement API, where a
23
+ * rendered stub is delivered (Workers resolves an alias to a file on disk,
24
+ * Lambda hands source to its bundler plugin), whether a missing `build` script
25
+ * is fatal, and how an SSR bundle's renderer export is verified are all
26
+ * per-plugin by design.
27
+ *
28
+ * One rule holds across the helpers here: a helper that *relates* two paths —
29
+ * a containment test, a relative specifier — canonicalizes both first, because
30
+ * whatever consumes the answer resolves links too. A helper that merely reads
31
+ * or writes one path passes it through, since the OS follows the links itself.
32
+ * That is why `resolveSsrEntryFile` compares raw strings (both operands derive
33
+ * from one `ssrDir`, so no link can come between them) and why the plugins'
34
+ * own `relative(root, out)` for `wrangler.jsonc` must stay lexical: that path
35
+ * is read by wrangler, not by a bundler resolving a module from its real path.
36
+ */
5
37
  function resolvePathLike(value) {
6
- return value instanceof URL ? fileURLToPath(value) : resolve(String(value));
38
+ return value instanceof URL ? fileURLToPath(value) : resolve(String(value));
7
39
  }
40
+ /**
41
+ * Read the first manifest that parses, tolerating both Vite layouts
42
+ * (`.vite/manifest.json` and the flat `manifest.json` older configs emit), and
43
+ * report which path it was. A malformed file is skipped rather than fatal —
44
+ * the caller decides what a missing manifest means for its platform. The path
45
+ * is part of the result because a caller publishing the manifest location to
46
+ * the runtime has to name the file that was actually parsed: testing which one
47
+ * *exists* picks the malformed one that was just skipped.
48
+ */
8
49
  function readManifest(...paths) {
9
- for (const path of paths) {
10
- if (!existsSync(path)) {
11
- continue;
12
- }
13
- try {
14
- return { manifest: JSON.parse(readFileSync(path, "utf8")), path };
15
- } catch {
16
- continue;
17
- }
18
- }
19
- return void 0;
50
+ for (const path of paths) {
51
+ if (!existsSync(path)) continue;
52
+ try {
53
+ return {
54
+ manifest: JSON.parse(readFileSync(path, "utf8")),
55
+ path
56
+ };
57
+ } catch {
58
+ continue;
59
+ }
60
+ }
20
61
  }
62
+ /** The two layouts `readManifest` accepts, in preference order. */
21
63
  function manifestPaths(dir) {
22
- return [resolve(dir, ".vite/manifest.json"), resolve(dir, "manifest.json")];
64
+ return [resolve(dir, ".vite/manifest.json"), resolve(dir, "manifest.json")];
23
65
  }
66
+ /**
67
+ * Resolve symlinks in the parts of `path` that exist, keeping the trailing
68
+ * components that do not. `realpathSync` throws on a path that is not there
69
+ * yet, and an output directory usually is not on a first build.
70
+ *
71
+ * A sibling of `realpathNearestExisting` in `@guren/cli`'s plugin-manifest.ts,
72
+ * kept as a copy because this module must not import beyond node builtins and
73
+ * cli cannot be imported from core. Only ENOENT walks up, matching the twin:
74
+ * any other failure (an unreadable or non-directory ancestor) is surfaced
75
+ * rather than silently treated as nonexistent — both callers relate two paths
76
+ * (a deletion guard, an import specifier) and neither may answer from a path
77
+ * it could not actually resolve.
78
+ */
24
79
  function realpathOfNearestExisting(path) {
25
- try {
26
- return realpathSync(path);
27
- } catch (error) {
28
- if (error.code !== "ENOENT") {
29
- throw error;
30
- }
31
- }
32
- const parent = dirname(path);
33
- if (parent === path) {
34
- return path;
35
- }
36
- return resolve(realpathOfNearestExisting(parent), basename(path));
80
+ try {
81
+ return realpathSync(path);
82
+ } catch (error) {
83
+ if (error.code !== "ENOENT") throw error;
84
+ }
85
+ const parent = dirname(path);
86
+ if (parent === path) return path;
87
+ return resolve(realpathOfNearestExisting(parent), basename(path));
37
88
  }
89
+ /**
90
+ * Throw unless `out` is safe to delete: it must be neither the app root nor a
91
+ * directory containing it.
92
+ *
93
+ * Relates two paths, so it canonicalizes both: comparing lexically would
94
+ * accept `outputDir` values that reach the app root the long way, and the
95
+ * delete that follows resolves the links regardless.
96
+ *
97
+ * Containment is then decided with `relative` rather than a string prefix
98
+ * because `out + sep` is `//` at the filesystem root, which no absolute path
99
+ * is prefixed by — a prefix test lets `outputDir: '/'` through. The escape
100
+ * test is `'..'` exactly or a `'../'` prefix, not `startsWith('..')`: a
101
+ * directory legitimately named `..-source` inside `out` yields the relative
102
+ * path `..-source`, which the looser test would read as an escape.
103
+ *
104
+ * Exported separately from `resetOutputDir` so a caller can validate the
105
+ * option early and delete later, but the delete itself should always go
106
+ * through `resetOutputDir`.
107
+ *
108
+ * @param label Platform name for the error message, e.g. `'Lambda build'`.
109
+ */
38
110
  function assertOutputDirOutsideRoot(out, root, label) {
39
- const outToRoot = relative(realpathOfNearestExisting(out), realpathOfNearestExisting(root));
40
- const rootIsInsideOut = outToRoot !== ".." && !outToRoot.startsWith(`..${sep}`) && !isAbsolute(outToRoot);
41
- if (outToRoot === "" || rootIsInsideOut) {
42
- throw new Error(
43
- `${label}: outputDir (${out}) must be a directory outside or below the app root, never the root itself or a parent of it \u2014 it is deleted on every build.`
44
- );
45
- }
111
+ const outToRoot = relative(realpathOfNearestExisting(out), realpathOfNearestExisting(root));
112
+ const rootIsInsideOut = outToRoot !== ".." && !outToRoot.startsWith(`..${sep}`) && !isAbsolute(outToRoot);
113
+ if (outToRoot === "" || rootIsInsideOut) throw new Error(`${label}: outputDir (${out}) must be a directory outside or below the app root, never the root itself or a parent of it — it is deleted on every build.`);
46
114
  }
115
+ /**
116
+ * Delete the output directory so the build starts from a clean slate, after
117
+ * checking it is safe to delete.
118
+ *
119
+ * The check and the delete are one call on purpose: they were separate
120
+ * statements in each plugin, and a plugin that had only the delete has already
121
+ * shipped.
122
+ *
123
+ * @param label Platform name for the error message, e.g. `'Lambda build'`.
124
+ */
47
125
  function resetOutputDir(out, root, label) {
48
- assertOutputDirOutsideRoot(out, root, label);
49
- if (existsSync(out)) {
50
- rmSync(out, { recursive: true, force: true });
51
- }
126
+ assertOutputDirOutsideRoot(out, root, label);
127
+ if (existsSync(out)) rmSync(out, {
128
+ recursive: true,
129
+ force: true
130
+ });
52
131
  }
132
+ /**
133
+ * Relative specifier for importing `target` from a module written into
134
+ * `fromDir`, in POSIX form so the emitted source is platform-agnostic.
135
+ *
136
+ * Relates two paths, so it canonicalizes both: the bundler resolves the
137
+ * emitted module from its real path, and a link that changes depth would
138
+ * otherwise leave the specifier short a `..` segment.
139
+ *
140
+ * @param label Platform name for the error message, e.g. `'Lambda build'`.
141
+ */
53
142
  function importSpecifier(fromDir, target, label) {
54
- const rel = relative(realpathOfNearestExisting(fromDir), realpathOfNearestExisting(target));
55
- if (isAbsolute(rel)) {
56
- throw new Error(
57
- `${label}: ${target} cannot be imported relative to ${fromDir} (different drive or root?). Keep the app, SSR output, and outputDir on the same volume.`
58
- );
59
- }
60
- const specifier = rel.split(sep).join("/");
61
- return specifier.startsWith(".") ? specifier : `./${specifier}`;
143
+ const rel = relative(realpathOfNearestExisting(fromDir), realpathOfNearestExisting(target));
144
+ if (isAbsolute(rel)) throw new Error(`${label}: ${target} cannot be imported relative to ${fromDir} (different drive or root?). Keep the app, SSR output, and outputDir on the same volume.`);
145
+ const specifier = rel.split(sep).join("/");
146
+ return specifier.startsWith(".") ? specifier : `./${specifier}`;
62
147
  }
148
+ /**
149
+ * Locate the built client entry and its CSS in the Vite client manifest, as
150
+ * the `/assets/`-prefixed URLs the Inertia head expects.
151
+ *
152
+ * Takes the public directory rather than the app root so a caller passing a
153
+ * custom `publicDir` is honoured.
154
+ *
155
+ * @param label Platform name for the warning message, e.g. `'Lambda build'`.
156
+ */
63
157
  function resolveClientAssetEnv(publicDir, clientEntryKey, label) {
64
- const manifest = readManifest(...manifestPaths(resolve(publicDir, "assets")))?.manifest;
65
- const entry = manifest?.[clientEntryKey];
66
- if (!entry?.file) {
67
- console.warn(
68
- `${label}: no client manifest entry for "${clientEntryKey}"; GUREN_INERTIA_ENTRY will not be set.`
69
- );
70
- return {};
71
- }
72
- return {
73
- entry: `/assets/${entry.file}`,
74
- styles: entry.css?.length ? entry.css.map((file) => `/assets/${file}`).join(",") : void 0
75
- };
158
+ const entry = (readManifest(...manifestPaths(resolve(publicDir, "assets")))?.manifest)?.[clientEntryKey];
159
+ if (!entry?.file) {
160
+ console.warn(`${label}: no client manifest entry for "${clientEntryKey}"; GUREN_INERTIA_ENTRY will not be set.`);
161
+ return {};
162
+ }
163
+ return {
164
+ entry: `/assets/${entry.file}`,
165
+ styles: entry.css?.length ? entry.css.map((file) => `/assets/${file}`).join(",") : void 0
166
+ };
76
167
  }
168
+ /**
169
+ * Absolute path of the built SSR entry chunk, or undefined when the app has no
170
+ * SSR build. Verifying that the chunk actually exports a renderer is left to
171
+ * the caller: the platforms disagree on whether importing it during a build is
172
+ * acceptable.
173
+ *
174
+ * @param label Platform name for the error messages, e.g. `'Lambda build'`.
175
+ */
77
176
  function resolveSsrEntryFile(ssrDir, ssrEntryKey, label) {
78
- const manifest = readManifest(...manifestPaths(ssrDir))?.manifest;
79
- const entryFile = manifest?.[ssrEntryKey]?.file;
80
- if (!entryFile) {
81
- return void 0;
82
- }
83
- const file = resolve(ssrDir, entryFile);
84
- if (!file.startsWith(ssrDir + sep)) {
85
- throw new Error(`${label}: SSR manifest entry "${entryFile}" escapes the SSR output directory ${ssrDir}.`);
86
- }
87
- if (!existsSync(file)) {
88
- throw new Error(`${label}: SSR manifest points at ${file}, but the file does not exist.`);
89
- }
90
- return file;
177
+ const entryFile = (readManifest(...manifestPaths(ssrDir))?.manifest)?.[ssrEntryKey]?.file;
178
+ if (!entryFile) return;
179
+ const file = resolve(ssrDir, entryFile);
180
+ if (!file.startsWith(ssrDir + sep)) throw new Error(`${label}: SSR manifest entry "${entryFile}" escapes the SSR output directory ${ssrDir}.`);
181
+ if (!existsSync(file)) throw new Error(`${label}: SSR manifest points at ${file}, but the file does not exist.`);
182
+ return file;
91
183
  }
184
+ /**
185
+ * Runtime locations of a staged SSR bundle, for platforms that copy `ssrDir`
186
+ * under the function root and hand the layout to the server through
187
+ * environment variables. `prefix` is where the caller stages the directory —
188
+ * it cannot be derived here because staging happens later in the caller's own
189
+ * flow.
190
+ *
191
+ * The manifest path is derived from the file that parsed rather than the
192
+ * first one that exists: both Vite layouts occur in the wild, and a malformed
193
+ * `.vite/manifest.json` alongside a valid flat one would otherwise publish the
194
+ * path to the file that was skipped. It is optional only for the mid-build
195
+ * race where the manifest vanishes between `resolveSsrEntryFile` and this
196
+ * call — callers already hold a chunk path that manifest produced.
197
+ */
92
198
  function ssrRuntimePaths(ssrDir, ssrFile, prefix) {
93
- const under = (target) => `${prefix}/${relative(ssrDir, target).split(sep).join("/")}`;
94
- const read = readManifest(...manifestPaths(ssrDir));
95
- return {
96
- entry: under(ssrFile),
97
- manifest: read ? under(read.path) : void 0
98
- };
199
+ const under = (target) => `${prefix}/${relative(ssrDir, target).split(sep).join("/")}`;
200
+ const read = readManifest(...manifestPaths(ssrDir));
201
+ return {
202
+ entry: under(ssrFile),
203
+ manifest: read ? under(read.path) : void 0
204
+ };
99
205
  }
206
+ /**
207
+ * Copy `public/` into a platform's static-asset staging directory.
208
+ *
209
+ * Two pieces of Guren-specific knowledge, not platform policy, which is why
210
+ * this is shared: the dev-mode `index.html` shell must never ship (it would
211
+ * shadow the app's root route on any host that serves static files first), and
212
+ * built assets self-reference the Vite plugin's derived base `/public/assets/`
213
+ * while HTML references use `/assets/` — so on a host without rewrites the
214
+ * built-assets directory has to appear under both prefixes.
215
+ */
100
216
  function stageStaticAssets(publicDir, assetsOut) {
101
- mkdirSync(assetsOut, { recursive: true });
102
- if (!existsSync(publicDir)) {
103
- return;
104
- }
105
- cpSync(publicDir, assetsOut, { recursive: true });
106
- const shadowingIndex = resolve(assetsOut, "index.html");
107
- if (existsSync(shadowingIndex)) {
108
- rmSync(shadowingIndex);
109
- }
110
- const clientAssetsDir = resolve(publicDir, "assets");
111
- if (existsSync(clientAssetsDir)) {
112
- cpSync(clientAssetsDir, resolve(assetsOut, "public/assets"), { recursive: true });
113
- }
114
- }
115
- var DEV_ONLY_MODULES = [
116
- { specifier: "bun:sqlite", kind: "sqlite", exportNames: ["Database"] },
117
- { specifier: "vite", kind: "vite", exportNames: ["createServer"] },
118
- { specifier: "@guren/cli", kind: "mcp", exportNames: [] },
119
- {
120
- specifier: "@modelcontextprotocol/sdk/server/mcp.js",
121
- kind: "mcp",
122
- exportNames: ["McpServer", "ResourceTemplate"]
123
- },
124
- {
125
- specifier: "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js",
126
- kind: "mcp",
127
- exportNames: ["WebStandardStreamableHTTPServerTransport"]
128
- }
217
+ mkdirSync(assetsOut, { recursive: true });
218
+ if (!existsSync(publicDir)) return;
219
+ cpSync(publicDir, assetsOut, { recursive: true });
220
+ const shadowingIndex = resolve(assetsOut, "index.html");
221
+ if (existsSync(shadowingIndex)) rmSync(shadowingIndex);
222
+ const clientAssetsDir = resolve(publicDir, "assets");
223
+ if (existsSync(clientAssetsDir)) cpSync(clientAssetsDir, resolve(assetsOut, "public/assets"), { recursive: true });
224
+ }
225
+ /**
226
+ * Modules that cannot run off Bun but sit in the graph of any app importing
227
+ * `@guren/core`, reached only through dev-time branches. Core aggregates
228
+ * `@guren/server` and `@guren/orm`, where these imports actually live, so it
229
+ * is the one package that sees the whole set — which is why the list lives
230
+ * here rather than in each plugin, where two copies had already drifted apart.
231
+ *
232
+ * Bundlers follow these imports even when they are dynamic, so without stubs
233
+ * the build either fails to resolve them or ships megabytes of dev tooling.
234
+ *
235
+ * - `sqlite` — the local sqlite ORM factory, opposite the platform's own
236
+ * database branch in `config/database.ts`.
237
+ * - `vite` — the dev asset server `Application` starts when serving locally.
238
+ * - `mcp` — the opt-in MCP endpoint's lazy imports, which drag the CLI
239
+ * generators (and Babel) plus the MCP SDK in behind them.
240
+ *
241
+ * SQL client libraries are deliberately *not* here: they are dev-only on
242
+ * Workers, where D1 is the only database, and load-bearing on Lambda and
243
+ * Vercel, which connect to Postgres. See `SQL_CLIENT_MODULES`.
244
+ *
245
+ * `as const` so a consumer can key an exhaustive table on the specifiers and
246
+ * have a new entry here surface as a compile error there.
247
+ */
248
+ const DEV_ONLY_MODULES = [
249
+ {
250
+ specifier: "bun:sqlite",
251
+ kind: "sqlite",
252
+ exportNames: ["Database"]
253
+ },
254
+ {
255
+ specifier: "vite",
256
+ kind: "vite",
257
+ exportNames: ["createServer"]
258
+ },
259
+ {
260
+ specifier: "@guren/cli",
261
+ kind: "mcp",
262
+ exportNames: []
263
+ },
264
+ {
265
+ specifier: "@modelcontextprotocol/sdk/server/mcp.js",
266
+ kind: "mcp",
267
+ exportNames: ["McpServer", "ResourceTemplate"]
268
+ },
269
+ {
270
+ specifier: "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js",
271
+ kind: "mcp",
272
+ exportNames: ["WebStandardStreamableHTTPServerTransport"]
273
+ }
129
274
  ];
130
- var DATABASE_FACTORIES = {
131
- createPostgresDatabase: "postgres",
132
- createMySqlDatabase: "mysql",
133
- createSqliteDatabase: "sqlite",
134
- createAwsDataApiDatabase: "aws-data-api",
135
- createD1Database: "d1"
275
+ /**
276
+ * The `@guren/orm` factory names an app's database config calls, and the
277
+ * dialect each one declares.
278
+ *
279
+ * Taken from `@guren/core`'s export allowlist rather than from the ORM's
280
+ * implementation files, and pinned there by a test: a list built from the
281
+ * implementation admits names that were never exported and misses the aliases
282
+ * that were. The spelling is `createMySqlDatabase`, not `createMysqlDatabase`
283
+ * — a build that filters on a name nobody exports detects nothing and stubs
284
+ * nothing, which is silent.
285
+ */
286
+ const DATABASE_FACTORIES = {
287
+ createPostgresDatabase: "postgres",
288
+ createMySqlDatabase: "mysql",
289
+ createSqliteDatabase: "sqlite",
290
+ createAwsDataApiDatabase: "aws-data-api",
291
+ createD1Database: "d1"
136
292
  };
137
- var SQL_CLIENT_MODULES = [
138
- { specifier: "postgres", kind: "sql-driver", dialect: "postgres", exportNames: [] },
139
- { specifier: "mysql2", kind: "sql-driver", dialect: "mysql", exportNames: [] },
140
- { specifier: "mysql2/promise", kind: "sql-driver", dialect: "mysql", exportNames: ["createPool"] },
141
- {
142
- specifier: "@aws-sdk/client-rds-data",
143
- kind: "sql-driver",
144
- dialect: "aws-data-api",
145
- exportNames: [
146
- "RDSDataClient",
147
- "BeginTransactionCommand",
148
- "CommitTransactionCommand",
149
- "ExecuteStatementCommand",
150
- "RollbackTransactionCommand"
151
- ]
152
- }
293
+ /**
294
+ * The database client libraries `@guren/orm`'s Postgres, MySQL and Aurora
295
+ * Data API factories reach for.
296
+ *
297
+ * They sit apart from `DEV_ONLY_MODULES` because whether they are dead weight
298
+ * depends on the platform: on Workers, D1 is the only database there is, so
299
+ * every one of these is unreachable; on Lambda and Vercel the app connects to
300
+ * Postgres through them and stubbing them would break a working deploy.
301
+ *
302
+ * That makes the list itself the wrong granularity for a platform that hosts
303
+ * more than one dialect. Workers stubs all of it; Lambda and Vercel stub the
304
+ * entries whose `dialect` the app's config does not declare, which is what
305
+ * `unusedSqlClients` decides.
306
+ *
307
+ * A platform where they are unreachable has to stub them rather than ignore
308
+ * them. `@guren/orm` names them in *literal* dynamic imports, which a bundler
309
+ * follows whether or not the branch can be taken — so a D1 app failed to
310
+ * bundle on `Could not resolve "postgres"`, naming a database its author had
311
+ * deliberately not chosen. Both the client and the drizzle entry point that
312
+ * imports it need stubbing: aliasing only the client leaves drizzle's own
313
+ * `import pgClient from "postgres"` to resolve.
314
+ *
315
+ * Export names are read off drizzle-orm's driver and session modules, which
316
+ * is what a bundler checks a stub against.
317
+ */
318
+ const SQL_CLIENT_MODULES = [
319
+ {
320
+ specifier: "postgres",
321
+ kind: "sql-driver",
322
+ dialect: "postgres",
323
+ exportNames: []
324
+ },
325
+ {
326
+ specifier: "mysql2",
327
+ kind: "sql-driver",
328
+ dialect: "mysql",
329
+ exportNames: []
330
+ },
331
+ {
332
+ specifier: "mysql2/promise",
333
+ kind: "sql-driver",
334
+ dialect: "mysql",
335
+ exportNames: ["createPool"]
336
+ },
337
+ {
338
+ specifier: "@aws-sdk/client-rds-data",
339
+ kind: "sql-driver",
340
+ dialect: "aws-data-api",
341
+ exportNames: [
342
+ "RDSDataClient",
343
+ "BeginTransactionCommand",
344
+ "CommitTransactionCommand",
345
+ "ExecuteStatementCommand",
346
+ "RollbackTransactionCommand"
347
+ ]
348
+ }
153
349
  ];
154
- var DATABASE_CONFIG_CANDIDATES = ["config/database.ts", "db/config.ts"];
350
+ /**
351
+ * Where an app declares its database, in the order it is looked for.
352
+ *
353
+ * The same pair `guren doctor` checks, kept as a copy for the same reason
354
+ * `realpathOfNearestExisting` above is one: this module must not import
355
+ * beyond node builtins, and cli cannot be imported from core. If the two ever
356
+ * disagree, a build would stub clients for an app whose config the doctor
357
+ * says is fine — so a change to either belongs in both.
358
+ */
359
+ const DATABASE_CONFIG_CANDIDATES = ["config/database.ts", "db/config.ts"];
360
+ /**
361
+ * Which databases an app connects to, read off its database config.
362
+ *
363
+ * A *union*, never a single answer: an app legitimately names two factories in
364
+ * one file, picking between them at runtime — the Workers app in this
365
+ * repository declares D1 for the deployed worker and sqlite for local
366
+ * development, and a Lambda app can pair Postgres with sqlite the same way.
367
+ * Taking the first match would stub a client the app really does reach for.
368
+ *
369
+ * Matching is a scan for the factory names, not a parse: every way of being
370
+ * wrong about a name that *is* in the file — mentioned in a comment, imported
371
+ * but never called, called in a branch this deploy will not take — errs
372
+ * toward reporting a dialect the app might not use, and the caller stubs
373
+ * fewer clients as a result. The opposite error is the dangerous one, so the
374
+ * cheap reading is the right one. A config that reaches a factory without
375
+ * naming it (a re-export, an indirection through another module) reports
376
+ * nothing, and the caller stubs nothing.
377
+ */
155
378
  function detectDatabaseDialects(root) {
156
- for (const candidate of DATABASE_CONFIG_CANDIDATES) {
157
- const path = resolve(root, candidate);
158
- if (!existsSync(path)) {
159
- continue;
160
- }
161
- let source;
162
- try {
163
- source = readFileSync(path, "utf8");
164
- } catch {
165
- return { source: candidate };
166
- }
167
- const dialects = /* @__PURE__ */ new Set();
168
- for (const [factory, dialect] of Object.entries(DATABASE_FACTORIES)) {
169
- if (new RegExp(`\\b${factory}\\b`).test(source)) {
170
- dialects.add(dialect);
171
- }
172
- }
173
- return dialects.size > 0 ? { dialects: [...dialects], source: candidate } : { source: candidate };
174
- }
175
- return {};
176
- }
177
- var DATABASE_DIALECTS = [...new Set(Object.values(DATABASE_FACTORIES))];
379
+ for (const candidate of DATABASE_CONFIG_CANDIDATES) {
380
+ const path = resolve(root, candidate);
381
+ if (!existsSync(path)) continue;
382
+ let source;
383
+ try {
384
+ source = readFileSync(path, "utf8");
385
+ } catch {
386
+ return { source: candidate };
387
+ }
388
+ const dialects = /* @__PURE__ */ new Set();
389
+ for (const [factory, dialect] of Object.entries(DATABASE_FACTORIES)) if (new RegExp(`\\b${factory}\\b`).test(source)) dialects.add(dialect);
390
+ return dialects.size > 0 ? {
391
+ dialects: [...dialects],
392
+ source: candidate
393
+ } : { source: candidate };
394
+ }
395
+ return {};
396
+ }
397
+ /** Every dialect name `databaseDialects` accepts, for validation and messages. */
398
+ const DATABASE_DIALECTS = [...new Set(Object.values(DATABASE_FACTORIES))];
399
+ /**
400
+ * Reject a dialect list that names nothing, or names something that is not a
401
+ * dialect.
402
+ *
403
+ * Both are rejected rather than dropped because both mean the same thing to
404
+ * the filter downstream — a dialect it never sees is a dialect whose client it
405
+ * stubs. An empty list stubs *every* client, and `['postgress']` stubs the
406
+ * Postgres one; either way the bundle builds clean and the deployed function
407
+ * cannot reach its own database. That is the failure the caller reached for
408
+ * this option to avoid, so it fails here, at build time, with the typo in the
409
+ * message.
410
+ *
411
+ * Deliberately not a fail-open: the surrounding code stubs nothing when it
412
+ * cannot *read* an app's dialects, but this input is a caller stating them.
413
+ * Falling back to detection would discard the override and then stub according
414
+ * to the very config the caller was overriding.
415
+ *
416
+ * @param label Platform name for the error message, e.g. `'Lambda build'`.
417
+ */
178
418
  function assertDatabaseDialects(names, label, quoted) {
179
- const unknown = names.filter((name) => !DATABASE_DIALECTS.includes(name));
180
- if (names.length === 0 || unknown.length > 0) {
181
- throw new Error(
182
- `${label}: ${quoted} does not name a database. Expected one or more of ${DATABASE_DIALECTS.join(", ")}.`
183
- );
184
- }
185
- return names;
419
+ const unknown = names.filter((name) => !DATABASE_DIALECTS.includes(name));
420
+ if (names.length === 0 || unknown.length > 0) throw new Error(`${label}: ${quoted} does not name a database. Expected one or more of ${DATABASE_DIALECTS.join(", ")}.`);
421
+ return names;
186
422
  }
423
+ /**
424
+ * Parse a comma-separated `--database` value into dialects.
425
+ *
426
+ * @param label Platform name for the error message, e.g. `'Lambda build'`.
427
+ */
187
428
  function parseDatabaseDialects(value, label) {
188
- const names = value.split(",").map((name) => name.trim()).filter((name) => name.length > 0);
189
- return assertDatabaseDialects(names, label, JSON.stringify(value));
429
+ return assertDatabaseDialects(value.split(",").map((name) => name.trim()).filter((name) => name.length > 0), label, JSON.stringify(value));
190
430
  }
431
+ /**
432
+ * The database clients an app does not connect through, for a platform where
433
+ * the ones it *does* connect through are load-bearing — Lambda and Vercel,
434
+ * as opposed to Workers, where D1 is the only database and every client in
435
+ * `SQL_CLIENT_MODULES` is unreachable regardless of what the config says.
436
+ *
437
+ * Fails open: when the dialects cannot be read, this warns and returns
438
+ * nothing to stub. The two errors are not symmetric. Under-stubbing leaves
439
+ * today's behaviour — the build fails to resolve a client the app never
440
+ * installed, loudly, at build time. Over-stubbing produces a bundle that
441
+ * builds clean and then cannot reach its own database, at runtime, in
442
+ * production. Only the second is worth protecting against, so anything less
443
+ * than positive evidence means stub nothing.
444
+ *
445
+ * @param dialects Overrides detection when the caller already knows, for an
446
+ * app whose config the scan cannot read.
447
+ * @param label Platform name for the messages, e.g. `'Lambda build'`.
448
+ */
191
449
  function unusedSqlClients(input) {
192
- const { root, label } = input;
193
- const detection = input.dialects ? { dialects: assertDatabaseDialects(input.dialects, label, `databaseDialects ${JSON.stringify(input.dialects)}`) } : detectDatabaseDialects(root);
194
- const declared = detection.dialects;
195
- if (!declared) {
196
- console.warn(
197
- `${label}: ${detection.source ? `${detection.source} names no @guren/orm database factory` : `no database config found (looked for ${DATABASE_CONFIG_CANDIDATES.join(", ")})`} \u2014 every database client stays in the module graph, and the build fails on any this app has not installed. Name them with the build's "databaseDialects" option (--database on the command line).`
198
- );
199
- return [];
200
- }
201
- const declaredList = declared.join(", ");
202
- return SQL_CLIENT_MODULES.filter((module) => !declared.includes(module.dialect)).map((module) => ({
203
- module,
204
- message: `${label}: the "${module.specifier}" client is stubbed \u2014 this app declares ${declaredList}, not ${module.dialect}. @guren/orm names every dialect's client in a dynamic import that bundlers follow even when the branch cannot be taken, so an uninstalled client would otherwise fail the build. If this app really does connect with ${module.dialect}, pass databaseDialects: ['${module.dialect}'] to the build.`
205
- }));
450
+ const { root, label } = input;
451
+ const detection = input.dialects ? { dialects: assertDatabaseDialects(input.dialects, label, `databaseDialects ${JSON.stringify(input.dialects)}`) } : detectDatabaseDialects(root);
452
+ const declared = detection.dialects;
453
+ if (!declared) {
454
+ console.warn(`${label}: ${detection.source ? `${detection.source} names no @guren/orm database factory` : `no database config found (looked for ${DATABASE_CONFIG_CANDIDATES.join(", ")})`} — every database client stays in the module graph, and the build fails on any this app has not installed. Name them with the build's "databaseDialects" option (--database on the command line).`);
455
+ return [];
456
+ }
457
+ const declaredList = declared.join(", ");
458
+ return SQL_CLIENT_MODULES.filter((module) => !declared.includes(module.dialect)).map((module) => ({
459
+ module,
460
+ message: `${label}: the "${module.specifier}" client is stubbed — this app declares ${declaredList}, not ${module.dialect}. @guren/orm names every dialect's client in a dynamic import that bundlers follow even when the branch cannot be taken, so an uninstalled client would otherwise fail the build. If this app really does connect with ${module.dialect}, pass databaseDialects: ['${module.dialect}'] to the build.`
461
+ }));
206
462
  }
463
+ /**
464
+ * Source for a stub replacing one dev-only module. Shared because what it
465
+ * encodes is a bundler constraint, not a platform choice: every name the
466
+ * importer destructures must be present or the bundle fails with "no matching
467
+ * export", and each is emitted as a throwing *function* because the stubbed
468
+ * names mix constructors (`new Database()`) with plain calls
469
+ * (`createServer()`) — a class invoked without `new` reports "Class
470
+ * constructor cannot be invoked without 'new'" instead of the real reason.
471
+ *
472
+ * @param message Platform-specific explanation, including the replacement API.
473
+ */
474
+ /**
475
+ * A JavaScript string literal for `value`.
476
+ *
477
+ * `JSON.stringify` alone is not one: JSON and JavaScript disagree about
478
+ * U+2028 and U+2029, which JSON leaves raw while JavaScript reads them as
479
+ * line terminators — so a message containing either ends the statement it was
480
+ * embedded in on any target below ES2019.
481
+ */
207
482
  function toJsStringLiteral(value) {
208
- return JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
483
+ return JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
209
484
  }
210
485
  function renderDevOnlyStub(module, message) {
211
- const comment = message.replace(/[\r\n\u2028\u2029]+/g, " ");
212
- const error = `throw new Error(${toJsStringLiteral(message)})`;
213
- const throwing = module.exportNames.map((name) => `export function ${name}() { ${error} }`).join("\n");
214
- const named = module.exportNames.length > 0 ? `, { ${module.exportNames.join(", ")} }` : "";
215
- const fallback = `function unavailable() { ${error} }`;
216
- return `// ${comment}
217
- ${throwing}
218
- ${fallback}
219
- export default Object.assign(unavailable${named})
220
- `;
221
- }
222
- var MCP_SDK_SUBPATH_PREFIX = "@modelcontextprotocol/sdk/";
223
- export {
224
- DATABASE_CONFIG_CANDIDATES,
225
- DATABASE_DIALECTS,
226
- DATABASE_FACTORIES,
227
- DEV_ONLY_MODULES,
228
- MCP_SDK_SUBPATH_PREFIX,
229
- SQL_CLIENT_MODULES,
230
- assertOutputDirOutsideRoot,
231
- detectDatabaseDialects,
232
- importSpecifier,
233
- parseDatabaseDialects,
234
- readManifest,
235
- renderDevOnlyStub,
236
- resetOutputDir,
237
- resolveClientAssetEnv,
238
- resolvePathLike,
239
- resolveSsrEntryFile,
240
- ssrRuntimePaths,
241
- stageStaticAssets,
242
- unusedSqlClients
243
- };
486
+ const comment = message.replace(/[\r\n\u2028\u2029]+/g, " ");
487
+ const error = `throw new Error(${toJsStringLiteral(message)})`;
488
+ const throwing = module.exportNames.map((name) => `export function ${name}() { ${error} }`).join("\n");
489
+ const named = module.exportNames.length > 0 ? `, { ${module.exportNames.join(", ")} }` : "";
490
+ return `// ${comment}\n${throwing}\n${`function unavailable() { ${error} }`}\nexport default Object.assign(unavailable${named})\n`;
491
+ }
492
+ /**
493
+ * The MCP SDK is only ever reached through subpaths, and a bundler alias on a
494
+ * package name does not cover them — which is why `DEV_ONLY_MODULES` lists
495
+ * each one. A platform whose aliasing supports prefixes should also route
496
+ * unlisted subpaths under this prefix to a stub, so a new subpath added
497
+ * upstream cannot pull the real SDK into a deployed bundle.
498
+ */
499
+ const MCP_SDK_SUBPATH_PREFIX = "@modelcontextprotocol/sdk/";
500
+ //#endregion
501
+ export { DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, MCP_SDK_SUBPATH_PREFIX, SQL_CLIENT_MODULES, assertOutputDirOutsideRoot, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, unusedSqlClients };