@guren/core 1.6.1 → 1.7.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/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ApiTokenStore, ApiToken, SessionStore, SessionData, OAuthStateStore, OAuthStatePayload } from '@guren/server';
2
2
  export * from '@guren/server';
3
- export { AccessorDefinitions, AccessorFn, AwsDataApiDatabase, AwsDataApiDatabaseOptions, AwsDataApiSeederContext, BelongsToManyRecord, BelongsToManyRelationResult, BelongsToRecord, BelongsToRelationResult, BelongsToRequiredRecord, CastType, D1DatabaseHandle, D1DatabaseOptions, DrizzleAdapter, FindManyOptions, GroupCondition, HasManyRecord, HasManyRelationResult, HasManyThroughRecord, HasManyThroughRelationResult, HasOneRecord, HasOneRelationResult, HookCallback, HookName, InferModelInsert, InferModelRecord, MassAssignmentException, Model, ModelHooks, ModelNotFoundException, ModelObserver, ModelObserverConstructor, ModelPaginationMeta, MorphManyRecord, MorphManyRelationResult, MorphToRecord, MorphToRelationResult, MutatorDefinitions, MutatorFn, MySqlDatabase, MySqlDatabaseOptions, MySqlSeederContext, ORMAdapter, ORMAdapterAdvanced, OrderByClause, OrderByInput, OrderDefinition, OrderDirection, PaginateOptions, PaginatedResult, PlainObject, PostgresDatabase, PostgresDatabaseOptions, PostgresSeederContext, QueryBuilder, QueryBuilderOptions, ScopeFunction, SeederContext, SeederHandler, SimpleCondition, SoftDeletes, SoftDeletesStatic, SqliteDatabase, SqliteDatabaseOptions, SqliteSeederContext, TransactionHandle, TransactionModelScope, WhereClause, WhereCondition, WhereGroupCallback, WhereOperator, WithRelations, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from '@guren/orm';
3
+ export { AccessorDefinitions, AccessorFn, AwsDataApiDatabase, AwsDataApiDatabaseOptions, AwsDataApiSeederContext, BelongsToManyRecord, BelongsToManyRelationResult, BelongsToRecord, BelongsToRelationResult, BelongsToRequiredRecord, CastType, D1DatabaseHandle, D1DatabaseOptions, DrizzleAdapter, EagerLoadConstraint, FindManyOptions, GroupCondition, HasManyRecord, HasManyRelationResult, HasManyThroughRecord, HasManyThroughRelationResult, HasOneRecord, HasOneRelationResult, HookCallback, HookName, InferModelInsert, InferModelRecord, MassAssignmentException, Model, ModelHooks, ModelNotFoundException, ModelObserver, ModelObserverConstructor, ModelPaginationMeta, ModelQueryOptions, MorphManyRecord, MorphManyRelationResult, MorphToRecord, MorphToRelationResult, MutatorDefinitions, MutatorFn, MySqlDatabase, MySqlDatabaseOptions, MySqlSeederContext, ORMAdapter, ORMAdapterAdvanced, OrderByClause, OrderByInput, OrderDefinition, OrderDirection, PaginateOptions, PaginatedResult, PlainObject, PostgresDatabase, PostgresDatabaseOptions, PostgresSeederContext, QueryBuilder, QueryBuilderOptions, ScopeFunction, SeederContext, SeederHandler, SimpleCondition, SoftDeletes, SoftDeletesStatic, SqliteDatabase, SqliteDatabaseOptions, SqliteSeederContext, TransactionHandle, TransactionModelScope, WhereClause, WhereCondition, WhereGroupCallback, WhereOperator, WithRelations, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from '@guren/orm';
4
4
 
5
5
  /**
6
6
  * Options for DatabaseApiTokenStore.
@@ -115,7 +115,7 @@ declare function ssrRuntimePaths(ssrDir: string, ssrFile: string, prefix: string
115
115
  */
116
116
  declare function stageStaticAssets(publicDir: string, assetsOut: string): void;
117
117
  /** What a dev-only module is needed for, so a plugin can word its own message. */
118
- type DevOnlyModuleKind = 'sqlite' | 'vite' | 'mcp';
118
+ type DevOnlyModuleKind = 'sqlite' | 'vite' | 'mcp' | 'sql-driver';
119
119
  interface DevOnlyModule {
120
120
  readonly specifier: string;
121
121
  readonly kind: DevOnlyModuleKind;
@@ -143,6 +143,10 @@ interface DevOnlyModule {
143
143
  * - `mcp` — the opt-in MCP endpoint's lazy imports, which drag the CLI
144
144
  * generators (and Babel) plus the MCP SDK in behind them.
145
145
  *
146
+ * SQL client libraries are deliberately *not* here: they are dev-only on
147
+ * Workers, where D1 is the only database, and load-bearing on Lambda and
148
+ * Vercel, which connect to Postgres. See `SQL_CLIENT_MODULES`.
149
+ *
146
150
  * `as const` so a consumer can key an exhaustive table on the specifiers and
147
151
  * have a new entry here surface as a compile error there.
148
152
  */
@@ -167,18 +171,156 @@ declare const DEV_ONLY_MODULES: readonly [{
167
171
  readonly kind: "mcp";
168
172
  readonly exportNames: readonly ["WebStandardStreamableHTTPServerTransport"];
169
173
  }];
170
- type DevOnlySpecifier = (typeof DEV_ONLY_MODULES)[number]['specifier'];
171
174
  /**
172
- * Source for a stub replacing one dev-only module. Shared because what it
173
- * encodes is a bundler constraint, not a platform choice: every name the
174
- * importer destructures must be present or the bundle fails with "no matching
175
- * export", and each is emitted as a throwing *function* because the stubbed
176
- * names mix constructors (`new Database()`) with plain calls
177
- * (`createServer()`) — a class invoked without `new` reports "Class
178
- * constructor cannot be invoked without 'new'" instead of the real reason.
175
+ * A database `@guren/orm` can connect through, named after the factory an
176
+ * app's database config calls to declare it.
177
+ */
178
+ type DatabaseDialect = 'postgres' | 'mysql' | 'sqlite' | 'aws-data-api' | 'd1';
179
+ /**
180
+ * The `@guren/orm` factory names an app's database config calls, and the
181
+ * dialect each one declares.
182
+ *
183
+ * Taken from `@guren/core`'s export allowlist rather than from the ORM's
184
+ * implementation files, and pinned there by a test: a list built from the
185
+ * implementation admits names that were never exported and misses the aliases
186
+ * that were. The spelling is `createMySqlDatabase`, not `createMysqlDatabase`
187
+ * — a build that filters on a name nobody exports detects nothing and stubs
188
+ * nothing, which is silent.
189
+ */
190
+ declare const DATABASE_FACTORIES: {
191
+ readonly createPostgresDatabase: "postgres";
192
+ readonly createMySqlDatabase: "mysql";
193
+ readonly createSqliteDatabase: "sqlite";
194
+ readonly createAwsDataApiDatabase: "aws-data-api";
195
+ readonly createD1Database: "d1";
196
+ };
197
+ /** A client library reached only by the dialect it belongs to. */
198
+ interface SqlClientModule extends DevOnlyModule {
199
+ readonly dialect: DatabaseDialect;
200
+ }
201
+ /**
202
+ * The database client libraries `@guren/orm`'s Postgres, MySQL and Aurora
203
+ * Data API factories reach for.
204
+ *
205
+ * They sit apart from `DEV_ONLY_MODULES` because whether they are dead weight
206
+ * depends on the platform: on Workers, D1 is the only database there is, so
207
+ * every one of these is unreachable; on Lambda and Vercel the app connects to
208
+ * Postgres through them and stubbing them would break a working deploy.
209
+ *
210
+ * That makes the list itself the wrong granularity for a platform that hosts
211
+ * more than one dialect. Workers stubs all of it; Lambda and Vercel stub the
212
+ * entries whose `dialect` the app's config does not declare, which is what
213
+ * `unusedSqlClients` decides.
214
+ *
215
+ * A platform where they are unreachable has to stub them rather than ignore
216
+ * them. `@guren/orm` names them in *literal* dynamic imports, which a bundler
217
+ * follows whether or not the branch can be taken — so a D1 app failed to
218
+ * bundle on `Could not resolve "postgres"`, naming a database its author had
219
+ * deliberately not chosen. Both the client and the drizzle entry point that
220
+ * imports it need stubbing: aliasing only the client leaves drizzle's own
221
+ * `import pgClient from "postgres"` to resolve.
222
+ *
223
+ * Export names are read off drizzle-orm's driver and session modules, which
224
+ * is what a bundler checks a stub against.
225
+ */
226
+ declare const SQL_CLIENT_MODULES: readonly [{
227
+ readonly specifier: "postgres";
228
+ readonly kind: "sql-driver";
229
+ readonly dialect: "postgres";
230
+ readonly exportNames: readonly [];
231
+ }, {
232
+ readonly specifier: "mysql2";
233
+ readonly kind: "sql-driver";
234
+ readonly dialect: "mysql";
235
+ readonly exportNames: readonly [];
236
+ }, {
237
+ readonly specifier: "mysql2/promise";
238
+ readonly kind: "sql-driver";
239
+ readonly dialect: "mysql";
240
+ readonly exportNames: readonly ["createPool"];
241
+ }, {
242
+ readonly specifier: "@aws-sdk/client-rds-data";
243
+ readonly kind: "sql-driver";
244
+ readonly dialect: "aws-data-api";
245
+ readonly exportNames: readonly ["RDSDataClient", "BeginTransactionCommand", "CommitTransactionCommand", "ExecuteStatementCommand", "RollbackTransactionCommand"];
246
+ }];
247
+ type SqlClientSpecifier = (typeof SQL_CLIENT_MODULES)[number]['specifier'];
248
+ /**
249
+ * Where an app declares its database, in the order it is looked for.
250
+ *
251
+ * The same pair `guren doctor` checks, kept as a copy for the same reason
252
+ * `realpathOfNearestExisting` above is one: this module must not import
253
+ * beyond node builtins, and cli cannot be imported from core. If the two ever
254
+ * disagree, a build would stub clients for an app whose config the doctor
255
+ * says is fine — so a change to either belongs in both.
256
+ */
257
+ declare const DATABASE_CONFIG_CANDIDATES: readonly ["config/database.ts", "db/config.ts"];
258
+ interface DatabaseDialectDetection {
259
+ /**
260
+ * Every dialect the config declares, or undefined when the build could not
261
+ * tell — which is not the same as "none", and callers must not treat it as
262
+ * an empty set.
263
+ */
264
+ dialects?: readonly DatabaseDialect[];
265
+ /** Root-relative path of the file that was read, when one was found. */
266
+ source?: string;
267
+ }
268
+ /**
269
+ * Which databases an app connects to, read off its database config.
179
270
  *
180
- * @param message Platform-specific explanation, including the replacement API.
271
+ * A *union*, never a single answer: an app legitimately names two factories in
272
+ * one file, picking between them at runtime — the Workers app in this
273
+ * repository declares D1 for the deployed worker and sqlite for local
274
+ * development, and a Lambda app can pair Postgres with sqlite the same way.
275
+ * Taking the first match would stub a client the app really does reach for.
276
+ *
277
+ * Matching is a scan for the factory names, not a parse: every way of being
278
+ * wrong about a name that *is* in the file — mentioned in a comment, imported
279
+ * but never called, called in a branch this deploy will not take — errs
280
+ * toward reporting a dialect the app might not use, and the caller stubs
281
+ * fewer clients as a result. The opposite error is the dangerous one, so the
282
+ * cheap reading is the right one. A config that reaches a factory without
283
+ * naming it (a re-export, an indirection through another module) reports
284
+ * nothing, and the caller stubs nothing.
181
285
  */
286
+ declare function detectDatabaseDialects(root: string): DatabaseDialectDetection;
287
+ /** Every dialect name `databaseDialects` accepts, for validation and messages. */
288
+ declare const DATABASE_DIALECTS: readonly DatabaseDialect[];
289
+ /**
290
+ * Parse a comma-separated `--database` value into dialects.
291
+ *
292
+ * @param label Platform name for the error message, e.g. `'Lambda build'`.
293
+ */
294
+ declare function parseDatabaseDialects(value: string, label: string): readonly DatabaseDialect[];
295
+ /** One client to stub, with the explanation its stub throws. */
296
+ interface UnusedSqlClient {
297
+ readonly module: SqlClientModule;
298
+ readonly message: string;
299
+ }
300
+ /**
301
+ * The database clients an app does not connect through, for a platform where
302
+ * the ones it *does* connect through are load-bearing — Lambda and Vercel,
303
+ * as opposed to Workers, where D1 is the only database and every client in
304
+ * `SQL_CLIENT_MODULES` is unreachable regardless of what the config says.
305
+ *
306
+ * Fails open: when the dialects cannot be read, this warns and returns
307
+ * nothing to stub. The two errors are not symmetric. Under-stubbing leaves
308
+ * today's behaviour — the build fails to resolve a client the app never
309
+ * installed, loudly, at build time. Over-stubbing produces a bundle that
310
+ * builds clean and then cannot reach its own database, at runtime, in
311
+ * production. Only the second is worth protecting against, so anything less
312
+ * than positive evidence means stub nothing.
313
+ *
314
+ * @param dialects Overrides detection when the caller already knows, for an
315
+ * app whose config the scan cannot read.
316
+ * @param label Platform name for the messages, e.g. `'Lambda build'`.
317
+ */
318
+ declare function unusedSqlClients(input: {
319
+ root: string;
320
+ label: string;
321
+ dialects?: readonly DatabaseDialect[];
322
+ }): readonly UnusedSqlClient[];
323
+ type DevOnlySpecifier = (typeof DEV_ONLY_MODULES)[number]['specifier'];
182
324
  declare function renderDevOnlyStub(module: DevOnlyModule, message: string): string;
183
325
  /**
184
326
  * The MCP SDK is only ever reached through subpaths, and a bundler alias on a
@@ -189,4 +331,4 @@ declare function renderDevOnlyStub(module: DevOnlyModule, message: string): stri
189
331
  */
190
332
  declare const MCP_SDK_SUBPATH_PREFIX = "@modelcontextprotocol/sdk/";
191
333
 
192
- export { type ClientAssetEnv, DEV_ONLY_MODULES, type DevOnlyModule, type DevOnlyModuleKind, type DevOnlySpecifier, MCP_SDK_SUBPATH_PREFIX, type Manifest, type ManifestEntry, type PathLike, assertOutputDirOutsideRoot, importSpecifier, readManifest, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets };
334
+ export { type ClientAssetEnv, DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, type DatabaseDialect, type DatabaseDialectDetection, type DevOnlyModule, type DevOnlyModuleKind, type DevOnlySpecifier, MCP_SDK_SUBPATH_PREFIX, type Manifest, type ManifestEntry, type PathLike, SQL_CLIENT_MODULES, type SqlClientModule, type SqlClientSpecifier, type UnusedSqlClient, assertOutputDirOutsideRoot, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, unusedSqlClients };
@@ -127,23 +127,110 @@ var DEV_ONLY_MODULES = [
127
127
  exportNames: ["WebStandardStreamableHTTPServerTransport"]
128
128
  }
129
129
  ];
130
- function renderDevOnlyStub(module, message) {
131
- if (module.exportNames.length === 0) {
132
- return `// ${message}
133
- export {}
134
- `;
130
+ var DATABASE_FACTORIES = {
131
+ createPostgresDatabase: "postgres",
132
+ createMySqlDatabase: "mysql",
133
+ createSqliteDatabase: "sqlite",
134
+ createAwsDataApiDatabase: "aws-data-api",
135
+ createD1Database: "d1"
136
+ };
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
+ }
153
+ ];
154
+ var DATABASE_CONFIG_CANDIDATES = ["config/database.ts", "db/config.ts"];
155
+ 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 };
135
174
  }
136
- const throwing = module.exportNames.map((name) => `export function ${name}() { throw new Error(${JSON.stringify(message)}) }`).join("\n");
137
- return `${throwing}
138
- export default { ${module.exportNames.join(", ")} }
175
+ return {};
176
+ }
177
+ var DATABASE_DIALECTS = [...new Set(Object.values(DATABASE_FACTORIES))];
178
+ 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;
186
+ }
187
+ 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));
190
+ }
191
+ 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
+ }));
206
+ }
207
+ function toJsStringLiteral(value) {
208
+ return JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
209
+ }
210
+ 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})
139
220
  `;
140
221
  }
141
222
  var MCP_SDK_SUBPATH_PREFIX = "@modelcontextprotocol/sdk/";
142
223
  export {
224
+ DATABASE_CONFIG_CANDIDATES,
225
+ DATABASE_DIALECTS,
226
+ DATABASE_FACTORIES,
143
227
  DEV_ONLY_MODULES,
144
228
  MCP_SDK_SUBPATH_PREFIX,
229
+ SQL_CLIENT_MODULES,
145
230
  assertOutputDirOutsideRoot,
231
+ detectDatabaseDialects,
146
232
  importSpecifier,
233
+ parseDatabaseDialects,
147
234
  readManifest,
148
235
  renderDevOnlyStub,
149
236
  resetOutputDir,
@@ -151,5 +238,6 @@ export {
151
238
  resolvePathLike,
152
239
  resolveSsrEntryFile,
153
240
  ssrRuntimePaths,
154
- stageStaticAssets
241
+ stageStaticAssets,
242
+ unusedSqlClients
155
243
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/core",
3
- "version": "1.6.1",
3
+ "version": "1.7.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -60,9 +60,9 @@
60
60
  "typecheck": "tsc --noEmit"
61
61
  },
62
62
  "dependencies": {
63
- "@guren/cli": "^2.5.0",
64
- "@guren/orm": "^2.4.0",
65
- "@guren/server": "^2.6.0"
63
+ "@guren/cli": "^2.6.2",
64
+ "@guren/orm": "^2.5.0",
65
+ "@guren/server": "^2.8.0"
66
66
  },
67
67
  "devDependencies": {
68
68
  "@types/node": "^20.14.10",