@rebasepro/cli 0.31.0-canary.g902a0ce → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-setup-DqAcoDcn.js → agent-setup-Cg_zBWoW.js} +3 -3
- package/dist/{agent-setup-DqAcoDcn.js.map → agent-setup-Cg_zBWoW.js.map} +1 -1
- package/dist/api-TbmW33D7.js +275 -0
- package/dist/api-TbmW33D7.js.map +1 -0
- package/dist/{api-keys-eIUjMqWn.js → api-keys-fPQ55DCm.js} +151 -158
- package/dist/api-keys-fPQ55DCm.js.map +1 -0
- package/dist/{apps-DExO4PEl.js → apps-DBTRoOeP.js} +18 -13
- package/dist/apps-DBTRoOeP.js.map +1 -0
- package/dist/{args-CaCcrYE1.js → args-DHyrshtI.js} +3 -132
- package/dist/args-DHyrshtI.js.map +1 -0
- package/dist/{atlas-dev-database-DOCKk6ht.js → atlas-dev-database-D6h65f2x.js} +3 -3
- package/dist/{atlas-dev-database-DOCKk6ht.js.map → atlas-dev-database-D6h65f2x.js.map} +1 -1
- package/dist/{auth-CyADghFQ.js → auth-BpyYLEFY.js} +93 -12
- package/dist/auth-BpyYLEFY.js.map +1 -0
- package/dist/auth-session-B6aT0Dyj.js +371 -0
- package/dist/auth-session-B6aT0Dyj.js.map +1 -0
- package/dist/{backend-guard-C0mVkXBw.js → backend-guard-Cf8eMK_f.js} +2 -2
- package/dist/{backend-guard-C0mVkXBw.js.map → backend-guard-Cf8eMK_f.js.map} +1 -1
- package/dist/{branch-pointer-DMPyvZoK.js → branch-pointer-BJOF2Ubv.js} +1 -1
- package/dist/{build-CA5R07tw.js → build-BfdT-AUR.js} +12 -10
- package/dist/{build-CA5R07tw.js.map → build-BfdT-AUR.js.map} +1 -1
- package/dist/{bundle-DgILeA5b.js → bundle-CIiKGrte.js} +78 -12
- package/dist/bundle-CIiKGrte.js.map +1 -0
- package/dist/bundle.d.ts +31 -1
- package/dist/{cloud-CYMk92iG.js → cloud-MqnyPnmX.js} +1540 -1531
- package/dist/cloud-MqnyPnmX.js.map +1 -0
- package/dist/{cms-directories-BK3vcswg.js → cms-directories-BaV-Is9a.js} +2 -2
- package/dist/{cms-directories-BK3vcswg.js.map → cms-directories-BaV-Is9a.js.map} +1 -1
- package/dist/codemod/collections-to-tables/backend.d.ts +0 -2
- package/dist/codemod/collections-to-tables/customization.d.ts +2 -1
- package/dist/codemod/collections-to-tables/modules.d.ts +32 -0
- package/dist/codemod/collections-to-tables/plan-context.d.ts +7 -1
- package/dist/{command-D5lhW_-B.js → command-D9g46gg9.js} +68 -42
- package/dist/command-D9g46gg9.js.map +1 -0
- package/dist/commands/api-keys.d.ts +89 -52
- package/dist/commands/api.d.ts +114 -0
- package/dist/commands/auth-session.d.ts +94 -0
- package/dist/commands/auth.d.ts +1 -1
- package/dist/commands/cloud/alerts.d.ts +29 -0
- package/dist/commands/cloud/context.d.ts +8 -0
- package/dist/commands/cloud/debug.d.ts +16 -1
- package/dist/commands/cloud/deploy-hooks.d.ts +19 -0
- package/dist/commands/cloud/deploy.d.ts +25 -0
- package/dist/commands/cloud/env.d.ts +1 -0
- package/dist/commands/cloud/index.d.ts +5 -0
- package/dist/commands/cloud/maintenance.d.ts +26 -1
- package/dist/commands/cloud/not-served.d.ts +27 -0
- package/dist/commands/cloud/orgs.d.ts +5 -0
- package/dist/commands/cloud/resources.d.ts +82 -2
- package/dist/commands/cloud/runtime-logs.d.ts +57 -0
- package/dist/commands/cloud/settings.d.ts +3 -0
- package/dist/commands/cron.d.ts +68 -0
- package/dist/commands/data.d.ts +197 -0
- package/dist/commands/functions.d.ts +38 -0
- package/dist/commands/logs.d.ts +22 -0
- package/dist/commands/rls.d.ts +31 -0
- package/dist/commands/schema-reconcile.d.ts +2 -1
- package/dist/commands/schema-show.d.ts +38 -0
- package/dist/commands/storage-objects.d.ts +88 -0
- package/dist/commands/storage.d.ts +18 -2
- package/dist/commands/users.d.ts +147 -0
- package/dist/{consent-BXLIrMl8.js → consent-UV6ObCME.js} +2 -2
- package/dist/{consent-BXLIrMl8.js.map → consent-UV6ObCME.js.map} +1 -1
- package/dist/{console-CMjhgMUE.js → console-BVoYOLAO.js} +6 -6
- package/dist/{console-CMjhgMUE.js.map → console-BVoYOLAO.js.map} +1 -1
- package/dist/{context--JwaHaZp.js → context-BOMEoKxn.js} +80 -9
- package/dist/{context--JwaHaZp.js.map → context-BOMEoKxn.js.map} +1 -1
- package/dist/cron-CpUsQ739.js +298 -0
- package/dist/cron-CpUsQ739.js.map +1 -0
- package/dist/cron-ZRXsla0v.js +259 -0
- package/dist/cron-ZRXsla0v.js.map +1 -0
- package/dist/{daemon-w30PsdwV.js → daemon-D5gdG7gx.js} +3 -3
- package/dist/{daemon-w30PsdwV.js.map → daemon-D5gdG7gx.js.map} +1 -1
- package/dist/{daemon-entry-zOC1revO.js → daemon-entry--ummUJnk.js} +2 -2
- package/dist/{daemon-entry-zOC1revO.js.map → daemon-entry--ummUJnk.js.map} +1 -1
- package/dist/data-BJ9AZFUC.js +947 -0
- package/dist/data-BJ9AZFUC.js.map +1 -0
- package/dist/{db-A7XDCIIO.js → db-D_iF4E-v.js} +60 -36
- package/dist/db-D_iF4E-v.js.map +1 -0
- package/dist/debug-nNbbxAeo.js +1114 -0
- package/dist/debug-nNbbxAeo.js.map +1 -0
- package/dist/{derive-C3ezmY-p.js → derive-Mky_u59_.js} +3 -3
- package/dist/{derive-C3ezmY-p.js.map → derive-Mky_u59_.js.map} +1 -1
- package/dist/{dev-tWwPyWkQ.js → dev-bj6dEeSQ.js} +13 -13
- package/dist/{dev-tWwPyWkQ.js.map → dev-bj6dEeSQ.js.map} +1 -1
- package/dist/dev-db/__fixtures__/unanswering-postgres.d.ts +11 -0
- package/dist/dev-db/attver.d.ts +38 -6
- package/dist/dev-db/local-timeouts.d.ts +25 -0
- package/dist/dev-db/pull.d.ts +49 -9
- package/dist/{dev-preflight-DjvcV6SK.js → dev-preflight-BMOf2N6r.js} +2 -2
- package/dist/{dev-preflight-DjvcV6SK.js.map → dev-preflight-BMOf2N6r.js.map} +1 -1
- package/dist/{dev-server-BLxCbQEP.js → dev-server-2XHSHM_q.js} +2 -2
- package/dist/{dev-server-BLxCbQEP.js.map → dev-server-2XHSHM_q.js.map} +1 -1
- package/dist/{doctor-BBM0dWvZ.js → doctor-2Jlau0Rm.js} +9 -8
- package/dist/{doctor-BBM0dWvZ.js.map → doctor-2Jlau0Rm.js.map} +1 -1
- package/dist/{eject-Bhzd6hgb.js → eject-DK_M9kor.js} +4 -4
- package/dist/{eject-Bhzd6hgb.js.map → eject-DK_M9kor.js.map} +1 -1
- package/dist/{fold-static-CKewnAPX.js → fold-static-2t3UUX4z.js} +10 -6
- package/dist/fold-static-2t3UUX4z.js.map +1 -0
- package/dist/fold-static.d.ts +7 -0
- package/dist/functions-B4JR6EZL.js +120 -0
- package/dist/functions-B4JR6EZL.js.map +1 -0
- package/dist/{generate-view-CTOluXvH.js → generate-view-BMaLQm8H.js} +5 -5
- package/dist/{generate-view-CTOluXvH.js.map → generate-view-BMaLQm8H.js.map} +1 -1
- package/dist/{generate_sdk-De-aLC1L.js → generate_sdk-ByD-gTsK.js} +7 -7
- package/dist/{generate_sdk-De-aLC1L.js.map → generate_sdk-ByD-gTsK.js.map} +1 -1
- package/dist/index.es.js +123 -47
- package/dist/index.es.js.map +1 -1
- package/dist/{init-Dtl-IcXf.js → init-DHCe5mJ5.js} +59 -11
- package/dist/init-DHCe5mJ5.js.map +1 -0
- package/dist/{invoked-command-CG_rIa_o.js → invoked-command-FBeIBS8o.js} +2 -2
- package/dist/{invoked-command-CG_rIa_o.js.map → invoked-command-FBeIBS8o.js.map} +1 -1
- package/dist/last-dev-database-CBVkEUEl.js +2 -0
- package/dist/local-timeouts-B1Kwligw.js +30 -0
- package/dist/local-timeouts-B1Kwligw.js.map +1 -0
- package/dist/logs-CIgfLBsu.js +192 -0
- package/dist/logs-CIgfLBsu.js.map +1 -0
- package/dist/{manifest-C3uLDrrJ.js → manifest-RjqxfCpb.js} +114 -5
- package/dist/manifest-RjqxfCpb.js.map +1 -0
- package/dist/{migrate-VrKoi3nB.js → migrate-Cx8-Y4TG.js} +5 -4
- package/dist/{migrate-VrKoi3nB.js.map → migrate-Cx8-Y4TG.js.map} +1 -1
- package/dist/{normalize-imports-DwxqEMYq.js → normalize-imports-P86NVfpo.js} +3 -3
- package/dist/{normalize-imports-DwxqEMYq.js.map → normalize-imports-P86NVfpo.js.map} +1 -1
- package/dist/{path-flags-7O5uPBcQ.js → path-flags-ekLdkbra.js} +3 -3
- package/dist/{path-flags-7O5uPBcQ.js.map → path-flags-ekLdkbra.js.map} +1 -1
- package/dist/{prepare-Ccxspoj-.js → prepare-BaJe0Zik.js} +4 -4
- package/dist/{prepare-Ccxspoj-.js.map → prepare-BaJe0Zik.js.map} +1 -1
- package/dist/{project-CLcF5i8c.js → project-DALmhb5R.js} +2 -2
- package/dist/{project-CLcF5i8c.js.map → project-DALmhb5R.js.map} +1 -1
- package/dist/project-command-Cl9EZzjr.js +662 -0
- package/dist/project-command-Cl9EZzjr.js.map +1 -0
- package/dist/{project-schema-CsSOG2gE.js → project-schema-Dm6Jk0Y_.js} +4 -2
- package/dist/{project-schema-CsSOG2gE.js.map → project-schema-Dm6Jk0Y_.js.map} +1 -1
- package/dist/{pull-D9WvpDYY.js → pull-CTIsST6T.js} +336 -55
- package/dist/pull-CTIsST6T.js.map +1 -0
- package/dist/resolve-C36px9tR.js +2 -0
- package/dist/{resources-Dpfs2y8P.js → resources-Db3USuPO.js} +5 -5
- package/dist/{resources-Dpfs2y8P.js.map → resources-Db3USuPO.js.map} +1 -1
- package/dist/rls-BxrQ0P50.js +133 -0
- package/dist/rls-BxrQ0P50.js.map +1 -0
- package/dist/{schema-DwFDI1iU.js → schema-_FzZEoB8.js} +54 -40
- package/dist/schema-_FzZEoB8.js.map +1 -0
- package/dist/{schema-dir-Cd1kvYbf.js → schema-dir-ChcYfWjP.js} +2 -2
- package/dist/{schema-dir-Cd1kvYbf.js.map → schema-dir-ChcYfWjP.js.map} +1 -1
- package/dist/schema-reconcile-DV14XY4o.js +2 -0
- package/dist/schema-show-h72UJ9zH.js +127 -0
- package/dist/schema-show-h72UJ9zH.js.map +1 -0
- package/dist/{skills-CXjA9TWw.js → skills-DQ2bZGkj.js} +6 -5
- package/dist/{skills-CXjA9TWw.js.map → skills-DQ2bZGkj.js.map} +1 -1
- package/dist/star-nudge.d.ts +28 -0
- package/dist/{start-Bwbtt2W5.js → start-Cjx4W0bJ.js} +7 -7
- package/dist/{start-Bwbtt2W5.js.map → start-Cjx4W0bJ.js.map} +1 -1
- package/dist/{status-DQ_PPz4C.js → status-CDBk25VO.js} +9 -9
- package/dist/{status-DQ_PPz4C.js.map → status-CDBk25VO.js.map} +1 -1
- package/dist/{storage-iTqj5-Av.js → storage-Clc8dLG8.js} +79 -36
- package/dist/storage-Clc8dLG8.js.map +1 -0
- package/dist/storage-objects-CfRKlTDe.js +279 -0
- package/dist/storage-objects-CfRKlTDe.js.map +1 -0
- package/dist/{telemetry-BP_1Cl9r.js → telemetry-DZU2-NCm.js} +5 -4
- package/dist/{telemetry-BP_1Cl9r.js.map → telemetry-DZU2-NCm.js.map} +1 -1
- package/dist/{telemetry-M3HjlyhZ.js → telemetry-EVtASbKb.js} +2 -2
- package/dist/{telemetry-M3HjlyhZ.js.map → telemetry-EVtASbKb.js.map} +1 -1
- package/dist/unknown-command-DnZ2uhGs.js +139 -0
- package/dist/unknown-command-DnZ2uhGs.js.map +1 -0
- package/dist/{upgrade-oZzJ13jM.js → upgrade-DhpUFb6p.js} +5 -5
- package/dist/{upgrade-oZzJ13jM.js.map → upgrade-DhpUFb6p.js.map} +1 -1
- package/dist/users-5PkqBY6R.js +561 -0
- package/dist/users-5PkqBY6R.js.map +1 -0
- package/dist/utils/project-command.d.ts +38 -0
- package/dist/utils/project-target.d.ts +193 -0
- package/dist/{verify-DkJqhYPI.js → verify-BdeqNb-V.js} +138 -12
- package/dist/verify-BdeqNb-V.js.map +1 -0
- package/dist/{version-Buyyo1ut.js → version-ONIeo7jl.js} +7 -2
- package/dist/{version-Buyyo1ut.js.map → version-ONIeo7jl.js.map} +1 -1
- package/package.json +10 -10
- package/dist/api-keys-eIUjMqWn.js.map +0 -1
- package/dist/apps-DExO4PEl.js.map +0 -1
- package/dist/args-CaCcrYE1.js.map +0 -1
- package/dist/auth-CyADghFQ.js.map +0 -1
- package/dist/bundle-DgILeA5b.js.map +0 -1
- package/dist/cloud-CYMk92iG.js.map +0 -1
- package/dist/command-D5lhW_-B.js.map +0 -1
- package/dist/db-A7XDCIIO.js.map +0 -1
- package/dist/fold-static-CKewnAPX.js.map +0 -1
- package/dist/init-Dtl-IcXf.js.map +0 -1
- package/dist/last-dev-database-Dc8cP01o.js +0 -2
- package/dist/manifest-C3uLDrrJ.js.map +0 -1
- package/dist/pull-D9WvpDYY.js.map +0 -1
- package/dist/resolve-BY7bSFRT.js +0 -2
- package/dist/schema-DwFDI1iU.js.map +0 -1
- package/dist/schema-reconcile-Tto54Qbv.js +0 -2
- package/dist/storage-iTqj5-Av.js.map +0 -1
- package/dist/verify-DkJqhYPI.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"verify-BdeqNb-V.js","names":[],"sources":["../src/commands/verify-cms.ts","../src/commands/verify.ts"],"sourcesContent":["/**\n * `rebase verify`, step \"CMS customizations\": the project's\n * `customizeTable(...)` calls held to the tables they customize.\n *\n * The panel applies a customization at runtime and, for a slug or a field the\n * tables do not have, only warns in the browser console in development\n * (`applyTableCustomizations`). An agent that misspells a slug, keeps a field\n * after renaming its column, or hides a required column from the form ships a\n * panel that silently ignores the edit — or one that cannot create a record.\n * The post-edit hook runs `rebase verify` after edits under `frontend/src/cms`,\n * so this step is what answers for those files.\n *\n * **Read statically.** A customization module imports `@rebasepro/cms` (React,\n * the browser panel) and the project's own components, so it cannot be\n * imported in Node without the frontend's toolchain. The calls are read with\n * ts-morph instead: the slug, the keys of `fields`, and the literal values of\n * the form options of each field. What a static read cannot see — a slug or\n * options computed at runtime, a spread, a computed key, a `dynamicProps` /\n * `conditions` that hides a field on some records, a global `beforeSave` hook\n * in `backend/hooks.ts` that fills a column — is either reported as not read\n * (`cms-not-static`) or not judged; it is never reported as a problem.\n *\n * Checks (stable ids):\n *\n * - `cms-unknown-table` — `customizeTable(\"x\")` for a slug no table declares.\n * - `cms-unknown-field` — a `fields` key that is neither a column key nor a\n * relation of that table.\n * - `cms-hidden-required` — a field kept off the form (`hiddenInForm`,\n * `readOnly`, `disabled`) whose column is `NOT NULL` with no default, that\n * neither the database nor the server fills, and that the customization does\n * not mark `filledByServer`: no record can be created from the panel. A\n * warning instead of an error when the table declares a `beforeSave` hook\n * (or the column a `beforeSave` transform), which may be what fills it.\n * - `cms-duplicate-customization` — two `customizeTable` calls for one slug.\n * The panel refuses to mount with both.\n * - `cms-not-static` — a call this step could not read (warning).\n * - `cms-ui-config-not-mounted` — `src/cms/ui-config.json` exists, where the\n * collection editor saves presentation in development, but no `<RebaseCMS>`\n * in the frontend passes `uiConfig`: the editor's changes are lost on\n * reload and never ship (warning). Said only when a `<RebaseCMS>` element\n * was found and none of them passes `uiConfig` or spreads props into it.\n * - `cms-backend-guard-missing` — the project has `backend/` and a frontend\n * whose Vite config does not use `rebaseBackendGuard()`: nothing refuses a\n * value import of a table, which would ship its server hooks to every\n * visitor (`utils/backend-guard.ts`). Quiet when the config imports a local\n * module that may add it, and checked whether or not `src/cms` exists.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport type { ColumnDescriptor, TableDescriptor } from \"@rebasepro/types\";\nimport type { Expression, Node, ObjectLiteralExpression, Project, SourceFile } from \"ts-morph\";\nimport { cmsDirectories } from \"../utils/cms-directories\";\nimport { BACKEND_GUARD_FIX, backendGuardMissingMessage, backendGuardStates } from \"../utils/backend-guard\";\n\ntype TsMorph = typeof import(\"ts-morph\");\n\n/** The package `customizeTable` is imported from. */\nconst CMS_PACKAGE = \"@rebasepro/cms\";\nconst CUSTOMIZE = \"customizeTable\";\n/** The panel's mount, and the file the collection editor writes presentation to in development. */\nconst MOUNT = \"RebaseCMS\";\nconst UI_CONFIG_FILE = \"ui-config.json\";\nconst SOURCE = /\\.(ts|tsx|mts|js|jsx|mjs)$/;\nconst NOT_SOURCE = /\\.(d|test|spec)\\.[cm]?[jt]sx?$/;\n\n/** The form options that keep a field from being edited on the form. */\nconst OFF_FORM_OPTIONS = [\"hiddenInForm\", \"readOnly\", \"disabled\"] as const;\ntype OffFormOption = typeof OFF_FORM_OPTIONS[number];\n\n/** A finding of this step, in `rebase verify`'s finding shape (step `cms`). */\nexport interface CmsFinding {\n check: \"cms-unknown-table\" | \"cms-unknown-field\" | \"cms-hidden-required\" | \"cms-duplicate-customization\" | \"cms-not-static\" | \"cms-ui-config-not-mounted\" | \"cms-backend-guard-missing\";\n severity: \"error\" | \"warning\";\n message: string;\n fix?: string;\n table?: string;\n /** Relative to the project root. */\n file: string;\n line: number;\n /** `customizeTable(\"posts\").fields.title`. */\n path?: string;\n}\n\n/** What the step read and found. */\nexport interface CmsCheckResult {\n /** The customization directories read, relative to the project root. Empty: nothing to check. */\n directories: string[];\n /** How many `customizeTable` calls were found. */\n customizations: number;\n findings: CmsFinding[];\n}\n\n/** One field of a customization, as far as a static read says. */\ninterface FieldRead {\n key: string;\n line: number;\n /** The off-form options written as `true` (an object for `disabled` counts). */\n offForm: OffFormOption[];\n /** `filledByServer` as written: true or false, `undefined` when not stated, `\"unknown\"` when not a literal. */\n filledByServer: boolean | undefined | \"unknown\";\n /** A spread in the field's options: what it carries is not known. */\n opaque: boolean;\n}\n\n/** One `customizeTable(...)` call, as far as a static read says. */\ninterface CustomizationRead {\n slug: string;\n file: string;\n line: number;\n fields: FieldRead[];\n /** What could not be read in it. */\n unread: string[];\n}\n\nfunction sourceFiles(dir: string): string[] {\n const out: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) out.push(...sourceFiles(full));\n else if (SOURCE.test(entry.name) && !NOT_SOURCE.test(entry.name)) out.push(full);\n }\n return out.sort();\n}\n\n// ─── The static read ──────────────────────────────────────────────────────────\n\nclass Reader {\n constructor(private readonly tsm: TsMorph) {}\n\n private unwrap(node: Node): Node {\n const N = this.tsm.Node;\n let current = node;\n while (N.isAsExpression(current) || N.isSatisfiesExpression(current) || N.isParenthesizedExpression(current) ||\n N.isNonNullExpression(current) || N.isTypeAssertion(current)) {\n current = current.getExpression();\n }\n return current;\n }\n\n /** The initializer of the top-level `const` an identifier names, in its own file. */\n private constOf(node: Node): Expression | undefined {\n const N = this.tsm.Node;\n if (!N.isIdentifier(node)) return undefined;\n const declaration = node.getSourceFile().getVariableDeclaration(node.getText());\n const statement = declaration?.getVariableStatement();\n if (!declaration || !statement || !N.isSourceFile(statement.getParent())) return undefined;\n if (statement.getDeclarationKind() !== this.tsm.VariableDeclarationKind.Const) return undefined;\n return declaration.getInitializer();\n }\n\n /** A string a node denotes: a literal, or a same-file `const` holding one. */\n string(node: Node | undefined, depth = 0): string | undefined {\n if (!node || depth > 4) return undefined;\n const N = this.tsm.Node;\n const current = this.unwrap(node);\n if (N.isStringLiteral(current) || N.isNoSubstitutionTemplateLiteral(current)) return current.getLiteralValue();\n const initializer = this.constOf(current);\n return initializer ? this.string(initializer, depth + 1) : undefined;\n }\n\n /** The object literal a node denotes: itself, or a same-file `const` holding one. */\n object(node: Node | undefined, depth = 0): ObjectLiteralExpression | undefined {\n if (!node || depth > 4) return undefined;\n const N = this.tsm.Node;\n const current = this.unwrap(node);\n if (N.isObjectLiteralExpression(current)) return current;\n const initializer = this.constOf(current);\n return initializer ? this.object(initializer, depth + 1) : undefined;\n }\n\n /** A property's name as written, or undefined for a computed one. */\n name(member: Node): string | undefined {\n const N = this.tsm.Node;\n if (!N.isPropertyAssignment(member) && !N.isShorthandPropertyAssignment(member) && !N.isMethodDeclaration(member)) return undefined;\n const nameNode = member.getNameNode();\n if (N.isIdentifier(nameNode)) return nameNode.getText();\n if (N.isStringLiteral(nameNode) || N.isNoSubstitutionTemplateLiteral(nameNode)) return nameNode.getLiteralValue();\n if (N.isNumericLiteral(nameNode)) return String(nameNode.getLiteralValue());\n if (N.isComputedPropertyName(nameNode)) return this.string(nameNode.getExpression());\n return undefined;\n }\n\n /** The value of a member: an assignment's initializer, a shorthand's identifier. */\n value(member: Node): Node | undefined {\n const N = this.tsm.Node;\n if (N.isPropertyAssignment(member)) return member.getInitializer();\n if (N.isShorthandPropertyAssignment(member)) return member.getNameNode();\n return undefined;\n }\n\n /** `true` / `false` as written, an object literal as `true` (for `disabled: { … }`), else unknown. */\n flag(node: Node | undefined, objectIsTrue: boolean): boolean | \"unknown\" {\n if (!node) return \"unknown\";\n const N = this.tsm.Node;\n const { SyntaxKind } = this.tsm;\n const current = this.unwrap(node);\n if (current.getKind() === SyntaxKind.TrueKeyword) return true;\n if (current.getKind() === SyntaxKind.FalseKeyword) return false;\n if (objectIsTrue && N.isObjectLiteralExpression(current)) return true;\n return \"unknown\";\n }\n\n /** The local names `customizeTable` is bound to, and namespaces of the CMS package. */\n private bindings(sf: SourceFile): { names: Set<string>; namespaces: Set<string> } {\n const names = new Set<string>();\n const namespaces = new Set<string>();\n for (const declaration of sf.getImportDeclarations()) {\n if (declaration.getModuleSpecifierValue() !== CMS_PACKAGE || declaration.isTypeOnly()) continue;\n const namespace = declaration.getNamespaceImport();\n if (namespace) namespaces.add(namespace.getText());\n for (const named of declaration.getNamedImports()) {\n if (named.getName() === CUSTOMIZE && !named.isTypeOnly()) names.add(named.getAliasNode()?.getText() ?? CUSTOMIZE);\n }\n }\n return { names, namespaces };\n }\n\n field(key: string, member: Node): FieldRead {\n const N = this.tsm.Node;\n const read: FieldRead = { key, line: member.getStartLineNumber(), offForm: [], filledByServer: undefined, opaque: false };\n const options = this.object(this.value(member));\n if (!options) {\n read.opaque = true;\n return read;\n }\n for (const property of options.getProperties()) {\n if (N.isSpreadAssignment(property)) {\n read.opaque = true;\n continue;\n }\n const name = this.name(property);\n if (name === undefined) {\n read.opaque = true;\n continue;\n }\n const value = this.value(property);\n if (name === \"filledByServer\") read.filledByServer = this.flag(value, false);\n const option = OFF_FORM_OPTIONS.find(candidate => candidate === name);\n if (option && this.flag(value, option === \"disabled\") === true) read.offForm.push(option);\n }\n return read;\n }\n\n /** Every `customizeTable(...)` call in a file, read as far as the source says. */\n customizations(sf: SourceFile, relativeFile: string): CustomizationRead[] {\n const N = this.tsm.Node;\n const { SyntaxKind } = this.tsm;\n const { names, namespaces } = this.bindings(sf);\n if (names.size === 0 && namespaces.size === 0) return [];\n const out: CustomizationRead[] = [];\n for (const call of sf.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const callee = call.getExpression();\n const isCustomize = (N.isIdentifier(callee) && names.has(callee.getText())) ||\n (N.isPropertyAccessExpression(callee) && callee.getName() === CUSTOMIZE && namespaces.has(callee.getExpression().getText()));\n if (!isCustomize) continue;\n const [slugNode, optionsNode] = call.getArguments();\n const read: CustomizationRead = { slug: \"\", file: relativeFile, line: call.getStartLineNumber(), fields: [], unread: [] };\n const slug = this.string(slugNode);\n if (slug === undefined) {\n read.unread.push(`the slug \\`${slugNode?.getText() ?? \"\"}\\` is not a string literal or a \\`const\\` of one in this file`);\n out.push(read);\n continue;\n }\n read.slug = slug;\n const options = this.object(optionsNode);\n if (!options) {\n read.unread.push(`the options \\`${optionsNode?.getText().split(\"\\n\")[0] ?? \"\"}\\` are not an object literal or a \\`const\\` of one in this file`);\n out.push(read);\n continue;\n }\n let fieldsNode: Node | undefined;\n for (const property of options.getProperties()) {\n if (N.isSpreadAssignment(property)) {\n read.unread.push(`\\`...${property.getExpression().getText()}\\` (line ${property.getStartLineNumber()}) may carry \\`fields\\``);\n continue;\n }\n if (this.name(property) === \"fields\") fieldsNode = this.value(property);\n }\n if (fieldsNode) {\n const fields = this.object(fieldsNode);\n if (!fields) {\n read.unread.push(`\\`fields\\` (line ${fieldsNode.getStartLineNumber()}) is not an object literal or a \\`const\\` of one in this file`);\n } else {\n for (const member of fields.getProperties()) {\n const key = this.name(member);\n if (key === undefined) {\n read.unread.push(`\\`${member.getText().split(\"\\n\")[0]}\\` (line ${member.getStartLineNumber()}) in \\`fields\\``);\n continue;\n }\n read.fields.push(this.field(key, member));\n }\n }\n }\n out.push(read);\n }\n return out;\n }\n}\n\n// ─── The checks ───────────────────────────────────────────────────────────────\n\n/** Levenshtein distance, for \"did you mean\". */\nfunction distance(a: string, b: string): number {\n const row = Array.from({ length: b.length + 1 }, (_, i) => i);\n for (let i = 1; i <= a.length; i++) {\n let previous = row[0];\n row[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const current = row[j];\n row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1].toLowerCase() === b[j - 1].toLowerCase() ? 0 : 1));\n previous = current;\n }\n }\n return row[b.length];\n}\n\nfunction closest(name: string, candidates: Iterable<string>): string | undefined {\n let best: string | undefined;\n let bestDistance = Math.max(2, Math.floor(name.length / 3)) + 1;\n for (const candidate of candidates) {\n const d = distance(name, candidate);\n if (d < bestDistance) {\n best = candidate;\n bestDistance = d;\n }\n }\n return best;\n}\n\nconst SERIAL_KINDS: ReadonlySet<string> = new Set([\"smallserial\", \"serial\", \"bigserial\"]);\n\n/**\n * Whether a create may leave the column out and still succeed without the\n * server's help from a hook: it is nullable, has a default (literal, SQL,\n * random uuid, identity, the database's), is a serial, is generated, is\n * stamped or read-only (the server writes it), or is the tenant column (the\n * server fills it from the caller).\n */\nfunction fillsItself(table: TableDescriptor, column: ColumnDescriptor): boolean {\n return column.nullable ||\n column.default !== undefined ||\n SERIAL_KINDS.has(column.type.kind) ||\n column.generated !== undefined ||\n column.stamp !== undefined ||\n column.readOnly === true ||\n table.tenant?.field === column.key;\n}\n\n/** The column a field key edits: the column itself, or the foreign key of a `belongsTo` relation. */\nfunction columnOfField(table: TableDescriptor, key: string): ColumnDescriptor | undefined {\n return table.columns.find(column => column.key === key) ??\n table.columns.find(column => column.foreignKeyOf === key);\n}\n\nfunction describeOffForm(options: readonly OffFormOption[]): string {\n return options.map(option => `\\`${option}\\``).join(\" and \");\n}\n\nfunction checkCustomization(read: CustomizationRead, table: TableDescriptor): CmsFinding[] {\n const findings: CmsFinding[] = [];\n const where = `customizeTable(\"${read.slug}\")`;\n const columnKeys = new Set(table.columns.map(column => column.key));\n const relationNames = new Set(table.relations.map(relation => relation.name));\n for (const field of read.fields) {\n const at = { table: table.slug, file: read.file, line: field.line, path: `${where}.fields.${field.key}` };\n if (!columnKeys.has(field.key) && !relationNames.has(field.key)) {\n const bySqlName = table.columns.find(column => column.column === field.key);\n const guess = bySqlName?.key ?? closest(field.key, [...columnKeys, ...relationNames]);\n findings.push({\n check: \"cms-unknown-field\",\n severity: \"error\",\n ...at,\n message: `${where} customizes \\`fields.${field.key}\\`, which is neither a column nor a relation of the \"${table.slug}\" table` +\n (bySqlName ? ` — that is the SQL name of the column whose key is \\`${bySqlName.key}\\`.` : \".\"),\n fix: guess\n ? `Rename the key to \\`${guess}\\`${bySqlName ? \" (fields are keyed by the column's key, as in `columns`)\" : \"\"}, or remove it.`\n : \"Remove it, or key it by one of the table's columns or relations (`columns` / `relations` in its `defineTable`).\"\n });\n continue;\n }\n if (field.offForm.length === 0 || field.filledByServer === true) continue;\n // A spread or a non-literal `filledByServer` may say it: not judged.\n if (field.opaque || field.filledByServer === \"unknown\") continue;\n const column = columnOfField(table, field.key);\n if (!column || fillsItself(table, column)) continue;\n const hooked = table.hooks?.beforeSave === true || column.transforms?.beforeSave === true;\n const what = column.key === field.key ? `the column \\`${column.column}\\`` : `its foreign key \\`${column.column}\\``;\n findings.push({\n check: \"cms-hidden-required\",\n severity: hooked ? \"warning\" : \"error\",\n ...at,\n message: `${where} keeps \\`${field.key}\\` off the form (${describeOffForm(field.offForm)}), but ${what} is NOT NULL with no default ` +\n (hooked\n ? `and only the table's \\`beforeSave\\` hook could fill it: unless it does, creating a record from the panel fails.`\n : `and nothing on the server fills it: creating a \"${table.slug}\" record from the panel always fails.`),\n fix: hooked\n ? `If the hook fills it on create, say so: \\`${field.key}: { …, filledByServer: true }\\`. Otherwise let the form edit it.`\n : `Let the form edit it (drop ${describeOffForm(field.offForm)}), give the column a default in its \\`defineTable\\` (\\`.default(…)\\`), ` +\n `or fill it in a \\`beforeSave\\` hook and mark the field \\`filledByServer: true\\`.`\n });\n }\n return findings;\n}\n\n/**\n * Read every `customizeTable(...)` call under the project's customization\n * directories and hold it to `tables`. Never throws on a file it cannot parse\n * as intended: what it cannot read is a `cms-not-static` warning.\n */\nexport async function checkCmsCustomizations(projectRoot: string, tables: readonly TableDescriptor[]): Promise<CmsCheckResult> {\n const directories = cmsDirectories(projectRoot);\n const result: CmsCheckResult = { directories: directories.map(dir => path.relative(projectRoot, dir)), customizations: 0, findings: [] };\n result.findings.push(...await backendGuardFindings(projectRoot));\n if (directories.length === 0) return result;\n\n const tsm: TsMorph = await import(\"ts-morph\");\n const project = new tsm.Project({\n useInMemoryFileSystem: true,\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true, jsx: tsm.ts.JsxEmit.Preserve, noLib: true }\n });\n const reader = new Reader(tsm);\n const bySlug = new Map(tables.map(table => [table.slug, table]));\n const first = new Map<string, CustomizationRead>();\n\n for (const dir of directories) {\n for (const file of sourceFiles(dir)) {\n const text = fs.readFileSync(file, \"utf-8\");\n if (!text.includes(CUSTOMIZE)) continue;\n const relativeFile = path.relative(projectRoot, file);\n const sf = project.createSourceFile(file, text, { overwrite: true });\n for (const read of reader.customizations(sf, relativeFile)) {\n result.customizations++;\n const label = read.slug ? `customizeTable(\"${read.slug}\")` : \"customizeTable(…)\";\n if (read.unread.length > 0) {\n result.findings.push({\n check: \"cms-not-static\",\n severity: \"warning\",\n file: read.file,\n line: read.line,\n ...(read.slug && { table: read.slug, path: label }),\n message: `${label} was not fully checked: ${read.unread.join(\"; \")}. ` +\n \"`rebase verify` reads customizations without running them, so only literals in the call are checked.\",\n fix: \"Write the slug and the `fields` object as literals in the call (a `const` in the same file also works), or ignore this warning.\"\n });\n }\n if (!read.slug) continue;\n const earlier = first.get(read.slug);\n if (earlier) {\n result.findings.push({\n check: \"cms-duplicate-customization\",\n severity: \"error\",\n table: read.slug,\n file: read.file,\n line: read.line,\n path: label,\n message: `${label} is written twice: here and in ${earlier.file}:${earlier.line}. The panel refuses to start with both.`,\n fix: \"Merge them into one `customizeTable` call and remove the other.\"\n });\n continue;\n }\n first.set(read.slug, read);\n const table = bySlug.get(read.slug);\n if (!table) {\n const guess = closest(read.slug, bySlug.keys());\n result.findings.push({\n check: \"cms-unknown-table\",\n severity: \"error\",\n table: read.slug,\n file: read.file,\n line: read.line,\n path: label,\n message: `${label} customizes \"${read.slug}\", which no table in the schema declares as its slug. The panel ignores it.`,\n fix: guess\n ? `Did you mean \"${guess}\"? The first argument is the table's slug (its \\`defineTable\\` name, unless it sets \\`slug\\`).`\n : \"Pass the slug of a table the schema index exports (its `defineTable` name, unless it sets `slug`), or remove the customization.\"\n });\n continue;\n }\n result.findings.push(...checkCustomization(read, table));\n }\n project.removeSourceFile(sf);\n }\n const unmounted = uiConfigNotMounted(tsm, project, projectRoot, dir);\n if (unmounted) result.findings.push(unmounted);\n }\n return result;\n}\n\n/**\n * The `cms-ui-config-not-mounted` finding for one customization directory, or\n * nothing. Undecided — no `<RebaseCMS>` element found under `src/` (mounted\n * through a wrapper, rendered without JSX) — is nothing, not a warning.\n */\nfunction uiConfigNotMounted(tsm: TsMorph, project: Project, projectRoot: string, cmsDir: string): CmsFinding | undefined {\n const uiConfig = path.join(cmsDir, UI_CONFIG_FILE);\n if (!fs.existsSync(uiConfig)) return undefined;\n const N = tsm.Node;\n const { SyntaxKind } = tsm;\n const mounts: { file: string; line: number; passes: boolean }[] = [];\n for (const file of sourceFiles(path.dirname(cmsDir))) {\n const text = fs.readFileSync(file, \"utf-8\");\n if (!text.includes(MOUNT)) continue;\n const sf = project.createSourceFile(file, text, { overwrite: true });\n const names = new Set<string>();\n for (const declaration of sf.getImportDeclarations()) {\n if (declaration.getModuleSpecifierValue() !== CMS_PACKAGE) continue;\n for (const named of declaration.getNamedImports()) {\n if (named.getName() === MOUNT) names.add(named.getAliasNode()?.getText() ?? MOUNT);\n }\n }\n const elements = [\n ...sf.getDescendantsOfKind(SyntaxKind.JsxOpeningElement),\n ...sf.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement)\n ];\n for (const element of elements) {\n if (!names.has(element.getTagNameNode().getText())) continue;\n const passes = element.getAttributes().some(attribute =>\n N.isJsxSpreadAttribute(attribute) || attribute.getNameNode().getText() === \"uiConfig\");\n mounts.push({ file: path.relative(projectRoot, file), line: element.getStartLineNumber(), passes });\n }\n project.removeSourceFile(sf);\n }\n if (mounts.length === 0 || mounts.some(mount => mount.passes)) return undefined;\n const [first] = mounts;\n return {\n check: \"cms-ui-config-not-mounted\",\n severity: \"warning\",\n file: first.file,\n line: first.line,\n message: `${path.relative(projectRoot, uiConfig)} holds what the collection editor saves in development, but \\`<RebaseCMS>\\` is not given it: ` +\n \"presentation edited in the editor is gone after a reload and never ships.\",\n fix: `Import it and pass it: \\`import uiConfig from \"./cms/${UI_CONFIG_FILE}\";\\` and \\`<RebaseCMS … uiConfig={uiConfig} />\\` ` +\n \"(the frontend's tsconfig needs `resolveJsonModule`).\"\n };\n}\n\n/**\n * `cms-backend-guard-missing`, one per frontend whose Vite config does not use\n * the guard. Nothing for a frontend the static read cannot decide.\n */\nasync function backendGuardFindings(projectRoot: string): Promise<CmsFinding[]> {\n return (await backendGuardStates(projectRoot))\n .filter(state => state.state === \"missing\")\n .map(state => ({\n check: \"cms-backend-guard-missing\",\n severity: \"error\",\n file: state.viteConfig,\n line: state.line,\n message: backendGuardMissingMessage(state),\n fix: BACKEND_GUARD_FIX\n }));\n}\n","/**\n * CLI command: rebase verify\n *\n * One command that says whether the tables are safe to ship, fast enough to\n * run after every edit. An agent editing `backend/schema/*.ts` gets a table\n * definition wrong — a relation to a table the index does not export, an\n * `rls: \"inherit\"` with no `defaultRls`, a table with no primary key — or\n * writes rules that hand every row of a per-user table to everyone; each of\n * those used to surface late: at boot, in review, or never. The project's\n * Claude Code hook (written by `rebase init` and `rebase skills --hooks`) runs\n * this after each edit to a schema file, and CI runs it on every push.\n *\n * Five steps, each reported on its own:\n *\n * 1. **Table definitions** — `backend/schema` loads and compiles through\n * `loadBackendSchema`, the loader the backend boots from, so every problem\n * it would refuse to boot on is a finding here, one per problem.\n * 2. **RLS coverage** — a table with a `user_id` / `owner_id` /\n * `organization_id` / `tenant_id` column whose rules (its own, or the\n * `defaultRls` it inherits) let a role read every row regardless of it.\n * `rls` itself is mandatory, so \"no rules at all\" is a step-1 error now.\n * And every compiled policy Postgres would refuse to expand (42P17): a\n * rule that reads its own table in a sub-select, or tables whose rules\n * read each other — `checkPolicyRecursion`.\n * 3. **CMS customizations** — every `customizeTable(...)` under\n * `frontend/src/cms`, read statically (`verify-cms.ts`): a slug no table\n * declares, a field that is not a column or relation of its table, a\n * required column kept off the form, one table customized twice. A\n * project without `frontend/src/cms` (headless) skips it.\n * 4. **Migration freshness** — whether `drizzle/migrations` still builds the\n * tables and columns the schema declares (offline), and with `--live`\n * whether the database has applied every migration.\n * 5. **Live RLS audit** — with `--live`, the `@rebasepro/rls-check` catalogue\n * against the project's database, resolved as `db *` resolves it (the\n * managed one unless something names another).\n *\n * `--json` prints one object an agent can act on: every finding carries the\n * file, the dotted path into the table and the fix.\n */\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport {\n adminRequestRoleFor,\n parseEnvBoolean,\n REBASE_ADMIN_REQUEST_ROLE,\n REBASE_ADMIN_ROLE,\n type SecurityRule,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport { isSchemaDefinitionError } from \"@rebasepro/common\";\nimport type { PolicyRecursion } from \"@rebasepro/rls-check\";\nimport type { PlannedPolicy } from \"@rebasepro/server-postgres\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { failAsJson, findBackendDir, getActiveBackendPlugin, readEnvFile, requireProjectRoot } from \"../utils/project\";\nimport { SCHEMA_DIR_FLAG_HELP, missingSchemaDir, refuseRemovedCollectionsFlag } from \"../utils/path-flags\";\nimport { resolveSchemaDir } from \"../utils/schema-dir\";\nimport { loadProjectSchema, type ModuleAliases, type ProjectSchema } from \"../utils/project-schema\";\nimport { checkCmsCustomizations } from \"./verify-cms\";\n\n/** The flags `rebase verify` takes. */\nexport const VERIFY_FLAGS = {\n \"--schema-dir\": String,\n \"--json\": Boolean,\n \"--quiet\": Boolean,\n \"-q\": \"--quiet\",\n \"--live\": Boolean,\n \"--database-url\": String,\n \"--docker\": Boolean\n} as const;\n\nconst VERIFY_FLAG_HELP: Record<string, string> = {\n \"--schema-dir\": SCHEMA_DIR_FLAG_HELP,\n \"--json\": \"Print one JSON object: every step, and every finding with its file, path and fix\",\n \"--quiet, -q\": \"Print nothing when everything passes; only the problems when something fails\",\n \"--live\": \"Also connect to the project's database: check migrations are applied and run the rls-check audit\",\n \"--database-url\": \"With --live: audit this database instead of the project's\",\n \"--docker\": \"With --live: use the database from docker compose, starting it if needed\"\n};\n\nexport type VerifyStepId = \"schema\" | \"rls\" | \"cms\" | \"migrations\" | \"live\";\n\nexport interface VerifyFinding {\n step: VerifyStepId;\n /** Stable, kebab-case: what kind of problem. An agent can branch on it. */\n check: string;\n severity: \"error\" | \"warning\";\n message: string;\n /** What to change, when there is one thing to change. */\n fix?: string;\n /** The table's slug. */\n table?: string;\n /** The file to open, relative to the project root. */\n file?: string;\n /** The line in {@link file}, when the finding points at one. */\n line?: number;\n /** Dotted path into the table definition — `posts.rls[0]`, `posts.author`. */\n path?: string;\n}\n\nexport interface VerifyStep {\n id: VerifyStepId;\n title: string;\n status: \"passed\" | \"failed\" | \"warnings\" | \"skipped\";\n /** Why a step was skipped, or what it covered. */\n detail?: string;\n}\n\nexport interface VerifyReport {\n ok: boolean;\n /** The schema directory, relative to the project root. */\n schemaDir: string;\n steps: VerifyStep[];\n findings: VerifyFinding[];\n summary: { errors: number; warnings: number };\n}\n\nexport interface VerifyOptions {\n projectRoot: string;\n /** The schema directory, absolute. */\n schemaDir: string;\n /** The backend package, where `drizzle/migrations` lives. Null for a project without one. */\n backendDir: string | null;\n live: boolean;\n databaseUrl?: string;\n /** Why no `databaseUrl` could be resolved for `--live`, when resolving it failed. */\n databaseUnavailable?: string;\n /**\n * Whether the backend refuses a request with no token (`AUTH_REQUIRE`, on\n * unless set to `false`). Decides how a Rebase-compiled public read reads.\n * Defaults to true, the runtime's default.\n */\n authRequired?: boolean;\n /** Module specifiers mapped to files when importing the schema (in-repo runs and tests). */\n moduleAliases?: ModuleAliases;\n}\n\nconst STEP_TITLES: Record<VerifyStepId, string> = {\n schema: \"Table definitions\",\n rls: \"RLS coverage\",\n cms: \"CMS customizations\",\n migrations: \"Migration freshness\",\n live: \"Live RLS audit\"\n};\n\n/**\n * Columns that say \"this row belongs to someone\". A table carrying one and\n * served without a row filter is the classic multi-tenant leak.\n */\nconst OWNER_COLUMNS: readonly string[] = [\"user_id\", \"owner_id\", \"organization_id\", \"tenant_id\"];\n\nconst MODULE_EXTENSIONS = [\".ts\", \".mts\", \".js\", \".mjs\"] as const;\n\n// ─── Step 1: table definitions ────────────────────────────────────────────────\n\n/** The schema as far as the later steps need it: the compiled tables, and where each one is written. */\ninterface VerifiedSchema {\n schema: ProjectSchema;\n descriptors: TableDescriptor[];\n /** The file each table is written in, by slug, relative to the project root. */\n files: Map<string, string>;\n}\n\n/**\n * Where a table is written, as far as the files say without running them:\n * the conventional `<schema>/<name>.ts` (or its slug, or its SQL name), else\n * the index that exports it.\n */\nfunction tableFile(projectRoot: string, schemaDir: string, indexFile: string, names: readonly string[]): string | undefined {\n for (const name of names) {\n for (const extension of MODULE_EXTENSIONS) {\n const candidate = path.join(schemaDir, `${name}${extension}`);\n if (fs.existsSync(candidate)) return path.relative(projectRoot, candidate);\n }\n }\n return indexFile ? path.relative(projectRoot, indexFile) : undefined;\n}\n\n/**\n * Load the schema the way the backend boots from it. A schema that does not\n * load or does not compile is a set of findings, not a crash — after an\n * agent's edit it is the most likely problem of all.\n */\nasync function loadSchema(\n options: VerifyOptions\n): Promise<{ verified: VerifiedSchema; failures: [] } | { verified: null; failures: VerifyFinding[] }> {\n const relative = (file: string) => path.relative(options.projectRoot, file);\n const indexOf = (): string => MODULE_EXTENSIONS\n .map(extension => path.join(options.schemaDir, `index${extension}`))\n .find(candidate => fs.existsSync(candidate)) ?? \"\";\n try {\n const schema = await loadProjectSchema(options.projectRoot, options.schemaDir, options.moduleAliases);\n const descriptors = schema.compiled.descriptors;\n const files = new Map<string, string>();\n for (const descriptor of descriptors) {\n const file = tableFile(options.projectRoot, options.schemaDir, schema.loaded.indexFile,\n [descriptor.name, descriptor.slug, descriptor.table]);\n if (file) files.set(descriptor.slug, file);\n }\n return { verified: { schema, descriptors, files }, failures: [] };\n } catch (error) {\n if (isSchemaDefinitionError(error)) {\n const index = indexOf();\n return {\n verified: null,\n failures: error.problems.map((problem): VerifyFinding => {\n const file = tableFile(options.projectRoot, options.schemaDir, index, [problem.table]);\n return {\n step: \"schema\",\n check: \"schema-definition\",\n severity: \"error\",\n table: problem.table,\n ...(file && { file }),\n path: problem.key ? `${problem.table}.${problem.key}` : problem.table,\n message: problem.message,\n fix: \"Change the definition as the message says. The backend refuses to boot on the same schema.\"\n };\n })\n };\n }\n const file = typeof error === \"object\" && error !== null && \"file\" in error && typeof error.file === \"string\"\n ? relative(error.file)\n : undefined;\n return {\n verified: null,\n failures: [{\n step: \"schema\",\n check: \"schema-load\",\n severity: \"error\",\n ...(file && { file }),\n message: error instanceof Error ? error.message : String(error),\n fix: \"Fix the module as the message says. The backend refuses to boot on the same files.\"\n }]\n };\n }\n}\n\n// ─── Step 2: RLS coverage ─────────────────────────────────────────────────────\n\n/** Whether a rule applies to reads. */\nfunction coversSelect(rule: SecurityRule): boolean {\n const operations = rule.operations ?? [rule.operation ?? \"all\"];\n return operations.includes(\"select\") || operations.includes(\"all\");\n}\n\n/**\n * A permissive read rule with no row filter: every row, to everyone the rule\n * names. `access: \"public\"` is the same thing said on purpose, so it is not\n * this; `roles: [\"admin\"]` restates the default admin read and adds nothing.\n */\nfunction isUnfilteredRead(rule: SecurityRule): boolean {\n if (!coversSelect(rule) || rule.mode === \"restrictive\") return false;\n if (rule.access === \"public\" || rule.ownerField || rule.condition) return false;\n if (rule.using !== undefined && !/^\\s*\\(?\\s*true\\s*\\)?\\s*$/i.test(rule.using)) return false;\n // A write-only check (`withCheck` with no `using`) filters nothing on read,\n // and it is not a read rule either.\n if (rule.using === undefined && rule.withCheck !== undefined) return false;\n const roles = rule.roles ?? [];\n return !(roles.length > 0 && roles.every(role => role === \"admin\"));\n}\n\n/** A read rule that returns every row to someone: an unfiltered one, or `access: \"public\"`. */\nfunction opensEveryRow(rule: SecurityRule): boolean {\n return isUnfilteredRead(rule) || (rule.access === \"public\" && coversSelect(rule) && rule.mode !== \"restrictive\");\n}\n\nfunction describeRuleTarget(rule: Pick<SecurityRule, \"roles\">): string {\n return rule.roles?.length ? `role${rule.roles.length > 1 ? \"s\" : \"\"} ${rule.roles.map(r => `\"${r}\"`).join(\", \")}` : \"every signed-in user\";\n}\n\nfunction checkRls(verified: VerifiedSchema): VerifyFinding[] {\n const findings: VerifyFinding[] = [];\n const defaultsFile = verified.schema.loaded.indexFile\n ? path.basename(verified.schema.loaded.indexFile)\n : \"the schema index\";\n for (const table of verified.descriptors) {\n // A view takes the policies of the tables it reads; the auth table gets\n // a self-read policy and an admin-only write gate from the framework.\n if (table.kind !== \"table\" || table.auth) continue;\n // `\"admin-only\"`, declared or inherited, is a posture said on purpose.\n if (table.rls.posture !== \"rules\") continue;\n // A tenant-scoped table is filtered by the tenant policy before any rule.\n if (table.tenant) continue;\n\n const owner = table.columns.find(column => OWNER_COLUMNS.includes(column.column));\n if (!owner) continue;\n\n const slug = table.slug;\n const file = verified.files.get(slug);\n const ownerField = owner.column;\n const perUser = ownerField === \"user_id\" || ownerField === \"owner_id\";\n const fix = perUser\n ? `Give it rules of its own: \\`rls: [{ operation: \"all\", ownerField: \"${ownerField}\" }]\\` so each user reaches only their own rows. ` +\n \"A table meant to be readable by everyone says so on the table: `{ operation: \\\"select\\\", access: \\\"public\\\" }`.\"\n : `Scope it with \\`tenant: { field: \"${owner.key}\", from: { claim: \"${ownerField}\" } }\\` (the claim that carries the caller's tenant), ` +\n \"plus the `rls` rules that grant access inside a tenant — e.g. `[{ operation: \\\"select\\\", access: \\\"public\\\" }]`.\";\n\n if (table.rls.inherited) {\n const opening = table.rls.rules.find(opensEveryRow);\n if (!opening) continue;\n // `defaultRls` is written for every table. On a tenant column,\n // inheriting an all-rows read is the cross-tenant leak; on a per-user\n // column it is often a public profile or author list, so it is said,\n // not failed.\n findings.push({\n step: \"rls\",\n check: perUser ? \"rls-inherited-read\" : \"rls-inherited-tenant-read\",\n severity: perUser ? \"warning\" : \"error\",\n table: slug,\n ...(file && { file }),\n path: `${slug}.rls`,\n message: `\"${slug}\" has a \\`${ownerField}\\` column and \\`rls: \"inherit\"\\`, so it takes \\`defaultRls\\` from ${defaultsFile}, ` +\n `which lets ${describeRuleTarget(opening)} read every row regardless of \\`${ownerField}\\`.`,\n fix\n });\n continue;\n }\n\n table.rls.rules.forEach((rule, index) => {\n if (!isUnfilteredRead(rule)) return;\n findings.push({\n step: \"rls\",\n check: \"rls-unfiltered-read\",\n severity: \"warning\",\n table: slug,\n ...(file && { file }),\n path: `${slug}.rls[${index}]`,\n message: `\"${slug}\" has a \\`${ownerField}\\` column, and rls[${index}] lets ${describeRuleTarget(rule)} read every row of it with no row filter.`,\n fix: `Filter the rule — \\`ownerField: \"${ownerField}\"\\` or a \\`condition\\` — or, if every row really is meant for ${describeRuleTarget(rule)}, keep it and ignore this warning.`\n });\n });\n }\n return findings;\n}\n\n// ─── Step 2, continued: policies Postgres refuses to expand ───────────────────\n\n/** How the statements a policy of this command guards read in a finding. */\nfunction statementsOf(command: PolicyRecursion[\"command\"], table: string): string {\n switch (command) {\n case \"INSERT\": return `every insert into ${table}`;\n case \"UPDATE\": return `every update of ${table}`;\n case \"DELETE\": return `every delete from ${table}`;\n case \"SELECT\": return `every read of ${table}`;\n default: return `every read and write of ${table}`;\n }\n}\n\nconst qualifiedName = (at: { schema: string; table: string }): string => `${at.schema}.${at.table}`;\n\n/**\n * Where the rule a policy compiles from is written: `rls[i]` of its table, the\n * `defaultRls` rule it inherits, or — for a policy Rebase derives (a junction's,\n * the admin baseline) — the table alone.\n */\nfunction ruleLocation(\n descriptor: TableDescriptor | undefined,\n planned: PlannedPolicy | undefined,\n recursion: PolicyRecursion\n): { path: string; label: string } {\n if (!descriptor) return { path: recursion.table, label: `policy \"${recursion.policy}\" of the junction table` };\n const slug = descriptor.slug;\n const fallback = { path: `${slug}.rls`, label: `policy \"${recursion.policy}\"` };\n if (!planned || planned.injected || descriptor.rls.posture !== \"rules\") return fallback;\n const rules = descriptor.rls.rules;\n const index = planned.ruleKey.startsWith(\"#\")\n ? Number(planned.ruleKey.slice(1))\n : rules.findIndex(rule => rule.name === planned.ruleKey);\n if (!Number.isInteger(index) || index < 0 || index >= rules.length) return fallback;\n return descriptor.rls.inherited\n ? { path: `${slug}.rls`, label: `the rule it inherits from \\`defaultRls\\` (defaultRls[${index}])` }\n : { path: `${slug}.rls[${index}]`, label: `rls[${index}]` };\n}\n\n/** One loop, in words: what the policy reads, and how that leads back to its table. */\nfunction describeLoop(recursion: PolicyRecursion): string {\n const home = qualifiedName(recursion);\n if (recursion.path.length === 1) return `its own table, ${home}, in a sub-select`;\n const through = recursion.path.slice(1).map((step, i, steps) => {\n const next = i + 1 < steps.length ? qualifiedName(steps[i + 1]) : home;\n return `whose read policy \"${step.policy}\" reads ${next}`;\n });\n return `${qualifiedName(recursion.reads)} in a sub-select, ${through.join(\", \")} back`;\n}\n\n/**\n * The tables' policies, compiled as the boot writes them, read for a loop\n * Postgres refuses to expand: a rule that reads its own table in a\n * sub-select, or two tables whose rules read each other. Since 0.25 every\n * `rebase.uid()` is compiled to `(SELECT rebase.uid())` and the admin policies\n * are sub-selects as well, so such a rule fails on every statement it guards,\n * with 42P17 — for users, the service key and `dataAsAdmin` alike — where it\n * worked on 0.21. The analysis is `findPolicyRecursion` from\n * `@rebasepro/rls-check`, over the compiled SQL rather than the rules, so a\n * structured `existsIn` and a junction's derived policy are read as well as\n * raw SQL.\n */\nasync function checkPolicyRecursion(verified: VerifiedSchema): Promise<VerifyFinding[]> {\n const { planPolicyDefinitions, REBASE_USER_ROLE } = await import(\"@rebasepro/server-postgres\");\n const { findPolicyRecursion } = await import(\"@rebasepro/rls-check\");\n let policies: PlannedPolicy[];\n try {\n // A database the boot made both admin roles on: every policy, every companion.\n policies = planPolicyDefinitions(verified.schema.compiled.tables, { adminRequestRoleAvailable: true });\n } catch (error) {\n return [{\n step: \"rls\",\n check: \"rls-policy-plan\",\n severity: \"error\",\n message: `The rules do not compile to policies: ${error instanceof Error ? error.message : String(error)}`,\n fix: \"Change the rules as the message says. The boot and `rebase db push` compile the same policies, and refuse them the same way.\"\n }];\n }\n\n // The two roles a request runs as: the request role, and the admin request\n // role that inherits it with both admin roles. The server context holds\n // `rebase_admin` alone, a subset of the second.\n const adminRequestRole = adminRequestRoleFor(REBASE_USER_ROLE);\n const recursions = findPolicyRecursion(policies, {\n contexts: [\n { name: REBASE_USER_ROLE, roles: [REBASE_USER_ROLE] },\n { name: adminRequestRole, roles: [adminRequestRole, REBASE_USER_ROLE, REBASE_ADMIN_ROLE, REBASE_ADMIN_REQUEST_ROLE] }\n ],\n // The search path Rebase pins on its connections, which the boot creates the policies under.\n searchPath: [\"public\"]\n });\n\n // One finding per policy, in the order the tables and their rules are written.\n const order = (at: { schema: string; table: string; policy: string }): number =>\n policies.findIndex(p => p.schema === at.schema && p.table === at.table && p.name === at.policy);\n const byPolicy = new Map<number, PolicyRecursion[]>();\n for (const recursion of recursions) {\n const at = order(recursion);\n byPolicy.set(at, [...(byPolicy.get(at) ?? []), recursion]);\n }\n\n return [...byPolicy.entries()].sort(([a], [b]) => a - b).map(([at, loops]): VerifyFinding => {\n const [first] = loops;\n const descriptor = verified.descriptors.find(d => d.kind === \"table\" && d.schema === first.schema && d.table === first.table);\n const planned: PlannedPolicy | undefined = policies[at];\n const { path: rulePath, label } = ruleLocation(descriptor, planned, first);\n const slug = descriptor?.slug ?? first.table;\n const file = descriptor ? verified.files.get(slug) : undefined;\n const home = qualifiedName(first);\n const certain = loops.some(loop => loop.confidence === \"certain\");\n // An admin request is subject to every policy a user's request is, and\n // more, so a loop a user's request closes closes for admins too.\n const who = loops.some(loop => loop.contexts.includes(REBASE_USER_ROLE))\n ? \"\"\n : \" for admin requests (the service key, `dataAsAdmin` and admin users)\";\n const caveats = certain ? [] : [...new Set(loops.flatMap(loop => loop.caveats))];\n const readTables = [...new Set(loops.map(loop => qualifiedName(loop.reads)))];\n return {\n step: \"rls\",\n check: \"rls-policy-recursion\",\n severity: certain ? \"error\" : \"warning\",\n table: slug,\n ...(file && { file }),\n path: rulePath,\n message: `\"${slug}\" ${label} (${first.command.toLowerCase()}) reads ${loops.map(describeLoop).join(\"; it also reads \")}, ` +\n `so Postgres refuses ${statementsOf(first.command, home)}${who} with 42P17 ` +\n `(infinite recursion detected in policy for relation \"${first.table}\"). ` +\n \"Before 0.25 such a rule could pass: since then the compiler writes `rebase.uid()` as `(SELECT rebase.uid())` and the admin policies as sub-selects, \" +\n \"so a table's own policies contain a sub-select even where its rules have none.\" +\n (caveats.length > 0 ? ` Not certain: ${caveats.join(\" \")}` : \"\"),\n fix: `Move the read of ${readTables.join(\" and \")} into a \\`SECURITY DEFINER\\` function, which Postgres does not expand while it applies policies, ` +\n \"and call that function from the rule — e.g. `CREATE FUNCTION public.can_access(…) RETURNS boolean LANGUAGE sql STABLE SECURITY DEFINER \" +\n `SET search_path = '' AS $$ SELECT EXISTS (SELECT 1 FROM ${readTables[0]} …) $$\\`, then \\`using: \"public.can_access(…)\"\\`. ` +\n \"Leave the policies Rebase generates as they are.\"\n };\n });\n}\n\n// ─── Step 3: migration freshness ──────────────────────────────────────────────\n\nconst POSTGRES_PLUGIN = \"@rebasepro/server-postgres\";\n\n/** One row of `rebase.atlas_schema_revisions`, as far as \"applied\" needs it. */\nexport interface AppliedRevision {\n version: string;\n /** Atlas's revision type, a bit set: 1 baseline, 2 executed, 4 resolved (`migrate set`). */\n type: number;\n}\n\n/** Atlas's baseline bit in `atlas_schema_revisions.type`. */\nconst REVISION_TYPE_BASELINE = 1;\n\n/**\n * The migration files the database has not run, as Atlas's own `migrate status`\n * counts them.\n *\n * A file is applied when its version has a row, or when it is at or behind the\n * newest *baseline* row: `migrate apply --baseline V` records V alone, and\n * means \"everything up to V is already here\". `rebase db migrate --baseline` is\n * what the CLI prescribes for a booted database, so set membership alone\n * reported the earlier migrations of every baselined database as not applied —\n * and prescribed `rebase db migrate`, which answers \"No migration files to\n * execute\". That run failed forever.\n */\nexport function pendingMigrations(\n files: readonly string[],\n revisions: readonly AppliedRevision[],\n compare: (a: string, b: string) => number,\n versionOf: (file: string) => string\n): string[] {\n const recorded = new Set(revisions.map(row => row.version));\n const baseline = revisions\n .filter(row => (Number(row.type) & REVISION_TYPE_BASELINE) !== 0)\n .map(row => row.version)\n .reduce<string | null>((newest, version) => (newest === null || compare(version, newest) > 0 ? version : newest), null);\n return files.filter((file) => {\n const version = versionOf(file);\n if (recorded.has(version)) return false;\n return baseline === null || compare(version, baseline) > 0;\n });\n}\n\nasync function checkMigrations(\n options: VerifyOptions,\n verified: VerifiedSchema,\n step: VerifyStep\n): Promise<VerifyFinding[]> {\n const skip = (detail: string): VerifyFinding[] => {\n step.status = \"skipped\";\n step.detail = detail;\n return [];\n };\n if (!options.backendDir) return skip(\"no backend/ directory\");\n const plugin = getActiveBackendPlugin(options.backendDir);\n if (plugin !== POSTGRES_PLUGIN) {\n return skip(`migrations are checked for ${POSTGRES_PLUGIN} projects${plugin ? `; this one uses ${plugin}` : \"\"}`);\n }\n const migrationsDir = path.join(options.backendDir, \"drizzle\", \"migrations\");\n const files = fs.existsSync(migrationsDir)\n ? fs.readdirSync(migrationsDir).filter(f => f.endsWith(\".sql\")).sort()\n : [];\n if (files.length === 0) {\n return skip(\"no migrations yet — the schema is applied with `rebase db push`; `rebase db generate` starts versioned migrations\");\n }\n\n const relativeDir = path.relative(options.projectRoot, migrationsDir);\n const { findUnmigratedSchema } = await import(\"@rebasepro/server-postgres\");\n const findings: VerifyFinding[] = [];\n const fix = \"Run `rebase db generate` to write the migration, then `rebase db migrate` to apply it.\";\n\n let changes: ReturnType<typeof findUnmigratedSchema>;\n try {\n changes = findUnmigratedSchema(\n verified.schema.compiled.tables,\n files.map(f => fs.readFileSync(path.join(migrationsDir, f), \"utf-8\"))\n );\n } catch (error) {\n return [{\n step: \"migrations\",\n check: \"migration-plan\",\n severity: \"error\",\n message: `Could not derive the SQL schema from the tables: ${error instanceof Error ? error.message : String(error)}`,\n fix: \"`rebase schema generate` reports the same problem with more context.\"\n }];\n }\n\n for (const change of changes) {\n const where = change.column ? `${change.table}.${change.column}` : change.table;\n const message = change.kind === \"missing-table\"\n ? `Table ${where} is declared in the schema but no migration in ${relativeDir} creates it.`\n : change.kind === \"missing-column\"\n ? `Column ${where} is declared in the schema but no migration in ${relativeDir} adds it.`\n : `Column ${where} is no longer declared in the schema, but the migrations in ${relativeDir} still create it.`;\n const file = change.slug ? verified.files.get(change.slug) : undefined;\n findings.push({\n step: \"migrations\",\n check: change.kind === \"removed-column\" ? \"migration-stale-column\" : \"migration-missing\",\n severity: \"error\",\n message,\n fix,\n ...(change.slug && { table: change.slug }),\n ...(file && { file })\n });\n }\n\n step.detail = `${files.length} migration${files.length === 1 ? \"\" : \"s\"} in ${relativeDir}`;\n\n if (options.live && options.databaseUrl) {\n findings.push(...await checkAppliedMigrations(options.databaseUrl, files));\n }\n return findings;\n}\n\n/** Which migration files the database has not run, from Atlas's revision table. */\nasync function checkAppliedMigrations(databaseUrl: string, files: string[]): Promise<VerifyFinding[]> {\n const pg = await import(\"pg\");\n const client = new pg.default.Client({ connectionString: databaseUrl, connectionTimeoutMillis: 5_000 });\n try {\n await client.connect();\n const present = await client.query<{ present: boolean }>(\n \"SELECT to_regclass('rebase.atlas_schema_revisions') IS NOT NULL AS present\"\n );\n if (!present.rows[0]?.present) {\n return [{\n step: \"migrations\",\n check: \"migration-unapplied\",\n severity: \"warning\",\n message: \"The database has no migration history (rebase.atlas_schema_revisions) — it was provisioned with `rebase db push`, or never migrated.\",\n fix: \"`rebase db migrate --baseline <version>` adopts an existing database; `rebase db migrate` applies the migrations to a new one.\"\n }];\n }\n const applied = await client.query<{ version: string; type: string | number }>(\n \"SELECT version, type FROM rebase.atlas_schema_revisions WHERE error IS NULL OR error = ''\"\n );\n const { compareMigrationVersions, migrationVersionOf } = await import(\"@rebasepro/server-postgres\");\n const pending = pendingMigrations(\n files,\n applied.rows.map(row => ({ version: row.version, type: Number(row.type) })),\n compareMigrationVersions,\n migrationVersionOf\n );\n if (pending.length === 0) return [];\n return [{\n step: \"migrations\",\n check: \"migration-unapplied\",\n severity: \"error\",\n message: `${pending.length} migration${pending.length === 1 ? \" has\" : \"s have\"} not been applied to the database: ${pending.join(\", \")}.`,\n fix: \"Run `rebase db migrate`.\"\n }];\n } catch (error) {\n return [{\n step: \"migrations\",\n check: \"migration-unapplied\",\n severity: \"warning\",\n message: `Could not read the database's migration history: ${error instanceof Error ? error.message : String(error)}`\n }];\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n// ─── Step 4: live RLS audit ───────────────────────────────────────────────────\n\n/** rls-check's severities, folded onto this command's two. `info` is not reported. */\nfunction liveSeverity(severity: string): VerifyFinding[\"severity\"] | null {\n if (severity === \"critical\" || severity === \"high\") return \"error\";\n if (severity === \"medium\" || severity === \"low\") return \"warning\";\n return null;\n}\n\n/**\n * Why the database `--live` was pointed at cannot be opened, or `null` when it\n * can. Asked once, before the live steps, so an unreachable database is one\n * error rather than a skipped audit and a migration warning: under `--live`\n * the audit was asked for, and a CI run in which it never ran is not green.\n */\nasync function databaseUnreachable(databaseUrl: string): Promise<string | null> {\n const pg = await import(\"pg\");\n const client = new pg.default.Client({ connectionString: databaseUrl, connectionTimeoutMillis: 5_000 });\n try {\n await client.connect();\n return null;\n } catch (error) {\n return error instanceof Error ? error.message : String(error);\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/**\n * A `USING (true)` read policy Rebase compiled from an `access: \"public\"`\n * select rule, on a backend that refuses a request with no token.\n *\n * rls-check reads the policy alone, and for the role every signed-in request\n * runs as it is \"every row to everyone\": critical. But the API answers 401\n * before RLS is consulted unless `AUTH_REQUIRE=false`, so what it grants is\n * every row to every *signed-in* user — exactly what step 2 accepts as a rule\n * said on purpose, and what boot reports as an info line. A fresh blog\n * scaffold failed its own `verify --live` with three such errors. It is a\n * warning here, as an unfiltered read is in step 2; with `AUTH_REQUIRE=false`\n * the rows really are public and it stays an error.\n */\nfunction isTokenGatedPublicRead(\n finding: { id: string; target: { table?: string; policy?: string } },\n authRequired: boolean,\n isGeneratedPolicyName: (name: string, table: string) => boolean\n): boolean {\n if (!authRequired || finding.id !== \"policy-always-true\") return false;\n const { table, policy } = finding.target;\n if (!table || !policy) return false;\n return isGeneratedPolicyName(policy, table) && policy.startsWith(`${table}_select_`);\n}\n\nasync function checkLive(databaseUrl: string, step: VerifyStep, authRequired: boolean): Promise<VerifyFinding[]> {\n const { scan, CHECKS } = await import(\"@rebasepro/rls-check\");\n const { isGeneratedPolicyName } = await import(\"@rebasepro/server-postgres\");\n let result: Awaited<ReturnType<typeof scan>>;\n try {\n result = await scan({ connectionString: databaseUrl, statementTimeoutMs: 10_000 });\n } catch (error) {\n step.detail = \"the audit did not run\";\n return [{\n step: \"live\",\n check: \"live-scan-failed\",\n severity: \"error\",\n message: `The live RLS audit failed: ${error instanceof Error ? error.message : String(error)}`,\n fix: \"`npx @rebasepro/rls-check <database-url>` runs the same audit on its own and reports the failure in full.\"\n }];\n }\n step.detail = `${CHECKS.length} rls-check checks against ${result.database.host}/${result.database.name}`;\n\n const findings: VerifyFinding[] = [];\n for (const finding of result.findings) {\n const severity = liveSeverity(finding.severity);\n if (!severity) continue;\n const tokenGated = severity === \"error\" && isTokenGatedPublicRead(finding, authRequired, isGeneratedPolicyName);\n findings.push({\n step: \"live\",\n check: finding.id,\n severity: tokenGated ? \"warning\" : severity,\n message: tokenGated\n ? `${finding.title} — compiled from an \\`access: \"public\"\\` read rule: every signed-in user reads every row. ` +\n \"A request with no token is refused by the API (AUTH_REQUIRE is on), so it is not an anonymous read.\"\n : finding.title,\n ...(finding.fix && { fix: finding.fix }),\n path: finding.target.table ? `${finding.target.schema}.${finding.target.table}` : finding.target.schema\n });\n }\n for (const degraded of result.diagnostics.degraded) {\n findings.push({\n step: \"live\",\n check: \"rls-check-degraded\",\n severity: \"warning\",\n message: `The audit could not read ${degraded.what}: ${degraded.error}. A clean result does not cover it.`\n });\n }\n return findings;\n}\n\n// ─── The run ──────────────────────────────────────────────────────────────────\n\nfunction settle(step: VerifyStep, findings: VerifyFinding[]): VerifyStep {\n if (step.status === \"skipped\") return step;\n const mine = findings.filter(f => f.step === step.id);\n step.status = mine.some(f => f.severity === \"error\") ? \"failed\" : mine.length > 0 ? \"warnings\" : \"passed\";\n return step;\n}\n/**\n * Run every step and return the report. Prints nothing and never exits, so a\n * caller — the command, a test — decides what to do with it.\n */\nexport async function runVerify(options: VerifyOptions): Promise<VerifyReport> {\n const findings: VerifyFinding[] = [];\n const steps: VerifyStep[] = ([\"schema\", \"rls\", \"cms\", \"migrations\", \"live\"] as const).map(id => ({\n id,\n title: STEP_TITLES[id],\n status: \"passed\"\n }));\n const [schemaStep, rlsStep, cmsStep, migrationsStep, liveStep] = steps;\n const schemaDir = path.relative(options.projectRoot, options.schemaDir) || \".\";\n const skipAll = (detail: string): VerifyReport => {\n for (const step of steps) {\n step.status = \"skipped\";\n step.detail = detail;\n }\n return { ok: true, schemaDir, steps, findings, summary: { errors: 0, warnings: 0 } };\n };\n\n // No schema is a project that declares no tables — its API is introspected\n // from the database (a headless one). A skip, not a failure.\n if (!fs.existsSync(options.schemaDir) || !fs.statSync(options.schemaDir).isDirectory()) {\n return skipAll(`no schema directory at ${schemaDir}`);\n }\n\n const { verified, failures } = await loadSchema(options);\n findings.push(...failures);\n if (verified && !verified.schema.loaded.indexFile) {\n return skipAll(`${schemaDir} has no index.ts, so it declares no tables`);\n }\n\n if (verified) {\n const tables = verified.descriptors.length;\n schemaStep.detail = `${tables} table${tables === 1 ? \"\" : \"s\"}, compiled as the backend boots them`;\n rlsStep.detail = `${tables} table${tables === 1 ? \"\" : \"s\"}`;\n findings.push(...checkRls(verified));\n findings.push(...await checkPolicyRecursion(verified));\n const cms = await checkCmsCustomizations(options.projectRoot, verified.descriptors);\n if (cms.directories.length === 0) {\n cmsStep.status = \"skipped\";\n cmsStep.detail = \"no frontend/src/cms\";\n // A frontend without src/cms still builds without the backend guard.\n for (const finding of cms.findings) findings.push({ step: \"cms\", ...finding });\n } else {\n cmsStep.detail = `${cms.customizations} customization${cms.customizations === 1 ? \"\" : \"s\"} in ${cms.directories.join(\", \")}, read without running them`;\n for (const finding of cms.findings) findings.push({ step: \"cms\", ...finding });\n }\n } else {\n for (const step of [rlsStep, cmsStep]) {\n step.status = \"skipped\";\n step.detail = \"fix the table definitions first\";\n }\n }\n\n // The database the live steps read, once it is known to answer. Under\n // `--live` a database that is missing or does not answer is an error: the\n // audit was asked for, and exit 0 without it is a green CI run over nothing.\n let liveUrl: string | undefined;\n if (options.live) {\n if (!options.databaseUrl) {\n liveStep.detail = \"no database to audit\";\n findings.push({\n step: \"live\",\n check: \"live-no-database\",\n severity: \"error\",\n message: options.databaseUnavailable\n ? `--live was asked for, and the database could not be prepared: ${options.databaseUnavailable}`\n : \"--live was asked for, and no database is configured to audit.\",\n fix: \"Pass --database-url <url> (or set DATABASE_URL), or run without --live for the offline checks.\"\n });\n } else {\n const unreachable = await databaseUnreachable(options.databaseUrl);\n if (unreachable) {\n liveStep.detail = \"the database did not answer\";\n findings.push({\n step: \"live\",\n check: \"live-unreachable\",\n severity: \"error\",\n message: `--live was asked for, and the database could not be reached: ${unreachable}. Neither the migration check nor the RLS audit ran.`,\n fix: \"Check the database is running and the URL is right (`rebase db url` prints the one this project resolves), or run without --live for the offline checks.\"\n });\n } else {\n liveUrl = options.databaseUrl;\n }\n }\n }\n\n if (!verified) {\n migrationsStep.status = \"skipped\";\n migrationsStep.detail = \"fix the table definitions first\";\n } else {\n findings.push(...await checkMigrations({ ...options, databaseUrl: liveUrl }, verified, migrationsStep));\n }\n\n if (!options.live) {\n liveStep.status = \"skipped\";\n liveStep.detail = \"pass --live to audit the database\";\n } else if (liveUrl) {\n findings.push(...await checkLive(liveUrl, liveStep, options.authRequired ?? true));\n }\n\n steps.forEach(step => settle(step, findings));\n const errors = findings.filter(f => f.severity === \"error\").length;\n return {\n ok: errors === 0,\n schemaDir,\n steps,\n findings,\n summary: { errors, warnings: findings.length - errors }\n };\n}\n\n// ─── Output ───────────────────────────────────────────────────────────────────\n\nfunction printFinding(finding: VerifyFinding): void {\n const mark = finding.severity === \"error\" ? chalk.red(\"✗\") : chalk.yellow(\"!\");\n const file = finding.file && finding.line !== undefined ? `${finding.file}:${finding.line}` : finding.file;\n const where = [file, finding.path].filter(Boolean).join(\" → \");\n console.log(` ${mark} ${where ? `${chalk.bold(where)} ` : \"\"}${finding.message}`);\n if (finding.fix) console.log(chalk.gray(` fix: ${finding.fix}`));\n}\n\nfunction summaryLine(report: VerifyReport): string {\n const { errors, warnings } = report.summary;\n return `${errors} error${errors === 1 ? \"\" : \"s\"}, ${warnings} warning${warnings === 1 ? \"\" : \"s\"}`;\n}\n\nexport function printReport(report: VerifyReport, quiet: boolean): void {\n if (quiet) {\n if (report.findings.length === 0) return;\n if (!report.ok) console.log(chalk.red(`rebase verify: ${summaryLine(report)}`));\n for (const finding of report.findings) printFinding(finding);\n return;\n }\n\n console.log(\"\");\n console.log(` ${chalk.bold(\"rebase verify\")} ${chalk.gray(report.schemaDir)}`);\n console.log(\"\");\n for (const step of report.steps) {\n const mark = step.status === \"passed\" ? chalk.green(\"✓\")\n : step.status === \"failed\" ? chalk.red(\"✗\")\n : step.status === \"warnings\" ? chalk.yellow(\"!\")\n : chalk.gray(\"–\");\n const detail = step.detail ? chalk.gray(step.status === \"skipped\" ? `skipped: ${step.detail}` : step.detail) : \"\";\n console.log(` ${mark} ${step.title.padEnd(22)} ${detail}`);\n }\n if (report.findings.length > 0) {\n console.log(\"\");\n for (const finding of report.findings) printFinding(finding);\n }\n console.log(\"\");\n console.log(report.ok ? chalk.green(` ✓ ${summaryLine(report)}`) : chalk.red(` ✗ ${summaryLine(report)}`));\n console.log(\"\");\n}\n\nfunction printVerifyHelp(): void {\n console.log(`\n${chalk.bold(\"rebase verify\")} — Check the tables are safe to ship\n\n${chalk.green.bold(\"Usage\")}\n rebase verify [options]\n\n${chalk.green.bold(\"Options\")}\n${Object.entries(VERIFY_FLAG_HELP).map(([flag, help]) => ` ${chalk.blue(flag.padEnd(20))} ${help}`).join(\"\\n\")}\n\n${chalk.green.bold(\"Steps\")}\n 1. Table definitions backend/schema loads and compiles as the backend boots it\n 2. RLS coverage owner and tenant columns are filtered on by the rules that read them,\n and no rule reads its own table back through a sub-select (42P17)\n 3. CMS customizations frontend/src/cms: each customizeTable names a table, its fields, and a form that can create\n 4. Migration freshness drizzle/migrations builds every declared table and column\n 5. Live RLS audit with --live: the rls-check catalogue against the project's database\n\nExits 1 when any step reports an error; warnings do not fail. Under --live, a\ndatabase that is missing or does not answer is an error. Fast and offline\nwithout --live: for CI, and for the Claude Code hook that ${chalk.cyan(\"rebase skills --hooks\")} installs.\n`);\n}\n\n/**\n * Whether the backend refuses a request with no token: `AUTH_REQUIRE` from the\n * environment, else `.env`, read as every boolean env var is read\n * (`parseEnvBoolean`: `false`/`0`/`no`/`off` turn it off). On unless one of\n * those says otherwise — the runtime's default. Compared raw, `AUTH_REQUIRE=0`\n * read as \"on\", and a compiled public read was reported as token-gated on a\n * backend that serves it to anyone.\n */\nexport function authRequiredFrom(\n environment: Record<string, string | undefined>,\n envFile: Record<string, string | undefined>\n): boolean {\n return parseEnvBoolean(environment.AUTH_REQUIRE ?? envFile.AUTH_REQUIRE) !== false;\n}\n\n/**\n * The database `--live` audits, resolved as every other database door resolves\n * it (`db *`, `console`, `doctor`): `--database-url`, `DATABASE_URL`, `.env`,\n * `--docker` or the last `rebase dev --docker`, and otherwise the managed\n * development database — started if it is not running. Reading only\n * `DATABASE_URL` meant the audit never ran on a fresh scaffold, whose database\n * is the managed one.\n *\n * Progress goes to stderr, so `--json` keeps stdout to the report.\n */\nasync function resolveLiveDatabase(\n projectRoot: string,\n rawArgs: readonly string[],\n options: { flagUrl: string | null; flagDocker: boolean; quiet: boolean }\n): Promise<Pick<VerifyOptions, \"databaseUrl\" | \"databaseUnavailable\">> {\n try {\n const { ensureDockerDatabase, databaseUrlOf } = await import(\"./db\");\n await ensureDockerDatabase(projectRoot, rawArgs);\n const { prepareDatabaseEnv } = await import(\"../dev-db/prepare\");\n const prepared = await prepareDatabaseEnv(projectRoot, {\n flagUrl: options.flagUrl,\n flagDocker: options.flagDocker,\n quiet: options.quiet,\n onProgress: options.quiet ? undefined : (line) => console.error(chalk.gray(` ${line}`))\n });\n return { databaseUrl: databaseUrlOf(prepared, readEnvFile(projectRoot)) };\n } catch (error) {\n return { databaseUnavailable: error instanceof Error ? error.message : String(error) };\n }\n}\n\nexport async function verifyCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) {\n printVerifyHelp();\n return;\n }\n refuseRemovedCollectionsFlag(rawArgs.slice(2), \"verify\");\n const { flags } = parseCommandArgs({\n spec: VERIFY_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"verify\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n const backendDir = findBackendDir(projectRoot);\n const typedDir = flags[\"--schema-dir\"];\n if (typedDir) {\n // A mistyped path used to skip every step and print \"0 errors\" with\n // exit 0 — a green CI run over nothing. Refused as `doctor` and\n // `schema` refuse it. Without the flag, a project with no schema\n // directory (a headless one) is still a skip, not a failure.\n const refusal = missingSchemaDir(rawArgs, process.cwd(), backendDir ?? projectRoot, \"verify\");\n if (refusal) {\n if (flags[\"--json\"]) {\n failAsJson(\n `Schema directory not found: \"${typedDir}\" (resolved to ${path.resolve(process.cwd(), typedDir)}).`,\n \"schema_dir_not_found\",\n \"Leave --schema-dir out (backend/schema is the default), or pass a directory that exists; relative paths are resolved from where you run the command.\"\n );\n }\n console.error(\"\");\n for (const line of refusal) console.error(line);\n console.error(\"\");\n process.exit(1);\n }\n }\n const schemaDir = typedDir ? path.resolve(process.cwd(), typedDir) : resolveSchemaDir(projectRoot);\n const live = flags[\"--live\"] === true;\n const database = live\n ? await resolveLiveDatabase(projectRoot, rawArgs, {\n flagUrl: flags[\"--database-url\"] ?? null,\n flagDocker: flags[\"--docker\"] === true,\n quiet: flags[\"--quiet\"] === true\n })\n : {};\n\n const report = await runVerify({\n projectRoot,\n schemaDir,\n backendDir,\n live,\n ...database,\n authRequired: authRequiredFrom(process.env, readEnvFile(projectRoot))\n });\n\n if (flags[\"--json\"]) {\n console.log(JSON.stringify(report, null, 2));\n } else {\n printReport(report, flags[\"--quiet\"] === true);\n }\n if (!report.ok) process.exitCode = 1;\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,IAAM,cAAc;AACpB,IAAM,YAAY;;AAElB,IAAM,QAAQ;AACd,IAAM,iBAAiB;AACvB,IAAM,SAAS;AACf,IAAM,aAAa;;AAGnB,IAAM,mBAAmB;CAAC;CAAgB;CAAY;AAAU;AAgDhE,SAAS,YAAY,KAAuB;CACxC,MAAM,MAAgB,CAAC;CACvB,KAAK,MAAM,SAAS,GAAG,YAAY,KAAK,EAAE,eAAe,KAAK,CAAC,GAAG;EAC9D,IAAI,MAAM,KAAK,WAAW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AI,CAAC,OAAO,IAAI,QAAQ,WAAW;AACvC"}
|
|
@@ -1,7 +1,12 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
1
2
|
import fs from "fs";
|
|
2
3
|
import path from "path";
|
|
3
4
|
import { fileURLToPath } from "url";
|
|
4
5
|
//#region src/utils/version.ts
|
|
6
|
+
var version_exports = /* @__PURE__ */ __exportAll({
|
|
7
|
+
cliUserAgent: () => cliUserAgent,
|
|
8
|
+
cliVersion: () => cliVersion
|
|
9
|
+
});
|
|
5
10
|
/**
|
|
6
11
|
* This CLI's own version, and the User-Agent built from it.
|
|
7
12
|
*
|
|
@@ -53,6 +58,6 @@ function cliUserAgent() {
|
|
|
53
58
|
return `rebase-cli/${cliVersion()}`;
|
|
54
59
|
}
|
|
55
60
|
//#endregion
|
|
56
|
-
export { cliVersion as n, cliUserAgent as t };
|
|
61
|
+
export { cliVersion as n, version_exports as r, cliUserAgent as t };
|
|
57
62
|
|
|
58
|
-
//# sourceMappingURL=version-
|
|
63
|
+
//# sourceMappingURL=version-ONIeo7jl.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version-
|
|
1
|
+
{"version":3,"file":"version-ONIeo7jl.js","names":[],"sources":["../src/utils/version.ts"],"sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\n/**\n * This CLI's own version, and the User-Agent built from it.\n *\n * Four call sites used to answer \"what version am I?\" and each answered it\n * differently. `cli.ts` walked one directory up from `__dirname`. `init.ts`\n * walked up looking for a folder literally named `cli`. `bundle.ts` had\n * `resolveCliVersion`, which walked up at most five levels for a manifest whose\n * `name` matched — the only one of the three that was actually correct, and the\n * one the other two did not know existed. Every HTTP request to the control\n * plane answered it not at all, which is the expensive gap: a control plane\n * cannot refuse a CLI that is too old for its wire format if no request ever\n * says which CLI is calling.\n *\n * One answer now, and it is `bundle.ts`'s: walk up for the manifest that names\n * this package, rather than counting directories or matching a folder name.\n * `dist/` is one level down in a published install and two in a source\n * checkout, and a folder called `cli` is not guaranteed to be ours. Two\n * differences from that original — `fileURLToPath` instead of `new\n * URL().pathname`, which is what makes it survive a path containing a space,\n * and no five-level ceiling.\n */\nfunction readVersion(): string {\n let dir = path.dirname(fileURLToPath(import.meta.url));\n const root = path.parse(dir).root;\n while (dir && dir !== root) {\n const manifest = path.join(dir, \"package.json\");\n if (fs.existsSync(manifest)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(manifest, \"utf-8\"));\n if (pkg.name === \"@rebasepro/cli\" && typeof pkg.version === \"string\") return pkg.version;\n } catch {\n // A malformed manifest on the way up is not ours to complain\n // about; keep walking.\n }\n }\n dir = path.dirname(dir);\n }\n return \"unknown\";\n}\n\nlet cached: string | undefined;\n\n/** The CLI's version, or `\"unknown\"` when it cannot be read. Memoized. */\nexport function cliVersion(): string {\n if (cached === undefined) cached = readVersion();\n return cached;\n}\n\n/**\n * `rebase-cli/0.17.3` — sent on every control-plane request.\n *\n * The control plane needs it to answer `CLI_TOO_OLD` with a minimum version\n * instead of failing somewhere further in with a shape error. A client that\n * does not identify itself can only ever be refused generically.\n */\nexport function cliUserAgent(): string {\n return `rebase-cli/${cliVersion()}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAS,cAAsB;CAC3B,IAAI,MAAM,KAAK,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC;CACrD,MAAM,OAAO,KAAK,MAAM,GAAG,CAAC,CAAC;CAC7B,OAAO,OAAO,QAAQ,MAAM;EACxB,MAAM,WAAW,KAAK,KAAK,KAAK,cAAc;EAC9C,IAAI,GAAG,WAAW,QAAQ,GACtB,IAAI;GACA,MAAM,MAAM,KAAK,MAAM,GAAG,aAAa,UAAU,OAAO,CAAC;GACzD,IAAI,IAAI,SAAS,oBAAoB,OAAO,IAAI,YAAY,UAAU,OAAO,IAAI;EACrF,QAAQ,CAGR;EAEJ,MAAM,KAAK,QAAQ,GAAG;CAC1B;CACA,OAAO;AACX;AAEA,IAAI;;AAGJ,SAAgB,aAAqB;CACjC,IAAI,WAAW,KAAA,GAAW,SAAS,YAAY;CAC/C,OAAO;AACX;;;;;;;;AASA,SAAgB,eAAuB;CACnC,OAAO,cAAc,WAAW;AACpC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rebasepro/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.32.0",
|
|
4
4
|
"description": "Developer tools for Rebase projects",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -45,15 +45,15 @@
|
|
|
45
45
|
"jiti": "^2.7.0",
|
|
46
46
|
"pg": "^8.22.0",
|
|
47
47
|
"ts-morph": "28.0.0",
|
|
48
|
-
"@rebasepro/
|
|
49
|
-
"@rebasepro/
|
|
50
|
-
"@rebasepro/
|
|
51
|
-
"@rebasepro/
|
|
52
|
-
"@rebasepro/
|
|
53
|
-
"@rebasepro/server": "0.
|
|
54
|
-
"@rebasepro/
|
|
55
|
-
"@rebasepro/
|
|
56
|
-
"@rebasepro/
|
|
48
|
+
"@rebasepro/codegen": "0.32.0",
|
|
49
|
+
"@rebasepro/agent-skills": "0.32.0",
|
|
50
|
+
"@rebasepro/common": "0.32.0",
|
|
51
|
+
"@rebasepro/rls-check": "0.32.0",
|
|
52
|
+
"@rebasepro/client": "0.32.0",
|
|
53
|
+
"@rebasepro/server": "0.32.0",
|
|
54
|
+
"@rebasepro/types": "0.32.0",
|
|
55
|
+
"@rebasepro/server-postgres": "0.32.0",
|
|
56
|
+
"@rebasepro/utils": "0.32.0"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
59
|
"@types/node": "^26.1.2",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"api-keys-eIUjMqWn.js","names":[],"sources":["../src/commands/api-keys.ts"],"sourcesContent":["/**\n * CLI command: rebase api-keys <action>\n *\n * The project's service keys, through `/api/admin/api-keys`, authenticated with\n * the service key from `.env`.\n *\n * Subcommands:\n * list — List the service keys (masked): kind, scopes, roles\n * get — Show one key\n * create — Create a service key holding the scopes named on the line\n * revoke — Revoke a key\n * scopes — List the scopes this backend knows, and which the caller holds\n */\nimport chalk from \"chalk\";\nimport type arg from \"arg\";\nimport { createRebaseClient, RebaseApiError } from \"@rebasepro/client\";\nimport {\n ADMIN_SCOPES,\n DATA_PLANE_SCOPES,\n KEY_MANAGEMENT_SCOPES,\n parseScope,\n type ApiKeyMasked,\n type ApiKeyWithSecret,\n type CreateApiKeyRequest,\n type ScopeSummary\n} from \"@rebasepro/types\";\nimport {\n requireProjectRoot,\n readEnvFile\n} from \"../utils/project\";\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { cliUserAgent } from \"../utils/version\";\nimport { serverUnreachableHint } from \"../utils/dev-server\";\nimport fs from \"fs\";\nimport path from \"path\";\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const API_KEYS_SUBCOMMANDS = [\"list\", \"get\", \"create\", \"revoke\", \"scopes\"] as const;\n\n/* ═══════════════════════════════════════════════════════════════\n Env helper — reads SERVICE_KEY and PORT from .env\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * Was a hand-rolled `indexOf(\"=\")` loop. It keyed `export KEY=value` as\n * `export KEY` and carried a trailing `# comment` into the value — so a key\n * that was present read as absent, or reached an `Authorization` header with a\n * comment attached and came back 401. See `readEnvFile`.\n */\nconst loadEnv = readEnvFile;\n\n/**\n * Where this project's backend is — or why the CLI will not say.\n *\n * `configured` is an address the developer named; `running` is the one this\n * project's backend recorded when it bound, and is still serving on. There is\n * no third, guessed, answer: the request carries the project's service key —\n * the `admin` role, every scope — and an address the CLI only guessed is one it\n * would hand that key to without knowing whose server answers.\n */\nexport type BackendAddress =\n | {\n url: string;\n source: \"configured\" | \"running\";\n /**\n * Set when the address came from `.env` and is the cloud project this\n * directory is linked to — which `rebase cloud init --claim` writes\n * there for the app and the SDK, not as a choice of where local\n * commands go. The command still goes there; {@link cloudTargetNote}\n * says so.\n */\n cloudProject?: string;\n }\n | { url: null; reason: string };\n\n/** Whether a process with this pid is alive and ours to signal. */\nfunction isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n // ESRCH: gone. EPERM: alive, but another user's — not this project's backend.\n return false;\n }\n}\n\n/**\n * The address the service key may be sent to. Shared with `rebase storage`.\n *\n * In order:\n *\n * 1. `REBASE_BASE_URL`, in the shell or in `.env` — the developer said where.\n * 2. `.rebase/state.json`, which this project's backend writes when it binds\n * and removes when it stops — and only while the pid it names is alive,\n * because a backend that was killed leaves the file behind.\n *\n * Nothing else. `.env`'s `PORT` was the fallback, and every scaffold writes\n * `PORT=3001`: with `rebase dev` stopped, `rebase api-keys list` sent this\n * project's service key to whatever listened on 3001 — on the tester's machine,\n * another project's server. `.rebase-dev-url` is not enough on its own either:\n * a `rebase dev` that was killed leaves it behind, pointing at a port some\n * other server may have taken since.\n */\nexport function resolveBackendAddress(env: Record<string, string>, projectRoot: string): BackendAddress {\n const fromShell = process.env.REBASE_BASE_URL?.trim();\n const configured = fromShell || env.REBASE_BASE_URL?.trim();\n if (configured) {\n const cloudProject = fromShell ? undefined : linkedCloudProjectAt(projectRoot, configured);\n return cloudProject ? { url: configured, source: \"configured\", cloudProject } : { url: configured, source: \"configured\" };\n }\n\n const state = readBackendState(projectRoot);\n if (state && isAlive(state.pid)) return { url: state.url, source: \"running\" };\n\n const last = state ? ` The last one recorded here, at ${state.url} (pid ${state.pid}), has stopped.` : \"\";\n return {\n url: null,\n reason: `This project's server is not running, so the service key was not sent anywhere.${last} ` +\n \"Start it with `rebase dev`. If it runs some other way — `rebase start`, a container — \" +\n \"set REBASE_BASE_URL in .env to its address.\"\n };\n}\n\n/** The slug of the cloud project `.rebase/cloud.json` links, when `url` is its address. */\nfunction linkedCloudProjectAt(projectRoot: string, url: string): string | undefined {\n let link: unknown;\n try {\n link = JSON.parse(fs.readFileSync(path.join(projectRoot, \".rebase\", \"cloud.json\"), \"utf-8\"));\n } catch {\n return undefined;\n }\n if (!isRecord(link) || link.mode === \"direct\" || typeof link.apiUrl !== \"string\") return undefined;\n const bare = (u: string) => u.trim().replace(/\\/+$/, \"\");\n if (bare(link.apiUrl) !== bare(url)) return undefined;\n const slug = typeof link.slug === \"string\" && link.slug ? link.slug : link.projectId;\n return typeof slug === \"string\" && slug ? slug : \"linked\";\n}\n\n/**\n * What a local command says before it sends the service key to the cloud\n * project `.env` names (see `BackendAddress.cloudProject`), or undefined.\n */\nexport function cloudTargetNote(address: BackendAddress): string | undefined {\n if (address.url === null || !address.cloudProject) return undefined;\n return `Sending this to ${address.url}: REBASE_BASE_URL in .env is the address of cloud project ${address.cloudProject} `\n + \"(`rebase cloud init --claim` writes it there for the app, the SDK and the MCP server), and that project does not \"\n + \"take this project's local service key. To reach the local backend instead, run the command with \"\n + \"REBASE_BASE_URL set to it in the shell, e.g. REBASE_BASE_URL=http://localhost:3001.\";\n}\n\n/** What `.rebase/state.json` says about the backend that wrote it, or null. */\nfunction readBackendState(projectRoot: string): { url: string; pid: number } | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(path.join(projectRoot, \".rebase\", \"state.json\"), \"utf-8\"));\n } catch {\n return null;\n }\n if (!isRecord(parsed) || typeof parsed.pid !== \"number\" || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return null;\n const url = typeof parsed.baseUrl === \"string\" && parsed.baseUrl.trim()\n ? parsed.baseUrl.trim()\n : typeof parsed.port === \"number\" ? `http://localhost:${parsed.port}` : null;\n\n return url ? { url, pid: parsed.pid } : null;\n}\n\n/**\n * The address to send the service key to, or the end of the command.\n *\n * Exits before any request is made: the refusal is the point.\n */\nexport function requireBackendUrl(env: Record<string, string>, projectRoot: string): string {\n const address = resolveBackendAddress(env, projectRoot);\n const note = cloudTargetNote(address);\n if (note) console.error(chalk.yellow(` ⚠ ${note}`));\n if (address.url !== null) return address.url;\n\n console.error(chalk.red(\"✗ No server to send the request to.\"));\n console.error(chalk.gray(` ${address.reason}`));\n process.exit(1);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n The backend, through the SDK\n ═══════════════════════════════════════════════════════════════ */\n\ntype ProjectClient = ReturnType<typeof createRebaseClient>;\n\ninterface Connection {\n client: ProjectClient;\n baseUrl: string;\n /** The variable the service key was read from, for a hint that names it. */\n keyVariable: ServiceKeyVariable;\n}\n\n/** Where a service key is read from: the name a scaffold writes, or the older one. */\ntype ServiceKeyVariable = \"REBASE_SERVICE_KEY\" | \"SERVICE_KEY\";\n\n/**\n * An SDK client for this project's backend, holding the service key.\n *\n * The service key is the project's own machine identity — the `admin` role,\n * every scope — so it is what may list, mint and revoke service keys. It is a\n * static bearer token: no session to restore or refresh, and no socket.\n */\nfunction connect(): Connection {\n const projectRoot = requireProjectRoot();\n const env = loadEnv(projectRoot);\n const keyVariable: ServiceKeyVariable = env.SERVICE_KEY ? \"SERVICE_KEY\" : \"REBASE_SERVICE_KEY\";\n const serviceKey = env[keyVariable];\n\n if (!serviceKey) {\n console.error(chalk.red(\"✗ REBASE_SERVICE_KEY not found in .env — required to manage API keys.\"));\n process.exit(1);\n }\n const baseUrl = requireBackendUrl(env, projectRoot);\n\n const client = createRebaseClient({\n baseUrl,\n token: serviceKey,\n realtime: false,\n headers: { \"User-Agent\": cliUserAgent() },\n auth: { persistSession: false, autoRefresh: false }\n });\n return { client, baseUrl, keyVariable };\n}\n\n/**\n * What to print when a request fails: the server's error code and message,\n * which is what says why — `SCOPE_EXCEEDS_CREATOR`, `INVALID_SCOPES`,\n * `ROLE_EXCEEDS_CREATOR`, `KEY_MANAGEMENT_SCOPE` — and a hint where one helps.\n *\n * Exported so its tests can read the lines without a server.\n */\nexport function describeFailure(\n action: string,\n error: unknown,\n baseUrl: string,\n keyVariable: ServiceKeyVariable = \"REBASE_SERVICE_KEY\"\n): string[] {\n if (!(error instanceof RebaseApiError)) {\n return [`✗ ${action}: ${error instanceof Error ? error.message : String(error)}`];\n }\n if (error.status === 0 || error.code === \"NETWORK_ERROR\") {\n return [`✗ ${action}: ${error.message}`, ...serverUnreachableHint(baseUrl)];\n }\n\n const label = [error.code, error.status ? `(${error.status})` : undefined].filter(Boolean).join(\" \");\n const lines = [`✗ ${action}${label ? ` — ${label}` : \"\"}: ${error.message}`];\n\n if (error.status === 401) {\n lines.push(` The server at ${baseUrl} did not accept ${keyVariable} from .env — is it this project's server?`);\n }\n // The message names the target that is not there; what *is* there rides\n // in `details`, and is the thing to pick from.\n if (error.code === \"UNKNOWN_SCOPE_TARGET\" && isRecord(error.details)) {\n for (const [kind, title] of [[\"collections\", \"Tables\"], [\"buckets\", \"Buckets\"], [\"functions\", \"Functions\"]] as const) {\n const names = error.details[kind];\n if (Array.isArray(names) && names.length > 0) {\n lines.push(` ${title}: ${names.map(String).join(\", \")}`);\n }\n }\n }\n return lines;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction fail(action: string, error: unknown, connection: Connection): never {\n for (const line of describeFailure(action, error, connection.baseUrl, connection.keyVariable)) {\n console.error(line.startsWith(\"✗\") ? chalk.red(line) : chalk.gray(line));\n }\n process.exit(1);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Entry\n ═══════════════════════════════════════════════════════════════ */\n\nexport async function apiKeysCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // `--help` is answered before dispatch, never by a handler. `cli.ts` only\n // rewrites the subcommand to `\"--help\"` when none was named, so\n // `rebase api-keys list --help` used to *list the keys* and\n // `rebase api-keys revoke --help` sent `DELETE /api/admin/api-keys/--help`.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printApiKeysHelp();\n return;\n }\n\n switch (subcommand) {\n case \"list\":\n await listKeys(rawArgs);\n break;\n case \"get\":\n await getKey(rawArgs);\n break;\n case \"create\":\n await createKey(rawArgs);\n break;\n case \"revoke\":\n await revokeKey(rawArgs);\n break;\n case \"scopes\":\n await listScopes(rawArgs);\n break;\n default:\n // The shape every other family uses. This one printed a bare line\n // to stderr *and* the whole help page to stdout, so a typo wrote\n // twenty lines to a stream a `--json` caller reads, with no `✗`, no\n // pointer at `--help`, and no did-you-mean — `craete` is one\n // transposition from `create`.\n unknownCommand(subcommand, API_KEYS_SUBCOMMANDS, \"api-keys\");\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Showing a key\n ═══════════════════════════════════════════════════════════════ */\n\nfunction keyStatus(key: ApiKeyMasked, now: Date): string {\n if (key.revoked_at) return chalk.red(\"revoked\");\n if (key.expires_at && new Date(key.expires_at) < now) return chalk.yellow(\"expired\");\n return chalk.green(\"active\");\n}\n\n/**\n * The lines that describe one key: what it is, what it may do and whom it\n * runs as.\n *\n * A service key runs as the RLS role `service` plus its own `roles`; a\n * personal key runs as its owner's roles as they are when it is used, so it\n * has none of its own to show.\n *\n * Exported so its tests can read the lines without a server.\n */\nexport function describeKey(key: ApiKeyMasked, now: Date = new Date()): string[] {\n const field = (label: string, value: string) => ` ${chalk.gray(`${label}:`.padEnd(12))}${value}`;\n const roles = key.kind === \"personal\"\n ? `its owner's (${key.owner_uid ?? \"unknown\"})`\n : [\"service\", ...key.roles].join(\", \");\n\n const lines = [\n ` ${chalk.bold(key.name)} ${chalk.gray(`[${key.key_prefix}•••]`)} ${keyStatus(key, now)}`,\n field(\"ID\", key.id),\n field(\"Kind\", key.kind),\n field(\"Scopes\", key.scopes.length > 0 ? key.scopes.join(\", \") : chalk.gray(\"none\")),\n field(\"Roles\", roles)\n ];\n if (key.rate_limit !== null) lines.push(field(\"Rate limit\", `${key.rate_limit} requests / 15 min`));\n if (key.expires_at) lines.push(field(\"Expires\", new Date(key.expires_at).toLocaleDateString()));\n lines.push(field(\"Created\", new Date(key.created_at).toLocaleDateString()));\n if (key.last_used_at) lines.push(field(\"Last used\", new Date(key.last_used_at).toLocaleDateString()));\n return lines;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n list\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys list` takes: none of its own. */\nexport const LIST_KEYS_FLAGS = {} as const;\n\nasync function listKeys(rawArgs: string[]): Promise<void> {\n parseCommandArgs({\n spec: LIST_KEYS_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys list\",\n maxPositionals: 0\n });\n\n const connection = connect();\n const { client } = connection;\n let keys: ApiKeyMasked[];\n try {\n ({ keys } = await client.apiKeys.listKeys());\n } catch (e: unknown) {\n fail(\"Failed to list API keys\", e, connection);\n }\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 API Keys\"));\n console.log(\"\");\n\n if (keys.length === 0) {\n console.log(chalk.gray(\" No API keys found.\"));\n console.log(\"\");\n return;\n }\n\n const now = new Date();\n for (const key of keys) {\n for (const line of describeKey(key, now)) console.log(line);\n console.log(\"\");\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n get\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys get` takes. */\nexport const GET_KEY_FLAGS = {\n \"--id\": String\n} as const;\n\n/**\n * Which key this invocation names, as a positional or as `--id`.\n *\n * Exported so its tests can drive the real parser rather than a copy of it.\n */\nexport function resolveGetKeyArgs(rawArgs: string[]): { id?: string } {\n const { flags, positionals } = parseCommandArgs({\n spec: GET_KEY_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys get\",\n maxPositionals: 1\n });\n\n return { id: flags[\"--id\"] || positionals[0] };\n}\n\nasync function getKey(rawArgs: string[]): Promise<void> {\n const { id } = resolveGetKeyArgs(rawArgs);\n if (!id) {\n throw new UsageError(\"Key ID is required: rebase api-keys get <key-id> (`rebase api-keys list` shows them).\");\n }\n\n const connection = connect();\n const { client } = connection;\n let key: ApiKeyMasked;\n try {\n ({ key } = await client.apiKeys.getKey(id));\n } catch (e: unknown) {\n fail(\"Failed to read API key\", e, connection);\n }\n\n console.log(\"\");\n for (const line of describeKey(key)) console.log(line);\n console.log(\"\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n create\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys create` takes. */\nexport const CREATE_KEY_FLAGS = {\n \"--name\": String,\n \"--scopes\": [String],\n \"--full-access\": Boolean,\n \"--roles\": [String],\n \"--rate-limit\": Number,\n \"--expires-in\": String,\n \"--expires-at\": String,\n \"-n\": \"--name\"\n} satisfies arg.Spec;\n\n/**\n * Options `create` refuses by name, each with the flag that does that job.\n *\n * Checked before the line is parsed: the strict parser would answer them\n * \"unknown option\", which does not say what to type instead.\n */\nexport const RETIRED_CREATE_OPTIONS: Readonly<Record<string, string>> = {\n \"--permissions\":\n \"--permissions is gone: name what the key may do with --scopes, e.g. \" +\n \"--scopes data:read:posts,data:write:posts (`rebase api-keys scopes` lists them).\",\n \"--admin\":\n \"--admin is gone: give the key the RLS role with --roles admin, and the admin-plane scopes it needs \" +\n \"with --scopes, e.g. --scopes users:read,schema:read.\",\n \"--expires\":\n \"--expires is gone: use --expires-in <days> (e.g. --expires-in 90) or --expires-at <ISO date>.\"\n};\n\n/** Refuse a retired option, wherever on the line and however it is spelled. */\nfunction refuseRetiredOptions(rawArgs: string[]): void {\n for (const token of rawArgs.slice(2)) {\n // Past `--` everything is a value, never an option.\n if (token === \"--\") return;\n const name = token.split(\"=\", 1)[0];\n const replacement = Object.prototype.hasOwnProperty.call(RETIRED_CREATE_OPTIONS, name)\n ? RETIRED_CREATE_OPTIONS[name]\n : undefined;\n if (replacement) throw new UsageError(replacement);\n }\n}\n\n/**\n * A list flag's values, whether repeated (`--scopes a --scopes b`) or\n * comma-separated (`--scopes a,b`) — or both — trimmed and deduplicated.\n * Whitespace separates too: no scope or role name contains any.\n */\nfunction splitList(values: readonly string[] | undefined): string[] {\n const out = new Set<string>();\n for (const value of values ?? []) {\n for (const entry of value.split(/[\\s,]+/)) {\n if (entry) out.add(entry);\n }\n }\n return [...out];\n}\n\nconst DAY_MS = 86_400_000;\n\nfunction resolveExpiry(expiresIn: string | undefined, expiresAt: string | undefined, now: Date): string | null {\n if (expiresIn !== undefined && expiresAt !== undefined) {\n throw new UsageError(\"Pass --expires-in or --expires-at, not both.\");\n }\n if (expiresIn !== undefined) {\n const days = /^\\d+$/.test(expiresIn.trim()) ? Number(expiresIn.trim()) : NaN;\n if (!Number.isSafeInteger(days) || days < 1) {\n throw new UsageError(`--expires-in takes a whole number of days, e.g. --expires-in 90 (got \"${expiresIn}\").`);\n }\n return new Date(now.getTime() + days * DAY_MS).toISOString();\n }\n if (expiresAt !== undefined) {\n const parsed = new Date(expiresAt);\n if (isNaN(parsed.getTime())) {\n throw new UsageError(`--expires-at takes an ISO date, e.g. --expires-at 2027-01-31 (got \"${expiresAt}\").`);\n }\n if (parsed.getTime() <= now.getTime()) {\n throw new UsageError(`--expires-at must be in the future (got ${parsed.toISOString()}).`);\n }\n return parsed.toISOString();\n }\n return null;\n}\n\n/** What `rebase api-keys create` was asked to mint. */\nexport interface CreateKeyPlan {\n name: string;\n /** The scopes named with `--scopes`, or `\"held\"` for `--full-access`. */\n scopes: string[] | \"held\";\n /** RLS roles beside `service`. */\n roles: string[];\n rate_limit: number | null;\n expires_at: string | null;\n}\n\n/**\n * What this invocation asks to be created.\n *\n * The name may be given either way — `--name \"My Key\"` or as the single\n * positional — and under the old permissive parse an undeclared flag became\n * that positional: `rebase api-keys create --debug --full-access` created a\n * key called `--debug` with access to everything, and `--debug` is what the\n * CLI prints after every failure as the thing to re-run with. Strict parsing\n * makes the flag an error instead of a name.\n *\n * What the key may do has to be asked for by name — `--scopes` or\n * `--full-access` — never defaulted: a forgotten flag must not mint a key that\n * reaches everything.\n *\n * Exported so its tests can drive the real parser rather than a copy of it.\n */\nexport function resolveCreateKeyArgs(rawArgs: string[], now: Date = new Date()): CreateKeyPlan {\n refuseRetiredOptions(rawArgs);\n\n const { flags, positionals } = parseCommandArgs({\n spec: CREATE_KEY_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys create\",\n maxPositionals: 1\n });\n\n const name = (flags[\"--name\"] || positionals[0] || \"\").trim();\n if (!name) {\n throw new UsageError('A key needs a name: rebase api-keys create \"CI\" --scopes data:read');\n }\n\n const named = splitList(flags[\"--scopes\"]);\n const fullAccess = flags[\"--full-access\"] === true;\n if (fullAccess && named.length > 0) {\n throw new UsageError(\"Pass --scopes or --full-access, not both: --full-access already means every scope you hold.\");\n }\n if (!fullAccess && named.length === 0) {\n throw new UsageError(\n \"Name what the key may do: --scopes data:read:posts,data:write:posts, or --full-access for every \" +\n \"scope you hold. `rebase api-keys scopes` lists them.\"\n );\n }\n\n const rateLimit = flags[\"--rate-limit\"];\n if (rateLimit !== undefined && (!Number.isSafeInteger(rateLimit) || rateLimit < 1)) {\n throw new UsageError(\"--rate-limit takes a whole number of requests per 15-minute window, e.g. --rate-limit 500.\");\n }\n\n return {\n name,\n scopes: fullAccess ? \"held\" : named,\n roles: splitList(flags[\"--roles\"]),\n rate_limit: rateLimit ?? null,\n expires_at: resolveExpiry(flags[\"--expires-in\"], flags[\"--expires-at\"], now)\n };\n}\n\n/**\n * The scopes `--full-access` puts on a key: every one the caller holds, less\n * key management, which no key may hold.\n *\n * Exported so its tests can check the subtraction without a server.\n */\nexport function grantableScopes(held: readonly string[]): string[] {\n const management: readonly string[] = KEY_MANAGEMENT_SCOPES;\n return held.filter(entry => !management.includes(parseScope(entry)?.scope ?? entry));\n}\n\nasync function createKey(rawArgs: string[]): Promise<void> {\n const plan = resolveCreateKeyArgs(rawArgs);\n const connection = connect();\n const { client } = connection;\n\n let scopes: string[];\n if (plan.scopes === \"held\") {\n let held: string[];\n try {\n ({ held } = await client.personalKeys.listScopes());\n } catch (e: unknown) {\n fail(\"Failed to read the scopes you hold\", e, connection);\n }\n scopes = grantableScopes(held);\n if (scopes.length === 0) {\n console.error(chalk.red(\"✗ You hold no scope a key may carry, so --full-access has nothing to grant.\"));\n process.exit(1);\n }\n } else {\n scopes = plan.scopes;\n }\n\n const request: CreateApiKeyRequest = {\n name: plan.name,\n scopes,\n ...(plan.roles.length > 0 ? { roles: plan.roles } : {}),\n ...(plan.rate_limit !== null ? { rate_limit: plan.rate_limit } : {}),\n ...(plan.expires_at !== null ? { expires_at: plan.expires_at } : {})\n };\n\n let created: ApiKeyWithSecret;\n try {\n ({ key: created } = await client.apiKeys.createKey(request));\n } catch (e: unknown) {\n fail(\"Failed to create API key\", e, connection);\n }\n\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key created\"));\n console.log(\"\");\n for (const line of describeKey(created)) console.log(line);\n console.log(\"\");\n console.log(chalk.bold.yellow(\" ⚠ Copy your key now — it won't be shown again:\"));\n console.log(\"\");\n console.log(` ${chalk.cyan(created.key)}`);\n console.log(\"\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n revoke\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys revoke` takes. */\nexport const REVOKE_KEY_FLAGS = {\n \"--id\": String\n} as const;\n\n/**\n * Which key this invocation names.\n *\n * The id is a positional, so the permissive parse handed one straight to the\n * DELETE: `rebase api-keys revoke --foo` sent\n * `DELETE /api/admin/api-keys/--foo`, and `rebase --debug api-keys revoke <id>`\n * shifted the words along and revoked the key named `revoke`.\n *\n * Exported so its tests can drive the real parser rather than a copy of it.\n */\nexport function resolveRevokeKeyArgs(rawArgs: string[]): { id?: string } {\n const { flags, positionals } = parseCommandArgs({\n spec: REVOKE_KEY_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys revoke\",\n maxPositionals: 1\n });\n\n return { id: flags[\"--id\"] || positionals[0] };\n}\n\nasync function revokeKey(rawArgs: string[]): Promise<void> {\n const { id } = resolveRevokeKeyArgs(rawArgs);\n\n if (!id) {\n throw new UsageError(\"Key ID is required: rebase api-keys revoke <key-id> (`rebase api-keys list` shows them).\");\n }\n\n const connection = connect();\n const { client } = connection;\n try {\n await client.apiKeys.revokeKey(id);\n } catch (e: unknown) {\n fail(\"Failed to revoke API key\", e, connection);\n }\n\n console.log(\"\");\n console.log(chalk.bold.green(\" ✓ API key revoked\"));\n console.log(` ${chalk.gray(\"ID:\")} ${id}`);\n console.log(\"\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n scopes\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `rebase api-keys scopes` takes: none of its own. */\nexport const SCOPES_LIST_FLAGS = {} as const;\n\nconst PLANES: ReadonlyArray<{ plane: ScopeSummary[\"plane\"]; title: string; note: string }> = [\n { plane: \"data\", title: \"Data\", note: \"narrow what a key reaches; row-level security still decides the rows\" },\n { plane: \"admin\", title: \"Admin\", note: \"nobody holds these unless a role grants them; the admin role holds all\" },\n { plane: \"app\", title: \"App\", note: \"declared by this app under auth.scopes on the users table\" }\n];\n\n/**\n * The scope catalogue as printed lines: one section per plane, each scope with\n * its label and what its target names, marked when the caller holds it.\n *\n * Exported so its tests can read the lines without a server.\n */\nexport function describeScopes(scopes: readonly ScopeSummary[], held: readonly string[]): string[] {\n const management: readonly string[] = KEY_MANAGEMENT_SCOPES;\n const width = Math.max(0, ...scopes.map(s => s.scope.length)) + 2;\n const labelWidth = Math.max(0, ...scopes.map(s => s.label.length)) + 2;\n const lines: string[] = [];\n for (const { plane, title, note } of PLANES) {\n const inPlane = scopes.filter(s => s.plane === plane);\n if (inPlane.length === 0) continue;\n lines.push(` ${chalk.bold(title)} ${chalk.gray(`— ${note}`)}`);\n for (const s of inPlane) {\n const mark = held.includes(s.scope) ? chalk.green(\"✓\") : \" \";\n const extra = management.includes(s.scope)\n ? chalk.gray(\"never on a key\")\n : s.target ? chalk.gray(`:<${s.target}>`) : \"\";\n lines.push(` ${mark} ${s.scope.padEnd(width)}${extra ? s.label.padEnd(labelWidth) : s.label}${extra}`);\n }\n lines.push(\"\");\n }\n return lines;\n}\n\nasync function listScopes(rawArgs: string[]): Promise<void> {\n parseCommandArgs({\n spec: SCOPES_LIST_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"api-keys scopes\",\n maxPositionals: 0\n });\n\n const connection = connect();\n const { client } = connection;\n let catalogue: { scopes: ScopeSummary[]; held: string[] };\n try {\n catalogue = await client.personalKeys.listScopes();\n } catch (e: unknown) {\n fail(\"Failed to read the scopes\", e, connection);\n }\n\n console.log(\"\");\n console.log(chalk.bold(\" Scopes\") + chalk.gray(\" (✓ = you hold it; :<target> narrows it to one)\"));\n console.log(\"\");\n for (const line of describeScopes(catalogue.scopes, catalogue.held)) console.log(line);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Help\n ═══════════════════════════════════════════════════════════════ */\n\nfunction printApiKeysHelp() {\n const keyable = ADMIN_SCOPES.filter(scope => !(KEY_MANAGEMENT_SCOPES as readonly string[]).includes(scope));\n console.log(`\n${chalk.bold(\"rebase api-keys\")} — Manage service API keys\n\n${chalk.green.bold(\"Usage\")}\n rebase api-keys ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"list\")} List the service keys: kind, scopes, roles\n ${chalk.blue.bold(\"get\")} ${chalk.gray(\"<id>\")} Show one key\n ${chalk.blue.bold(\"create\")} Create a service key\n ${chalk.blue.bold(\"revoke\")} ${chalk.gray(\"<id>\")} Revoke a key\n ${chalk.blue.bold(\"scopes\")} List the scopes this backend knows, and which you hold\n\n${chalk.green.bold(\"create Options\")}\n ${chalk.blue(\"--name, -n\")} Key name ${chalk.gray(\"(required; or the first argument)\")}\n ${chalk.blue(\"--scopes\")} What the key may do, comma-separated or repeated\n ${chalk.gray(\"(required unless --full-access)\")}\n ${chalk.blue(\"--full-access\")} Every scope you hold, less keys:read and keys:write\n ${chalk.blue(\"--roles\")} RLS roles the key runs as beside ${chalk.gray(\"service\")}, e.g. admin\n ${chalk.blue(\"--rate-limit\")} Requests per 15-min window ${chalk.gray(\"(default: the server's API-key limit)\")}\n ${chalk.blue(\"--expires-in\")} Days until the key expires\n ${chalk.blue(\"--expires-at\")} Expiry as an ISO date, e.g. 2027-01-31\n\n${chalk.green.bold(\"get / revoke Options\")}\n ${chalk.blue(\"--id\")} API key ID ${chalk.gray(\"(or the first argument)\")}\n\n${chalk.green.bold(\"Scopes\")}\n A scope is ${chalk.blue(\"resource:action\")}, optionally narrowed to one target:\n ${chalk.blue(\"data:read:posts\")} reads the posts table and nothing else.\n Data ${DATA_PLANE_SCOPES.join(\", \")}\n ${chalk.gray(\"target: a table slug, a storage source id (default), a function name\")}\n Admin ${keyable.join(\", \")}\n App whatever the app declares under auth.scopes ${chalk.gray(\"(rebase api-keys scopes)\")}\n\n${chalk.green.bold(\"Examples\")}\n rebase api-keys list\n rebase api-keys create \"Analytics\" --scopes data:read:events\n rebase api-keys create -n \"Blog CI\" --scopes data:read:posts,data:write:posts --expires-in 90\n rebase api-keys create -n \"Mailer\" --scopes \"functions:invoke:send-email,storage:read:(default)\"\n rebase api-keys create -n \"Ops\" --full-access --roles admin --expires-at 2027-01-31\n rebase api-keys get abc123-def456\n rebase api-keys revoke abc123-def456\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,IAAa,uBAAuB;CAAC;CAAQ;CAAO;CAAU;CAAU;AAAQ;;;;;;;AAYhF,IAAM,UAAU;;AA2BhB,SAAS,QAAQ,KAAsB;CACnC,IAAI;EACA,QAAQ,KAAK,KAAK,CAAC;EACnB,OAAO;CACX,QAAQ;EAEJ,OAAO;CACX;AACJ;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,sBAAsB,KAA6B,aAAqC;CACpG,MAAM,YAAY,QAAQ,IAAI,iBAAiB,KAAK;CACpD,MAAM,aAAa,aAAa,IAAI,iBAAiB,KAAK;CAC1D,IAAI,YAAY;EACZ,MAAM,eAAe,YAAY,KAAA,IAAY,qBAAqB,aAAa,UAAU;EACzF,OAAO,eAAe;GAAE,KAAK;GAAY,QAAQ;GAAc;EAAa,IAAI;GAAE,KAAK;GAAY,QAAQ;EAAa;CAC5H;CAEA,MAAM,Q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,UAAU,EAAE;;;;;;;;CAQ9B;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"apps-DExO4PEl.js","names":[],"sources":["../src/commands/apps.ts"],"sourcesContent":["/**\n * CLI command: rebase apps\n *\n * Inspect the apps this repository contributes to a project, adopt a\n * `rebase.json` for a project that predates it, and print the client bootstrap\n * an app needs to reach its backend.\n *\n * The distinction that runs through all of this: a *repository* declares apps,\n * a *project* owns them. Two repositories can contribute to the same project and\n * never know about each other, which is what makes a separate frontend repo — or\n * a mobile app with no repo relationship at all — an ordinary thing rather than\n * a special case.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport type { RebaseAppConfig, RebaseProjectManifest } from \"@rebasepro/types\";\nimport { failAsJson, requireProjectRoot } from \"../utils/project\";\nimport { devServerUrl, runningBackendUrl } from \"../utils/dev-server\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport {\n assessManagedCompatibility,\n DEFAULT_TABLES_DIR,\n findBackendApp,\n formatAppAddress,\n loadManifest,\n ManifestError,\n manifestExists,\n staticAppAddress,\n synthesizeManifest,\n writeManifest\n} from \"../manifest\";\nimport { readLink } from \"./cloud/context\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { foldableApps } from \"../fold-static\";\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase apps\")} — the apps this repository contributes\n\n${chalk.bold(\"Usage\")}\n rebase apps list List declared apps and their build outputs\n rebase apps init Write a rebase.json inferred from this project\n rebase apps config <app> Print the client configuration for an app\n\n${chalk.bold(\"Options\")}\n --json Machine-readable output\n --force Replace an existing rebase.json (apps init), keeping\n each app's name, path and cms\n -h, --help Show this help\n`.trim());\n}\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const APPS_SUBCOMMANDS = [\"list\", \"init\", \"config\"] as const;\n\nexport async function appsCommand(subcommand: string | undefined, rawArgs: string[] = []): Promise<void> {\n // Help is answered before parsing, so `rebase apps config --help` prints the\n // page rather than being rejected for naming no app.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printHelp();\n return;\n }\n\n // Only `apps` is a command word here: this one parser serves every\n // subcommand, so the subcommand stays in the positionals and the app name\n // `apps config` takes follows it.\n const { flags: args, positionals } = parseCommandArgs({\n spec: {\n \"--json\": Boolean,\n \"--force\": Boolean\n },\n rawArgs,\n commandWords: 1,\n command: \"apps\",\n maxPositionals: 2\n });\n\n switch (subcommand) {\n case \"list\":\n await listApps(Boolean(args[\"--json\"]));\n break;\n case \"init\":\n if (positionals[1] !== undefined) {\n // It never registered one app: the name was ignored and the\n // whole manifest inferred, which is not what the reader asked for.\n console.error(chalk.red(`✗ rebase apps init takes no app name (got \"${positionals[1]}\").`));\n console.error(chalk.dim(\" It infers every app from this project and writes the whole rebase.json.\"));\n console.error(chalk.dim(\" To add one app, declare it under \\\"apps\\\" in rebase.json.\"));\n process.exit(1);\n }\n await initManifest(Boolean(args[\"--force\"]));\n break;\n case \"config\":\n await printAppConfig(positionals[1], Boolean(args[\"--json\"]));\n break;\n default:\n unknownCommand(subcommand, APPS_SUBCOMMANDS, \"apps\");\n }\n}\n\n/**\n * One app's line in `rebase apps list`.\n *\n * A static app shows its full address — the https URL when its `path` gives it\n * a hostname — and the CMS as the address a browser would open. `CMS at /` on\n * an app that lives on `admin.example.com` reads as the project's own root,\n * which is the one place that CMS is not.\n */\nexport function describeApp(name: string, app: RebaseAppConfig): string {\n switch (app.type) {\n case \"backend\":\n return app.runtime === \"custom\"\n // The context is named only when it is not the project, which is\n // the case where it changes what you would type. A workspace app\n // builds from the workspace root, and a listing that showed only\n // the Dockerfile implied a `docker build .` beside it that fails.\n ? `custom runtime — ${app.dockerfile ?? \"Dockerfile\"}`\n + (app.context && app.context !== \".\" ? ` (context: ${app.context})` : \"\")\n : `managed runtime, tables: ${app.tables ?? DEFAULT_TABLES_DIR}`;\n case \"static\": {\n const address = staticAppAddress(name, app);\n return `${app.root} → ${app.output} @ ${formatAppAddress(address)}`\n + (app.cms ? ` ${chalk.magenta(`CMS at ${formatAppAddress({ ...address, path: app.cms })}`)}` : \"\");\n }\n default:\n return \"\";\n }\n}\n\nasync function listApps(asJson: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n const loaded = loadManifestOrExit(projectRoot, asJson);\n const compatibility = assessManagedCompatibility(loaded.manifest);\n\n if (asJson) {\n console.log(JSON.stringify(\n {\n source: loaded.source,\n rebase: loaded.manifest.rebase,\n apps: loaded.manifest.apps,\n managed: compatibility\n },\n null,\n 2\n ));\n return;\n }\n\n if (loaded.source === \"synthesized\") {\n console.log(chalk.dim(\"No rebase.json — showing the layout inferred from this project.\"));\n console.log(chalk.dim(`Run ${chalk.cyan(\"rebase apps init\")} to write it down.\\n`));\n }\n\n console.log(chalk.bold(`Rebase ${loaded.manifest.rebase}`));\n console.log(\"\");\n\n const entries = Object.entries(loaded.manifest.apps);\n if (entries.length === 0) {\n console.log(chalk.yellow(\"No apps declared.\"));\n return;\n }\n\n const width = Math.max(...entries.map(([name]) => name.length));\n for (const [name, app] of entries) {\n console.log(\n ` ${chalk.cyan(name.padEnd(width))} ${chalk.dim(app.type.padEnd(8))} ${describeApp(name, app)}`\n );\n }\n\n console.log(\"\");\n if (compatibility.eligible) {\n console.log(chalk.green(\"✓ Eligible for the managed runtime.\"));\n } else {\n console.log(chalk.yellow(\"• Uses the custom runtime:\"));\n for (const reason of compatibility.reasons) {\n console.log(chalk.dim(` ${reason}`));\n }\n }\n}\n\n/** A static app's `root`, compared as a directory: `./frontend/` is `frontend`. */\nfunction sameRoot(a: string, b: string): boolean {\n const normal = (root: string): string => path.posix.normalize(root.replace(/\\\\/g, \"/\")).replace(/\\/+$/, \"\");\n return normal(a) === normal(b);\n}\n\n/**\n * Re-infer over a manifest the project already declares, keeping what only the\n * declaration knows.\n *\n * An inferred app takes the name the file gives the app it matches — the\n * backend, or the static app with the same `root` — and that app's `path` and\n * `cms`. The name is the app's identity on a deployed project, so renaming it\n * would deploy a second app beside the first. `path` can carry the hostname the\n * app is registered on. `cms` is a client-side route that nothing in the project\n * shows. Everything else is inferred again, which is what `--force` asks for.\n *\n * A declared app the inference does not find is returned in `removed`, so the\n * command can say so rather than drop it in silence.\n */\nfunction keepDeclaredIdentity(\n inferred: RebaseProjectManifest,\n declared: RebaseProjectManifest\n): { manifest: RebaseProjectManifest; removed: Array<{ name: string; app: RebaseAppConfig }> } {\n const apps: Record<string, RebaseAppConfig> = {};\n const matched = new Set<string>();\n\n for (const [name, app] of Object.entries(inferred.apps)) {\n if (app.type === \"backend\") {\n const backend = findBackendApp(declared);\n const keptName = backend && !matched.has(backend.name) ? backend.name : name;\n matched.add(keptName);\n apps[keptName] = app;\n continue;\n }\n const match = Object.entries(declared.apps).find(([declaredName, candidate]) =>\n !matched.has(declaredName) && candidate.type === \"static\" && sameRoot(candidate.root, app.root));\n const declaredApp = match?.[1];\n if (!match || declaredApp?.type !== \"static\") {\n apps[name] = app;\n continue;\n }\n const keptName = match[0];\n matched.add(keptName);\n const address = declaredApp.path ?? app.path;\n apps[keptName] = {\n ...app,\n ...(address !== undefined ? { path: address } : {}),\n ...(declaredApp.cms !== undefined ? { cms: declaredApp.cms } : {})\n };\n }\n\n const removed = Object.entries(declared.apps)\n .filter(([name]) => !matched.has(name))\n .map(([name, app]) => ({ name, app }));\n return { manifest: { ...inferred, apps }, removed };\n}\n\nasync function initManifest(force: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n\n let declared: RebaseProjectManifest | undefined;\n if (manifestExists(projectRoot)) {\n if (!force) {\n console.error(chalk.red(\"✗ rebase.json already exists.\"));\n console.error(chalk.dim(\" Pass --force to replace it with an inferred one, keeping each app's name, path and cms.\"));\n process.exit(1);\n }\n try {\n declared = loadManifest(projectRoot).manifest;\n } catch (err) {\n if (!(err instanceof ManifestError)) throw err;\n const issues = err.issues.map(issue => `${issue.path ? `${issue.path}: ` : \"\"}${issue.message}`);\n console.log(chalk.yellow(\"• The existing rebase.json is invalid, so no app name, path or cms in it is kept:\"));\n for (const issue of issues.length > 0 ? issues : [err.message]) console.log(chalk.dim(` ${issue}`));\n }\n }\n\n const inferred = synthesizeManifest(projectRoot);\n const { manifest, removed } = declared\n ? keepDeclaredIdentity(inferred, declared)\n : { manifest: inferred, removed: [] };\n const filePath = writeManifest(projectRoot, manifest);\n\n console.log(chalk.green(`✓ Wrote ${path.relative(projectRoot, filePath)}`));\n console.log(\"\");\n for (const [name, app] of Object.entries(manifest.apps)) {\n console.log(` ${chalk.cyan(name)} ${chalk.dim(`(${app.type})`)}`);\n }\n for (const { name, app } of removed) {\n const where = app.type === \"static\" ? `, root ${app.root}` : \"\";\n console.log(` ${chalk.yellow(name)} ${chalk.dim(`(${app.type}${where})`)} ${chalk.yellow(\"— not found in this project, removed\")}`);\n }\n\n const compatibility = assessManagedCompatibility(manifest);\n if (!compatibility.eligible) {\n console.log(\"\");\n console.log(chalk.yellow(\"This project will use the custom runtime:\"));\n for (const reason of compatibility.reasons) {\n console.log(chalk.dim(` ${reason}`));\n }\n }\n}\n\n/**\n * Print what a client needs to reach this project.\n *\n * Never prints a secret. The API URL and an app's publishable identity are meant\n * to ship inside a client bundle; anything that is not safe there does not belong\n * in output that will inevitably be pasted into a `.env` that gets committed.\n */\nasync function printAppConfig(appName: string | undefined, asJson: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n const loaded = loadManifestOrExit(projectRoot, asJson);\n\n if (!appName) {\n if (asJson) {\n failAsJson(\"Which app? Usage: rebase apps config <app>\", \"app_not_named\",\n `Declared: ${Object.keys(loaded.manifest.apps).join(\", \") || \"(none)\"}`);\n }\n console.error(chalk.red(\"✗ Which app? Usage: rebase apps config <app>\"));\n process.exit(1);\n }\n\n const app = loaded.manifest.apps[appName];\n if (!app) {\n if (asJson) {\n failAsJson(`No app named \"${appName}\" in rebase.json.`, \"app_not_found\",\n `Declared: ${Object.keys(loaded.manifest.apps).join(\", \") || \"(none)\"}`);\n }\n console.error(chalk.red(`✗ No app named \"${appName}\" in rebase.json.`));\n console.error(chalk.dim(` Declared: ${Object.keys(loaded.manifest.apps).join(\", \") || \"(none)\"}`));\n process.exit(1);\n }\n\n const link = readLink(projectRoot);\n // An app the backend bundle serves calls the API on its own origin, so the\n // right value is empty — wherever the project is linked, and whatever a\n // dev server once wrote down. A URL here is baked into the build and\n // follows the bundle into production.\n const sameOrigin = servedByBackend(loaded.manifest, appName);\n const apiUrl = sameOrigin ? \"\" : resolveApiUrl(projectRoot, link);\n\n const config = {\n app: appName,\n type: app.type,\n apiUrl: apiUrl ?? null,\n sameOrigin,\n project: link?.projectId ?? link?.slug ?? null\n };\n\n if (asJson) {\n console.log(JSON.stringify(config, null, 2));\n return;\n }\n\n if (sameOrigin) {\n console.log(chalk.bold(`# ${appName}`));\n console.log(\"\");\n console.log(\"VITE_API_URL=\");\n console.log(\"\");\n console.log(chalk.dim(`Empty on purpose: \\`rebase build\\` folds ${appName} into the backend bundle, so it`));\n console.log(chalk.dim(\"calls the API on the same origin it is served from, locally and deployed alike.\"));\n console.log(chalk.dim(\"(`rebase dev` points it at the dev backend by itself.)\"));\n return;\n }\n\n // Whether the checkout is linked is a fact about the link, not about\n // whether `rebase dev` happens to be running: a running dev's address\n // used to fill the same slot, and the notice disappeared with it.\n if (!link?.apiUrl) {\n console.log(chalk.yellow(\"This checkout is not linked to a project yet.\"));\n // `rebase cloud link`, not `rebase link`. There has never been a\n // top-level `link` command — `cli.ts` dispatches `cloud`, and the link\n // lives inside that family — so this hint named something that exits 1\n // on the very screen that exists to tell you what to run next.\n console.log(chalk.dim(` Run ${chalk.cyan(\"rebase cloud link\")} (cloud) or ${chalk.cyan(\"rebase cloud link <url>\")} (self-hosted).`));\n console.log(chalk.dim(` Until then, this is the address ${chalk.cyan(\"rebase dev\")} serves this project on.`));\n console.log(\"\");\n }\n\n console.log(chalk.bold(`# ${appName}`));\n console.log(\"\");\n // Unlinked: the dev backend this project runs on, not a fixed 3001 — `rebase dev`\n // derives a port per project.\n console.log(`VITE_API_URL=${apiUrl ?? devServerUrl(projectRoot).url}`);\n console.log(\"\");\n console.log(chalk.dim(\"Then, in the app:\"));\n console.log(chalk.dim(\" const rebase = createRebaseClient({ baseUrl: import.meta.env.VITE_API_URL });\"));\n}\n\n/**\n * Work out the API base URL for this checkout.\n *\n * Prefers an explicit link, then the dev server's own record of where it bound.\n * The dev port is chosen dynamically, so a hardcoded default would be wrong on\n * any machine running more than one project.\n */\nfunction resolveApiUrl(projectRoot: string, link: ReturnType<typeof readLink>): string | undefined {\n if (link?.apiUrl) return link.apiUrl;\n // Only a dev server that is still running: the state file outlives the\n // process, and a port nothing listens on is not an address.\n return runningBackendUrl(projectRoot) ?? undefined;\n}\n\n/**\n * Whether `rebase build` folds this static app into the backend bundle, which\n * then serves it on the API's own origin: a managed backend, and an app with\n * built output to fold. The same predicate the build folds by.\n */\nexport function servedByBackend(manifest: ReturnType<typeof loadManifest>[\"manifest\"], appName: string): boolean {\n const backend = findBackendApp(manifest);\n if (!backend || backend.app.type !== \"backend\" || backend.app.runtime === \"custom\") return false;\n return foldableApps(manifest).apps.some(app => app.name === appName);\n}\n\nfunction loadManifestOrExit(projectRoot: string, asJson = false): ReturnType<typeof loadManifest> {\n try {\n return loadManifest(projectRoot);\n } catch (err) {\n if (err instanceof ManifestError) {\n // A caller that asked for JSON gets one on this exit too. It used\n // to get the human bullet list on stderr and an empty stdout —\n // `apps list --json` against the one manifest a caller most needs\n // to be told about.\n if (asJson) {\n failAsJson(err.message, \"manifest_invalid\", \"Fix rebase.json, then run this again.\",\n err.issues.map(issue => ({ path: issue.path, message: issue.message })));\n }\n console.error(chalk.red(`✗ ${err.message}`));\n for (const issue of err.issues) {\n console.error(chalk.red(` ${issue.path ? `${issue.path}: ` : \"\"}${issue.message}`));\n }\n process.exit(1);\n }\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAS,YAAkB;CACvB,QAAQ,IAAI;EACd,MAAM,KAAK,aAAa,EAAE;;EAE1B,MAAM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KAAK,KAAA;AAC7C;;;;;;AAOA,SAAgB,gBAAgB,UAAuD,SAA0B;CAC7G,MAAM,UAAU,eAAe,QAAQ;CACvC,IAAI,CAAC,WAAW,QAAQ,IAAI,SAAS,aAAa,QAAQ,IAAI,YAAY,UAAU,OAAO;CAC3F,OAAO,aAAa,QAAQ,CAAC,CAAC,KAAK,MAAK,QAAO,IAAI,SAAS,OAAO;AACvE;AAEA,SAAS,mBAAmB,aAAqB,SAAS,OAAwC;CAC9F,IAAI;EACA,OAAO,aAAa,WAAW;CACnC,SAAS,KAAK;EACV,IAAI,eAAe,eAAe;GAK9B,IAAI,QACA,WAAW,IAAI,SAAS,oBAAoB,yCACxC,IAAI,OAAO,KAAI,WAAU;IAAE,MAAM,MAAM;IAAM,SAAS,MAAM;GAAQ,EAAE,CAAC;GAE/E,QAAQ,MAAM,MAAM,IAAI,KAAK,IAAI,SAAS,CAAC;GAC3C,KAAK,MAAM,SAAS,IAAI,QACpB,QAAQ,MAAM,MAAM,IAAI,OAAO,MAAM,OAAO,GAAG,MAAM,KAAK,MAAM,KAAK,MAAM,SAAS,CAAC;GAEzF,QAAQ,KAAK,CAAC;EAClB;EACA,MAAM;CACV;AACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"args-CaCcrYE1.js","names":[],"sources":["../src/utils/redact.ts","../src/utils/unknown-command.ts","../src/utils/args.ts"],"sourcesContent":["/**\n * Connection-string passwords, replaced before a line is printed.\n *\n * A refusal that repeats what was typed repeats a password with it, and these\n * lines land in terminals, CI logs and issues. `user:***@` is the form every\n * other message uses: the driver's `redactConnectionPasswords` in\n * `@rebasepro/server-postgres`, which its entry does not export, and this\n * mirrors. Covers the user-info password and a `password=` parameter.\n */\nexport function redactConnectionPasswords(text: string): string {\n return text\n .replace(/(\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s/?#@'\"]*):[^\\s/?#'\"]*@/gi, \"$1:***@\")\n .replace(/(\\bpassword\\s*=\\s*)('[^']*'|[^\\s&'\"]+)/gi, \"$1***\");\n}\n","/**\n * What every command family says when it does not recognise a subcommand.\n *\n * Six families each did it differently, and the differences were not stylistic:\n *\n * rebase statsu \"Unknown command: statsu\" + the whole top-level help\n * rebase auth foo \"Unknown auth command: foo\" + the whole auth help\n * rebase apps foo \"Unknown subcommand: foo\" — which command's?\n * rebase skills foo \"Unknown skills subcommand: foo\" + the whole help\n * rebase telemetry x the help, silently, with exit code 1 and no error line\n * rebase cloud debug x both a JSON error *and* the human one, in JSON mode\n *\n * Dumping a screen of help after an error is the wrong shape: the one line that\n * says what happened scrolls off the top, and in a CI log it is buried in\n * forty. None of them offered the correction, which for a typo is the entire\n * answer — `statsu` is one transposition from `status`.\n *\n * So: one line, the near-miss when there is one, and where to read the rest.\n */\nimport chalk from \"chalk\";\n\nimport { redactConnectionPasswords } from \"./redact\";\n\n/**\n * Damerau–Levenshtein distance, capped by the caller.\n *\n * The transposition is the reason this is not plain Levenshtein: `statsu` for\n * `status` and `craete` for `create` are the two most common typing errors\n * there are, and both are distance 2 without it — the same as two unrelated\n * edits, which is too far to suggest anything at all.\n */\nfunction editDistance(a: string, b: string): number {\n const rows = a.length + 1;\n const cols = b.length + 1;\n const d: number[][] = Array.from({ length: rows }, () => new Array<number>(cols).fill(0));\n\n for (let i = 0; i < rows; i++) d[i][0] = i;\n for (let j = 0; j < cols; j++) d[0][j] = j;\n\n for (let i = 1; i < rows; i++) {\n for (let j = 1; j < cols; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n d[i][j] = Math.min(\n d[i - 1][j] + 1,\n d[i][j - 1] + 1,\n d[i - 1][j - 1] + cost\n );\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n return d[a.length][b.length];\n}\n\n/**\n * The one command the user probably meant, or nothing.\n *\n * Tight on purpose. A suggestion that is wrong is worse than none: it sends\n * someone to read the help for a command that was never the answer, and on a\n * family like `db` — where `push` and `pull` are one edit apart — a loose\n * threshold would confidently propose the destructive neighbour of what they\n * typed. So: one edit for a short word, two for a long one, and a prefix match\n * always counts (`rebase cloud dep` for `deploy`).\n */\nexport function suggestCommand(typed: string, known: readonly string[]): string | undefined {\n const word = typed.toLowerCase();\n if (!word) return undefined;\n\n // An abbreviation, but only when it names exactly one command. \"res\" is a\n // prefix of both `reset` and `restore`, and picking whichever comes first\n // in the list would be a coin toss dressed up as an answer.\n if (word.length >= 3) {\n const prefixed = known.filter(name => name.toLowerCase().startsWith(word));\n if (prefixed.length === 1) return prefixed[0];\n }\n\n const budget = word.length <= 4 ? 1 : 2;\n let best: { name: string; distance: number } | undefined;\n\n for (const candidate of known) {\n const distance = editDistance(word, candidate.toLowerCase());\n if (distance > budget) continue;\n if (!best || distance < best.distance) best = { name: candidate, distance };\n }\n\n return best?.name;\n}\n\n/**\n * The family command a word names exactly, as `<family> <command>`, or nothing.\n *\n * `rebase deploy` is `rebase cloud deploy`: the word is a whole command one\n * level down. Exact only — a near miss there is a guess about both the family\n * and the command.\n */\nfunction familyCommand(typed: string, families: Readonly<Record<string, readonly string[]>>): string | undefined {\n const word = typed.toLowerCase();\n for (const [family, commands] of Object.entries(families)) {\n const match = commands.find(name => name.toLowerCase() === word);\n if (match) return `${family} ${match}`;\n }\n return undefined;\n}\n\n/**\n * The line itself, without printing it — so callers that must answer in JSON\n * (the cloud family, whose `fail()` writes a machine-readable envelope) use the\n * same words as the ones that print.\n *\n * `family` is empty for the top level: `rebase --help`, not `rebase --help`.\n * `families` are the command families below this level, by name, whose\n * commands a word may be one of.\n *\n * The typed word is repeated with any connection-string password masked: a URL\n * pasted where the command goes (`rebase db \"postgres://u:pw@h/db\"`) is a\n * word like any other here, and this line lands in terminals and CI logs.\n */\nexport function unknownCommandMessage(\n typed: string | undefined,\n known: readonly string[],\n family = \"\",\n families: Readonly<Record<string, readonly string[]>> = {}\n): string {\n const what = family ? `${family} command` : \"command\";\n const suggestion = typed ? suggestCommand(typed, known) ?? familyCommand(typed, families) : undefined;\n const help = family ? `rebase ${family} --help` : \"rebase --help\";\n const shown = redactConnectionPasswords(typed ?? \"\");\n\n return suggestion\n ? `Unknown ${what} \"${shown}\" — did you mean \\`${suggestion}\\`? Run \\`${help}\\` for the rest.`\n : `Unknown ${what} \"${shown}\". Run \\`${help}\\` for the ones there are.`;\n}\n\n/**\n * Print the line to stderr and exit 1.\n *\n * stderr, not stdout: a mistyped command is a failure, and the families with a\n * `--json` mode guarantee that stdout holds only their envelope.\n */\nexport function unknownCommand(\n typed: string | undefined,\n known: readonly string[],\n family = \"\",\n families: Readonly<Record<string, readonly string[]>> = {}\n): never {\n console.error(chalk.red(`✗ ${unknownCommandMessage(typed, known, family, families)}`));\n process.exit(1);\n}\n","/**\n * Argument parsing for the commands that take positional arguments.\n *\n * Every command in the small group used to parse its own line the same way:\n * `arg(spec, { argv: rawArgs.slice(4), permissive: true })`, then read `_[0]`\n * and `_[1]`. Both halves of that are wrong in a way that costs data.\n *\n * - **`permissive: true` turns an unknown flag into a positional.** `arg`\n * pushes an undeclared flag into `_` as a bare token, so `_[1]` is whatever\n * came second on the line, flag or not. `rebase auth reset-password\n * bob@example.com --debug` set Bob's password to the literal `--debug` — and\n * `--debug` is what `bin/rebase.js` prints after *every* failure as the thing\n * to re-run with, so the single most likely next keystroke after a failed\n * reset was the one that reset the account to a two-word string.\n * - **`slice(4)` assumes the command words are at fixed indices.** They are\n * not: a flag before the command shifts everything, so `rebase --debug auth\n * reset-password bob@example.com NewPass1!` read the email as\n * `reset-password` and the password as `bob@example.com`.\n *\n * So: parse the *whole* line — `rawArgs` is `process.argv` — against a spec\n * strictly, with no permissive mode. `arg` then consumes every flag wherever it\n * appears and rejects the ones nobody declared, which leaves `_` holding the\n * command words followed by the real positionals, in order and at a known\n * offset. An unrecognised flag becomes an error naming the command's help,\n * which is the only safe answer: the alternative is guessing that it was meant\n * as a value.\n *\n * `commands/cloud/index.ts` resolves its positionals against its own spec for\n * the same reason; this is that idea for the commands whose positionals are\n * credentials rather than resource names.\n */\nimport arg from \"arg\";\n\nimport { redactConnectionPasswords } from \"./redact\";\nimport { suggestCommand } from \"./unknown-command\";\n\n/**\n * Flags accepted on top of whatever a command declares.\n *\n * `--debug` is read by `bin/rebase.js` off `process.argv` and never by a\n * command, but it has to be *declared* somewhere or strict parsing rejects the\n * exact flag the CLI tells people to add. `--help`/`-h` are answered by each\n * command's dispatcher before any work happens.\n */\nexport const GLOBAL_COMMAND_FLAGS = {\n \"--debug\": Boolean,\n \"--help\": Boolean,\n \"-h\": \"--help\"\n} as const;\n\n/**\n * The declared long flag an undeclared one was probably meant to be: one edit\n * or one swap away (`--form` → `--from`), or an abbreviation of exactly one\n * (`--anon` → `--anonymize`).\n */\nfunction closestDeclaredFlag(typed: string, declared: readonly string[]): string | undefined {\n if (!typed.startsWith(\"--\")) return undefined;\n const near = suggestCommand(typed.slice(2), declared.filter(flag => flag.startsWith(\"--\")).map(flag => flag.slice(2)));\n return near ? `--${near}` : undefined;\n}\n\n/** Past this many, a refusal names the help page rather than listing every flag. */\nconst LISTED_FLAGS_MAX = 8;\n\n/**\n * The sentence an undeclared flag is refused with — the one `db backup`,\n * `db restore` and `db branch` say, so one CLI answers a typo one way:\n *\n * `rebase db pull` has no option --anonymise — did you mean --anonymize?\n * Nothing was run. See `rebase db pull --help`.\n *\n * With nothing close it lists what the command takes, when that list is short\n * enough to read.\n *\n * `typed` is the argument as `arg` refused it, and only its flag part is\n * repeated: a value given inline (`--fro=postgres://u:pw@h/db`) is not. One\n * argument holding a flag and its value, quoted together, is named as that,\n * and what it quotes is password-masked: `\"--fro postgres://u:pw@h/db\"` was\n * refused with the whole URL, password included, in the middle of a garbled\n * sentence.\n *\n * Exported for the commands that refuse a flag outside `parseCommandArgs`.\n */\nexport function unknownOptionMessage(command: string, typed: string, spec: Readonly<Record<string, unknown>>): string {\n const declared = Object.keys({ ...GLOBAL_COMMAND_FLAGS, ...spec });\n const name = typed.split(/[=\\s]/)[0];\n const near = closestDeclaredFlag(name, declared);\n const tail = ` Nothing was run. See \\`rebase ${command} --help\\`.`;\n\n if (/\\s/.test(typed.trim())) {\n const flag = declared.includes(name) ? name : near;\n const how = flag\n ? ` Write them as two arguments, ${flag} <value>, or as ${flag}=<value>.`\n : \" Write a flag and its value as two arguments.\";\n return `\\`rebase ${command}\\` has no option \"${redactConnectionPasswords(typed)}\": ` +\n `that is a flag and a value in one argument, quoted together.${how}${tail}`;\n }\n\n const own = Object.keys(spec).filter(flag => flag.startsWith(\"--\") && !(flag in GLOBAL_COMMAND_FLAGS));\n const takes = near\n ? ` — did you mean ${near}?`\n : own.length === 0\n ? \" — it takes no options.\"\n : own.length <= LISTED_FLAGS_MAX ? ` — it takes ${own.join(\", \")}.` : \".\";\n\n return `\\`rebase ${command}\\` has no option ${name}${takes}${tail}`;\n}\n\n/** What a flag resolves to, through its alias (`\"-y\": \"--yes\"`). */\nfunction handlerOf(spec: Readonly<Record<string, unknown>>, flag: string): unknown {\n const declared = spec[flag];\n return typeof declared === \"string\" ? spec[declared] : declared;\n}\n\n/** A flag that takes no value: on when given, off when left out. */\nfunction isSwitch(handler: unknown): boolean {\n return handler === Boolean || (Array.isArray(handler) && handler[0] === Boolean);\n}\n\n/** The values a switch reads as on, and as off, after its `=`. */\nconst SWITCH_ON = /^(?:true|1)$/i;\nconst SWITCH_OFF = /^(?:false|0)$/i;\n\n/**\n * A line with every `--switch=value` resolved: `=true` or `=1` is the switch\n * alone, `=false` or `=0` drops it, and any other value is refused.\n *\n * `arg` drops the value of a flag that takes none and turns the flag on, so\n * `--anonymize=false` anonymized and `--yes=false` answered yes. `=true` kept\n * working by that same accident, and scripts write it, so the two readings a\n * value can have are honoured and nothing else is guessed at. Past `--` every\n * word is a positional, so nothing there is read.\n *\n * @throws UsageError naming the switch and the values it takes.\n */\nexport function resolveSwitchValues(\n spec: Readonly<Record<string, unknown>>,\n argv: readonly string[],\n command: string\n): string[] {\n const resolved: string[] = [];\n for (let index = 0; index < argv.length; index += 1) {\n const word = argv[index];\n if (word === \"--\") {\n resolved.push(...argv.slice(index));\n break;\n }\n const flag = word.startsWith(\"--\") && word.includes(\"=\") ? word.slice(0, word.indexOf(\"=\")) : null;\n if (flag === null || !isSwitch(handlerOf(spec, flag))) {\n resolved.push(word);\n continue;\n }\n const value = word.slice(flag.length + 1);\n if (SWITCH_ON.test(value)) resolved.push(flag);\n else if (!SWITCH_OFF.test(value)) throw new UsageError(switchValueMessage(command, flag, word));\n }\n return resolved;\n}\n\n/**\n * Whether a switch is on in a line read by hand: given alone, or as `=true`\n * or `=1`, before any `--`. The reading {@link resolveSwitchValues} gives the\n * parsed flags, for the code that looks at `rawArgs` itself.\n */\nexport function switchOn(rawArgs: readonly string[], flag: string): boolean {\n for (const word of rawArgs) {\n if (word === \"--\") return false;\n if (word === flag) return true;\n if (word.startsWith(`${flag}=`) && SWITCH_ON.test(word.slice(flag.length + 1))) return true;\n }\n return false;\n}\n\n/** The sentence a switch given a value it cannot read is refused with. */\nexport function switchValueMessage(command: string, flag: string, typed: string): string {\n return `\\`rebase ${command}\\` cannot read ${redactConnectionPasswords(typed)}: ${flag} is a switch, ` +\n `and after its = it takes true or 1 to turn it on, false or 0 to turn it off. ` +\n `Nothing was run. See \\`rebase ${command} --help\\`.`;\n}\n\nexport interface ParsedCommand<S extends arg.Spec> {\n /** The declared flags, as `arg` resolved them. */\n flags: arg.Result<S>;\n /** What is left after the command words — never a flag. */\n positionals: string[];\n /** `--help` or `-h` appeared anywhere on the line. */\n help: boolean;\n}\n\n/** Did the line ask for help? Answered before dispatch, never by a handler. */\nexport function wantsHelp(rawArgs: string[]): boolean {\n return rawArgs.includes(\"--help\") || rawArgs.includes(\"-h\");\n}\n\n/**\n * The command line was wrong — nothing ran, and there is no stack to want.\n *\n * `bin/rebase.js` ends every failure with \"Re-run with --debug for the stack\n * trace.\", which is right when something broke inside a command and absurd for\n * a typo: the stack points at `arg` and this file, neither of which the person\n * who mistyped `--ouput` has any interest in. Worse, `--debug` is a flag, so\n * the suggested next command is *another* command line — and the one thing we\n * have just established is that the command line is what went wrong.\n *\n * Marked with a property rather than left to `instanceof`, because the reader\n * is `bin/rebase.js`: it imports the bundle, so the class object it would test\n * against is not the one this file compiled to.\n */\nexport class UsageError extends Error {\n readonly isUsageError = true;\n\n constructor(message: string) {\n super(message);\n this.name = \"UsageError\";\n }\n}\n\n/**\n * Resolve a command's flags and positionals from the full `process.argv`.\n *\n * `commandWords` is how many words name the command itself — 2 for\n * `auth reset-password`, 1 for `start` — and is applied to the *parsed*\n * positionals rather than to `argv`, so a flag placed before the command no\n * longer shifts them.\n *\n * `command` names the command in error messages, e.g. `auth reset-password`.\n *\n * Throws on an unknown flag, on a switch given a value other than true,\n * false, 1 or 0 (`--yes=maybe`), on a positional that looks like a flag, and\n * on more positionals than the command takes. `bin/rebase.js` turns each into\n * a one-line `✗ …` and exit 1.\n */\nexport function parseCommandArgs<S extends arg.Spec>({\n spec,\n rawArgs,\n commandWords,\n command,\n maxPositionals\n}: {\n spec: S;\n rawArgs: string[];\n commandWords: number;\n command: string;\n maxPositionals?: number;\n}): ParsedCommand<S> {\n let parsed: arg.Result<S> & { \"--help\"?: boolean };\n const merged = {\n ...GLOBAL_COMMAND_FLAGS,\n ...spec\n };\n const argv = resolveSwitchValues(merged, rawArgs.slice(2), command);\n try {\n parsed = arg(merged, { argv }) as arg.Result<S> & { \"--help\"?: boolean };\n } catch (err) {\n if (err instanceof Error && (err as arg.ArgError).code === \"ARG_UNKNOWN_OPTION\") {\n // arg's wording: `unknown or unexpected option: --form`, naming\n // the argument up to its first `=`, past a space in it too. The\n // word it came from is what was typed.\n const named = /option: ([\\s\\S]+)$/.exec(err.message)?.[1] ?? \"\";\n const typed = rawArgs.slice(2).find(word => word === named || word.startsWith(`${named}=`)) ?? named;\n throw new UsageError(unknownOptionMessage(command, typed, spec));\n }\n throw err;\n }\n\n const positionals = parsed._.slice(commandWords);\n\n for (const value of positionals) {\n // Only reachable past a `--` separator or for a bare `-`, since anything\n // else beginning with `-` was either declared or already rejected above.\n // Still refused rather than accepted: a value that looks like a flag is\n // as likely to be a typo as an argument, and one of these positions is a\n // password.\n if (value.startsWith(\"-\")) {\n throw new UsageError(\n `\\`${redactConnectionPasswords(value)}\\` looks like an option, not a value — pass it with an explicit flag ` +\n `(\\`rebase ${command} --help\\`).`\n );\n }\n }\n\n if (maxPositionals !== undefined && positionals.length > maxPositionals) {\n // Redacted: a connection string passed where a flag's value belongs\n // (`rebase db pull \"$PROD\"`) is still a password.\n throw new UsageError(\n `rebase ${command} takes ${maxPositionals} argument${maxPositionals === 1 ? \"\" : \"s\"}, ` +\n `got ${positionals.length}: ${redactConnectionPasswords(positionals.join(\" \"))}`\n );\n }\n\n return {\n flags: parsed,\n positionals,\n help: Boolean(parsed[\"--help\"])\n };\n}\n"],"mappings":";;;;;;;;;;;;AASA,SAAgB,0BAA0B,MAAsB;CAC5D,OAAO,KACF,QAAQ,yDAAyD,SAAS,CAAC,CAC3E,QAAQ,4CAA4C,OAAO;AACpE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACkBA,SAAS,aAAa,GAAW,GAAmB;CAChD,MAAM,OAAO,EAAE,SAAS;CACxB,MAAM,OAAO,EAAE,SAAS;CACxB,MAAM,IAAgB,MAAM,KAAK,EAAE,QAAQ,KAAK,SAAS,IAAI,MAAc,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC;CAExF,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK,EAAE,EAAE,CAAC,KAAK;CACzC,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK,EAAE,EAAE,CAAC,KAAK;CAEzC,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KACtB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK;EAC3B,MAAM,OAAO,EAAE,IAAI,OAAO,EAAE,IAAI,KAAK,IAAI;EACzC,EAAE,EAAE,CAAC,KAAK,KAAK,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