gencow 0.1.286 → 0.1.288

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.
Files changed (72) hide show
  1. package/bin/gencow.mjs +15 -15
  2. package/core/index.js +169 -24
  3. package/core/package.json +1 -1
  4. package/dashboard/assets/{index-BnBn8uo4.js → index-M4J2Ub-u.js} +3 -3
  5. package/dashboard/assets/index-OH2xW1ZG.css +2 -0
  6. package/dashboard/index.html +2 -2
  7. package/docs/api.md +6 -0
  8. package/docs/commands.md +9 -0
  9. package/docs/packaging.md +1 -1
  10. package/docs/troubleshooting.md +11 -0
  11. package/lib/app-command.mjs +18 -3
  12. package/lib/app-error-diagnostic.mjs +38 -0
  13. package/lib/app-response-error.mjs +39 -17
  14. package/lib/backend-bundle-file-plan.mjs +88 -5
  15. package/lib/cli-command-runner.mjs +52 -2
  16. package/lib/cli-project-runtime.mjs +54 -36
  17. package/lib/codegen-command.mjs +2 -0
  18. package/lib/coding-guardrails.mjs +8 -0
  19. package/lib/db-command.mjs +14 -4
  20. package/lib/db-metadata-command.mjs +155 -0
  21. package/lib/db-migration-command-steps.mjs +104 -10
  22. package/lib/db-push-command.mjs +49 -45
  23. package/lib/db-seed-failure-render.mjs +7 -3
  24. package/lib/deploy-admission-transport-failure.mjs +46 -1
  25. package/lib/deploy-audit-errors.mjs +20 -0
  26. package/lib/deploy-bundle-staging.mjs +53 -4
  27. package/lib/deploy-codegen-preflight.mjs +22 -1
  28. package/lib/deploy-failure-diagnostic.mjs +69 -6
  29. package/lib/deploy-migration-codegen-stage.mjs +65 -0
  30. package/lib/deploy-package-runtime.mjs +18 -38
  31. package/lib/deployment-operation-poll.mjs +44 -5
  32. package/lib/dev-cloud-bundle.mjs +57 -5
  33. package/lib/dev-cloud-command.mjs +4 -1
  34. package/lib/dev-cloud-migrations.mjs +3 -0
  35. package/lib/dev-local-command.mjs +32 -1
  36. package/lib/doctor-command.mjs +23 -1
  37. package/lib/drizzle-generate.mjs +28 -6
  38. package/lib/literal-config-syntax.mjs +42 -0
  39. package/lib/metadata-conversion.mjs +182 -0
  40. package/lib/metadata-diagnostic.mjs +121 -0
  41. package/lib/metadata-publication.mjs +263 -0
  42. package/lib/metadata-upgrade.mjs +292 -0
  43. package/lib/migration-bundle-roundtrip.mjs +7 -2
  44. package/lib/migration-bundle-staging.mjs +13 -1
  45. package/lib/migration-client-diagnostic.mjs +53 -2
  46. package/lib/migration-diagnostic.mjs +47 -0
  47. package/lib/migration-folder-format.mjs +17 -14
  48. package/lib/migration-operation-client.mjs +3 -1
  49. package/lib/opencode-command.mjs +202 -0
  50. package/lib/opencode-config.mjs +229 -0
  51. package/lib/prod-create-region-diagnostic.mjs +6 -2
  52. package/lib/project-context.mjs +8 -0
  53. package/lib/project-migration-manifest.mjs +5 -1
  54. package/lib/release-client.mjs +59 -18
  55. package/lib/ts-codegen-import-extension.mjs +11 -5
  56. package/package.json +14 -14
  57. package/runtime/dependency-lock.mjs +5 -1
  58. package/runtime/server.mjs +942 -757
  59. package/runtime/tooling.mjs +556 -282
  60. package/scripts/bundle-core.mjs +2 -2
  61. package/scripts/bundle-shared.mjs +4 -4
  62. package/scripts/synchronous-bundler.mjs +14 -0
  63. package/templateFeature/ai/ai-facade.ts +3 -2
  64. package/templateFeature/ai/ai-image-jobs.ts +532 -0
  65. package/templateFeature/ai/ai-image.ts +2 -2
  66. package/templateFeature/ai/ai.ts +10 -0
  67. package/templateFeature/ai/manifest.json +2 -0
  68. package/templates/ai-chat/README.md +1 -0
  69. package/templates/ai-chat/prompt.md +1 -1
  70. package/templates/fullstack/README.md +1 -0
  71. package/templates/fullstack/prompt.md +1 -1
  72. package/dashboard/assets/index-C6-BpKKR.css +0 -2
package/bin/gencow.mjs CHANGED
@@ -10,6 +10,8 @@
10
10
  * gencow dev — watch, auto-deploy to dev, and stream logs
11
11
  * --local — run the local Bun development server
12
12
  * gencow db:generate — generate migration SQL from configured schemas
13
+ * gencow db:upgrade-metadata — upgrade migration snapshots without generating SQL
14
+ * gencow db:recover-metadata — finish an interrupted snapshot upgrade
13
15
  * gencow db:check — inspect cloud migrations without applying SQL
14
16
  * gencow db:push — apply committed migrations to the cloud database
15
17
  * gencow db:migrate — apply pending migrations to the running project DB
@@ -63,11 +65,13 @@ import { updateComponentReadme } from "../lib/component-readme.mjs";
63
65
  import { createConfigCommand } from "../lib/config-command.mjs";
64
66
  import { createCorsCommand } from "../lib/cors-command.mjs";
65
67
  import { createDbCommands } from "../lib/db-command.mjs";
68
+ import { createDbMetadataCommands } from "../lib/db-metadata-command.mjs";
66
69
  import { createDevCloudCommand } from "../lib/dev-cloud-command.mjs";
67
70
  import { createDevLocalCommands } from "../lib/dev-local-command.mjs";
68
71
  import { handleDeployReadonlySubcommand, renderDeployHelp, verifyAppReady } from "../lib/deploy-command.mjs";
69
72
  import { createDeployCommand } from "../lib/deploy-runtime.mjs";
70
73
  import { createCreditsCommands } from "../lib/credits-command.mjs";
74
+ import { createOpencodeCommands } from "../lib/opencode-command.mjs";
71
75
  import { createDomainCommand } from "../lib/domain-command.mjs";
72
76
  import { createEnvCommand } from "../lib/env-command.mjs";
73
77
  import { createFilesCommand } from "../lib/files-command.mjs";
@@ -75,7 +79,7 @@ import { createInitCommand } from "../lib/init-command.mjs";
75
79
  import { createJobsCommand } from "../lib/jobs-command.mjs";
76
80
  import { createLogsCommand } from "../lib/logs-command.mjs";
77
81
  import { createOriginsCommand } from "../lib/origins-command.mjs";
78
- import { parseProjectSelectionArgs, setCliInvocationSelection } from "../lib/project-context.mjs";
82
+ import { parseProjectSelectionArgs, resolveCliInvocationSelection, setCliInvocationSelection } from "../lib/project-context.mjs";
79
83
  import { createRuntimeCommand } from "../lib/runtime-command.mjs";
80
84
  import { createStaticDeployRuntime } from "../lib/static-deploy-command.mjs";
81
85
  import { createStaticCommand } from "../lib/static-command.mjs";
@@ -110,6 +114,9 @@ const CLI_PACKAGE_JSON = JSON.parse(readFileSync(resolve(__dirname, "..", "packa
110
114
  const CLI_VERSION = CLI_PACKAGE_JSON.version || "0.0.0";
111
115
  const CLI_SOURCE_REVISION = resolveCliArtifactSourceRevision(CLI_VERSION);
112
116
  const _drizzleKitCmd = (subcmd, options = {}) => buildDrizzleKitCommand(subcmd, options);
117
+ const { dbUpgradeMetadata, dbRecoverMetadata } = createDbMetadataCommands({
118
+ loadConfig, buildEnv, drizzleKitCmdImpl: _drizzleKitCmd, infoImpl: info, logImpl: log,
119
+ });
113
120
  const generateApiTs = createApiCodegenRuntime({
114
121
  cliVersion: CLI_VERSION,
115
122
  sourceRevision: CLI_SOURCE_REVISION,
@@ -346,32 +353,21 @@ const runTemplatesCommand = createTemplateMarketplaceCommand();
346
353
  // ─── Commands ─────────────────────────────────────────────
347
354
 
348
355
  const commands = {
349
- // ── init ─────────────────────────────────────────────
350
356
  init: runInitCommand,
351
-
352
- // ── db:reset ─────────────────────────────────────────
353
357
  "db:reset": runDbResetCommand,
354
-
355
- // ── db:seed ──────────────────────────────────────────
356
358
  "db:seed": runDbSeedCommand,
357
-
358
- // ── db:restore ───────────────────────────────────────
359
359
  "db:restore": runDbRestoreCommand,
360
-
361
- // ── dev ──────────────────────────────────────────────
362
360
  dev: runDevCommand,
363
361
 
364
- // ── dev:local (로컬 PGlite + hot-reload) ─────────────
365
362
  "dev:local": runDevLocalCommand,
366
363
 
367
- // ── db:push ──────────────────────────────────────────
368
364
  "db:push": runDbPushCommand,
369
365
 
370
- // ── db:check ─────────────────────────────────────────
371
366
  "db:check": runDbCheckCommand,
372
367
 
373
- // ── db:generate ──────────────────────────────────────
374
368
  "db:generate": runDbGenerateCommand,
369
+ "db:upgrade-metadata": dbUpgradeMetadata,
370
+ "db:recover-metadata": dbRecoverMetadata,
375
371
 
376
372
  // ── db:migrate ───────────────────────────────────────
377
373
  "db:migrate": runDbMigrateCommand,
@@ -415,6 +411,7 @@ ${BOLD}Commands (login required):${RESET}
415
411
  ${GREEN}whoami${RESET} Show current user info
416
412
  ${GREEN}credits${RESET} Show credit balance and plan ${DIM}(--json)${RESET}
417
413
  ${GREEN}usage${RESET} Show usage by app/service ${DIM}(--month YYYY-MM, --app NAME, --json)${RESET}
414
+ ${GREEN}opencode setup${RESET} Connect OpenCode to Gencow LLM ${DIM}(llm/code, uses your login)${RESET}
418
415
  ${GREEN}dev${RESET} Watch + auto-deploy to cloud + live logs
419
416
  ${DIM}--local Run local Bun + Hono + PGlite development${RESET}
420
417
  ${DIM}--verbose Show all HTTP logs (including admin/ws)${RESET}
@@ -423,6 +420,8 @@ ${BOLD}Commands (login required):${RESET}
423
420
  ${GREEN}db:check${RESET} Audit cloud migrations without applying DDL
424
421
  ${DIM}--prod Check production DB without mutation${RESET}
425
422
  ${GREEN}db:generate${RESET} Generate SQL migration files from schema.ts
423
+ ${GREEN}db:upgrade-metadata${RESET} Upgrade local migration snapshots
424
+ ${GREEN}db:recover-metadata${RESET} Finish an interrupted migration snapshot upgrade
426
425
  ${GREEN}db:seed${RESET} Run gencow/seed.ts on cloud app
427
426
  ${DIM}--prod Seed production app (confirmation required)${RESET}
428
427
  ${GREEN}static [dir]${RESET} Deploy static files only ${DIM}(dist/, out/, build/)${RESET}
@@ -518,6 +517,7 @@ ${BOLD}Examples:${RESET}
518
517
  logout: runLogoutCommand,
519
518
  whoami: runWhoamiCommand,
520
519
  ...createCreditsCommands(),
520
+ ...createOpencodeCommands(),
521
521
 
522
522
  // ── static — 정적 파일 배포 (dev 기본, --prod 로 프로덕션) ──
523
523
  static: runStaticCommand,
@@ -579,7 +579,7 @@ ${BOLD}Examples:${RESET}
579
579
 
580
580
  const [, , rawCmd = "help", ...rawArgs] = process.argv;
581
581
  const globalProjectSelection = parseProjectSelectionArgs(rawArgs);
582
- setCliInvocationSelection(globalProjectSelection);
582
+ setCliInvocationSelection(resolveCliInvocationSelection(globalProjectSelection, process.cwd()));
583
583
  const args = [...globalProjectSelection.remainingArgs];
584
584
  const cmd =
585
585
  rawCmd === "--help" || rawCmd === "-h"
package/core/index.js CHANGED
@@ -4030,6 +4030,7 @@ var RESERVED_TENANT_RUNTIME_ENV_KEYS = [
4030
4030
  "DATABASE_URL",
4031
4031
  "GENCOW_DB_URL",
4032
4032
  "BETTER_AUTH_SECRET",
4033
+ "GENCOW_PLATFORM_AUTH_SECRET",
4033
4034
  "BETTER_AUTH_URL",
4034
4035
  "IS_PLATFORM",
4035
4036
  "GENCOW_PLATFORM_CONFIG_FILE",
@@ -4107,6 +4108,7 @@ var RESERVED_TENANT_RUNTIME_ENV_KEYS = [
4107
4108
  "GENCOW_INTERNAL_TOKEN",
4108
4109
  "GENCOW_CRON_TOKEN",
4109
4110
  "GENCOW_SCHEDULED_JOB_PUBLIC_KEY",
4111
+ "GENCOW_TRUSTED_CLIENT_ADDRESS_PEERS",
4110
4112
  "GENCOW_DEPLOY_ID",
4111
4113
  "GENCOW_AI_PROXY_URL",
4112
4114
  "GENCOW_AI_PROXY_URL_ALT",
@@ -4119,6 +4121,7 @@ var RESERVED_TENANT_RUNTIME_ENV_KEYS = [
4119
4121
  "GENCOW_SHUTDOWN_MARKER_PATH",
4120
4122
  "GENCOW_SKIP_MIGRATION",
4121
4123
  "GENCOW_DB_MAX_CONNECTIONS",
4124
+ "GENCOW_DB_SYSTEM_MAX_CONNECTIONS",
4122
4125
  "GENCOW_DB_POOL_POLICY_VERSION",
4123
4126
  "GENCOW_DB_IDLE_TIMEOUT_SECONDS",
4124
4127
  "GENCOW_DB_CONNECTION_TIMEOUT_SECONDS",
@@ -4604,7 +4607,7 @@ var unsupportedByReason = {
4604
4607
  },
4605
4608
  relations: {
4606
4609
  message: "This relational builder is not from the verified Drizzle v1 integration.",
4607
- retryPrecondition: "Check the installed version with `pnpm why drizzle-orm`; use verified drizzle-orm@1.0.0-rc.4 without custom relational builders before retrying."
4610
+ retryPrecondition: "Check the installed version with `pnpm why drizzle-orm`; use verified drizzle-orm 1.0.0-rc.4 or 1.0.0-rc.5 without custom relational builders before retrying."
4608
4611
  },
4609
4612
  session: {
4610
4613
  message: "This Drizzle session cannot be safely bound to the transaction-scoped RLS client.",
@@ -4639,8 +4642,8 @@ function matchingRlsExecutionClient(scope) {
4639
4642
  const active = activeRlsExecution.getStore();
4640
4643
  return active?.active && active.scope === scope ? active.client : void 0;
4641
4644
  }
4642
- async function runWithRlsScope(scope, client, work) {
4643
- const active = { scope, client, active: true };
4645
+ async function runWithRlsScope(scope, client, work, holdsQueue = false) {
4646
+ const active = { scope, client, active: true, holdsQueue };
4644
4647
  return activeRlsExecution.run(active, async () => {
4645
4648
  try {
4646
4649
  return await work();
@@ -4649,6 +4652,67 @@ async function runWithRlsScope(scope, client, work) {
4649
4652
  }
4650
4653
  });
4651
4654
  }
4655
+ var contextBoundBuilders = /* @__PURE__ */ new WeakSet();
4656
+ var runtimeMayDropContext = true;
4657
+ void (async () => {
4658
+ try {
4659
+ const probe = new AsyncLocalStorage();
4660
+ const seen = await probe.run(1, async () => {
4661
+ await null;
4662
+ return { then: (resolve) => resolve(probe.getStore()) };
4663
+ });
4664
+ runtimeMayDropContext = seen !== 1;
4665
+ } catch {
4666
+ runtimeMayDropContext = true;
4667
+ }
4668
+ })();
4669
+ function isNativePromiseOrArray(value) {
4670
+ return value instanceof Promise || Array.isArray(value);
4671
+ }
4672
+ function isThenable(value) {
4673
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
4674
+ }
4675
+ function isQueryStage(value) {
4676
+ const stage = value;
4677
+ return ["from", "values", "set", "select"].some((key) => typeof stage[key] === "function");
4678
+ }
4679
+ function bindLazyQueryToRlsContext(value) {
4680
+ if (value === null || typeof value !== "object") return value;
4681
+ const store = activeRlsExecution.getStore();
4682
+ if (!store?.active) return value;
4683
+ return bindToStore(value, store);
4684
+ }
4685
+ function bindToStore(value, store) {
4686
+ if (isNativePromiseOrArray(value) || contextBoundBuilders.has(value)) return value;
4687
+ if (!isThenable(value) && !isQueryStage(value)) return value;
4688
+ const proxy = new Proxy(value, {
4689
+ get(target, prop, receiver) {
4690
+ const member = Reflect.get(target, prop, receiver);
4691
+ if (typeof member !== "function" || typeof prop === "symbol" || prop === "constructor") return member;
4692
+ if (prop !== "then" && Function.prototype.toString.call(member).startsWith("class")) return member;
4693
+ if (prop === "then") {
4694
+ return (...args) => {
4695
+ const current = activeRlsExecution.getStore();
4696
+ if (current?.active) return Reflect.apply(member, receiver, args);
4697
+ if (store.active && runtimeMayDropContext) {
4698
+ return activeRlsExecution.run(store, () => Reflect.apply(member, receiver, args));
4699
+ }
4700
+ if (store.active || runtimeMayDropContext) {
4701
+ return Promise.reject(createRlsScopeConflictError()).then(...args);
4702
+ }
4703
+ return Reflect.apply(member, receiver, args);
4704
+ };
4705
+ }
4706
+ return (...args) => {
4707
+ const out = Reflect.apply(member, receiver, args);
4708
+ if (out === receiver || out === null || typeof out !== "object") return out;
4709
+ return bindToStore(out, store);
4710
+ };
4711
+ }
4712
+ });
4713
+ contextBoundBuilders.add(proxy);
4714
+ return proxy;
4715
+ }
4652
4716
  function runWithRlsTransactionScope(scope, tx, work) {
4653
4717
  assertRlsScopeMayEnter(scope);
4654
4718
  return runWithRlsScope(scope, tx.session?.client, work);
@@ -4678,12 +4742,12 @@ function createRlsRelationalQueryRegistry(query2, session, baseSession) {
4678
4742
  Object.defineProperties(scopedBuilder, {
4679
4743
  findMany: {
4680
4744
  value: function(config) {
4681
- return Reflect.apply(trustedFindMany, this, [config]);
4745
+ return bindLazyQueryToRlsContext(Reflect.apply(trustedFindMany, this, [config]));
4682
4746
  }
4683
4747
  },
4684
4748
  findFirst: {
4685
4749
  value: function(config) {
4686
- return Reflect.apply(trustedFindFirst, this, [config]);
4750
+ return bindLazyQueryToRlsContext(Reflect.apply(trustedFindFirst, this, [config]));
4687
4751
  }
4688
4752
  }
4689
4753
  });
@@ -4812,14 +4876,70 @@ async function withRlsLeasedConnection(leased, rls, fn, scope) {
4812
4876
  leased.release();
4813
4877
  }
4814
4878
  }
4815
- async function withRlsConnection(session, rls, reuseOuterConnection, scope, fn) {
4879
+ var outerConnectionQueues = /* @__PURE__ */ new Map();
4880
+ function isObjectLike(value) {
4881
+ return !!value && (typeof value === "object" || typeof value === "function");
4882
+ }
4883
+ function isBunSqlClient(client) {
4884
+ const c = client;
4885
+ return typeof c.unsafe === "function" && typeof c.savepoint === "function";
4886
+ }
4887
+ async function readConnectionIdentity(client) {
4888
+ if (!isBunSqlClient(client)) return client;
4889
+ const rows4 = await client.unsafe(
4890
+ "select pg_backend_pid()::text as pid, current_database()::text as db"
4891
+ );
4892
+ const row = Array.isArray(rows4) ? rows4[0] : void 0;
4893
+ if (!row || typeof row.pid !== "string" || typeof row.db !== "string") {
4894
+ throw createRlsUnsupportedError("session");
4895
+ }
4896
+ return `bun-pg:${row.db}:${row.pid}`;
4897
+ }
4898
+ function resolveConnectionIdentity(ref) {
4899
+ if (!ref.identity) {
4900
+ const pending = readConnectionIdentity(ref.client);
4901
+ ref.identity = pending;
4902
+ pending.catch(() => {
4903
+ if (ref.identity === pending) ref.identity = void 0;
4904
+ });
4905
+ }
4906
+ return ref.identity;
4907
+ }
4908
+ async function withOuterConnectionExclusive(ref, work) {
4909
+ if (!ref || !isObjectLike(ref.client)) return work();
4910
+ const identity = await resolveConnectionIdentity(ref);
4911
+ const key = identity;
4912
+ const previous = outerConnectionQueues.get(key) ?? Promise.resolve();
4913
+ let release;
4914
+ const mine = new Promise((resolve) => {
4915
+ release = resolve;
4916
+ });
4917
+ const tail = previous.then(() => mine);
4918
+ outerConnectionQueues.set(key, tail);
4919
+ await previous.catch(() => void 0);
4920
+ try {
4921
+ return await work();
4922
+ } finally {
4923
+ release();
4924
+ if (outerConnectionQueues.get(key) === tail) outerConnectionQueues.delete(key);
4925
+ }
4926
+ }
4927
+ async function withRlsConnection(session, rls, reuseOuterConnection, scope, fn, queueKey) {
4816
4928
  assertRlsScopeMayEnter(scope);
4817
4929
  if (reuseOuterConnection) {
4818
4930
  const c2 = session.client;
4819
- return runWithRlsScope(scope, c2, async () => {
4820
- await applyRlsSessionVars(c2, rls);
4821
- return fn(c2);
4822
- });
4931
+ return withOuterConnectionExclusive(
4932
+ queueKey ?? { client: c2 },
4933
+ () => runWithRlsScope(
4934
+ scope,
4935
+ c2,
4936
+ async () => {
4937
+ await applyRlsSessionVars(c2, rls);
4938
+ return fn(c2);
4939
+ },
4940
+ true
4941
+ )
4942
+ );
4823
4943
  }
4824
4944
  const c = session.client;
4825
4945
  const runInner = async (client) => runWithRlsScope(scope, client, async () => {
@@ -4845,7 +4965,10 @@ function createClientBoundSession(session, client) {
4845
4965
  return client;
4846
4966
  }
4847
4967
  const value = Reflect.get(target, prop, receiver);
4848
- return typeof value === "function" ? value.bind(receiver) : value;
4968
+ if (typeof value !== "function") return value;
4969
+ const bound = value.bind(receiver);
4970
+ if (typeof prop === "symbol" || prop === "constructor") return bound;
4971
+ return (...args) => bindLazyQueryToRlsContext(bound(...args));
4849
4972
  }
4850
4973
  });
4851
4974
  }
@@ -4875,9 +4998,9 @@ function createPreparedQueryClientExecutors(params) {
4875
4998
  params.prepareArgs
4876
4999
  );
4877
5000
  }
4878
- async function runPreparedQueryWithRls(session, rls, reuseOuterConnection, scope, runOnClient, placeholderValues) {
5001
+ async function runPreparedQueryWithRls(session, rls, reuseOuterConnection, scope, queueKey, runOnClient, placeholderValues) {
4879
5002
  const active = currentRlsExecution(scope);
4880
- if (active) {
5003
+ if (active && (active.holdsQueue || !reuseOuterConnection)) {
4881
5004
  return runOnClient(active.client, placeholderValues);
4882
5005
  }
4883
5006
  return withRlsConnection(
@@ -4885,10 +5008,11 @@ async function runPreparedQueryWithRls(session, rls, reuseOuterConnection, scope
4885
5008
  rls,
4886
5009
  reuseOuterConnection,
4887
5010
  scope,
4888
- (client) => runOnClient(client, placeholderValues)
5011
+ (client) => runOnClient(client, placeholderValues),
5012
+ queueKey
4889
5013
  );
4890
5014
  }
4891
- function wrapPreparedQuery(pq, session, baseSession, prepareQuery, prepareArgs, rls, reuseOuterConnection, scope) {
5015
+ function wrapPreparedQuery(pq, session, baseSession, prepareQuery, prepareArgs, rls, reuseOuterConnection, scope, queueKey) {
4892
5016
  const clientExecutors = createPreparedQueryClientExecutors({
4893
5017
  pq,
4894
5018
  baseSession,
@@ -4900,6 +5024,7 @@ function wrapPreparedQuery(pq, session, baseSession, prepareQuery, prepareArgs,
4900
5024
  rls,
4901
5025
  reuseOuterConnection,
4902
5026
  scope,
5027
+ queueKey,
4903
5028
  clientExecutors.execute,
4904
5029
  placeholderValues
4905
5030
  );
@@ -4909,12 +5034,13 @@ function wrapPreparedQuery(pq, session, baseSession, prepareQuery, prepareArgs,
4909
5034
  rls,
4910
5035
  reuseOuterConnection,
4911
5036
  scope,
5037
+ queueKey,
4912
5038
  clientExecutors.all,
4913
5039
  placeholderValues
4914
5040
  );
4915
5041
  }
4916
5042
  }
4917
- function wrapSession(session, rls, reuseOuterConnection, scope) {
5043
+ function wrapSession(session, rls, reuseOuterConnection, scope, queueKey) {
4918
5044
  return new Proxy(session, {
4919
5045
  get(sTarget, sProp, sRecv) {
4920
5046
  if (sProp === "client") {
@@ -4925,7 +5051,7 @@ function wrapSession(session, rls, reuseOuterConnection, scope) {
4925
5051
  const prepareQuery = Reflect.get(sTarget, sProp, sRecv);
4926
5052
  if (typeof prepareQuery !== "function") throw createRlsUnsupportedError("session");
4927
5053
  const pq = Reflect.apply(prepareQuery, sRecv, args);
4928
- wrapPreparedQuery(pq, sRecv, sTarget, prepareQuery, args, rls, reuseOuterConnection, scope);
5054
+ wrapPreparedQuery(pq, sRecv, sTarget, prepareQuery, args, rls, reuseOuterConnection, scope, queueKey);
4929
5055
  return pq;
4930
5056
  };
4931
5057
  }
@@ -4935,6 +5061,14 @@ function wrapSession(session, rls, reuseOuterConnection, scope) {
4935
5061
  });
4936
5062
  }
4937
5063
  function createRlsDb(db, rls, options = {}) {
5064
+ return createRlsDbInScope(db, rls, options, createRlsScopeToken());
5065
+ }
5066
+ function wrapSharedConnectionCallbackTx(tx, rls, options, scope, queueKey) {
5067
+ const session = tx?.session ?? tx?._?.session;
5068
+ if (!session || typeof session !== "object") return tx;
5069
+ return createRlsDbInScope(tx, rls, options, scope, queueKey);
5070
+ }
5071
+ function createRlsDbInScope(db, rls, options, scope, inheritedQueueKey) {
4938
5072
  const reuseOuterConnection = isDrizzleTransactionDb(db);
4939
5073
  const database = db;
4940
5074
  const baseSession = database.session ?? database._?.session;
@@ -4944,8 +5078,13 @@ function createRlsDb(db, rls, options = {}) {
4944
5078
  if (hasUnpartitionedRlsCache(db, baseSession)) {
4945
5079
  throw createRlsUnsupportedError("cache");
4946
5080
  }
4947
- const scope = createRlsScopeToken();
4948
- const wrappedSession = wrapSession(baseSession, rls, reuseOuterConnection, scope);
5081
+ const outerClient = baseSession.client;
5082
+ const queueKey = reuseOuterConnection ? inheritedQueueKey ?? (isObjectLike(outerClient) ? { client: outerClient } : void 0) : void 0;
5083
+ const injectScopeOnTx = (tx) => reuseOuterConnection && queueKey ? withOuterConnectionExclusive(
5084
+ queueKey,
5085
+ () => injectRlsVarsOnTx(tx, rls, options.onTransactionContextFailure)
5086
+ ) : injectRlsVarsOnTx(tx, rls, options.onTransactionContextFailure);
5087
+ const wrappedSession = wrapSession(baseSession, rls, reuseOuterConnection, scope, queueKey);
4949
5088
  const baseQuery = Reflect.get(db, "query", db);
4950
5089
  const scopedQuery = baseQuery && typeof baseQuery === "object" ? createRlsRelationalQueryRegistry(baseQuery, wrappedSession, baseSession) : baseQuery;
4951
5090
  return new Proxy(db, {
@@ -4979,9 +5118,10 @@ function createRlsDb(db, rls, options = {}) {
4979
5118
  return await target.transaction(
4980
5119
  async (tx) => {
4981
5120
  if (configStatement) await tx.execute(configStatement);
4982
- await injectRlsVarsOnTx(tx, rls, options.onTransactionContextFailure);
5121
+ await injectScopeOnTx(tx);
4983
5122
  callbackStarted = true;
4984
- return await runWithRlsTransactionScope(scope, tx, () => callback(tx));
5123
+ const handle = reuseOuterConnection ? wrapSharedConnectionCallbackTx(tx, rls, options, scope, queueKey) : tx;
5124
+ return await runWithRlsTransactionScope(scope, tx, () => callback(handle));
4985
5125
  },
4986
5126
  ...transactionArgs
4987
5127
  );
@@ -5005,13 +5145,17 @@ function createRlsDb(db, rls, options = {}) {
5005
5145
  ...characteristics?.isolationLevel ? { isolationLevel: characteristics.isolationLevel } : {},
5006
5146
  ...characteristics?.readOnly ? { accessMode: "read only" } : {}
5007
5147
  });
5008
- await injectRlsVarsOnTx(tx, rls, options.onTransactionContextFailure);
5009
- return runWithRlsTransactionScope(scope, tx, () => callback(tx));
5148
+ await injectScopeOnTx(tx);
5149
+ const handle = reuseOuterConnection ? wrapSharedConnectionCallbackTx(tx, rls, options, scope, queueKey) : tx;
5150
+ return runWithRlsTransactionScope(scope, tx, () => callback(handle));
5010
5151
  });
5011
5152
  };
5012
5153
  }
5013
5154
  const value = Reflect.get(target, prop, receiver);
5014
- return typeof value === "function" ? value.bind(receiver) : value;
5155
+ if (typeof value !== "function") return value;
5156
+ const bound = value.bind(receiver);
5157
+ if (typeof prop === "symbol" || prop === "constructor") return bound;
5158
+ return (...args) => bindLazyQueryToRlsContext(bound(...args));
5015
5159
  }
5016
5160
  });
5017
5161
  }
@@ -6121,6 +6265,7 @@ export {
6121
6265
  GencowValidationError,
6122
6266
  JobAdmissionError,
6123
6267
  MAX_FILE_SIZE,
6268
+ RESERVED_TENANT_RUNTIME_ENV_KEYS,
6124
6269
  RLS_SESSION_KEY_RE,
6125
6270
  RealtimeChannelEventValidationError,
6126
6271
  STORAGE_LIST_DEFAULT_LIMIT,
package/core/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gencow/core",
3
- "version": "0.1.47",
3
+ "version": "0.1.48",
4
4
  "type": "module",
5
5
  "main": "index.js"
6
6
  }