everything-dev 2.0.0-rc.7 → 2.0.0-rc.8

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 (47) hide show
  1. package/dist/api/auth-middleware.cjs +14 -1
  2. package/dist/api/auth-middleware.cjs.map +1 -1
  3. package/dist/api/auth-middleware.d.cts +9 -0
  4. package/dist/api/auth-middleware.d.mts +9 -0
  5. package/dist/api/auth-middleware.mjs +14 -1
  6. package/dist/api/auth-middleware.mjs.map +1 -1
  7. package/dist/cli/init.cjs +22 -10
  8. package/dist/cli/init.cjs.map +1 -1
  9. package/dist/cli/init.mjs +22 -10
  10. package/dist/cli/init.mjs.map +1 -1
  11. package/dist/cli.cjs +4 -3
  12. package/dist/cli.cjs.map +1 -1
  13. package/dist/cli.mjs +4 -3
  14. package/dist/cli.mjs.map +1 -1
  15. package/dist/commands/keys.cjs +1 -1
  16. package/dist/commands/keys.cjs.map +1 -1
  17. package/dist/commands/keys.mjs +1 -1
  18. package/dist/commands/keys.mjs.map +1 -1
  19. package/dist/contract.meta.cjs +1 -1
  20. package/dist/contract.meta.cjs.map +1 -1
  21. package/dist/contract.meta.d.cts +1 -1
  22. package/dist/contract.meta.d.mts +1 -1
  23. package/dist/contract.meta.mjs +1 -1
  24. package/dist/contract.meta.mjs.map +1 -1
  25. package/dist/db/core.cjs +22 -4
  26. package/dist/db/core.cjs.map +1 -1
  27. package/dist/db/core.mjs +22 -4
  28. package/dist/db/core.mjs.map +1 -1
  29. package/dist/http-client.cjs +14 -4
  30. package/dist/http-client.cjs.map +1 -1
  31. package/dist/http-client.mjs +14 -4
  32. package/dist/http-client.mjs.map +1 -1
  33. package/dist/infra/planner.cjs +6 -2
  34. package/dist/infra/planner.cjs.map +1 -1
  35. package/dist/infra/planner.mjs +6 -2
  36. package/dist/infra/planner.mjs.map +1 -1
  37. package/dist/ui/auth.d.cts +217 -123
  38. package/dist/ui/auth.d.mts +217 -123
  39. package/dist/ui/router-client.cjs +2 -1
  40. package/dist/ui/router-client.cjs.map +1 -1
  41. package/dist/ui/router-client.mjs +2 -1
  42. package/dist/ui/router-client.mjs.map +1 -1
  43. package/package.json +10 -10
  44. package/skills/api-and-auth/SKILL.md +12 -9
  45. package/skills/api-and-auth/references/middleware.md +38 -0
  46. package/skills/cli-reference/SKILL.md +22 -6
  47. package/skills/talk-to-the-app/SKILL.md +32 -5
@@ -1 +1 @@
1
- {"version":3,"file":"keys.mjs","names":[],"sources":["../../src/commands/keys.ts"],"sourcesContent":["import { join } from \"node:path\";\nimport process from \"node:process\";\nimport { Context, Effect } from \"effect\";\nimport { type KeyPair, parseKey } from \"near-kit\";\nimport { openInBrowser, startDeviceLogin } from \"../auth-login\";\nimport {\n deleteSessionHandle,\n nearCredentialsPath,\n readSessionHandle,\n removePublishedKeyFile,\n type SessionCredential,\n writeSessionHandle,\n} from \"../auth-session\";\nimport { MISSING_CONFIG_MESSAGE } from \"../config\";\nimport type { LoginResult } from \"../contract\";\nimport { getRegistryNamespaceForAccount } from \"../fastkv\";\nimport {\n addFunctionCallAccessKey,\n deleteAccessKeys,\n ensureNearCli,\n generateNearKeyPair,\n listPublishKeys,\n} from \"../near-cli\";\nimport { getNetworkIdForAccount } from \"../network\";\nimport type { ResolutionSession } from \"../resolution/session\";\nimport { colors } from \"../utils/theme\";\nimport { type BosBuilder, BosDepsTag } from \"./shared\";\n\nconst PUBLISH_FUNCTION_NAMES = [\"__fastdata_kv\"];\n\nexport function registerKeys(builder: BosBuilder) {\n return {\n keyPublish: builder.keyPublish.handler(async ({ input, context }) => {\n const deps = Context.get(context[\"effect/context\"], BosDepsTag);\n const session = deps.session;\n if (!session?.config) {\n return {\n status: \"error\" as const,\n account: \"\",\n network: \"mainnet\" as const,\n env: input.env,\n contract: \"\",\n allowance: input.allowance,\n functionNames: PUBLISH_FUNCTION_NAMES,\n error: MISSING_CONFIG_MESSAGE,\n };\n }\n\n const account =\n input.env === \"staging\"\n ? (session.config.staging?.account ?? session.config.account)\n : session.config.account;\n const network = getNetworkIdForAccount(account);\n const contract = getRegistryNamespaceForAccount(account, input.registry);\n try {\n await Effect.runPromise(ensureNearCli);\n\n const oldKeys = await listPublishKeys({ account, contract, network });\n\n const keyPair = await addFunctionCallAccessKey({\n account,\n contract,\n allowance: input.allowance,\n functionNames: PUBLISH_FUNCTION_NAMES,\n network,\n });\n\n if (oldKeys.length > 0) {\n console.log();\n console.log(\n ` Found ${oldKeys.length} existing publish key${oldKeys.length > 1 ? \"s\" : \"\"}:`,\n );\n for (const k of oldKeys) {\n console.log(` ${colors.dim(k)}`);\n }\n\n if (input.removeOldKeys !== false) {\n try {\n await deleteAccessKeys(account, oldKeys, network);\n console.log(\n ` ${colors.green(\"✓\")} Removed ${oldKeys.length} old key${\n oldKeys.length > 1 ? \"s\" : \"\"\n }`,\n );\n } catch {\n console.log(\n ` ${colors.yellow(\"⚠\")} Failed to remove old key${\n oldKeys.length > 1 ? \"s\" : \"\"\n } (new key still active)`,\n );\n }\n } else {\n console.log(` ${colors.dim(\"Old key(s) retained.\")}`);\n }\n }\n\n return {\n status: \"published\" as const,\n account,\n network,\n env: input.env,\n contract,\n allowance: input.allowance,\n functionNames: PUBLISH_FUNCTION_NAMES,\n publicKey: keyPair.publicKey,\n privateKey: keyPair.privateKey,\n };\n } catch (error) {\n return {\n status: \"error\" as const,\n account,\n network,\n env: input.env,\n contract,\n allowance: input.allowance,\n functionNames: PUBLISH_FUNCTION_NAMES,\n error: error instanceof Error ? error.message : \"Unknown error\",\n };\n }\n }),\n\n login: builder.login.handler(async ({ input, context }) => {\n const deps = Context.get(context[\"effect/context\"], BosDepsTag);\n const staging = input.env === \"staging\";\n const account = staging\n ? (deps.session?.config?.staging?.account ?? deps.session?.config?.account ?? \"\")\n : (deps.session?.config?.account ?? \"\");\n\n try {\n const siteUrl = resolveLoginSiteUrl(input.site, deps.session, staging);\n const login = await startDeviceLogin({\n siteUrl,\n device: input.device,\n account: account || undefined,\n expiresIn: input.expiresIn,\n });\n\n console.log();\n console.log(` One-time code: ${colors.cyan(login.userCode)}`);\n await openInBrowser(login.verificationUrl).catch((error: unknown) => {\n console.log(colors.yellow(` ⚠ ${(error as Error).message}`));\n });\n console.log();\n console.log(` Waiting for approval at ${colors.dim(login.verificationUrl)}…`);\n\n const approval = await login.waitForApproval();\n\n if (!approval.apiKey) {\n return {\n status: \"error\" as const,\n siteUrl,\n loginUrl: login.verificationUrl,\n error: \"Login approved but no CLI credential was created\",\n };\n }\n\n const expiresAt = new Date(Date.now() + input.expiresIn * 1000).toISOString();\n writeSessionHandle(deps.session?.root ?? process.cwd(), {\n version: 1,\n credential: {\n kind: \"session\",\n apiKey: approval.apiKey.key,\n apiKeyId: approval.apiKey.id,\n accountId: approval.accountId,\n label: input.device ?? siteUrl,\n siteUrl,\n createdAt: new Date().toISOString(),\n expiresAt,\n },\n publishKey: null,\n delegateKey: null,\n });\n\n let warning: string | null = null;\n if (account && approval.accountId && approval.accountId !== account) {\n warning = `Logged in as ${approval.accountId}, but the authored config account is ${account}. Publishes will use the configured account.`;\n }\n\n let publishKey: LoginResult[\"publishKey\"] = null;\n if (input.key) {\n try {\n publishKey = await exportPublishKey(account, input.registry);\n } catch (error) {\n warning = `Session stored, but publish-key export failed: ${\n error instanceof Error ? error.message : \"unknown error\"\n }`;\n }\n }\n\n return {\n status: \"logged-in\" as const,\n siteUrl,\n accountId: approval.accountId,\n expiresAt,\n loginUrl: login.verificationUrl,\n publishKey,\n warning,\n };\n } catch (error) {\n return {\n status: \"error\" as const,\n siteUrl: input.site ?? \"\",\n error: error instanceof Error ? error.message : \"Unknown error\",\n };\n }\n }),\n\n logout: builder.logout.handler(async ({ input, context }) => {\n const deps = Context.get(context[\"effect/context\"], BosDepsTag);\n const configDir = input.configDir ?? deps.session?.root ?? process.cwd();\n\n try {\n const session = readSessionHandle(configDir);\n let revokedApiKey = false;\n let removedPublishKey = false;\n let warning: string | null = null;\n\n if (session?.credential) {\n revokedApiKey = await revokeApiKey(session.credential).catch(() => false);\n if (!revokedApiKey) {\n warning =\n \"Could not revoke the API key remotely — revoke it manually under Settings → API keys.\";\n }\n }\n\n if (session?.publishKey) {\n const account = session.credential?.accountId ?? deps.session?.config?.account ?? \"\";\n removePublishedKeyFile(session.publishKey.network, account, session.publishKey.publicKey);\n removedPublishKey = true;\n warning = warning\n ? `${warning} Re-run ${colors.cyan(\"bos login --key\")} to re-export a publish key.`\n : \"Removed the exported publish key. Re-run bos login --key to re-export one.\";\n }\n\n deleteSessionHandle(configDir);\n return {\n status: \"logged-out\" as const,\n revokedApiKey,\n removedPublishKey,\n warning,\n };\n } catch (error) {\n return {\n status: \"error\" as const,\n revokedApiKey: false,\n removedPublishKey: false,\n error: error instanceof Error ? error.message : \"Unknown error\",\n };\n }\n }),\n };\n}\n\nfunction resolveLoginSiteUrl(\n siteInput: string | undefined,\n session: ResolutionSession | null,\n staging: boolean,\n): string {\n if (siteInput) {\n return siteInput.replace(/\\/+$/, \"\");\n }\n if (staging) {\n const stagingDomain = session?.config?.staging?.domain ?? session?.config?.domain;\n return stagingDomain ? `https://${stagingDomain}` : (session?.runtime?.ui?.url ?? \"\");\n }\n const devUiUrl = session?.runtime?.ui?.url;\n if (devUiUrl && /^https?:\\/\\/(localhost|127\\.0\\.0\\.1)/.test(devUiUrl)) {\n return devUiUrl.replace(/\\/+$/, \"\");\n }\n const domain = session?.config?.domain;\n return domain ? `https://${domain}` : \"\";\n}\n\nasync function exportPublishKey(\n account: string,\n registry: string | undefined,\n): Promise<NonNullable<LoginResult[\"publishKey\"]>> {\n if (!account) {\n throw new Error(\"the authored config has no account to export a publish key for\");\n }\n\n await Effect.runPromise(ensureNearCli);\n\n const network = getNetworkIdForAccount(account);\n const contract = getRegistryNamespaceForAccount(account, registry);\n await listPublishKeys({ account, contract, network });\n\n const keyPair = generateNearKeyPair();\n await addFunctionCallAccessKey({\n account,\n contract,\n allowance: \"1NEAR\",\n functionNames: PUBLISH_FUNCTION_NAMES,\n network,\n keyPair,\n });\n\n const { FileKeyStore } = await import(\"near-kit/keys/file\");\n const keyStore = new FileKeyStore(\"~/.near-credentials\", network);\n await keyStore.add(account, parseNearPrivateKey(keyPair.privateKey));\n try {\n const { statSync, chmodSync } = await import(\"node:fs\");\n const { homedir } = await import(\"node:os\");\n const credentialPath = join(\n homedir(),\n \".near-credentials\",\n network === \"mainnet\" ? \"mainnet\" : network,\n `${account}.json`,\n );\n if (statSync(credentialPath).mode & 0o077) {\n chmodSync(credentialPath, 0o600);\n }\n } catch {}\n\n return {\n publicKey: keyPair.publicKey,\n network,\n contract,\n exportedTo: nearCredentialsPath(network, account),\n };\n}\nfunction parseNearPrivateKey(privateKey: string): KeyPair {\n return parseKey(privateKey) as KeyPair;\n}\n\nasync function revokeApiKey(credential: SessionCredential): Promise<boolean> {\n if (!credential.apiKey || !credential.siteUrl) return false;\n try {\n const response = await fetch(`${credential.siteUrl}/api/auth/api-key/delete`, {\n method: \"POST\",\n headers: {\n \"x-api-key\": credential.apiKey,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ keyId: credential.apiKeyId }),\n signal: AbortSignal.timeout(10_000),\n });\n return response.ok;\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA4BA,MAAM,yBAAyB,CAAC,eAAe;AAE/C,SAAgB,aAAa,SAAqB;CAChD,OAAO;EACL,YAAY,QAAQ,WAAW,QAAQ,OAAO,EAAE,OAAO,cAAc;GAEnE,MAAM,UADO,QAAQ,IAAI,QAAQ,mBAAmB,UACjC,CAAC,CAAC;GACrB,IAAI,CAAC,SAAS,QACZ,OAAO;IACL,QAAQ;IACR,SAAS;IACT,SAAS;IACT,KAAK,MAAM;IACX,UAAU;IACV,WAAW,MAAM;IACjB,eAAe;IACf,OAAO;GACT;GAGF,MAAM,UACJ,MAAM,QAAQ,YACT,QAAQ,OAAO,SAAS,WAAW,QAAQ,OAAO,UACnD,QAAQ,OAAO;GACrB,MAAM,UAAU,uBAAuB,OAAO;GAC9C,MAAM,WAAW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AAW,SAAS,OAAO;CACtD,IAAI;EAUF,QAAO,MATgB,MAAM,GAAG,WAAW,QAAQ,2BAA2B;GAC5E,QAAQ;GACR,SAAS;IACP,aAAa,WAAW;IACxB,gBAAgB;GAClB;GACA,MAAM,KAAK,UAAU,EAAE,OAAO,WAAW,SAAS,CAAC;GACnD,QAAQ,YAAY,QAAQ,GAAM;EACpC,CAAC,EACc,CAAC;CAClB,QAAQ;EACN,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"keys.mjs","names":[],"sources":["../../src/commands/keys.ts"],"sourcesContent":["import { join } from \"node:path\";\nimport process from \"node:process\";\nimport { Context, Effect } from \"effect\";\nimport { type KeyPair, parseKey } from \"near-kit\";\nimport { openInBrowser, startDeviceLogin } from \"../auth-login\";\nimport {\n deleteSessionHandle,\n nearCredentialsPath,\n readSessionHandle,\n removePublishedKeyFile,\n type SessionCredential,\n writeSessionHandle,\n} from \"../auth-session\";\nimport { MISSING_CONFIG_MESSAGE } from \"../config\";\nimport type { LoginResult } from \"../contract\";\nimport { getRegistryNamespaceForAccount } from \"../fastkv\";\nimport {\n addFunctionCallAccessKey,\n deleteAccessKeys,\n ensureNearCli,\n generateNearKeyPair,\n listPublishKeys,\n} from \"../near-cli\";\nimport { getNetworkIdForAccount } from \"../network\";\nimport type { ResolutionSession } from \"../resolution/session\";\nimport { colors } from \"../utils/theme\";\nimport { type BosBuilder, BosDepsTag } from \"./shared\";\n\nconst PUBLISH_FUNCTION_NAMES = [\"__fastdata_kv\"];\n\nexport function registerKeys(builder: BosBuilder) {\n return {\n keyPublish: builder.keyPublish.handler(async ({ input, context }) => {\n const deps = Context.get(context[\"effect/context\"], BosDepsTag);\n const session = deps.session;\n if (!session?.config) {\n return {\n status: \"error\" as const,\n account: \"\",\n network: \"mainnet\" as const,\n env: input.env,\n contract: \"\",\n allowance: input.allowance,\n functionNames: PUBLISH_FUNCTION_NAMES,\n error: MISSING_CONFIG_MESSAGE,\n };\n }\n\n const account =\n input.env === \"staging\"\n ? (session.config.staging?.account ?? session.config.account)\n : session.config.account;\n const network = getNetworkIdForAccount(account);\n const contract = getRegistryNamespaceForAccount(account, input.registry);\n try {\n await Effect.runPromise(ensureNearCli);\n\n const oldKeys = await listPublishKeys({ account, contract, network });\n\n const keyPair = await addFunctionCallAccessKey({\n account,\n contract,\n allowance: input.allowance,\n functionNames: PUBLISH_FUNCTION_NAMES,\n network,\n });\n\n if (oldKeys.length > 0) {\n console.log();\n console.log(\n ` Found ${oldKeys.length} existing publish key${oldKeys.length > 1 ? \"s\" : \"\"}:`,\n );\n for (const k of oldKeys) {\n console.log(` ${colors.dim(k)}`);\n }\n\n if (input.removeOldKeys === true) {\n try {\n await deleteAccessKeys(account, oldKeys, network);\n console.log(\n ` ${colors.green(\"✓\")} Removed ${oldKeys.length} old key${\n oldKeys.length > 1 ? \"s\" : \"\"\n }`,\n );\n } catch {\n console.log(\n ` ${colors.yellow(\"⚠\")} Failed to remove old key${\n oldKeys.length > 1 ? \"s\" : \"\"\n } (new key still active)`,\n );\n }\n } else {\n console.log(` ${colors.dim(\"Old key(s) retained.\")}`);\n }\n }\n\n return {\n status: \"published\" as const,\n account,\n network,\n env: input.env,\n contract,\n allowance: input.allowance,\n functionNames: PUBLISH_FUNCTION_NAMES,\n publicKey: keyPair.publicKey,\n privateKey: keyPair.privateKey,\n };\n } catch (error) {\n return {\n status: \"error\" as const,\n account,\n network,\n env: input.env,\n contract,\n allowance: input.allowance,\n functionNames: PUBLISH_FUNCTION_NAMES,\n error: error instanceof Error ? error.message : \"Unknown error\",\n };\n }\n }),\n\n login: builder.login.handler(async ({ input, context }) => {\n const deps = Context.get(context[\"effect/context\"], BosDepsTag);\n const staging = input.env === \"staging\";\n const account = staging\n ? (deps.session?.config?.staging?.account ?? deps.session?.config?.account ?? \"\")\n : (deps.session?.config?.account ?? \"\");\n\n try {\n const siteUrl = resolveLoginSiteUrl(input.site, deps.session, staging);\n const login = await startDeviceLogin({\n siteUrl,\n device: input.device,\n account: account || undefined,\n expiresIn: input.expiresIn,\n });\n\n console.log();\n console.log(` One-time code: ${colors.cyan(login.userCode)}`);\n await openInBrowser(login.verificationUrl).catch((error: unknown) => {\n console.log(colors.yellow(` ⚠ ${(error as Error).message}`));\n });\n console.log();\n console.log(` Waiting for approval at ${colors.dim(login.verificationUrl)}…`);\n\n const approval = await login.waitForApproval();\n\n if (!approval.apiKey) {\n return {\n status: \"error\" as const,\n siteUrl,\n loginUrl: login.verificationUrl,\n error: \"Login approved but no CLI credential was created\",\n };\n }\n\n const expiresAt = new Date(Date.now() + input.expiresIn * 1000).toISOString();\n writeSessionHandle(deps.session?.root ?? process.cwd(), {\n version: 1,\n credential: {\n kind: \"session\",\n apiKey: approval.apiKey.key,\n apiKeyId: approval.apiKey.id,\n accountId: approval.accountId,\n label: input.device ?? siteUrl,\n siteUrl,\n createdAt: new Date().toISOString(),\n expiresAt,\n },\n publishKey: null,\n delegateKey: null,\n });\n\n let warning: string | null = null;\n if (account && approval.accountId && approval.accountId !== account) {\n warning = `Logged in as ${approval.accountId}, but the authored config account is ${account}. Publishes will use the configured account.`;\n }\n\n let publishKey: LoginResult[\"publishKey\"] = null;\n if (input.key) {\n try {\n publishKey = await exportPublishKey(account, input.registry);\n } catch (error) {\n warning = `Session stored, but publish-key export failed: ${\n error instanceof Error ? error.message : \"unknown error\"\n }`;\n }\n }\n\n return {\n status: \"logged-in\" as const,\n siteUrl,\n accountId: approval.accountId,\n expiresAt,\n loginUrl: login.verificationUrl,\n publishKey,\n warning,\n };\n } catch (error) {\n return {\n status: \"error\" as const,\n siteUrl: input.site ?? \"\",\n error: error instanceof Error ? error.message : \"Unknown error\",\n };\n }\n }),\n\n logout: builder.logout.handler(async ({ input, context }) => {\n const deps = Context.get(context[\"effect/context\"], BosDepsTag);\n const configDir = input.configDir ?? deps.session?.root ?? process.cwd();\n\n try {\n const session = readSessionHandle(configDir);\n let revokedApiKey = false;\n let removedPublishKey = false;\n let warning: string | null = null;\n\n if (session?.credential) {\n revokedApiKey = await revokeApiKey(session.credential).catch(() => false);\n if (!revokedApiKey) {\n warning =\n \"Could not revoke the API key remotely — revoke it manually under Settings → API keys.\";\n }\n }\n\n if (session?.publishKey) {\n const account = session.credential?.accountId ?? deps.session?.config?.account ?? \"\";\n removePublishedKeyFile(session.publishKey.network, account, session.publishKey.publicKey);\n removedPublishKey = true;\n warning = warning\n ? `${warning} Re-run ${colors.cyan(\"bos login --key\")} to re-export a publish key.`\n : \"Removed the exported publish key. Re-run bos login --key to re-export one.\";\n }\n\n deleteSessionHandle(configDir);\n return {\n status: \"logged-out\" as const,\n revokedApiKey,\n removedPublishKey,\n warning,\n };\n } catch (error) {\n return {\n status: \"error\" as const,\n revokedApiKey: false,\n removedPublishKey: false,\n error: error instanceof Error ? error.message : \"Unknown error\",\n };\n }\n }),\n };\n}\n\nfunction resolveLoginSiteUrl(\n siteInput: string | undefined,\n session: ResolutionSession | null,\n staging: boolean,\n): string {\n if (siteInput) {\n return siteInput.replace(/\\/+$/, \"\");\n }\n if (staging) {\n const stagingDomain = session?.config?.staging?.domain ?? session?.config?.domain;\n return stagingDomain ? `https://${stagingDomain}` : (session?.runtime?.ui?.url ?? \"\");\n }\n const devUiUrl = session?.runtime?.ui?.url;\n if (devUiUrl && /^https?:\\/\\/(localhost|127\\.0\\.0\\.1)/.test(devUiUrl)) {\n return devUiUrl.replace(/\\/+$/, \"\");\n }\n const domain = session?.config?.domain;\n return domain ? `https://${domain}` : \"\";\n}\n\nasync function exportPublishKey(\n account: string,\n registry: string | undefined,\n): Promise<NonNullable<LoginResult[\"publishKey\"]>> {\n if (!account) {\n throw new Error(\"the authored config has no account to export a publish key for\");\n }\n\n await Effect.runPromise(ensureNearCli);\n\n const network = getNetworkIdForAccount(account);\n const contract = getRegistryNamespaceForAccount(account, registry);\n await listPublishKeys({ account, contract, network });\n\n const keyPair = generateNearKeyPair();\n await addFunctionCallAccessKey({\n account,\n contract,\n allowance: \"1NEAR\",\n functionNames: PUBLISH_FUNCTION_NAMES,\n network,\n keyPair,\n });\n\n const { FileKeyStore } = await import(\"near-kit/keys/file\");\n const keyStore = new FileKeyStore(\"~/.near-credentials\", network);\n await keyStore.add(account, parseNearPrivateKey(keyPair.privateKey));\n try {\n const { statSync, chmodSync } = await import(\"node:fs\");\n const { homedir } = await import(\"node:os\");\n const credentialPath = join(\n homedir(),\n \".near-credentials\",\n network === \"mainnet\" ? \"mainnet\" : network,\n `${account}.json`,\n );\n if (statSync(credentialPath).mode & 0o077) {\n chmodSync(credentialPath, 0o600);\n }\n } catch {}\n\n return {\n publicKey: keyPair.publicKey,\n network,\n contract,\n exportedTo: nearCredentialsPath(network, account),\n };\n}\nfunction parseNearPrivateKey(privateKey: string): KeyPair {\n return parseKey(privateKey) as KeyPair;\n}\n\nasync function revokeApiKey(credential: SessionCredential): Promise<boolean> {\n if (!credential.apiKey || !credential.siteUrl) return false;\n try {\n const response = await fetch(`${credential.siteUrl}/api/auth/api-key/delete`, {\n method: \"POST\",\n headers: {\n \"x-api-key\": credential.apiKey,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ keyId: credential.apiKeyId }),\n signal: AbortSignal.timeout(10_000),\n });\n return response.ok;\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA4BA,MAAM,yBAAyB,CAAC,eAAe;AAE/C,SAAgB,aAAa,SAAqB;CAChD,OAAO;EACL,YAAY,QAAQ,WAAW,QAAQ,OAAO,EAAE,OAAO,cAAc;GAEnE,MAAM,UADO,QAAQ,IAAI,QAAQ,mBAAmB,UACjC,CAAC,CAAC;GACrB,IAAI,CAAC,SAAS,QACZ,OAAO;IACL,QAAQ;IACR,SAAS;IACT,SAAS;IACT,KAAK,MAAM;IACX,UAAU;IACV,WAAW,MAAM;IACjB,eAAe;IACf,OAAO;GACT;GAGF,MAAM,UACJ,MAAM,QAAQ,YACT,QAAQ,OAAO,SAAS,WAAW,QAAQ,OAAO,UACnD,QAAQ,OAAO;GACrB,MAAM,UAAU,uBAAuB,O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AC,WAAW,UAAU,CAAC,WAAW,SAAS,OAAO;CACtD,IAAI;EAUF,QAAO,MATgB,MAAM,GAAG,WAAW,QAAQ,2BAA2B;GAC5E,QAAQ;GACR,SAAS;IACP,aAAa,WAAW;IACxB,gBAAgB;GAClB;GACA,MAAM,KAAK,UAAU,EAAE,OAAO,WAAW,SAAS,CAAC;GACnD,QAAQ,YAAY,QAAQ,GAAM;EACpC,CAAC,EACc,CAAC;CAClB,QAAQ;EACN,OAAO;CACT;AACF"}
@@ -165,7 +165,7 @@ const cliCommandMeta = {
165
165
  fields: {
166
166
  env: { description: "Environment: production or staging" },
167
167
  allowance: { description: "NEAR allowance for the key (default: 1NEAR, min: 0.3NEAR)" },
168
- removeOldKeys: { description: "Remove existing publish key(s) without prompting (default: ask on a TTY, yes when non-interactive)" },
168
+ removeOldKeys: { description: "Remove existing publish key(s) without prompting (default: ask on a TTY, defaulting to keep; keep when non-interactive — pass --remove-old-keys to remove)" },
169
169
  registry: { description: "Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)" }
170
170
  }
171
171
  },
@@ -1 +1 @@
1
- {"version":3,"file":"contract.meta.cjs","names":[],"sources":["../src/contract.meta.ts"],"sourcesContent":["export type CliCommandMeta = {\n commandPath?: string[];\n summary: string;\n description?: string;\n examples?: string[];\n interactive?: boolean;\n longRunning?: boolean;\n fields?: Record<string, { positional?: boolean; description?: string }>;\n};\n\nexport const cliCommandMeta = {\n dev: {\n commandPath: [\"dev\"],\n summary: \"Start a development session\",\n interactive: true,\n longRunning: true,\n fields: {\n remotePlugins: {\n description:\n \"Comma-separated plugin IDs to force remote (e.g. --remote-plugins auth,registry)\",\n },\n logLevel: {\n description:\n \"Log tail level: error, warn (default), info, or debug (overrides BOS_LOG_LEVEL; the file always gets everything)\",\n },\n },\n },\n start: {\n commandPath: [\"start\"],\n summary: \"Start the production host\",\n interactive: false,\n longRunning: true,\n fields: {\n env: { description: \"Environment: production or staging\" },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n configPath: {\n description:\n \"Boot from a local bos config file — skips FastKV resolution and SRI integrity verification\",\n },\n },\n },\n build: {\n commandPath: [\"build\"],\n summary: \"Build selected workspaces\",\n interactive: false,\n fields: {\n packages: { positional: true, description: \"Comma-separated package list\" },\n },\n },\n config: {\n commandPath: [\"config\"],\n summary: \"Print the loaded BOS configuration\",\n interactive: false,\n fields: {\n full: { description: \"Print the fully resolved configuration\" },\n },\n },\n registryUse: {\n commandPath: [\"registry\", \"use\"],\n summary:\n \"Compose app.ui/app.host/app.api/plugins.<key> sections from a published runtime into bos.config.json\",\n interactive: false,\n fields: {\n from: {\n positional: true,\n description:\n \"Published runtime (account/gateway or bos:// URL), e.g. v1.citynode.near/citynode.app\",\n },\n sections: {\n description: \"Comma-separated sections to compose, e.g. app.ui,plugins.apps\",\n },\n dryRun: { description: \"Preview the merged config without writing\" },\n },\n },\n pluginAdd: {\n commandPath: [\"plugin\", \"add\"],\n summary: \"Add a plugin attachment\",\n interactive: false,\n fields: {\n source: {\n positional: true,\n description: \"Plugin source (local:path, bos://account/domain, or URL)\",\n },\n as: { description: \"Plugin alias\" },\n production: { description: \"Production URL override\" },\n },\n },\n pluginRemove: {\n commandPath: [\"plugin\", \"remove\"],\n summary: \"Remove a plugin attachment\",\n interactive: false,\n fields: { key: { positional: true, description: \"Plugin key\" } },\n },\n pluginList: {\n commandPath: [\"plugin\", \"list\"],\n summary: \"List configured plugins\",\n interactive: false,\n },\n pluginPublish: {\n commandPath: [\"plugin\", \"publish\"],\n summary: \"Publish a single plugin\",\n interactive: false,\n fields: { key: { positional: true, description: \"Plugin key\" } },\n },\n publish: {\n commandPath: [\"publish\"],\n summary:\n \"Publish the current workspace configuration (no build — use bos deploy for the full train)\",\n interactive: false,\n fields: {\n dryRun: { description: \"Preview what would be published without writing\" },\n verbose: { description: \"Show full build output instead of clean summary\" },\n env: { description: \"Environment: production or staging\" },\n network: { description: \"NEAR network: mainnet or testnet\" },\n wallet: {\n description:\n \"Publish gaslessly with a one-time wallet approval (NEP-366 delegate action relayed by the platform relayer)\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n rollback: {\n commandPath: [\"rollback\"],\n summary: \"Republish an earlier config snapshot from the registry publish history\",\n interactive: true,\n fields: {\n version: { description: \"Block height (or timestamp) of the snapshot from the listing\" },\n previous: { description: \"Roll back to the write immediately before the current one\" },\n force: {\n description:\n \"Allow pre-Phase-A snapshots without verifiable manifest pins (their bytes were overwritten in place)\",\n },\n limit: { description: \"Listing depth (1-200, default 20)\" },\n dryRun: { description: \"Preview the rollback without publishing\" },\n env: { description: \"Environment: production or staging\" },\n network: { description: \"NEAR network: mainnet or testnet\" },\n wallet: {\n description:\n \"Publish gaslessly with a one-time wallet approval (NEP-366 delegate action relayed by the platform relayer)\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n deploy: {\n commandPath: [\"deploy\"],\n summary:\n \"Deploy train: preflight → build → upload bundles → publish config → runtime image (pre-pushed digest or local docker build) → post-publish smoke (optional) → Railway (image-backed, no build)\",\n interactive: false,\n fields: {\n env: { description: \"Environment: production or staging\" },\n build: { description: \"Build and deploy workspaces before publish (default: true)\" },\n dryRun: { description: \"Preview what would be deployed without writing\" },\n verbose: { description: \"Show full build output instead of clean summary\" },\n service: { description: \"Override Railway service name from config\" },\n imageDigest: {\n description:\n \"Digest of a pre-pushed runtime image (sha256:…) — skips the local image build/push; Railway pins this digest\",\n },\n smoke: {\n description:\n \"Gate the Railway promotion on a post-publish boot smoke of the runtime image — a red smoke rolls the config back\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n smoke: {\n commandPath: [\"smoke\"],\n summary:\n \"Boot a runtime image the way production boots (identity-driven, published config) and assert the boot surface: /health, SSR, OpenAPI spec, in-image mf check\",\n interactive: false,\n fields: {\n image: { description: \"Runtime image ref to boot (required)\" },\n port: { description: \"Host port to publish the container on (default: 3000)\" },\n keep: { description: \"Keep the container after the run (debugging)\" },\n account: { description: \"Registry identity — defaults to the resolved session config\" },\n },\n },\n login: {\n commandPath: [\"login\"],\n summary:\n \"Sign in with your NEAR account via the hosted site (wallet, passkey, or social login)\",\n interactive: true,\n fields: {\n key: { description: \"Also mint and export a scoped publish key for headless/CI use\" },\n site: { description: \"Override site URL hosting the CLI login page\" },\n device: { description: \"Device label recorded on the credential (default: hostname)\" },\n expiresIn: { description: \"Session lifetime in seconds (default: 90 days)\" },\n env: { description: \"Environment: production (default) or staging\" },\n },\n },\n logout: {\n commandPath: [\"logout\"],\n summary: \"Revoke the stored CLI session and delete the exported publish key\",\n interactive: false,\n },\n keyPublish: {\n commandPath: [\"key\", \"generate\"],\n summary: \"Generate a publish access key\",\n interactive: true,\n fields: {\n env: { description: \"Environment: production or staging\" },\n allowance: { description: \"NEAR allowance for the key (default: 1NEAR, min: 0.3NEAR)\" },\n removeOldKeys: {\n description:\n \"Remove existing publish key(s) without prompting (default: ask on a TTY, yes when non-interactive)\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n init: {\n commandPath: [\"init\"],\n summary: \"Scaffold a new project by extending a deployed app or template\",\n interactive: true,\n fields: {\n domain: {\n positional: true,\n description: \"New project domain (e.g. myapp.everything.dev)\",\n },\n extends: {\n description: \"Parent to extend from (e.g. bos://account/gateway or account/gateway)\",\n },\n account: { description: \"New project NEAR account (auto-derived from extends)\" },\n directory: { description: \"Target directory (auto-derived from domain)\" },\n source: { description: \"Local source dir (skips GitHub download)\" },\n plugins: {\n description: \"Comma-separated plugin keys to include (requires --overrides=plugins)\",\n },\n overrides: {\n description: \"Comma-separated sections to customize locally: ui,api,host,plugins\",\n },\n level: {\n description:\n \"Starter complexity: simple (public shell) or advanced (adds dashboard, orgs, admin)\",\n },\n noInteractive: { description: \"Skip prompts, use flags only\" },\n noInstall: { description: \"Skip pnpm install\" },\n },\n },\n sync: {\n commandPath: [\"sync\"],\n summary: \"Sync template files from parent project\",\n interactive: false,\n fields: {\n dryRun: { description: \"Preview changes without writing files\" },\n noInstall: { description: \"Skip pnpm install\" },\n },\n },\n upgrade: {\n commandPath: [\"upgrade\"],\n summary: \"Upgrade framework packages and sync template files\",\n interactive: true,\n fields: {\n dryRun: { description: \"Preview changes without writing\" },\n noInstall: { description: \"Skip pnpm install\" },\n noSync: { description: \"Only upgrade packages, skip template sync\" },\n },\n },\n typesGen: {\n commandPath: [\"types\", \"gen\"],\n summary: \"Generate type definitions from configured API and plugin contracts\",\n interactive: false,\n fields: {\n env: { description: \"Environment: development (default) or production\" },\n dryRun: { description: \"Preview what would be fetched without writing files\" },\n remotePlugins: {\n description:\n \"Comma-separated plugin IDs to fetch contract types remotely (e.g. --remote-plugins auth,registry)\",\n },\n },\n },\n typecheck: {\n commandPath: [\"typecheck\"],\n summary: \"Run TypeScript type checking across all local workspaces\",\n interactive: false,\n fields: {\n packages: {\n positional: true,\n description: \"Comma-separated workspace list (default: all)\",\n },\n },\n },\n mfCheck: {\n commandPath: [\"mf\", \"check\"],\n summary:\n \"Verify Module Federation runtime compatibility across published host + plugin bundles\",\n interactive: false,\n },\n dbStudio: {\n commandPath: [\"db\", \"studio\"],\n summary: \"Open Drizzle Studio for a plugin's database\",\n fields: {\n plugin: {\n positional: true,\n description: \"Plugin key: api, auth, or a plugin name (default: api)\",\n },\n },\n },\n dbDoctor: {\n commandPath: [\"db\", \"doctor\"],\n summary: \"Diagnose migration health for a plugin's database\",\n fields: {\n plugin: {\n positional: true,\n description: \"Plugin key: api, auth, or a plugin name\",\n },\n },\n },\n dbRepair: {\n commandPath: [\"db\", \"repair\"],\n summary: \"Reset migration history and reapply migrations for a plugin\",\n fields: {\n plugin: {\n positional: true,\n description: \"Plugin key: api, auth, or a plugin name\",\n },\n mode: {\n description: \"Repair mode: history-reset (default) or recreate (not yet supported)\",\n },\n yes: {\n description: \"Skip confirmation prompt\",\n },\n },\n },\n status: {\n commandPath: [\"status\"],\n summary: \"Show project health, versions, and update availability\",\n interactive: false,\n },\n ps: {\n commandPath: [\"ps\"],\n summary: \"List tracked development processes\",\n interactive: false,\n },\n logs: {\n commandPath: [\"logs\"],\n summary: \"Read dev session logs (.bos/logs/dev-latest.log)\",\n interactive: false,\n fields: {\n service: {\n description: \"Filter by service name (e.g. host, api, auth, ui, plugin:votes)\",\n },\n tail: { description: \"Show only the last N lines\" },\n follow: { description: \"Stream the log as lines are appended\" },\n },\n },\n kill: {\n commandPath: [\"kill\"],\n summary: \"Stop tracked development processes\",\n interactive: false,\n fields: {\n configDir: { description: \"Kill processes owned by a config directory (defaults to cwd)\" },\n signal: { description: \"Signal: SIGTERM (default) or SIGKILL\" },\n all: { description: \"Kill processes across all config directories\" },\n },\n },\n infraExport: {\n commandPath: [\"infra\", \"export\"],\n summary: \"Emit the resolved CI infra plan (env + services) for the current runtime\",\n interactive: false,\n fields: {\n target: { description: \"Export target: ci (default) or local\" },\n network: { description: \"NEAR network: mainnet or testnet\" },\n configDir: { description: \"Override config directory\" },\n },\n },\n} as const satisfies Record<string, CliCommandMeta>;\n"],"mappings":";;AAUA,MAAa,iBAAiB;CAC5B,KAAK;EACH,aAAa,CAAC,KAAK;EACnB,SAAS;EACT,aAAa;EACb,aAAa;EACb,QAAQ;GACN,eAAe,EACb,aACE,mFACJ;GACA,UAAU,EACR,aACE,mHACJ;EACF;CACF;CACA,OAAO;EACL,aAAa,CAAC,OAAO;EACrB,SAAS;EACT,aAAa;EACb,aAAa;EACb,QAAQ;GACN,KAAK,EAAE,aAAa,qCAAqC;GACzD,UAAU,EACR,aACE,uGACJ;GACA,YAAY,EACV,aACE,6FACJ;EACF;CACF;CACA,OAAO;EACL,aAAa,CAAC,OAAO;EACrB,SAAS;EACT,aAAa;EACb,QAAQ,EACN,UAAU;GAAE,YAAY;GAA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Z,aAAa;EACf,EACF;CACF;CACA,UAAU;EACR,aAAa,CAAC,MAAM,QAAQ;EAC5B,SAAS;EACT,QAAQ,EACN,QAAQ;GACN,YAAY;GACZ,aAAa;EACf,EACF;CACF;CACA,UAAU;EACR,aAAa,CAAC,MAAM,QAAQ;EAC5B,SAAS;EACT,QAAQ;GACN,QAAQ;IACN,YAAY;IACZ,aAAa;GACf;GACA,MAAM,EACJ,aAAa,uEACf;GACA,KAAK,EACH,aAAa,2BACf;EACF;CACF;CACA,QAAQ;EACN,aAAa,CAAC,QAAQ;EACtB,SAAS;EACT,aAAa;CACf;CACA,IAAI;EACF,aAAa,CAAC,IAAI;EAClB,SAAS;EACT,aAAa;CACf;CACA,MAAM;EACJ,aAAa,CAAC,MAAM;EACpB,SAAS;EACT,aAAa;EACb,QAAQ;GACN,SAAS,EACP,aAAa,kEACf;GACA,MAAM,EAAE,aAAa,6BAA6B;GAClD,QAAQ,EAAE,aAAa,uCAAuC;EAChE;CACF;CACA,MAAM;EACJ,aAAa,CAAC,MAAM;EACpB,SAAS;EACT,aAAa;EACb,QAAQ;GACN,WAAW,EAAE,aAAa,+DAA+D;GACzF,QAAQ,EAAE,aAAa,uCAAuC;GAC9D,KAAK,EAAE,aAAa,+CAA+C;EACrE;CACF;CACA,aAAa;EACX,aAAa,CAAC,SAAS,QAAQ;EAC/B,SAAS;EACT,aAAa;EACb,QAAQ;GACN,QAAQ,EAAE,aAAa,uCAAuC;GAC9D,SAAS,EAAE,aAAa,mCAAmC;GAC3D,WAAW,EAAE,aAAa,4BAA4B;EACxD;CACF;AACF"}
1
+ {"version":3,"file":"contract.meta.cjs","names":[],"sources":["../src/contract.meta.ts"],"sourcesContent":["export type CliCommandMeta = {\n commandPath?: string[];\n summary: string;\n description?: string;\n examples?: string[];\n interactive?: boolean;\n longRunning?: boolean;\n fields?: Record<string, { positional?: boolean; description?: string }>;\n};\n\nexport const cliCommandMeta = {\n dev: {\n commandPath: [\"dev\"],\n summary: \"Start a development session\",\n interactive: true,\n longRunning: true,\n fields: {\n remotePlugins: {\n description:\n \"Comma-separated plugin IDs to force remote (e.g. --remote-plugins auth,registry)\",\n },\n logLevel: {\n description:\n \"Log tail level: error, warn (default), info, or debug (overrides BOS_LOG_LEVEL; the file always gets everything)\",\n },\n },\n },\n start: {\n commandPath: [\"start\"],\n summary: \"Start the production host\",\n interactive: false,\n longRunning: true,\n fields: {\n env: { description: \"Environment: production or staging\" },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n configPath: {\n description:\n \"Boot from a local bos config file — skips FastKV resolution and SRI integrity verification\",\n },\n },\n },\n build: {\n commandPath: [\"build\"],\n summary: \"Build selected workspaces\",\n interactive: false,\n fields: {\n packages: { positional: true, description: \"Comma-separated package list\" },\n },\n },\n config: {\n commandPath: [\"config\"],\n summary: \"Print the loaded BOS configuration\",\n interactive: false,\n fields: {\n full: { description: \"Print the fully resolved configuration\" },\n },\n },\n registryUse: {\n commandPath: [\"registry\", \"use\"],\n summary:\n \"Compose app.ui/app.host/app.api/plugins.<key> sections from a published runtime into bos.config.json\",\n interactive: false,\n fields: {\n from: {\n positional: true,\n description:\n \"Published runtime (account/gateway or bos:// URL), e.g. v1.citynode.near/citynode.app\",\n },\n sections: {\n description: \"Comma-separated sections to compose, e.g. app.ui,plugins.apps\",\n },\n dryRun: { description: \"Preview the merged config without writing\" },\n },\n },\n pluginAdd: {\n commandPath: [\"plugin\", \"add\"],\n summary: \"Add a plugin attachment\",\n interactive: false,\n fields: {\n source: {\n positional: true,\n description: \"Plugin source (local:path, bos://account/domain, or URL)\",\n },\n as: { description: \"Plugin alias\" },\n production: { description: \"Production URL override\" },\n },\n },\n pluginRemove: {\n commandPath: [\"plugin\", \"remove\"],\n summary: \"Remove a plugin attachment\",\n interactive: false,\n fields: { key: { positional: true, description: \"Plugin key\" } },\n },\n pluginList: {\n commandPath: [\"plugin\", \"list\"],\n summary: \"List configured plugins\",\n interactive: false,\n },\n pluginPublish: {\n commandPath: [\"plugin\", \"publish\"],\n summary: \"Publish a single plugin\",\n interactive: false,\n fields: { key: { positional: true, description: \"Plugin key\" } },\n },\n publish: {\n commandPath: [\"publish\"],\n summary:\n \"Publish the current workspace configuration (no build — use bos deploy for the full train)\",\n interactive: false,\n fields: {\n dryRun: { description: \"Preview what would be published without writing\" },\n verbose: { description: \"Show full build output instead of clean summary\" },\n env: { description: \"Environment: production or staging\" },\n network: { description: \"NEAR network: mainnet or testnet\" },\n wallet: {\n description:\n \"Publish gaslessly with a one-time wallet approval (NEP-366 delegate action relayed by the platform relayer)\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n rollback: {\n commandPath: [\"rollback\"],\n summary: \"Republish an earlier config snapshot from the registry publish history\",\n interactive: true,\n fields: {\n version: { description: \"Block height (or timestamp) of the snapshot from the listing\" },\n previous: { description: \"Roll back to the write immediately before the current one\" },\n force: {\n description:\n \"Allow pre-Phase-A snapshots without verifiable manifest pins (their bytes were overwritten in place)\",\n },\n limit: { description: \"Listing depth (1-200, default 20)\" },\n dryRun: { description: \"Preview the rollback without publishing\" },\n env: { description: \"Environment: production or staging\" },\n network: { description: \"NEAR network: mainnet or testnet\" },\n wallet: {\n description:\n \"Publish gaslessly with a one-time wallet approval (NEP-366 delegate action relayed by the platform relayer)\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n deploy: {\n commandPath: [\"deploy\"],\n summary:\n \"Deploy train: preflight → build → upload bundles → publish config → runtime image (pre-pushed digest or local docker build) → post-publish smoke (optional) → Railway (image-backed, no build)\",\n interactive: false,\n fields: {\n env: { description: \"Environment: production or staging\" },\n build: { description: \"Build and deploy workspaces before publish (default: true)\" },\n dryRun: { description: \"Preview what would be deployed without writing\" },\n verbose: { description: \"Show full build output instead of clean summary\" },\n service: { description: \"Override Railway service name from config\" },\n imageDigest: {\n description:\n \"Digest of a pre-pushed runtime image (sha256:…) — skips the local image build/push; Railway pins this digest\",\n },\n smoke: {\n description:\n \"Gate the Railway promotion on a post-publish boot smoke of the runtime image — a red smoke rolls the config back\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n smoke: {\n commandPath: [\"smoke\"],\n summary:\n \"Boot a runtime image the way production boots (identity-driven, published config) and assert the boot surface: /health, SSR, OpenAPI spec, in-image mf check\",\n interactive: false,\n fields: {\n image: { description: \"Runtime image ref to boot (required)\" },\n port: { description: \"Host port to publish the container on (default: 3000)\" },\n keep: { description: \"Keep the container after the run (debugging)\" },\n account: { description: \"Registry identity — defaults to the resolved session config\" },\n },\n },\n login: {\n commandPath: [\"login\"],\n summary:\n \"Sign in with your NEAR account via the hosted site (wallet, passkey, or social login)\",\n interactive: true,\n fields: {\n key: { description: \"Also mint and export a scoped publish key for headless/CI use\" },\n site: { description: \"Override site URL hosting the CLI login page\" },\n device: { description: \"Device label recorded on the credential (default: hostname)\" },\n expiresIn: { description: \"Session lifetime in seconds (default: 90 days)\" },\n env: { description: \"Environment: production (default) or staging\" },\n },\n },\n logout: {\n commandPath: [\"logout\"],\n summary: \"Revoke the stored CLI session and delete the exported publish key\",\n interactive: false,\n },\n keyPublish: {\n commandPath: [\"key\", \"generate\"],\n summary: \"Generate a publish access key\",\n interactive: true,\n fields: {\n env: { description: \"Environment: production or staging\" },\n allowance: { description: \"NEAR allowance for the key (default: 1NEAR, min: 0.3NEAR)\" },\n removeOldKeys: {\n description:\n \"Remove existing publish key(s) without prompting (default: ask on a TTY, defaulting to keep; keep when non-interactive — pass --remove-old-keys to remove)\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n init: {\n commandPath: [\"init\"],\n summary: \"Scaffold a new project by extending a deployed app or template\",\n interactive: true,\n fields: {\n domain: {\n positional: true,\n description: \"New project domain (e.g. myapp.everything.dev)\",\n },\n extends: {\n description: \"Parent to extend from (e.g. bos://account/gateway or account/gateway)\",\n },\n account: { description: \"New project NEAR account (auto-derived from extends)\" },\n directory: { description: \"Target directory (auto-derived from domain)\" },\n source: { description: \"Local source dir (skips GitHub download)\" },\n plugins: {\n description: \"Comma-separated plugin keys to include (requires --overrides=plugins)\",\n },\n overrides: {\n description: \"Comma-separated sections to customize locally: ui,api,host,plugins\",\n },\n level: {\n description:\n \"Starter complexity: simple (public shell) or advanced (adds dashboard, orgs, admin)\",\n },\n noInteractive: { description: \"Skip prompts, use flags only\" },\n noInstall: { description: \"Skip pnpm install\" },\n },\n },\n sync: {\n commandPath: [\"sync\"],\n summary: \"Sync template files from parent project\",\n interactive: false,\n fields: {\n dryRun: { description: \"Preview changes without writing files\" },\n noInstall: { description: \"Skip pnpm install\" },\n },\n },\n upgrade: {\n commandPath: [\"upgrade\"],\n summary: \"Upgrade framework packages and sync template files\",\n interactive: true,\n fields: {\n dryRun: { description: \"Preview changes without writing\" },\n noInstall: { description: \"Skip pnpm install\" },\n noSync: { description: \"Only upgrade packages, skip template sync\" },\n },\n },\n typesGen: {\n commandPath: [\"types\", \"gen\"],\n summary: \"Generate type definitions from configured API and plugin contracts\",\n interactive: false,\n fields: {\n env: { description: \"Environment: development (default) or production\" },\n dryRun: { description: \"Preview what would be fetched without writing files\" },\n remotePlugins: {\n description:\n \"Comma-separated plugin IDs to fetch contract types remotely (e.g. --remote-plugins auth,registry)\",\n },\n },\n },\n typecheck: {\n commandPath: [\"typecheck\"],\n summary: \"Run TypeScript type checking across all local workspaces\",\n interactive: false,\n fields: {\n packages: {\n positional: true,\n description: \"Comma-separated workspace list (default: all)\",\n },\n },\n },\n mfCheck: {\n commandPath: [\"mf\", \"check\"],\n summary:\n \"Verify Module Federation runtime compatibility across published host + plugin bundles\",\n interactive: false,\n },\n dbStudio: {\n commandPath: [\"db\", \"studio\"],\n summary: \"Open Drizzle Studio for a plugin's database\",\n fields: {\n plugin: {\n positional: true,\n description: \"Plugin key: api, auth, or a plugin name (default: api)\",\n },\n },\n },\n dbDoctor: {\n commandPath: [\"db\", \"doctor\"],\n summary: \"Diagnose migration health for a plugin's database\",\n fields: {\n plugin: {\n positional: true,\n description: \"Plugin key: api, auth, or a plugin name\",\n },\n },\n },\n dbRepair: {\n commandPath: [\"db\", \"repair\"],\n summary: \"Reset migration history and reapply migrations for a plugin\",\n fields: {\n plugin: {\n positional: true,\n description: \"Plugin key: api, auth, or a plugin name\",\n },\n mode: {\n description: \"Repair mode: history-reset (default) or recreate (not yet supported)\",\n },\n yes: {\n description: \"Skip confirmation prompt\",\n },\n },\n },\n status: {\n commandPath: [\"status\"],\n summary: \"Show project health, versions, and update availability\",\n interactive: false,\n },\n ps: {\n commandPath: [\"ps\"],\n summary: \"List tracked development processes\",\n interactive: false,\n },\n logs: {\n commandPath: [\"logs\"],\n summary: \"Read dev session logs (.bos/logs/dev-latest.log)\",\n interactive: false,\n fields: {\n service: {\n description: \"Filter by service name (e.g. host, api, auth, ui, plugin:votes)\",\n },\n tail: { description: \"Show only the last N lines\" },\n follow: { description: \"Stream the log as lines are appended\" },\n },\n },\n kill: {\n commandPath: [\"kill\"],\n summary: \"Stop tracked development processes\",\n interactive: false,\n fields: {\n configDir: { description: \"Kill processes owned by a config directory (defaults to cwd)\" },\n signal: { description: \"Signal: SIGTERM (default) or SIGKILL\" },\n all: { description: \"Kill processes across all config directories\" },\n },\n },\n infraExport: {\n commandPath: [\"infra\", \"export\"],\n summary: \"Emit the resolved CI infra plan (env + services) for the current runtime\",\n interactive: false,\n fields: {\n target: { description: \"Export target: ci (default) or local\" },\n network: { description: \"NEAR network: mainnet or testnet\" },\n configDir: { description: \"Override config directory\" },\n },\n },\n} as const satisfies Record<string, CliCommandMeta>;\n"],"mappings":";;AAUA,MAAa,iBAAiB;CAC5B,KAAK;EACH,aAAa,CAAC,KAAK;EACnB,SAAS;EACT,aAAa;EACb,aAAa;EACb,QAAQ;GACN,eAAe,E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AAS,EAAE,aAAa,mCAAmC;GAC3D,WAAW,EAAE,aAAa,4BAA4B;EACxD;CACF;AACF"}
@@ -273,7 +273,7 @@ declare const cliCommandMeta: {
273
273
  readonly description: "NEAR allowance for the key (default: 1NEAR, min: 0.3NEAR)";
274
274
  };
275
275
  readonly removeOldKeys: {
276
- readonly description: "Remove existing publish key(s) without prompting (default: ask on a TTY, yes when non-interactive)";
276
+ readonly description: "Remove existing publish key(s) without prompting (default: ask on a TTY, defaulting to keep; keep when non-interactive — pass --remove-old-keys to remove)";
277
277
  };
278
278
  readonly registry: {
279
279
  readonly description: "Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)";
@@ -273,7 +273,7 @@ declare const cliCommandMeta: {
273
273
  readonly description: "NEAR allowance for the key (default: 1NEAR, min: 0.3NEAR)";
274
274
  };
275
275
  readonly removeOldKeys: {
276
- readonly description: "Remove existing publish key(s) without prompting (default: ask on a TTY, yes when non-interactive)";
276
+ readonly description: "Remove existing publish key(s) without prompting (default: ask on a TTY, defaulting to keep; keep when non-interactive — pass --remove-old-keys to remove)";
277
277
  };
278
278
  readonly registry: {
279
279
  readonly description: "Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)";
@@ -164,7 +164,7 @@ const cliCommandMeta = {
164
164
  fields: {
165
165
  env: { description: "Environment: production or staging" },
166
166
  allowance: { description: "NEAR allowance for the key (default: 1NEAR, min: 0.3NEAR)" },
167
- removeOldKeys: { description: "Remove existing publish key(s) without prompting (default: ask on a TTY, yes when non-interactive)" },
167
+ removeOldKeys: { description: "Remove existing publish key(s) without prompting (default: ask on a TTY, defaulting to keep; keep when non-interactive — pass --remove-old-keys to remove)" },
168
168
  registry: { description: "Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)" }
169
169
  }
170
170
  },
@@ -1 +1 @@
1
- {"version":3,"file":"contract.meta.mjs","names":[],"sources":["../src/contract.meta.ts"],"sourcesContent":["export type CliCommandMeta = {\n commandPath?: string[];\n summary: string;\n description?: string;\n examples?: string[];\n interactive?: boolean;\n longRunning?: boolean;\n fields?: Record<string, { positional?: boolean; description?: string }>;\n};\n\nexport const cliCommandMeta = {\n dev: {\n commandPath: [\"dev\"],\n summary: \"Start a development session\",\n interactive: true,\n longRunning: true,\n fields: {\n remotePlugins: {\n description:\n \"Comma-separated plugin IDs to force remote (e.g. --remote-plugins auth,registry)\",\n },\n logLevel: {\n description:\n \"Log tail level: error, warn (default), info, or debug (overrides BOS_LOG_LEVEL; the file always gets everything)\",\n },\n },\n },\n start: {\n commandPath: [\"start\"],\n summary: \"Start the production host\",\n interactive: false,\n longRunning: true,\n fields: {\n env: { description: \"Environment: production or staging\" },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n configPath: {\n description:\n \"Boot from a local bos config file — skips FastKV resolution and SRI integrity verification\",\n },\n },\n },\n build: {\n commandPath: [\"build\"],\n summary: \"Build selected workspaces\",\n interactive: false,\n fields: {\n packages: { positional: true, description: \"Comma-separated package list\" },\n },\n },\n config: {\n commandPath: [\"config\"],\n summary: \"Print the loaded BOS configuration\",\n interactive: false,\n fields: {\n full: { description: \"Print the fully resolved configuration\" },\n },\n },\n registryUse: {\n commandPath: [\"registry\", \"use\"],\n summary:\n \"Compose app.ui/app.host/app.api/plugins.<key> sections from a published runtime into bos.config.json\",\n interactive: false,\n fields: {\n from: {\n positional: true,\n description:\n \"Published runtime (account/gateway or bos:// URL), e.g. v1.citynode.near/citynode.app\",\n },\n sections: {\n description: \"Comma-separated sections to compose, e.g. app.ui,plugins.apps\",\n },\n dryRun: { description: \"Preview the merged config without writing\" },\n },\n },\n pluginAdd: {\n commandPath: [\"plugin\", \"add\"],\n summary: \"Add a plugin attachment\",\n interactive: false,\n fields: {\n source: {\n positional: true,\n description: \"Plugin source (local:path, bos://account/domain, or URL)\",\n },\n as: { description: \"Plugin alias\" },\n production: { description: \"Production URL override\" },\n },\n },\n pluginRemove: {\n commandPath: [\"plugin\", \"remove\"],\n summary: \"Remove a plugin attachment\",\n interactive: false,\n fields: { key: { positional: true, description: \"Plugin key\" } },\n },\n pluginList: {\n commandPath: [\"plugin\", \"list\"],\n summary: \"List configured plugins\",\n interactive: false,\n },\n pluginPublish: {\n commandPath: [\"plugin\", \"publish\"],\n summary: \"Publish a single plugin\",\n interactive: false,\n fields: { key: { positional: true, description: \"Plugin key\" } },\n },\n publish: {\n commandPath: [\"publish\"],\n summary:\n \"Publish the current workspace configuration (no build — use bos deploy for the full train)\",\n interactive: false,\n fields: {\n dryRun: { description: \"Preview what would be published without writing\" },\n verbose: { description: \"Show full build output instead of clean summary\" },\n env: { description: \"Environment: production or staging\" },\n network: { description: \"NEAR network: mainnet or testnet\" },\n wallet: {\n description:\n \"Publish gaslessly with a one-time wallet approval (NEP-366 delegate action relayed by the platform relayer)\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n rollback: {\n commandPath: [\"rollback\"],\n summary: \"Republish an earlier config snapshot from the registry publish history\",\n interactive: true,\n fields: {\n version: { description: \"Block height (or timestamp) of the snapshot from the listing\" },\n previous: { description: \"Roll back to the write immediately before the current one\" },\n force: {\n description:\n \"Allow pre-Phase-A snapshots without verifiable manifest pins (their bytes were overwritten in place)\",\n },\n limit: { description: \"Listing depth (1-200, default 20)\" },\n dryRun: { description: \"Preview the rollback without publishing\" },\n env: { description: \"Environment: production or staging\" },\n network: { description: \"NEAR network: mainnet or testnet\" },\n wallet: {\n description:\n \"Publish gaslessly with a one-time wallet approval (NEP-366 delegate action relayed by the platform relayer)\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n deploy: {\n commandPath: [\"deploy\"],\n summary:\n \"Deploy train: preflight → build → upload bundles → publish config → runtime image (pre-pushed digest or local docker build) → post-publish smoke (optional) → Railway (image-backed, no build)\",\n interactive: false,\n fields: {\n env: { description: \"Environment: production or staging\" },\n build: { description: \"Build and deploy workspaces before publish (default: true)\" },\n dryRun: { description: \"Preview what would be deployed without writing\" },\n verbose: { description: \"Show full build output instead of clean summary\" },\n service: { description: \"Override Railway service name from config\" },\n imageDigest: {\n description:\n \"Digest of a pre-pushed runtime image (sha256:…) — skips the local image build/push; Railway pins this digest\",\n },\n smoke: {\n description:\n \"Gate the Railway promotion on a post-publish boot smoke of the runtime image — a red smoke rolls the config back\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n smoke: {\n commandPath: [\"smoke\"],\n summary:\n \"Boot a runtime image the way production boots (identity-driven, published config) and assert the boot surface: /health, SSR, OpenAPI spec, in-image mf check\",\n interactive: false,\n fields: {\n image: { description: \"Runtime image ref to boot (required)\" },\n port: { description: \"Host port to publish the container on (default: 3000)\" },\n keep: { description: \"Keep the container after the run (debugging)\" },\n account: { description: \"Registry identity — defaults to the resolved session config\" },\n },\n },\n login: {\n commandPath: [\"login\"],\n summary:\n \"Sign in with your NEAR account via the hosted site (wallet, passkey, or social login)\",\n interactive: true,\n fields: {\n key: { description: \"Also mint and export a scoped publish key for headless/CI use\" },\n site: { description: \"Override site URL hosting the CLI login page\" },\n device: { description: \"Device label recorded on the credential (default: hostname)\" },\n expiresIn: { description: \"Session lifetime in seconds (default: 90 days)\" },\n env: { description: \"Environment: production (default) or staging\" },\n },\n },\n logout: {\n commandPath: [\"logout\"],\n summary: \"Revoke the stored CLI session and delete the exported publish key\",\n interactive: false,\n },\n keyPublish: {\n commandPath: [\"key\", \"generate\"],\n summary: \"Generate a publish access key\",\n interactive: true,\n fields: {\n env: { description: \"Environment: production or staging\" },\n allowance: { description: \"NEAR allowance for the key (default: 1NEAR, min: 0.3NEAR)\" },\n removeOldKeys: {\n description:\n \"Remove existing publish key(s) without prompting (default: ask on a TTY, yes when non-interactive)\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n init: {\n commandPath: [\"init\"],\n summary: \"Scaffold a new project by extending a deployed app or template\",\n interactive: true,\n fields: {\n domain: {\n positional: true,\n description: \"New project domain (e.g. myapp.everything.dev)\",\n },\n extends: {\n description: \"Parent to extend from (e.g. bos://account/gateway or account/gateway)\",\n },\n account: { description: \"New project NEAR account (auto-derived from extends)\" },\n directory: { description: \"Target directory (auto-derived from domain)\" },\n source: { description: \"Local source dir (skips GitHub download)\" },\n plugins: {\n description: \"Comma-separated plugin keys to include (requires --overrides=plugins)\",\n },\n overrides: {\n description: \"Comma-separated sections to customize locally: ui,api,host,plugins\",\n },\n level: {\n description:\n \"Starter complexity: simple (public shell) or advanced (adds dashboard, orgs, admin)\",\n },\n noInteractive: { description: \"Skip prompts, use flags only\" },\n noInstall: { description: \"Skip pnpm install\" },\n },\n },\n sync: {\n commandPath: [\"sync\"],\n summary: \"Sync template files from parent project\",\n interactive: false,\n fields: {\n dryRun: { description: \"Preview changes without writing files\" },\n noInstall: { description: \"Skip pnpm install\" },\n },\n },\n upgrade: {\n commandPath: [\"upgrade\"],\n summary: \"Upgrade framework packages and sync template files\",\n interactive: true,\n fields: {\n dryRun: { description: \"Preview changes without writing\" },\n noInstall: { description: \"Skip pnpm install\" },\n noSync: { description: \"Only upgrade packages, skip template sync\" },\n },\n },\n typesGen: {\n commandPath: [\"types\", \"gen\"],\n summary: \"Generate type definitions from configured API and plugin contracts\",\n interactive: false,\n fields: {\n env: { description: \"Environment: development (default) or production\" },\n dryRun: { description: \"Preview what would be fetched without writing files\" },\n remotePlugins: {\n description:\n \"Comma-separated plugin IDs to fetch contract types remotely (e.g. --remote-plugins auth,registry)\",\n },\n },\n },\n typecheck: {\n commandPath: [\"typecheck\"],\n summary: \"Run TypeScript type checking across all local workspaces\",\n interactive: false,\n fields: {\n packages: {\n positional: true,\n description: \"Comma-separated workspace list (default: all)\",\n },\n },\n },\n mfCheck: {\n commandPath: [\"mf\", \"check\"],\n summary:\n \"Verify Module Federation runtime compatibility across published host + plugin bundles\",\n interactive: false,\n },\n dbStudio: {\n commandPath: [\"db\", \"studio\"],\n summary: \"Open Drizzle Studio for a plugin's database\",\n fields: {\n plugin: {\n positional: true,\n description: \"Plugin key: api, auth, or a plugin name (default: api)\",\n },\n },\n },\n dbDoctor: {\n commandPath: [\"db\", \"doctor\"],\n summary: \"Diagnose migration health for a plugin's database\",\n fields: {\n plugin: {\n positional: true,\n description: \"Plugin key: api, auth, or a plugin name\",\n },\n },\n },\n dbRepair: {\n commandPath: [\"db\", \"repair\"],\n summary: \"Reset migration history and reapply migrations for a plugin\",\n fields: {\n plugin: {\n positional: true,\n description: \"Plugin key: api, auth, or a plugin name\",\n },\n mode: {\n description: \"Repair mode: history-reset (default) or recreate (not yet supported)\",\n },\n yes: {\n description: \"Skip confirmation prompt\",\n },\n },\n },\n status: {\n commandPath: [\"status\"],\n summary: \"Show project health, versions, and update availability\",\n interactive: false,\n },\n ps: {\n commandPath: [\"ps\"],\n summary: \"List tracked development processes\",\n interactive: false,\n },\n logs: {\n commandPath: [\"logs\"],\n summary: \"Read dev session logs (.bos/logs/dev-latest.log)\",\n interactive: false,\n fields: {\n service: {\n description: \"Filter by service name (e.g. host, api, auth, ui, plugin:votes)\",\n },\n tail: { description: \"Show only the last N lines\" },\n follow: { description: \"Stream the log as lines are appended\" },\n },\n },\n kill: {\n commandPath: [\"kill\"],\n summary: \"Stop tracked development processes\",\n interactive: false,\n fields: {\n configDir: { description: \"Kill processes owned by a config directory (defaults to cwd)\" },\n signal: { description: \"Signal: SIGTERM (default) or SIGKILL\" },\n all: { description: \"Kill processes across all config directories\" },\n },\n },\n infraExport: {\n commandPath: [\"infra\", \"export\"],\n summary: \"Emit the resolved CI infra plan (env + services) for the current runtime\",\n interactive: false,\n fields: {\n target: { description: \"Export target: ci (default) or local\" },\n network: { description: \"NEAR network: mainnet or testnet\" },\n configDir: { description: \"Override config directory\" },\n },\n },\n} as const satisfies Record<string, CliCommandMeta>;\n"],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ACF;CACA,aAAa;EACX,aAAa,CAAC,SAAS,QAAQ;EAC/B,SAAS;EACT,aAAa;EACb,QAAQ;GACN,QAAQ,EAAE,aAAa,uCAAuC;GAC9D,SAAS,EAAE,aAAa,mCAAmC;GAC3D,WAAW,EAAE,aAAa,4BAA4B;EACxD;CACF;AACF"}
1
+ {"version":3,"file":"contract.meta.mjs","names":[],"sources":["../src/contract.meta.ts"],"sourcesContent":["export type CliCommandMeta = {\n commandPath?: string[];\n summary: string;\n description?: string;\n examples?: string[];\n interactive?: boolean;\n longRunning?: boolean;\n fields?: Record<string, { positional?: boolean; description?: string }>;\n};\n\nexport const cliCommandMeta = {\n dev: {\n commandPath: [\"dev\"],\n summary: \"Start a development session\",\n interactive: true,\n longRunning: true,\n fields: {\n remotePlugins: {\n description:\n \"Comma-separated plugin IDs to force remote (e.g. --remote-plugins auth,registry)\",\n },\n logLevel: {\n description:\n \"Log tail level: error, warn (default), info, or debug (overrides BOS_LOG_LEVEL; the file always gets everything)\",\n },\n },\n },\n start: {\n commandPath: [\"start\"],\n summary: \"Start the production host\",\n interactive: false,\n longRunning: true,\n fields: {\n env: { description: \"Environment: production or staging\" },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n configPath: {\n description:\n \"Boot from a local bos config file — skips FastKV resolution and SRI integrity verification\",\n },\n },\n },\n build: {\n commandPath: [\"build\"],\n summary: \"Build selected workspaces\",\n interactive: false,\n fields: {\n packages: { positional: true, description: \"Comma-separated package list\" },\n },\n },\n config: {\n commandPath: [\"config\"],\n summary: \"Print the loaded BOS configuration\",\n interactive: false,\n fields: {\n full: { description: \"Print the fully resolved configuration\" },\n },\n },\n registryUse: {\n commandPath: [\"registry\", \"use\"],\n summary:\n \"Compose app.ui/app.host/app.api/plugins.<key> sections from a published runtime into bos.config.json\",\n interactive: false,\n fields: {\n from: {\n positional: true,\n description:\n \"Published runtime (account/gateway or bos:// URL), e.g. v1.citynode.near/citynode.app\",\n },\n sections: {\n description: \"Comma-separated sections to compose, e.g. app.ui,plugins.apps\",\n },\n dryRun: { description: \"Preview the merged config without writing\" },\n },\n },\n pluginAdd: {\n commandPath: [\"plugin\", \"add\"],\n summary: \"Add a plugin attachment\",\n interactive: false,\n fields: {\n source: {\n positional: true,\n description: \"Plugin source (local:path, bos://account/domain, or URL)\",\n },\n as: { description: \"Plugin alias\" },\n production: { description: \"Production URL override\" },\n },\n },\n pluginRemove: {\n commandPath: [\"plugin\", \"remove\"],\n summary: \"Remove a plugin attachment\",\n interactive: false,\n fields: { key: { positional: true, description: \"Plugin key\" } },\n },\n pluginList: {\n commandPath: [\"plugin\", \"list\"],\n summary: \"List configured plugins\",\n interactive: false,\n },\n pluginPublish: {\n commandPath: [\"plugin\", \"publish\"],\n summary: \"Publish a single plugin\",\n interactive: false,\n fields: { key: { positional: true, description: \"Plugin key\" } },\n },\n publish: {\n commandPath: [\"publish\"],\n summary:\n \"Publish the current workspace configuration (no build — use bos deploy for the full train)\",\n interactive: false,\n fields: {\n dryRun: { description: \"Preview what would be published without writing\" },\n verbose: { description: \"Show full build output instead of clean summary\" },\n env: { description: \"Environment: production or staging\" },\n network: { description: \"NEAR network: mainnet or testnet\" },\n wallet: {\n description:\n \"Publish gaslessly with a one-time wallet approval (NEP-366 delegate action relayed by the platform relayer)\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n rollback: {\n commandPath: [\"rollback\"],\n summary: \"Republish an earlier config snapshot from the registry publish history\",\n interactive: true,\n fields: {\n version: { description: \"Block height (or timestamp) of the snapshot from the listing\" },\n previous: { description: \"Roll back to the write immediately before the current one\" },\n force: {\n description:\n \"Allow pre-Phase-A snapshots without verifiable manifest pins (their bytes were overwritten in place)\",\n },\n limit: { description: \"Listing depth (1-200, default 20)\" },\n dryRun: { description: \"Preview the rollback without publishing\" },\n env: { description: \"Environment: production or staging\" },\n network: { description: \"NEAR network: mainnet or testnet\" },\n wallet: {\n description:\n \"Publish gaslessly with a one-time wallet approval (NEP-366 delegate action relayed by the platform relayer)\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n deploy: {\n commandPath: [\"deploy\"],\n summary:\n \"Deploy train: preflight → build → upload bundles → publish config → runtime image (pre-pushed digest or local docker build) → post-publish smoke (optional) → Railway (image-backed, no build)\",\n interactive: false,\n fields: {\n env: { description: \"Environment: production or staging\" },\n build: { description: \"Build and deploy workspaces before publish (default: true)\" },\n dryRun: { description: \"Preview what would be deployed without writing\" },\n verbose: { description: \"Show full build output instead of clean summary\" },\n service: { description: \"Override Railway service name from config\" },\n imageDigest: {\n description:\n \"Digest of a pre-pushed runtime image (sha256:…) — skips the local image build/push; Railway pins this digest\",\n },\n smoke: {\n description:\n \"Gate the Railway promotion on a post-publish boot smoke of the runtime image — a red smoke rolls the config back\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n smoke: {\n commandPath: [\"smoke\"],\n summary:\n \"Boot a runtime image the way production boots (identity-driven, published config) and assert the boot surface: /health, SSR, OpenAPI spec, in-image mf check\",\n interactive: false,\n fields: {\n image: { description: \"Runtime image ref to boot (required)\" },\n port: { description: \"Host port to publish the container on (default: 3000)\" },\n keep: { description: \"Keep the container after the run (debugging)\" },\n account: { description: \"Registry identity — defaults to the resolved session config\" },\n },\n },\n login: {\n commandPath: [\"login\"],\n summary:\n \"Sign in with your NEAR account via the hosted site (wallet, passkey, or social login)\",\n interactive: true,\n fields: {\n key: { description: \"Also mint and export a scoped publish key for headless/CI use\" },\n site: { description: \"Override site URL hosting the CLI login page\" },\n device: { description: \"Device label recorded on the credential (default: hostname)\" },\n expiresIn: { description: \"Session lifetime in seconds (default: 90 days)\" },\n env: { description: \"Environment: production (default) or staging\" },\n },\n },\n logout: {\n commandPath: [\"logout\"],\n summary: \"Revoke the stored CLI session and delete the exported publish key\",\n interactive: false,\n },\n keyPublish: {\n commandPath: [\"key\", \"generate\"],\n summary: \"Generate a publish access key\",\n interactive: true,\n fields: {\n env: { description: \"Environment: production or staging\" },\n allowance: { description: \"NEAR allowance for the key (default: 1NEAR, min: 0.3NEAR)\" },\n removeOldKeys: {\n description:\n \"Remove existing publish key(s) without prompting (default: ask on a TTY, defaulting to keep; keep when non-interactive — pass --remove-old-keys to remove)\",\n },\n registry: {\n description:\n \"Override FastKV registry contract account (defaults: dev.everything.near / dev.allthethings.testnet)\",\n },\n },\n },\n init: {\n commandPath: [\"init\"],\n summary: \"Scaffold a new project by extending a deployed app or template\",\n interactive: true,\n fields: {\n domain: {\n positional: true,\n description: \"New project domain (e.g. myapp.everything.dev)\",\n },\n extends: {\n description: \"Parent to extend from (e.g. bos://account/gateway or account/gateway)\",\n },\n account: { description: \"New project NEAR account (auto-derived from extends)\" },\n directory: { description: \"Target directory (auto-derived from domain)\" },\n source: { description: \"Local source dir (skips GitHub download)\" },\n plugins: {\n description: \"Comma-separated plugin keys to include (requires --overrides=plugins)\",\n },\n overrides: {\n description: \"Comma-separated sections to customize locally: ui,api,host,plugins\",\n },\n level: {\n description:\n \"Starter complexity: simple (public shell) or advanced (adds dashboard, orgs, admin)\",\n },\n noInteractive: { description: \"Skip prompts, use flags only\" },\n noInstall: { description: \"Skip pnpm install\" },\n },\n },\n sync: {\n commandPath: [\"sync\"],\n summary: \"Sync template files from parent project\",\n interactive: false,\n fields: {\n dryRun: { description: \"Preview changes without writing files\" },\n noInstall: { description: \"Skip pnpm install\" },\n },\n },\n upgrade: {\n commandPath: [\"upgrade\"],\n summary: \"Upgrade framework packages and sync template files\",\n interactive: true,\n fields: {\n dryRun: { description: \"Preview changes without writing\" },\n noInstall: { description: \"Skip pnpm install\" },\n noSync: { description: \"Only upgrade packages, skip template sync\" },\n },\n },\n typesGen: {\n commandPath: [\"types\", \"gen\"],\n summary: \"Generate type definitions from configured API and plugin contracts\",\n interactive: false,\n fields: {\n env: { description: \"Environment: development (default) or production\" },\n dryRun: { description: \"Preview what would be fetched without writing files\" },\n remotePlugins: {\n description:\n \"Comma-separated plugin IDs to fetch contract types remotely (e.g. --remote-plugins auth,registry)\",\n },\n },\n },\n typecheck: {\n commandPath: [\"typecheck\"],\n summary: \"Run TypeScript type checking across all local workspaces\",\n interactive: false,\n fields: {\n packages: {\n positional: true,\n description: \"Comma-separated workspace list (default: all)\",\n },\n },\n },\n mfCheck: {\n commandPath: [\"mf\", \"check\"],\n summary:\n \"Verify Module Federation runtime compatibility across published host + plugin bundles\",\n interactive: false,\n },\n dbStudio: {\n commandPath: [\"db\", \"studio\"],\n summary: \"Open Drizzle Studio for a plugin's database\",\n fields: {\n plugin: {\n positional: true,\n description: \"Plugin key: api, auth, or a plugin name (default: api)\",\n },\n },\n },\n dbDoctor: {\n commandPath: [\"db\", \"doctor\"],\n summary: \"Diagnose migration health for a plugin's database\",\n fields: {\n plugin: {\n positional: true,\n description: \"Plugin key: api, auth, or a plugin name\",\n },\n },\n },\n dbRepair: {\n commandPath: [\"db\", \"repair\"],\n summary: \"Reset migration history and reapply migrations for a plugin\",\n fields: {\n plugin: {\n positional: true,\n description: \"Plugin key: api, auth, or a plugin name\",\n },\n mode: {\n description: \"Repair mode: history-reset (default) or recreate (not yet supported)\",\n },\n yes: {\n description: \"Skip confirmation prompt\",\n },\n },\n },\n status: {\n commandPath: [\"status\"],\n summary: \"Show project health, versions, and update availability\",\n interactive: false,\n },\n ps: {\n commandPath: [\"ps\"],\n summary: \"List tracked development processes\",\n interactive: false,\n },\n logs: {\n commandPath: [\"logs\"],\n summary: \"Read dev session logs (.bos/logs/dev-latest.log)\",\n interactive: false,\n fields: {\n service: {\n description: \"Filter by service name (e.g. host, api, auth, ui, plugin:votes)\",\n },\n tail: { description: \"Show only the last N lines\" },\n follow: { description: \"Stream the log as lines are appended\" },\n },\n },\n kill: {\n commandPath: [\"kill\"],\n summary: \"Stop tracked development processes\",\n interactive: false,\n fields: {\n configDir: { description: \"Kill processes owned by a config directory (defaults to cwd)\" },\n signal: { description: \"Signal: SIGTERM (default) or SIGKILL\" },\n all: { description: \"Kill processes across all config directories\" },\n },\n },\n infraExport: {\n commandPath: [\"infra\", \"export\"],\n summary: \"Emit the resolved CI infra plan (env + services) for the current runtime\",\n interactive: false,\n fields: {\n target: { description: \"Export target: ci (default) or local\" },\n network: { description: \"NEAR network: mainnet or testnet\" },\n configDir: { description: \"Override config directory\" },\n },\n },\n} as const satisfies Record<string, CliCommandMeta>;\n"],"mappings":";AAUA,MAAa,iBAAiB;CAC5B,KAAK;EACH,aAAa,CAAC,KAAK;EACnB,SAAS;EACT,aAAa;EACb,aAAa;EACb,QAAQ;GACN,eAAe,EACb,aACE,mFACJ;GACA,UAAU,EACR,aACE,mHACJ;EACF;CACF;CACA,OAAO;EACL,aAAa,CAAC,OAAO;EACrB,SAAS;EACT,aAAa;EACb,aAAa;EACb,QAAQ;GACN,KAAK,EAAE,aAAa,qCAAqC;GACzD,UAAU,EACR,aACE,uGACJ;GACA,YAAY,EACV,aACE,6FACJ;EACF;CACF;CACA,OAAO;EACL,aAAa,CAAC,OAAO;EACrB,SAAS;EACT,aAAa;EACb,QAAQ,EACN,UAAU;GAAE,YAAY;GAAM,aAAa;EAA+B,EAC5E;CACF;CACA,QAAQ;EACN,aAAa,CAAC,QAAQ;EACtB,SAAS;EACT,aAAa;EACb,QAAQ,EACN,MAAM,EAAE,aAAa,yCAAyC,EAChE;CACF;CACA,aAAa;EACX,aAAa,CAAC,YAAY,KAAK;EAC/B,SACE;EACF,aAAa;EACb,QAAQ;GACN,MAAM;IACJ,YAAY;IACZ,aACE;GACJ;GACA,UAAU,EACR,aAAa,gEACf;GACA,QAAQ,EAAE,aAAa,4CAA4C;EACrE;CACF;CACA,WAAW;EACT,aAAa,CAAC,UAAU,KAAK;EAC7B,SAAS;EACT,aAAa;EACb,QAAQ;GACN,QAAQ;IACN,YAAY;IACZ,aAAa;GACf;GACA,IAAI,EAAE,aAA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AC,MAAM;EACpB,SAAS;EACT,aAAa;EACb,QAAQ;GACN,SAAS,EACP,aAAa,kEACf;GACA,MAAM,EAAE,aAAa,6BAA6B;GAClD,QAAQ,EAAE,aAAa,uCAAuC;EAChE;CACF;CACA,MAAM;EACJ,aAAa,CAAC,MAAM;EACpB,SAAS;EACT,aAAa;EACb,QAAQ;GACN,WAAW,EAAE,aAAa,+DAA+D;GACzF,QAAQ,EAAE,aAAa,uCAAuC;GAC9D,KAAK,EAAE,aAAa,+CAA+C;EACrE;CACF;CACA,aAAa;EACX,aAAa,CAAC,SAAS,QAAQ;EAC/B,SAAS;EACT,aAAa;EACb,QAAQ;GACN,QAAQ,EAAE,aAAa,uCAAuC;GAC9D,SAAS,EAAE,aAAa,mCAAmC;GAC3D,WAAW,EAAE,aAAa,4BAA4B;EACxD;CACF;AACF"}
package/dist/db/core.cjs CHANGED
@@ -179,10 +179,28 @@ function suppressPgQueryQueueDeprecation() {
179
179
  }
180
180
  function extractExpectedTables(migrations) {
181
181
  const tables = /* @__PURE__ */ new Set();
182
- const re = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:"([^"]+)"\.)?"([^"]+)"/gi;
183
- for (const migration of migrations) for (const stmt of migration.sql) for (const match of stmt.matchAll(re)) {
184
- const tableName = match[2];
185
- if (tableName) tables.add(tableName);
182
+ const ident = String.raw`(?:"([^"]+)"|(\w+))`;
183
+ const qualified = String.raw`(?:${ident}\.)?`;
184
+ const createRe = new RegExp(String.raw`CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?${qualified}${ident}`, "gi");
185
+ const dropRe = new RegExp(String.raw`DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?${qualified}${ident}`, "gi");
186
+ const renameRe = new RegExp(String.raw`ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?${qualified}${ident}${String.raw`\s+RENAME\s+TO\s+`}${ident}`, "gi");
187
+ for (const migration of migrations) for (const stmt of migration.sql) {
188
+ for (const match of stmt.matchAll(createRe)) {
189
+ const tableName = match[3] ?? match[4];
190
+ if (tableName) tables.add(tableName);
191
+ }
192
+ for (const match of stmt.matchAll(dropRe)) {
193
+ const tableName = match[3] ?? match[4];
194
+ if (tableName) tables.delete(tableName);
195
+ }
196
+ for (const match of stmt.matchAll(renameRe)) {
197
+ const from = match[3] ?? match[4];
198
+ const to = match[5] ?? match[6];
199
+ if (from && to) {
200
+ tables.delete(from);
201
+ tables.add(to);
202
+ }
203
+ }
186
204
  }
187
205
  return [...tables];
188
206
  }
@@ -1 +1 @@
1
- {"version":3,"file":"core.cjs","names":["join","existsSync","readFileSync","dirname"],"sources":["../../src/db/core.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nexport interface MigrationStorage {\n schema: string;\n table: string;\n slug: string;\n}\n\nconst DEFAULT_MIGRATION_JOURNAL = {\n schema: \"drizzle\",\n table: \"__drizzle_migrations\",\n} as const;\n\nconst PER_PLUGIN_ISOLATION = false;\n\nexport function normalizeSlug(name: string): string {\n const basename = name.split(\"/\").pop() ?? name;\n return basename\n .replace(/^@/, \"\")\n .replace(/[^a-zA-Z0-9_-]/g, \"_\")\n .replace(/-plugin$/i, \"\")\n .replace(/-/g, \"_\")\n .toLowerCase();\n}\n\nexport function getMigrationSlug(dir?: string): string {\n if (!dir) return normalizeSlug(process.env.npm_package_name ?? \"unknown\");\n let current = dir;\n for (let i = 0; i < 10; i++) {\n const pkgPath = join(current, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as { name?: string };\n return normalizeSlug(pkg.name ?? current);\n } catch {\n return normalizeSlug(current);\n }\n }\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return normalizeSlug(dir);\n}\n\nexport function getMigrationStorage(\n slug?: string,\n options?: { isolated?: boolean },\n): MigrationStorage {\n const s = normalizeSlug(slug ?? getMigrationSlug());\n const isolated = options?.isolated ?? PER_PLUGIN_ISOLATION;\n if (isolated) {\n return {\n schema: DEFAULT_MIGRATION_JOURNAL.schema,\n table: `__drizzle_migrations_${s}`,\n slug: s,\n };\n }\n return {\n schema: DEFAULT_MIGRATION_JOURNAL.schema,\n table: DEFAULT_MIGRATION_JOURNAL.table,\n slug: s,\n };\n}\n\n/**\n * Format a JavaScript string array as a PostgreSQL text array literal for use\n * with Drizzle's `sql` tag. Example return:\n * `'{\"h1\",\"h2\"}'::text[]`\n *\n * Usage: sql`WHERE col = ANY(${toSqlArray(values)})`\n *\n * Drizzle's default parameter binding does not handle array types correctly\n * with the pg driver (it emits `ANY(($1))` with a single string, which\n * Postgres rejects as a malformed array literal).\n */\nexport function toSqlArray(arr: string[]): string {\n if (arr.length === 0) return `'{}'::text[]`;\n const escaped = arr.map((v) => v.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"'));\n return `'{${escaped.map((v) => `\"${v}\"`).join(\",\")}}'::text[]`;\n}\n\nexport function pluginMigrationSlug(key: string): string {\n return normalizeSlug(key);\n}\n\nexport function getDatabaseUrlSecretName(slug: string): string {\n return `${slug.toUpperCase().replace(/-/g, \"_\")}_DATABASE_URL`;\n}\n\nexport const DUPLICATE_OBJECT_SQLSTATES: readonly string[] = [\"42710\", \"42701\", \"42P07\"];\n\n/**\n * Walk `error` and its `cause` chain (bounded), invoking `visit` on each link.\n * Postgres driver errors arrive wrapped by drizzle/Effect at varying depths,\n * so every error-shape predicate below shares this traversal.\n */\nexport function visitCauses(\n error: unknown,\n depth: number,\n visit: (link: object) => boolean,\n): boolean {\n let current: unknown = error;\n for (let i = 0; i < depth && current; i++) {\n if (typeof current === \"object\" && current !== null && visit(current)) return true;\n current = (current as { cause?: unknown })?.cause;\n }\n return false;\n}\n\n/**\n * pg_catalog unique indexes that can surface a concurrent-DDL race as SQLSTATE\n * 23505 instead of a duplicate-object class. When two connections run\n * `CREATE TABLE <name>` at the same time, the loser fails its insert into\n * `pg_type` (\"duplicate key value violates unique constraint\n * `pg_type_typname_nsp_index`\") rather than seeing 42P07, because the winner's\n * table is not yet committed. The same shape exists for schemas and other\n * relations.\n */\nconst CONCURRENT_DDL_CONSTRAINTS: ReadonlySet<string> = new Set([\n \"pg_type_typname_nsp_index\",\n \"pg_namespace_nspname_index\",\n \"pg_class_relname_nsp_index\",\n]);\n\n/**\n * Whether a SQLSTATE 23505 unique violation is the concurrent-DDL catalog\n * collision signature rather than a data-level constraint on a user table.\n * Data-level violations must keep failing loudly; only the pg_catalog indexes\n * above are treated as duplicate-DDL tolerance candidates.\n */\nexport function isConcurrentDdlUniqueViolation(error: unknown): boolean {\n return visitCauses(error, 6, (link) => {\n const { code, constraint, message } = link as {\n code?: unknown;\n constraint?: unknown;\n message?: unknown;\n };\n if (code !== \"23505\") return false;\n if (typeof constraint === \"string\" && CONCURRENT_DDL_CONSTRAINTS.has(constraint)) return true;\n if (typeof message !== \"string\") return false;\n for (const name of CONCURRENT_DDL_CONSTRAINTS) {\n if (message.includes(name)) return true;\n }\n return false;\n });\n}\n\nconst RETRYABLE_SQLSTATES: ReadonlySet<string> = new Set([\n \"42P06\",\n \"42710\",\n \"42701\",\n \"42P07\",\n \"23505\",\n \"40001\",\n \"40P01\",\n \"55P03\",\n]);\n\nconst RETRYABLE_DRIVER_CODES: ReadonlySet<string> = new Set([\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n]);\n\nfunction matchesRetryableStates(error: unknown, states: ReadonlySet<string>): boolean {\n return visitCauses(error, 6, (link) => {\n const code = (link as { code?: unknown }).code;\n if (typeof code !== \"string\") return false;\n return states.has(code) || code.startsWith(\"08\") || RETRYABLE_DRIVER_CODES.has(code);\n });\n}\n\n/**\n * Decide whether a failed migration-init statement (schema/journal creation)\n * is worth retrying. Covers the concurrent `CREATE SCHEMA IF NOT EXISTS`\n * race (unique violation on `pg_namespace`, duplicate-object errors),\n * serialization/deadlock errors, and transient connection failures.\n */\nexport function isRetryableMigrationError(error: unknown): boolean {\n return matchesRetryableStates(error, RETRYABLE_SQLSTATES);\n}\n\nconst RETRYABLE_STATEMENT_SQLSTATES: ReadonlySet<string> = new Set([\n \"40001\", // serialization_failure\n \"40P01\", // deadlock_detected\n \"55P03\", // lock_not_available\n]);\n\n/**\n * Decide whether a failed migration *statement* (inside its transaction) is\n * worth retrying. Deliberately narrower than `isRetryableMigrationError`:\n * duplicate-object classes are tolerated at the SAVEPOINT level, and a 23505\n * is either the concurrent-DDL catalog collision (also tolerated) or a\n * deterministic data-level violation (retrying is pointless) — so only\n * lock/serialization/transient-connection states justify re-running the\n * transaction.\n */\nexport function isRetryableMigrationExecutionError(error: unknown): boolean {\n return matchesRetryableStates(error, RETRYABLE_STATEMENT_SQLSTATES);\n}\n\nconst PG_QUERY_QUEUE_DEPRECATION = \"client.query() when the client is already executing a query\";\n\nlet pgWarningFilterInstalled = false;\n\n/**\n * Silence pg's query-queue deprecation warning (fires once per process from\n * pg-pool's internal dispatch under concurrent boot load — node-postgres#3612,\n * #3617). Node's default warning handler prints even when user listeners are\n * attached, so it is removed first; every other warning is re-printed here.\n */\nexport function suppressPgQueryQueueDeprecation(): void {\n if (pgWarningFilterInstalled) return;\n if (typeof process === \"undefined\" || typeof process.on !== \"function\") return;\n pgWarningFilterInstalled = true;\n process.removeAllListeners(\"warning\");\n process.on(\"warning\", (warning) => {\n if (\n warning.name === \"DeprecationWarning\" &&\n warning.message.includes(PG_QUERY_QUEUE_DEPRECATION)\n ) {\n return;\n }\n console.error(warning.stack || `${warning.name}: ${warning.message}`);\n });\n}\n\nexport function extractExpectedTables(migrations: { sql: string[] }[]): string[] {\n const tables = new Set<string>();\n const re = /CREATE\\s+TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(?:\"([^\"]+)\"\\.)?\"([^\"]+)\"/gi;\n for (const migration of migrations) {\n for (const stmt of migration.sql) {\n for (const match of stmt.matchAll(re)) {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,SAAS,UAAU,OAAO;EACrC,OAAO,OAAO,IAAI,IAAI,KAAK,KAAK,WAAW,IAAI,KAAK,uBAAuB,IAAI,IAAI;CACrF,CAAC;AACH;;;;;;;AAQA,SAAgB,0BAA0B,OAAyB;CACjE,OAAO,uBAAuB,OAAO,mBAAmB;AAC1D;AAEA,MAAM,gDAAqD,IAAI,IAAI;CACjE;CACA;CACA;AACF,CAAC;;;;;;;;;;AAWD,SAAgB,mCAAmC,OAAyB;CAC1E,OAAO,uBAAuB,OAAO,6BAA6B;AACpE;AAEA,MAAM,6BAA6B;AAEnC,IAAI,2BAA2B;;;;;;;AAQ/B,SAAgB,kCAAwC;CACtD,IAAI,0BAA0B;CAC9B,IAAI,OAAO,YAAY,eAAe,OAAO,QAAQ,OAAO,YAAY;CACxE,2BAA2B;CAC3B,QAAQ,mBAAmB,SAAS;CACpC,QAAQ,GAAG,YAAY,YAAY;EACjC,IACE,QAAQ,SAAS,wBACjB,QAAQ,QAAQ,SAAS,0BAA0B,GAEnD;EAEF,QAAQ,MAAM,QAAQ,SAAS,GAAG,QAAQ,KAAK,IAAI,QAAQ,SAAS;CACtE,CAAC;AACH;AAEA,SAAgB,sBAAsB,YAA2C;CAC/E,MAAM,yBAAS,IAAI,IAAY;CAC/B,MAAM,KAAK;CACX,KAAK,MAAM,aAAa,YACtB,KAAK,MAAM,QAAQ,UAAU,KAC3B,KAAK,MAAM,SAAS,KAAK,SAAS,EAAE,GAAG;EACrC,MAAM,YAAY,MAAM;EACxB,IAAI,WACF,OAAO,IAAI,SAAS;CAExB;CAGJ,OAAO,CAAC,GAAG,MAAM;AACnB"}
1
+ {"version":3,"file":"core.cjs","names":["join","existsSync","readFileSync","dirname"],"sources":["../../src/db/core.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nexport interface MigrationStorage {\n schema: string;\n table: string;\n slug: string;\n}\n\nconst DEFAULT_MIGRATION_JOURNAL = {\n schema: \"drizzle\",\n table: \"__drizzle_migrations\",\n} as const;\n\nconst PER_PLUGIN_ISOLATION = false;\n\nexport function normalizeSlug(name: string): string {\n const basename = name.split(\"/\").pop() ?? name;\n return basename\n .replace(/^@/, \"\")\n .replace(/[^a-zA-Z0-9_-]/g, \"_\")\n .replace(/-plugin$/i, \"\")\n .replace(/-/g, \"_\")\n .toLowerCase();\n}\n\nexport function getMigrationSlug(dir?: string): string {\n if (!dir) return normalizeSlug(process.env.npm_package_name ?? \"unknown\");\n let current = dir;\n for (let i = 0; i < 10; i++) {\n const pkgPath = join(current, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as { name?: string };\n return normalizeSlug(pkg.name ?? current);\n } catch {\n return normalizeSlug(current);\n }\n }\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return normalizeSlug(dir);\n}\n\nexport function getMigrationStorage(\n slug?: string,\n options?: { isolated?: boolean },\n): MigrationStorage {\n const s = normalizeSlug(slug ?? getMigrationSlug());\n const isolated = options?.isolated ?? PER_PLUGIN_ISOLATION;\n if (isolated) {\n return {\n schema: DEFAULT_MIGRATION_JOURNAL.schema,\n table: `__drizzle_migrations_${s}`,\n slug: s,\n };\n }\n return {\n schema: DEFAULT_MIGRATION_JOURNAL.schema,\n table: DEFAULT_MIGRATION_JOURNAL.table,\n slug: s,\n };\n}\n\n/**\n * Format a JavaScript string array as a PostgreSQL text array literal for use\n * with Drizzle's `sql` tag. Example return:\n * `'{\"h1\",\"h2\"}'::text[]`\n *\n * Usage: sql`WHERE col = ANY(${toSqlArray(values)})`\n *\n * Drizzle's default parameter binding does not handle array types correctly\n * with the pg driver (it emits `ANY(($1))` with a single string, which\n * Postgres rejects as a malformed array literal).\n */\nexport function toSqlArray(arr: string[]): string {\n if (arr.length === 0) return `'{}'::text[]`;\n const escaped = arr.map((v) => v.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"'));\n return `'{${escaped.map((v) => `\"${v}\"`).join(\",\")}}'::text[]`;\n}\n\nexport function pluginMigrationSlug(key: string): string {\n return normalizeSlug(key);\n}\n\nexport function getDatabaseUrlSecretName(slug: string): string {\n return `${slug.toUpperCase().replace(/-/g, \"_\")}_DATABASE_URL`;\n}\n\nexport const DUPLICATE_OBJECT_SQLSTATES: readonly string[] = [\"42710\", \"42701\", \"42P07\"];\n\n/**\n * Walk `error` and its `cause` chain (bounded), invoking `visit` on each link.\n * Postgres driver errors arrive wrapped by drizzle/Effect at varying depths,\n * so every error-shape predicate below shares this traversal.\n */\nexport function visitCauses(\n error: unknown,\n depth: number,\n visit: (link: object) => boolean,\n): boolean {\n let current: unknown = error;\n for (let i = 0; i < depth && current; i++) {\n if (typeof current === \"object\" && current !== null && visit(current)) return true;\n current = (current as { cause?: unknown })?.cause;\n }\n return false;\n}\n\n/**\n * pg_catalog unique indexes that can surface a concurrent-DDL race as SQLSTATE\n * 23505 instead of a duplicate-object class. When two connections run\n * `CREATE TABLE <name>` at the same time, the loser fails its insert into\n * `pg_type` (\"duplicate key value violates unique constraint\n * `pg_type_typname_nsp_index`\") rather than seeing 42P07, because the winner's\n * table is not yet committed. The same shape exists for schemas and other\n * relations.\n */\nconst CONCURRENT_DDL_CONSTRAINTS: ReadonlySet<string> = new Set([\n \"pg_type_typname_nsp_index\",\n \"pg_namespace_nspname_index\",\n \"pg_class_relname_nsp_index\",\n]);\n\n/**\n * Whether a SQLSTATE 23505 unique violation is the concurrent-DDL catalog\n * collision signature rather than a data-level constraint on a user table.\n * Data-level violations must keep failing loudly; only the pg_catalog indexes\n * above are treated as duplicate-DDL tolerance candidates.\n */\nexport function isConcurrentDdlUniqueViolation(error: unknown): boolean {\n return visitCauses(error, 6, (link) => {\n const { code, constraint, message } = link as {\n code?: unknown;\n constraint?: unknown;\n message?: unknown;\n };\n if (code !== \"23505\") return false;\n if (typeof constraint === \"string\" && CONCURRENT_DDL_CONSTRAINTS.has(constraint)) return true;\n if (typeof message !== \"string\") return false;\n for (const name of CONCURRENT_DDL_CONSTRAINTS) {\n if (message.includes(name)) return true;\n }\n return false;\n });\n}\n\nconst RETRYABLE_SQLSTATES: ReadonlySet<string> = new Set([\n \"42P06\",\n \"42710\",\n \"42701\",\n \"42P07\",\n \"23505\",\n \"40001\",\n \"40P01\",\n \"55P03\",\n]);\n\nconst RETRYABLE_DRIVER_CODES: ReadonlySet<string> = new Set([\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n]);\n\nfunction matchesRetryableStates(error: unknown, states: ReadonlySet<string>): boolean {\n return visitCauses(error, 6, (link) => {\n const code = (link as { code?: unknown }).code;\n if (typeof code !== \"string\") return false;\n return states.has(code) || code.startsWith(\"08\") || RETRYABLE_DRIVER_CODES.has(code);\n });\n}\n\n/**\n * Decide whether a failed migration-init statement (schema/journal creation)\n * is worth retrying. Covers the concurrent `CREATE SCHEMA IF NOT EXISTS`\n * race (unique violation on `pg_namespace`, duplicate-object errors),\n * serialization/deadlock errors, and transient connection failures.\n */\nexport function isRetryableMigrationError(error: unknown): boolean {\n return matchesRetryableStates(error, RETRYABLE_SQLSTATES);\n}\n\nconst RETRYABLE_STATEMENT_SQLSTATES: ReadonlySet<string> = new Set([\n \"40001\", // serialization_failure\n \"40P01\", // deadlock_detected\n \"55P03\", // lock_not_available\n]);\n\n/**\n * Decide whether a failed migration *statement* (inside its transaction) is\n * worth retrying. Deliberately narrower than `isRetryableMigrationError`:\n * duplicate-object classes are tolerated at the SAVEPOINT level, and a 23505\n * is either the concurrent-DDL catalog collision (also tolerated) or a\n * deterministic data-level violation (retrying is pointless) — so only\n * lock/serialization/transient-connection states justify re-running the\n * transaction.\n */\nexport function isRetryableMigrationExecutionError(error: unknown): boolean {\n return matchesRetryableStates(error, RETRYABLE_STATEMENT_SQLSTATES);\n}\n\nconst PG_QUERY_QUEUE_DEPRECATION = \"client.query() when the client is already executing a query\";\n\nlet pgWarningFilterInstalled = false;\n\n/**\n * Silence pg's query-queue deprecation warning (fires once per process from\n * pg-pool's internal dispatch under concurrent boot load — node-postgres#3612,\n * #3617). Node's default warning handler prints even when user listeners are\n * attached, so it is removed first; every other warning is re-printed here.\n */\nexport function suppressPgQueryQueueDeprecation(): void {\n if (pgWarningFilterInstalled) return;\n if (typeof process === \"undefined\" || typeof process.on !== \"function\") return;\n pgWarningFilterInstalled = true;\n process.removeAllListeners(\"warning\");\n process.on(\"warning\", (warning) => {\n if (\n warning.name === \"DeprecationWarning\" &&\n warning.message.includes(PG_QUERY_QUEUE_DEPRECATION)\n ) {\n return;\n }\n console.error(warning.stack || `${warning.name}: ${warning.message}`);\n });\n}\n\nexport function extractExpectedTables(migrations: { sql: string[] }[]): string[] {\n const tables = new Set<string>();\n const ident = String.raw`(?:\"([^\"]+)\"|(\\w+))`;\n const qualified = String.raw`(?:${ident}\\.)?`;\n const createRe = new RegExp(\n String.raw`CREATE\\s+TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?${qualified}${ident}`,\n \"gi\",\n );\n const dropRe = new RegExp(\n String.raw`DROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?${qualified}${ident}`,\n \"gi\",\n );\n const renameRe = new RegExp(\n String.raw`ALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?${qualified}${ident}${String.raw`\\s+RENAME\\s+TO\\s+`}${ident}`,\n \"gi\",\n );\n for (const migration of migrations) {\n for (const stmt of migration.sql) {\n for (const match of stmt.matchAll(createRe)) {\n const tableName = match[3] ?? match[4];\n if (tableName) {\n tables.add(tableName);\n }\n }\n for (const match of stmt.matchAll(dropRe)) {\n const tableName = match[3] ?? match[4];\n if (tableName) {\n tables.delete(tableName);\n }\n }\n for (const match of stmt.matchAll(renameRe)) {\n const from = match[3] ?? match[4];\n const to = match[5] ?? match[6];\n if (from && to) {\n tables.delete(from);\n tables.add(to);\n }\n }\n }\n }\n return [...tables];\n}\n"],"mappings":";;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AAG;GACzC,MAAM,YAAY,MAAM,MAAM,MAAM;GACpC,IAAI,WACF,OAAO,OAAO,SAAS;EAE3B;EACA,KAAK,MAAM,SAAS,KAAK,SAAS,QAAQ,GAAG;GAC3C,MAAM,OAAO,MAAM,MAAM,MAAM;GAC/B,MAAM,KAAK,MAAM,MAAM,MAAM;GAC7B,IAAI,QAAQ,IAAI;IACd,OAAO,OAAO,IAAI;IAClB,OAAO,IAAI,EAAE;GACf;EACF;CACF;CAEF,OAAO,CAAC,GAAG,MAAM;AACnB"}
package/dist/db/core.mjs CHANGED
@@ -179,10 +179,28 @@ function suppressPgQueryQueueDeprecation() {
179
179
  }
180
180
  function extractExpectedTables(migrations) {
181
181
  const tables = /* @__PURE__ */ new Set();
182
- const re = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:"([^"]+)"\.)?"([^"]+)"/gi;
183
- for (const migration of migrations) for (const stmt of migration.sql) for (const match of stmt.matchAll(re)) {
184
- const tableName = match[2];
185
- if (tableName) tables.add(tableName);
182
+ const ident = String.raw`(?:"([^"]+)"|(\w+))`;
183
+ const qualified = String.raw`(?:${ident}\.)?`;
184
+ const createRe = new RegExp(String.raw`CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?${qualified}${ident}`, "gi");
185
+ const dropRe = new RegExp(String.raw`DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?${qualified}${ident}`, "gi");
186
+ const renameRe = new RegExp(String.raw`ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?${qualified}${ident}${String.raw`\s+RENAME\s+TO\s+`}${ident}`, "gi");
187
+ for (const migration of migrations) for (const stmt of migration.sql) {
188
+ for (const match of stmt.matchAll(createRe)) {
189
+ const tableName = match[3] ?? match[4];
190
+ if (tableName) tables.add(tableName);
191
+ }
192
+ for (const match of stmt.matchAll(dropRe)) {
193
+ const tableName = match[3] ?? match[4];
194
+ if (tableName) tables.delete(tableName);
195
+ }
196
+ for (const match of stmt.matchAll(renameRe)) {
197
+ const from = match[3] ?? match[4];
198
+ const to = match[5] ?? match[6];
199
+ if (from && to) {
200
+ tables.delete(from);
201
+ tables.add(to);
202
+ }
203
+ }
186
204
  }
187
205
  return [...tables];
188
206
  }
@@ -1 +1 @@
1
- {"version":3,"file":"core.mjs","names":[],"sources":["../../src/db/core.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nexport interface MigrationStorage {\n schema: string;\n table: string;\n slug: string;\n}\n\nconst DEFAULT_MIGRATION_JOURNAL = {\n schema: \"drizzle\",\n table: \"__drizzle_migrations\",\n} as const;\n\nconst PER_PLUGIN_ISOLATION = false;\n\nexport function normalizeSlug(name: string): string {\n const basename = name.split(\"/\").pop() ?? name;\n return basename\n .replace(/^@/, \"\")\n .replace(/[^a-zA-Z0-9_-]/g, \"_\")\n .replace(/-plugin$/i, \"\")\n .replace(/-/g, \"_\")\n .toLowerCase();\n}\n\nexport function getMigrationSlug(dir?: string): string {\n if (!dir) return normalizeSlug(process.env.npm_package_name ?? \"unknown\");\n let current = dir;\n for (let i = 0; i < 10; i++) {\n const pkgPath = join(current, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as { name?: string };\n return normalizeSlug(pkg.name ?? current);\n } catch {\n return normalizeSlug(current);\n }\n }\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return normalizeSlug(dir);\n}\n\nexport function getMigrationStorage(\n slug?: string,\n options?: { isolated?: boolean },\n): MigrationStorage {\n const s = normalizeSlug(slug ?? getMigrationSlug());\n const isolated = options?.isolated ?? PER_PLUGIN_ISOLATION;\n if (isolated) {\n return {\n schema: DEFAULT_MIGRATION_JOURNAL.schema,\n table: `__drizzle_migrations_${s}`,\n slug: s,\n };\n }\n return {\n schema: DEFAULT_MIGRATION_JOURNAL.schema,\n table: DEFAULT_MIGRATION_JOURNAL.table,\n slug: s,\n };\n}\n\n/**\n * Format a JavaScript string array as a PostgreSQL text array literal for use\n * with Drizzle's `sql` tag. Example return:\n * `'{\"h1\",\"h2\"}'::text[]`\n *\n * Usage: sql`WHERE col = ANY(${toSqlArray(values)})`\n *\n * Drizzle's default parameter binding does not handle array types correctly\n * with the pg driver (it emits `ANY(($1))` with a single string, which\n * Postgres rejects as a malformed array literal).\n */\nexport function toSqlArray(arr: string[]): string {\n if (arr.length === 0) return `'{}'::text[]`;\n const escaped = arr.map((v) => v.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"'));\n return `'{${escaped.map((v) => `\"${v}\"`).join(\",\")}}'::text[]`;\n}\n\nexport function pluginMigrationSlug(key: string): string {\n return normalizeSlug(key);\n}\n\nexport function getDatabaseUrlSecretName(slug: string): string {\n return `${slug.toUpperCase().replace(/-/g, \"_\")}_DATABASE_URL`;\n}\n\nexport const DUPLICATE_OBJECT_SQLSTATES: readonly string[] = [\"42710\", \"42701\", \"42P07\"];\n\n/**\n * Walk `error` and its `cause` chain (bounded), invoking `visit` on each link.\n * Postgres driver errors arrive wrapped by drizzle/Effect at varying depths,\n * so every error-shape predicate below shares this traversal.\n */\nexport function visitCauses(\n error: unknown,\n depth: number,\n visit: (link: object) => boolean,\n): boolean {\n let current: unknown = error;\n for (let i = 0; i < depth && current; i++) {\n if (typeof current === \"object\" && current !== null && visit(current)) return true;\n current = (current as { cause?: unknown })?.cause;\n }\n return false;\n}\n\n/**\n * pg_catalog unique indexes that can surface a concurrent-DDL race as SQLSTATE\n * 23505 instead of a duplicate-object class. When two connections run\n * `CREATE TABLE <name>` at the same time, the loser fails its insert into\n * `pg_type` (\"duplicate key value violates unique constraint\n * `pg_type_typname_nsp_index`\") rather than seeing 42P07, because the winner's\n * table is not yet committed. The same shape exists for schemas and other\n * relations.\n */\nconst CONCURRENT_DDL_CONSTRAINTS: ReadonlySet<string> = new Set([\n \"pg_type_typname_nsp_index\",\n \"pg_namespace_nspname_index\",\n \"pg_class_relname_nsp_index\",\n]);\n\n/**\n * Whether a SQLSTATE 23505 unique violation is the concurrent-DDL catalog\n * collision signature rather than a data-level constraint on a user table.\n * Data-level violations must keep failing loudly; only the pg_catalog indexes\n * above are treated as duplicate-DDL tolerance candidates.\n */\nexport function isConcurrentDdlUniqueViolation(error: unknown): boolean {\n return visitCauses(error, 6, (link) => {\n const { code, constraint, message } = link as {\n code?: unknown;\n constraint?: unknown;\n message?: unknown;\n };\n if (code !== \"23505\") return false;\n if (typeof constraint === \"string\" && CONCURRENT_DDL_CONSTRAINTS.has(constraint)) return true;\n if (typeof message !== \"string\") return false;\n for (const name of CONCURRENT_DDL_CONSTRAINTS) {\n if (message.includes(name)) return true;\n }\n return false;\n });\n}\n\nconst RETRYABLE_SQLSTATES: ReadonlySet<string> = new Set([\n \"42P06\",\n \"42710\",\n \"42701\",\n \"42P07\",\n \"23505\",\n \"40001\",\n \"40P01\",\n \"55P03\",\n]);\n\nconst RETRYABLE_DRIVER_CODES: ReadonlySet<string> = new Set([\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n]);\n\nfunction matchesRetryableStates(error: unknown, states: ReadonlySet<string>): boolean {\n return visitCauses(error, 6, (link) => {\n const code = (link as { code?: unknown }).code;\n if (typeof code !== \"string\") return false;\n return states.has(code) || code.startsWith(\"08\") || RETRYABLE_DRIVER_CODES.has(code);\n });\n}\n\n/**\n * Decide whether a failed migration-init statement (schema/journal creation)\n * is worth retrying. Covers the concurrent `CREATE SCHEMA IF NOT EXISTS`\n * race (unique violation on `pg_namespace`, duplicate-object errors),\n * serialization/deadlock errors, and transient connection failures.\n */\nexport function isRetryableMigrationError(error: unknown): boolean {\n return matchesRetryableStates(error, RETRYABLE_SQLSTATES);\n}\n\nconst RETRYABLE_STATEMENT_SQLSTATES: ReadonlySet<string> = new Set([\n \"40001\", // serialization_failure\n \"40P01\", // deadlock_detected\n \"55P03\", // lock_not_available\n]);\n\n/**\n * Decide whether a failed migration *statement* (inside its transaction) is\n * worth retrying. Deliberately narrower than `isRetryableMigrationError`:\n * duplicate-object classes are tolerated at the SAVEPOINT level, and a 23505\n * is either the concurrent-DDL catalog collision (also tolerated) or a\n * deterministic data-level violation (retrying is pointless) — so only\n * lock/serialization/transient-connection states justify re-running the\n * transaction.\n */\nexport function isRetryableMigrationExecutionError(error: unknown): boolean {\n return matchesRetryableStates(error, RETRYABLE_STATEMENT_SQLSTATES);\n}\n\nconst PG_QUERY_QUEUE_DEPRECATION = \"client.query() when the client is already executing a query\";\n\nlet pgWarningFilterInstalled = false;\n\n/**\n * Silence pg's query-queue deprecation warning (fires once per process from\n * pg-pool's internal dispatch under concurrent boot load — node-postgres#3612,\n * #3617). Node's default warning handler prints even when user listeners are\n * attached, so it is removed first; every other warning is re-printed here.\n */\nexport function suppressPgQueryQueueDeprecation(): void {\n if (pgWarningFilterInstalled) return;\n if (typeof process === \"undefined\" || typeof process.on !== \"function\") return;\n pgWarningFilterInstalled = true;\n process.removeAllListeners(\"warning\");\n process.on(\"warning\", (warning) => {\n if (\n warning.name === \"DeprecationWarning\" &&\n warning.message.includes(PG_QUERY_QUEUE_DEPRECATION)\n ) {\n return;\n }\n console.error(warning.stack || `${warning.name}: ${warning.message}`);\n });\n}\n\nexport function extractExpectedTables(migrations: { sql: string[] }[]): string[] {\n const tables = new Set<string>();\n const re = /CREATE\\s+TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(?:\"([^\"]+)\"\\.)?\"([^\"]+)\"/gi;\n for (const migration of migrations) {\n for (const stmt of migration.sql) {\n for (const match of stmt.matchAll(re)) {\n const tableName = match[2];\n if (tableName) {\n tables.add(tableName);\n }\n }\n }\n }\n return [...tables];\n}\n"],"mappings":";;;;AASA,MAAM,4BAA4B;CAChC,QAAQ;CACR,OAAO;AACT;AAEA,MAAM,uBAAuB;AAE7B,SAAgB,cAAc,MAAsB;CAElD,QADiB,KAAK,MAAM,GAAG,CAA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I,IAAI;CACjE;CACA;CACA;AACF,CAAC;;;;;;;;;;AAWD,SAAgB,mCAAmC,OAAyB;CAC1E,OAAO,uBAAuB,OAAO,6BAA6B;AACpE;AAEA,MAAM,6BAA6B;AAEnC,IAAI,2BAA2B;;;;;;;AAQ/B,SAAgB,kCAAwC;CACtD,IAAI,0BAA0B;CAC9B,IAAI,OAAO,YAAY,eAAe,OAAO,QAAQ,OAAO,YAAY;CACxE,2BAA2B;CAC3B,QAAQ,mBAAmB,SAAS;CACpC,QAAQ,GAAG,YAAY,YAAY;EACjC,IACE,QAAQ,SAAS,wBACjB,QAAQ,QAAQ,SAAS,0BAA0B,GAEnD;EAEF,QAAQ,MAAM,QAAQ,SAAS,GAAG,QAAQ,KAAK,IAAI,QAAQ,SAAS;CACtE,CAAC;AACH;AAEA,SAAgB,sBAAsB,YAA2C;CAC/E,MAAM,yBAAS,IAAI,IAAY;CAC/B,MAAM,KAAK;CACX,KAAK,MAAM,aAAa,YACtB,KAAK,MAAM,QAAQ,UAAU,KAC3B,KAAK,MAAM,SAAS,KAAK,SAAS,EAAE,GAAG;EACrC,MAAM,YAAY,MAAM;EACxB,IAAI,WACF,OAAO,IAAI,SAAS;CAExB;CAGJ,OAAO,CAAC,GAAG,MAAM;AACnB"}
1
+ {"version":3,"file":"core.mjs","names":[],"sources":["../../src/db/core.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nexport interface MigrationStorage {\n schema: string;\n table: string;\n slug: string;\n}\n\nconst DEFAULT_MIGRATION_JOURNAL = {\n schema: \"drizzle\",\n table: \"__drizzle_migrations\",\n} as const;\n\nconst PER_PLUGIN_ISOLATION = false;\n\nexport function normalizeSlug(name: string): string {\n const basename = name.split(\"/\").pop() ?? name;\n return basename\n .replace(/^@/, \"\")\n .replace(/[^a-zA-Z0-9_-]/g, \"_\")\n .replace(/-plugin$/i, \"\")\n .replace(/-/g, \"_\")\n .toLowerCase();\n}\n\nexport function getMigrationSlug(dir?: string): string {\n if (!dir) return normalizeSlug(process.env.npm_package_name ?? \"unknown\");\n let current = dir;\n for (let i = 0; i < 10; i++) {\n const pkgPath = join(current, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as { name?: string };\n return normalizeSlug(pkg.name ?? current);\n } catch {\n return normalizeSlug(current);\n }\n }\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return normalizeSlug(dir);\n}\n\nexport function getMigrationStorage(\n slug?: string,\n options?: { isolated?: boolean },\n): MigrationStorage {\n const s = normalizeSlug(slug ?? getMigrationSlug());\n const isolated = options?.isolated ?? PER_PLUGIN_ISOLATION;\n if (isolated) {\n return {\n schema: DEFAULT_MIGRATION_JOURNAL.schema,\n table: `__drizzle_migrations_${s}`,\n slug: s,\n };\n }\n return {\n schema: DEFAULT_MIGRATION_JOURNAL.schema,\n table: DEFAULT_MIGRATION_JOURNAL.table,\n slug: s,\n };\n}\n\n/**\n * Format a JavaScript string array as a PostgreSQL text array literal for use\n * with Drizzle's `sql` tag. Example return:\n * `'{\"h1\",\"h2\"}'::text[]`\n *\n * Usage: sql`WHERE col = ANY(${toSqlArray(values)})`\n *\n * Drizzle's default parameter binding does not handle array types correctly\n * with the pg driver (it emits `ANY(($1))` with a single string, which\n * Postgres rejects as a malformed array literal).\n */\nexport function toSqlArray(arr: string[]): string {\n if (arr.length === 0) return `'{}'::text[]`;\n const escaped = arr.map((v) => v.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"'));\n return `'{${escaped.map((v) => `\"${v}\"`).join(\",\")}}'::text[]`;\n}\n\nexport function pluginMigrationSlug(key: string): string {\n return normalizeSlug(key);\n}\n\nexport function getDatabaseUrlSecretName(slug: string): string {\n return `${slug.toUpperCase().replace(/-/g, \"_\")}_DATABASE_URL`;\n}\n\nexport const DUPLICATE_OBJECT_SQLSTATES: readonly string[] = [\"42710\", \"42701\", \"42P07\"];\n\n/**\n * Walk `error` and its `cause` chain (bounded), invoking `visit` on each link.\n * Postgres driver errors arrive wrapped by drizzle/Effect at varying depths,\n * so every error-shape predicate below shares this traversal.\n */\nexport function visitCauses(\n error: unknown,\n depth: number,\n visit: (link: object) => boolean,\n): boolean {\n let current: unknown = error;\n for (let i = 0; i < depth && current; i++) {\n if (typeof current === \"object\" && current !== null && visit(current)) return true;\n current = (current as { cause?: unknown })?.cause;\n }\n return false;\n}\n\n/**\n * pg_catalog unique indexes that can surface a concurrent-DDL race as SQLSTATE\n * 23505 instead of a duplicate-object class. When two connections run\n * `CREATE TABLE <name>` at the same time, the loser fails its insert into\n * `pg_type` (\"duplicate key value violates unique constraint\n * `pg_type_typname_nsp_index`\") rather than seeing 42P07, because the winner's\n * table is not yet committed. The same shape exists for schemas and other\n * relations.\n */\nconst CONCURRENT_DDL_CONSTRAINTS: ReadonlySet<string> = new Set([\n \"pg_type_typname_nsp_index\",\n \"pg_namespace_nspname_index\",\n \"pg_class_relname_nsp_index\",\n]);\n\n/**\n * Whether a SQLSTATE 23505 unique violation is the concurrent-DDL catalog\n * collision signature rather than a data-level constraint on a user table.\n * Data-level violations must keep failing loudly; only the pg_catalog indexes\n * above are treated as duplicate-DDL tolerance candidates.\n */\nexport function isConcurrentDdlUniqueViolation(error: unknown): boolean {\n return visitCauses(error, 6, (link) => {\n const { code, constraint, message } = link as {\n code?: unknown;\n constraint?: unknown;\n message?: unknown;\n };\n if (code !== \"23505\") return false;\n if (typeof constraint === \"string\" && CONCURRENT_DDL_CONSTRAINTS.has(constraint)) return true;\n if (typeof message !== \"string\") return false;\n for (const name of CONCURRENT_DDL_CONSTRAINTS) {\n if (message.includes(name)) return true;\n }\n return false;\n });\n}\n\nconst RETRYABLE_SQLSTATES: ReadonlySet<string> = new Set([\n \"42P06\",\n \"42710\",\n \"42701\",\n \"42P07\",\n \"23505\",\n \"40001\",\n \"40P01\",\n \"55P03\",\n]);\n\nconst RETRYABLE_DRIVER_CODES: ReadonlySet<string> = new Set([\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n]);\n\nfunction matchesRetryableStates(error: unknown, states: ReadonlySet<string>): boolean {\n return visitCauses(error, 6, (link) => {\n const code = (link as { code?: unknown }).code;\n if (typeof code !== \"string\") return false;\n return states.has(code) || code.startsWith(\"08\") || RETRYABLE_DRIVER_CODES.has(code);\n });\n}\n\n/**\n * Decide whether a failed migration-init statement (schema/journal creation)\n * is worth retrying. Covers the concurrent `CREATE SCHEMA IF NOT EXISTS`\n * race (unique violation on `pg_namespace`, duplicate-object errors),\n * serialization/deadlock errors, and transient connection failures.\n */\nexport function isRetryableMigrationError(error: unknown): boolean {\n return matchesRetryableStates(error, RETRYABLE_SQLSTATES);\n}\n\nconst RETRYABLE_STATEMENT_SQLSTATES: ReadonlySet<string> = new Set([\n \"40001\", // serialization_failure\n \"40P01\", // deadlock_detected\n \"55P03\", // lock_not_available\n]);\n\n/**\n * Decide whether a failed migration *statement* (inside its transaction) is\n * worth retrying. Deliberately narrower than `isRetryableMigrationError`:\n * duplicate-object classes are tolerated at the SAVEPOINT level, and a 23505\n * is either the concurrent-DDL catalog collision (also tolerated) or a\n * deterministic data-level violation (retrying is pointless) — so only\n * lock/serialization/transient-connection states justify re-running the\n * transaction.\n */\nexport function isRetryableMigrationExecutionError(error: unknown): boolean {\n return matchesRetryableStates(error, RETRYABLE_STATEMENT_SQLSTATES);\n}\n\nconst PG_QUERY_QUEUE_DEPRECATION = \"client.query() when the client is already executing a query\";\n\nlet pgWarningFilterInstalled = false;\n\n/**\n * Silence pg's query-queue deprecation warning (fires once per process from\n * pg-pool's internal dispatch under concurrent boot load — node-postgres#3612,\n * #3617). Node's default warning handler prints even when user listeners are\n * attached, so it is removed first; every other warning is re-printed here.\n */\nexport function suppressPgQueryQueueDeprecation(): void {\n if (pgWarningFilterInstalled) return;\n if (typeof process === \"undefined\" || typeof process.on !== \"function\") return;\n pgWarningFilterInstalled = true;\n process.removeAllListeners(\"warning\");\n process.on(\"warning\", (warning) => {\n if (\n warning.name === \"DeprecationWarning\" &&\n warning.message.includes(PG_QUERY_QUEUE_DEPRECATION)\n ) {\n return;\n }\n console.error(warning.stack || `${warning.name}: ${warning.message}`);\n });\n}\n\nexport function extractExpectedTables(migrations: { sql: string[] }[]): string[] {\n const tables = new Set<string>();\n const ident = String.raw`(?:\"([^\"]+)\"|(\\w+))`;\n const qualified = String.raw`(?:${ident}\\.)?`;\n const createRe = new RegExp(\n String.raw`CREATE\\s+TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?${qualified}${ident}`,\n \"gi\",\n );\n const dropRe = new RegExp(\n String.raw`DROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?${qualified}${ident}`,\n \"gi\",\n );\n const renameRe = new RegExp(\n String.raw`ALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?${qualified}${ident}${String.raw`\\s+RENAME\\s+TO\\s+`}${ident}`,\n \"gi\",\n );\n for (const migration of migrations) {\n for (const stmt of migration.sql) {\n for (const match of stmt.matchAll(createRe)) {\n const tableName = match[3] ?? match[4];\n if (tableName) {\n tables.add(tableName);\n }\n }\n for (const match of stmt.matchAll(dropRe)) {\n const tableName = match[3] ?? match[4];\n if (tableName) {\n tables.delete(tableName);\n }\n }\n for (const match of stmt.matchAll(renameRe)) {\n const from = match[3] ?? match[4];\n const to = match[5] ?? match[6];\n if (from && to) {\n tables.delete(from);\n tables.add(to);\n }\n }\n }\n }\n return [...tables];\n}\n"],"mappings":";;;;AASA,MAAM,4BAA4B;CAChC,QAAQ;CACR,OAAO;AACT;AAEA,MAAM,uBAAuB;AAE7B,SAAgB,cAAc,MAAsB;CAElD,QADiB,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK,KAC3B,CACZ,QAAQ,MAAM,EAAE,CAAC,CACjB,QAAQ,mBAAmB,GAAG,CAAC,CAC/B,QAAQ,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,IAAI;IAClB,OAAO,IAAI,EAAE;GACf;EACF;CACF;CAEF,OAAO,CAAC,GAAG,MAAM;AACnB"}
@@ -72,6 +72,19 @@ var HttpFetch = class HttpFetch extends effect.Context.Service()("everything-dev
72
72
  };
73
73
  const getCache = /* @__PURE__ */ new Map();
74
74
  const GET_CACHE_TTL_MS = 3e4;
75
+ const GET_CACHE_MAX_ENTRIES = 128;
76
+ function setCached(url, data) {
77
+ const now = Date.now();
78
+ for (const [key, entry] of getCache) if (entry.expiresAt <= now) getCache.delete(key);
79
+ if (getCache.size >= GET_CACHE_MAX_ENTRIES) for (const key of getCache.keys()) {
80
+ getCache.delete(key);
81
+ if (getCache.size < GET_CACHE_MAX_ENTRIES) break;
82
+ }
83
+ getCache.set(url, {
84
+ data,
85
+ expiresAt: now + GET_CACHE_TTL_MS
86
+ });
87
+ }
75
88
  function isCacheable(_url, options) {
76
89
  if (options?.method && options.method !== "GET") return false;
77
90
  if (options?.body) return false;
@@ -99,10 +112,7 @@ const fetchJsonOrNull = async (url, options) => {
99
112
  }
100
113
  try {
101
114
  const data = await (await effect.Effect.runPromise(defaultHttpFetch.get(url, options))).json();
102
- if (isCacheable(url, options)) getCache.set(url, {
103
- data,
104
- expiresAt: Date.now() + GET_CACHE_TTL_MS
105
- });
115
+ if (isCacheable(url, options)) setCached(url, data);
106
116
  return data;
107
117
  } catch (error) {
108
118
  const msg = error instanceof FetchNetworkError ? `[http] Network error: ${error.url} — ${String(error.cause)}` : error instanceof FetchTimeoutError ? `[http] Timeout: ${error.url}` : error instanceof FetchHttpError ? `[http] HTTP ${error.status}: ${error.url}` : `[http] Unknown error while fetching ${url}`;