@rebasepro/cli 0.31.0 → 0.33.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-ofQETpM5.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-E5hfEWKj.js} +23 -10
- package/dist/build-E5hfEWKj.js.map +1 -0
- 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-DNJyUU0T.js} +1715 -1516
- package/dist/cloud-DNJyUU0T.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 +7 -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-Bks5xkrQ.js} +89 -44
- package/dist/command-Bks5xkrQ.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 +12 -1
- 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/service-key.d.ts +33 -1
- 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-DjThnr3f.js → console-BVoYOLAO.js} +6 -6
- package/dist/{console-DjThnr3f.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-Bz2RFGJj.js → db-D_iF4E-v.js} +38 -34
- package/dist/{db-Bz2RFGJj.js.map → db-D_iF4E-v.js.map} +1 -1
- 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-D8TxrE_I.js → dev-bj6dEeSQ.js} +13 -13
- package/dist/{dev-D8TxrE_I.js.map → dev-bj6dEeSQ.js.map} +1 -1
- package/dist/dev-db/pull.d.ts +13 -3
- 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-Du-mSxoE.js → doctor-FaBObSlb.js} +29 -10
- package/dist/doctor-FaBObSlb.js.map +1 -0
- package/dist/doctor-environment.d.ts +9 -0
- 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/legacy-layout-DI2VeQSV.js +36 -0
- package/dist/legacy-layout-DI2VeQSV.js.map +1 -0
- package/dist/logs-DpuMukJe.js +192 -0
- package/dist/logs-DpuMukJe.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-CSY9ZDKy.js} +5 -4
- package/dist/{migrate-VrKoi3nB.js.map → migrate-CSY9ZDKy.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-BMuiUyjb.js → pull-CTIsST6T.js} +66 -5
- 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-Dv6nHkb0.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-BTgTWzlQ.js → status-CDBk25VO.js} +9 -9
- package/dist/{status-BTgTWzlQ.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-ZASvgxWM.js} +41 -9
- package/dist/{upgrade-oZzJ13jM.js.map → upgrade-ZASvgxWM.js.map} +1 -1
- package/dist/users-5PkqBY6R.js +561 -0
- package/dist/users-5PkqBY6R.js.map +1 -0
- package/dist/utils/legacy-layout.d.ts +22 -0
- package/dist/utils/project-command.d.ts +38 -0
- package/dist/utils/project-target.d.ts +193 -0
- package/dist/{verify-BkUVGLqo.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/templates/overlays/baas/backend/package.json +3 -1
- package/templates/template/backend/package.json +3 -1
- 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-ofQETpM5.js.map +0 -1
- package/dist/build-CA5R07tw.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/doctor-Du-mSxoE.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-BMuiUyjb.js.map +0 -1
- package/dist/resolve-BY7bSFRT.js +0 -2
- package/dist/schema-Dv6nHkb0.js.map +0 -1
- package/dist/schema-reconcile-CjxLaRHB.js +0 -2
- package/dist/storage-iTqj5-Av.js.map +0 -1
- package/dist/verify-BkUVGLqo.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-view-CTOluXvH.js","names":[],"sources":["../src/commands/generate-view.ts"],"sourcesContent":["/**\n * `rebase generate view <slug>` — scaffold a custom admin screen and register it.\n *\n * Most back-office screens are a table, a form or a board, and the admin draws\n * those from the table. The rest — a dispatch board, a reconciliation\n * screen, a record's audit trail — are a hundred lines of React. Written inside\n * the admin they inherit the sign-in, the security rules, the sidebar, the UI\n * kit and the data layer; written as a separate app they have to rebuild every\n * one of those. This command writes the first version of that file where the\n * admin will find it, so the screen starts native and registered.\n *\n * Two places, one file each:\n *\n * - **A screen** (default): `<frontend>/src/views/<Name>View.tsx`, listed in\n * `<frontend>/src/views/index.ts` as an `AppView`, which `App.tsx` hands to\n * `<RebaseCMS views>`. The first run wires `App.tsx`; later runs only append\n * to the list.\n * - **A record tab** (`--collection <slug>`, the slug of a table in\n * `backend/schema`): the same file location, with a component that takes\n * `EntityCustomViewParams`, added to the `entityViews` of that table's\n * `customizeTable(…)` in `<frontend>/src/cms/` — imported directly, because\n * that directory is the admin's own code and the backend never reads it. A\n * table with no customization yet gets one, `<frontend>/src/cms/<slug>.tsx`,\n * listed in `cms/index.ts`'s `tableCustomizations` when there is one.\n *\n * The frontend is where `rebase.json` says the CMS is (the static app with a\n * `cms` mount), which is `frontend/` in everything `rebase init` writes. A\n * project with no admin panel (`rebase init --headless`) is refused: there is\n * nowhere for a view to render.\n *\n * Edits to existing files are textual and conservative. When `App.tsx` already\n * passes its own `views`, or a customization's shape is not one this can read, the\n * view file is still written and the command prints the one line to add by\n * hand instead of guessing.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport chalk from \"chalk\";\n\nimport { tableIdentifier } from \"@rebasepro/common\";\nimport { cmsMountOf, loadManifest } from \"../manifest\";\nimport { resolveSchemaDir } from \"../utils/schema-dir\";\nimport { declaredTables } from \"../utils/schema-text\";\nimport { requireProjectRoot } from \"../utils/project\";\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\n/** What `rebase generate` dispatches. Read by `cli.ts` to name the subcommand. */\nexport const GENERATE_SUBCOMMANDS = [\"view\"] as const;\n\nconst VIEW_FLAGS = {\n \"--collection\": String,\n \"--name\": String,\n \"--icon\": String,\n \"--dry-run\": Boolean,\n \"--force\": Boolean\n} as const;\n\n/** A slug is a URL segment and an entity view key: kebab-case, starting with a letter. */\nconst SLUG_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\n\n/**\n * Top-level paths the admin's own routes answer (`RebaseRouteDefs` in\n * `@rebasepro/cms`): `/c/*` the collections, `/s` Studio, `/settings`. They are\n * declared before custom views, so a screen at one of them was listed in the\n * sidebar and opened the built-in page instead.\n */\nconst RESERVED_SCREEN_SLUGS: readonly string[] = [\"c\", \"s\", \"settings\"];\n\nexport interface GenerateViewOptions {\n projectRoot: string;\n slug: string;\n /** Register as a tab on this table's records (its slug) instead of as a screen. */\n collection?: string;\n /** The label in the sidebar or on the tab. Defaults to the slug in sentence case. */\n name?: string;\n /** A Lucide icon name for the sidebar. Screens only. */\n icon?: string;\n /** Replace an existing view file. Registration is never duplicated. */\n force?: boolean;\n}\n\nexport interface PlannedFile {\n /** Absolute path. */\n path: string;\n contents: string;\n action: \"create\" | \"update\" | \"replace\";\n}\n\nexport interface GenerateViewPlan {\n kind: \"app\" | \"entity\";\n componentName: string;\n viewFile: string;\n files: PlannedFile[];\n /** Steps the command could not take itself, as sentences to print. */\n manualSteps: string[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Names\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** `orders-board` → `OrdersBoardView`; `sales-view` → `SalesView`, not `SalesViewView`. */\nexport function viewComponentName(slug: string): string {\n const pascal = slug.split(\"-\").map(part => part.charAt(0).toUpperCase() + part.slice(1)).join(\"\");\n return pascal.endsWith(\"View\") ? pascal : `${pascal}View`;\n}\n\n/** `orders-board` → `Orders board`: labels are sentence case in the admin. */\nexport function viewLabel(slug: string): string {\n const words = slug.split(\"-\").join(\" \");\n return words.charAt(0).toUpperCase() + words.slice(1);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Reading source without a parser\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The source with every string, template literal, regular expression and\n * comment blanked out, character for character, so brackets and keys can be\n * found by position without being fooled by a `{` inside a string. String\n * contents become `_` (they are still \"something\"), comments become spaces.\n *\n * Exported for its tests.\n */\nexport function maskCode(source: string): string {\n const out = source.split(\"\");\n let i = 0;\n const blank = (from: number, to: number, fill: string) => {\n for (let k = from; k < to; k++) if (out[k] !== \"\\n\") out[k] = fill;\n };\n const previousSignificant = (at: number): string => {\n for (let k = at - 1; k >= 0; k--) {\n const ch = out[k];\n if (ch !== \" \" && ch !== \"\\t\" && ch !== \"\\n\" && ch !== \"\\r\") return ch;\n }\n return \"\";\n };\n while (i < source.length) {\n const ch = source[i];\n const next = source[i + 1];\n if (ch === \"/\" && next === \"/\") {\n const end = source.indexOf(\"\\n\", i);\n const stop = end === -1 ? source.length : end;\n blank(i, stop, \" \");\n i = stop;\n } else if (ch === \"/\" && next === \"*\") {\n const end = source.indexOf(\"*/\", i + 2);\n const stop = end === -1 ? source.length : end + 2;\n blank(i, stop, \" \");\n i = stop;\n } else if (ch === \"\\\"\" || ch === \"'\" || ch === \"`\") {\n let k = i + 1;\n while (k < source.length && source[k] !== ch) {\n if (source[k] === \"\\\\\") k++;\n k++;\n }\n blank(i + 1, k, \"_\");\n i = k + 1;\n } else if (ch === \"/\" && (previousSignificant(i) === \"\" || \"(,=:[!&|?{;\".includes(previousSignificant(i)))) {\n // A regular expression literal: `/` where a value is expected. Not\n // after `}`, which in a .tsx file is far more often `{value}/>`.\n let k = i + 1;\n let inClass = false;\n while (k < source.length && source[k] !== \"\\n\") {\n if (source[k] === \"\\\\\") k++;\n else if (source[k] === \"[\") inClass = true;\n else if (source[k] === \"]\") inClass = false;\n else if (source[k] === \"/\" && !inClass) break;\n k++;\n }\n blank(i + 1, k, \"_\");\n i = k + 1;\n } else {\n i++;\n }\n }\n return out.join(\"\");\n}\n\nconst CLOSERS: Record<string, string> = { \"{\": \"}\", \"[\": \"]\", \"(\": \")\" };\n\n/** The index of the bracket closing the one at `open`, in masked source. */\nfunction matchClose(masked: string, open: number): number {\n const stack: string[] = [];\n for (let i = open; i < masked.length; i++) {\n const ch = masked[i];\n if (ch in CLOSERS) stack.push(CLOSERS[ch]);\n else if (ch === \"}\" || ch === \"]\" || ch === \")\") {\n if (stack.pop() !== ch) return -1;\n if (stack.length === 0) return i;\n }\n }\n return -1;\n}\n\n/** The index of the innermost `{` still open at `at`, in masked source. */\nfunction enclosingBrace(masked: string, at: number): number {\n const stack: number[] = [];\n for (let i = 0; i < at; i++) {\n const ch = masked[i];\n if (ch === \"{\" || ch === \"[\" || ch === \"(\") stack.push(i);\n else if (ch === \"}\" || ch === \"]\" || ch === \")\") stack.pop();\n }\n for (let k = stack.length - 1; k >= 0; k--) {\n if (masked[stack[k]] === \"{\") return stack[k];\n }\n return -1;\n}\n\n/**\n * The position of `key:` as a direct property of the object whose `{` is at\n * `open`, followed by `opener` (`{` or `[`) — or -1.\n */\nfunction directProperty(masked: string, open: number, key: string, opener: \"{\" | \"[\"): { keyAt: number; valueOpen: number } | undefined {\n const close = matchClose(masked, open);\n if (close === -1) return undefined;\n const pattern = new RegExp(`(^|[\\\\s,{])${key}\\\\s*:\\\\s*\\\\${opener}`, \"g\");\n const body = masked.slice(open + 1, close);\n for (const match of body.matchAll(pattern)) {\n const keyAt = open + 1 + (match.index ?? 0) + match[1].length;\n if (enclosingBrace(masked, keyAt) !== open) continue;\n return { keyAt, valueOpen: open + 1 + (match.index ?? 0) + match[0].length - 1 };\n }\n return undefined;\n}\n\nfunction lineStart(source: string, at: number): number {\n return source.lastIndexOf(\"\\n\", at - 1) + 1;\n}\n\nfunction indentAt(source: string, at: number): string {\n const start = lineStart(source, at);\n return /^[ \\t]*/.exec(source.slice(start))?.[0] ?? \"\";\n}\n\n/**\n * The indentation step a file uses: the smallest non-zero leading run of\n * spaces, not counting the ` * ` lines of a block comment.\n */\nfunction indentUnit(source: string): string {\n if (/^\\t/m.test(source)) return \"\\t\";\n let unit = Infinity;\n for (const match of source.matchAll(/^( +)[^\\s*]/gm)) unit = Math.min(unit, match[1].length);\n return \" \".repeat(Number.isFinite(unit) ? unit : 4);\n}\n\nfunction reindent(block: string, indent: string): string {\n return block.split(\"\\n\").map(line => (line ? indent + line : line)).join(\"\\n\");\n}\n\n/**\n * Insert `element` (already indented one level past `indent`) as the last item\n * of the array whose `[` is at `open`.\n */\nfunction appendToArray(source: string, masked: string, open: number, element: string): string {\n const close = matchClose(masked, open);\n const inner = masked.slice(open + 1, close);\n const indent = indentAt(source, open);\n if (inner.trim() === \"\") {\n return `${source.slice(0, open + 1)}\\n${element}\\n${indent}${source.slice(close)}`;\n }\n // After the last non-blank character of the content, keeping any comment\n // after it where it was.\n let last = close - 1;\n while (last > open && /\\s/.test(masked[last])) last--;\n const hasTrailingComma = masked[last] === \",\";\n const insertAt = last + 1;\n return `${source.slice(0, insertAt)}${hasTrailingComma ? \"\" : \",\"}\\n${element}${source.slice(insertAt)}`;\n}\n\n/** Add an import line after the file's last import statement. */\nfunction addImport(source: string, line: string): string {\n const masked = maskCode(source);\n let end = 0;\n for (const match of masked.matchAll(/^import\\b[\\s\\S]*?[\"'][^\"'\\n]*[\"'];?[ \\t]*$/gm)) {\n end = (match.index ?? 0) + match[0].length;\n }\n if (end === 0) return `${line}\\n${source}`;\n return `${source.slice(0, end)}\\n${line}${source.slice(end)}`;\n}\n\n/** A path import from `fromDir` to `toFile`, without extension, always starting with `.`. */\nfunction relativeImport(fromDir: string, toFile: string): string {\n const relative = path.relative(fromDir, toFile).split(path.sep).join(\"/\").replace(/\\.tsx?$/, \"\");\n return relative.startsWith(\".\") ? relative : `./${relative}`;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Where things are\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** The admin's frontend directory: the static app that mounts the CMS, or `frontend/`. */\nexport function resolveFrontendDir(projectRoot: string): string | undefined {\n try {\n const cms = cmsMountOf(loadManifest(projectRoot).manifest);\n if (cms) return path.join(projectRoot, cms.app.root);\n } catch {\n // A malformed rebase.json is reported by the commands that own it.\n }\n const fallback = path.join(projectRoot, \"frontend\");\n return fs.existsSync(path.join(fallback, \"src\")) ? fallback : undefined;\n}\n\n/** The tables directory, as the backend app declares it — one resolver for every command. */\nexport { resolveSchemaDir };\n\n/** Every source file under the admin's `src/cms`, sorted: where table customizations live. */\nfunction customizationFiles(dir: string): string[] {\n if (!fs.existsSync(dir)) return [];\n const out: string[] = [];\n const entries = fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name !== \"node_modules\") out.push(...customizationFiles(full));\n } else if (/\\.tsx?$/.test(entry.name) && !/\\.(test|spec|d)\\.tsx?$/.test(entry.name)) {\n out.push(full);\n }\n }\n return out;\n}\n\n/**\n * Every `customizeTable(\"<slug>\", {` of a table, in code (not in a comment or\n * a string): the file, and where the options object opens. Empty when no file\n * under `cmsDir` customizes the table.\n */\nfunction findCustomization(cmsDir: string, slug: string): { file: string; optionsOpen: number }[] {\n const found: { file: string; optionsOpen: number }[] = [];\n const call = /\\bcustomizeTable\\s*(?:<[^>]*>)?\\(\\s*([\"'`])([^\"'`\\n]+)\\1\\s*,\\s*\\{/g;\n for (const file of customizationFiles(cmsDir)) {\n const source = fs.readFileSync(file, \"utf8\");\n const masked = maskCode(source);\n for (const match of source.matchAll(call)) {\n const at = match.index ?? 0;\n if (match[2] !== slug || masked[at] !== \"c\") continue;\n found.push({ file, optionsOpen: at + match[0].length - 1 });\n }\n }\n return found;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The files\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The scaffolds live in `templates/views/` rather than in template literals\n * here: they import React and the admin packages, and this package's sources\n * must not name those, even inside a string (`pnpm check:types-headless`).\n */\nfunction viewTemplate(name: string): string {\n const cliRoot = findCliRoot(__dirname);\n if (!cliRoot) throw new Error(`The CLI's templates/views folder is missing from ${__dirname}.`);\n return fs.readFileSync(path.join(cliRoot, \"templates\", \"views\", name), \"utf8\");\n}\n\n/** Walk up to the package root, which holds `templates/views`. */\nfunction findCliRoot(from: string): string | null {\n const root = path.parse(from).root;\n let dir = from;\n while (dir && dir !== root) {\n if (fs.existsSync(path.join(dir, \"templates\", \"views\"))) return dir;\n dir = path.dirname(dir);\n }\n return null;\n}\n\ntype ViewTemplateOptions = { slug: string; componentName: string; label: string; collection: string };\n\n/** The `{ key, name, Builder }` an entity view is registered as, with `unit` indentation inside. */\nfunction entityViewEntry(view: { key: string; name: string; componentName: string }, unit: string): string {\n return [\n \"{\",\n `${unit}key: ${JSON.stringify(view.key)},`,\n `${unit}name: ${JSON.stringify(view.name)},`,\n `${unit}Builder: ${view.componentName}`,\n \"}\"\n ].join(\"\\n\");\n}\n\n/**\n * A label as JSX text: written as is when it is plain, as a string expression\n * when it holds a character JSX reads — `{`, `}`, `<`, `>`, `&`. Pasted raw,\n * `--name \"KPIs {beta}\"` wrote `<Typography>KPIs {beta}</Typography>`, and the\n * view did not compile (\"Cannot find name 'beta'\").\n */\nfunction jsxText(text: string): string {\n return /[{}<>&]/.test(text) ? `{${JSON.stringify(text)}}` : text;\n}\n\n/** A label inside the leading `/** … *\\/` comment: one line, and no `*\\/` to close it early. */\nfunction commentText(text: string): string {\n return text.replace(/[\\r\\n]+/g, \" \").replaceAll(\"*/\", \"*\\\\/\");\n}\n\nfunction fillViewTemplate(template: string, options: ViewTemplateOptions): string {\n const { slug, componentName, label, collection } = options;\n return template\n .replaceAll(\"\\\"__COLLECTION__\\\"\", JSON.stringify(collection))\n .replaceAll(\"__COLLECTION__\", collection)\n .replaceAll(\"__COMPONENT__\", componentName)\n .replaceAll(\"__label_jsx__\", jsxText(label.toLowerCase()))\n .replaceAll(\"__LABEL_JSX__\", jsxText(label))\n .replaceAll(\"__label__\", commentText(label.toLowerCase()))\n .replaceAll(\"__LABEL__\", commentText(label))\n .replaceAll(\"__SLUG__\", slug);\n}\n\nexport function appViewSource(options: ViewTemplateOptions): string {\n return fillViewTemplate(viewTemplate(\"AppView.tsx.tmpl\"), options);\n}\n\nexport function entityViewSource(options: ViewTemplateOptions): string {\n return fillViewTemplate(viewTemplate(\"EntityView.tsx.tmpl\"), options);\n}\n\nfunction viewsIndexHeader(): string {\n return viewTemplate(\"index.ts.tmpl\");\n}\n\nfunction appViewEntry(options: { slug: string; label: string; icon: string; componentName: string }, unit: string): string {\n return [\n \"{\",\n `${unit}slug: ${JSON.stringify(options.slug)},`,\n `${unit}name: ${JSON.stringify(options.label)},`,\n `${unit}icon: ${JSON.stringify(options.icon)},`,\n `${unit}view: ${options.componentName}`,\n \"}\"\n ].join(\"\\n\");\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Planning\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction readIfExists(file: string): string | undefined {\n return fs.existsSync(file) ? fs.readFileSync(file, \"utf8\") : undefined;\n}\n\n/**\n * The frontend's package.json gains `@rebasepro/cms-types` when it lacks it.\n *\n * The view files import their prop types from it, and under pnpm a package the\n * frontend does not declare does not resolve from the frontend — the frontend's\n * `tsc` would fail on the first generated view. The version is the one the\n * frontend already uses for `@rebasepro/cms`, so the two cannot drift.\n */\nfunction planCmsTypesDependency(frontendDir: string, files: PlannedFile[], manualSteps: string[]): void {\n const manifestFile = path.join(frontendDir, \"package.json\");\n const raw = readIfExists(manifestFile);\n if (raw === undefined) return;\n let manifest: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };\n try {\n manifest = JSON.parse(raw);\n } catch {\n return;\n }\n const declared = { ...manifest.devDependencies, ...manifest.dependencies };\n if (declared[\"@rebasepro/cms-types\"]) return;\n const version = declared[\"@rebasepro/cms\"] ?? declared[\"@rebasepro/app\"];\n if (!version) return;\n const dependencies = { ...manifest.dependencies, \"@rebasepro/cms-types\": version };\n const sorted = Object.fromEntries(Object.entries(dependencies).sort(([a], [b]) => a.localeCompare(b)));\n const indent = /^(\\s+)\"/m.exec(raw)?.[1] ?? \" \";\n files.push({\n path: manifestFile,\n contents: `${JSON.stringify({ ...manifest, dependencies: sorted }, null, indent)}\\n`,\n action: \"update\"\n });\n manualSteps.push(`Run your package manager's install: ${path.basename(frontendDir)}/package.json now depends on @rebasepro/cms-types, which the view imports its types from.`);\n}\n\nfunction defaultCollectionFor(projectRoot: string): string {\n const slugs = declaredTables(resolveSchemaDir(projectRoot)).map(entry => entry.slug);\n return slugs.find(slug => slug !== \"users\") ?? slugs[0] ?? \"users\";\n}\n\n/**\n * Everything `rebase generate view` would write, without writing it.\n *\n * @throws UsageError when the slug is not a slug, there is no admin panel, the\n * view already exists (without `force`), or `--collection` names nothing.\n */\nexport function planGenerateView(options: GenerateViewOptions): GenerateViewPlan {\n const { projectRoot, slug } = options;\n if (!SLUG_PATTERN.test(slug)) {\n throw new UsageError(\n `\"${slug}\" is not a view slug: use lowercase letters, digits and dashes, starting with a letter (e.g. orders-board).`\n );\n }\n if (!options.collection && RESERVED_SCREEN_SLUGS.includes(slug)) {\n throw new UsageError(\n `\"${slug}\" is reserved: the admin's own routes answer /${slug}, so a screen there would never show. ` +\n `Pick another slug (e.g. ${slug === \"settings\" ? \"app-settings\" : `${slug}-view`}).`\n );\n }\n const frontendDir = resolveFrontendDir(projectRoot);\n if (!frontendDir) {\n throw new UsageError(\n \"This project has no admin panel to add a view to: rebase.json declares no app with a `cms` mount, and there is no frontend/src. \" +\n \"A project created with `rebase init --headless` has no admin.\"\n );\n }\n\n const componentName = viewComponentName(slug);\n const label = options.name?.trim() || viewLabel(slug);\n const viewsDir = path.join(frontendDir, \"src\", \"views\");\n const viewFile = path.join(viewsDir, `${componentName}.tsx`);\n const files: PlannedFile[] = [];\n const manualSteps: string[] = [];\n\n const viewExists = fs.existsSync(viewFile);\n if (viewExists && !options.force) {\n throw new UsageError(\n `${path.relative(projectRoot, viewFile)} already exists. Pass --force to replace it; its registration is kept.`\n );\n }\n const viewAction: PlannedFile[\"action\"] = viewExists ? \"replace\" : \"create\";\n\n if (options.collection) {\n const kind = \"entity\" as const;\n const table = options.collection;\n const schemaDir = resolveSchemaDir(projectRoot);\n const declared = declaredTables(schemaDir);\n if (!declared.some(entry => entry.slug === table)) {\n const known = [...new Set(declared.map(entry => entry.slug))].sort();\n throw new UsageError(\n `No table with slug \"${table}\" under ${path.relative(projectRoot, schemaDir) || \".\"}.` +\n (known.length ? ` Declared: ${known.join(\", \")}.` : \"\")\n );\n }\n const cmsDir = path.join(frontendDir, \"src\", \"cms\");\n const customizations = findCustomization(cmsDir, table);\n if (customizations.length > 1) {\n throw new UsageError(\n `More than one customizeTable(\"${table}\", …) under ${path.relative(projectRoot, cmsDir)}: ` +\n `${[...new Set(customizations.map(entry => path.relative(projectRoot, entry.file)))].join(\", \")}.`\n );\n }\n\n files.push({\n path: viewFile,\n contents: entityViewSource({ slug, componentName, label, collection: table }),\n action: viewAction\n });\n\n const view = { key: slug, name: label, componentName };\n if (customizations.length === 1) {\n const [{ file, optionsOpen }] = customizations;\n const importLine = `import { ${componentName} } from \"${relativeImport(path.dirname(file), viewFile)}\";`;\n const source = fs.readFileSync(file, \"utf8\");\n const updated = registerEntityView(source, optionsOpen, view);\n const where = path.relative(projectRoot, file);\n if (updated === \"already\") {\n // Registered on an earlier run: --force replaced the file only.\n } else if (updated === undefined) {\n manualSteps.push(\n `Add this to the entityViews of customizeTable(\"${table}\", …) in ${where}: ` +\n `{ key: ${JSON.stringify(slug)}, name: ${JSON.stringify(label)}, Builder: ${componentName} }, and ${importLine}`\n );\n } else {\n files.push({ path: file, contents: addImport(updated, importLine), action: \"update\" });\n }\n } else {\n const identifier = `${tableIdentifier(table)}Cms`;\n const file = path.join(cmsDir, `${table}.tsx`);\n if (fs.existsSync(file)) {\n throw new UsageError(\n `${path.relative(projectRoot, file)} exists but holds no customizeTable(\"${table}\", …): ` +\n \"add the record tab to the table's customization by hand, or move that file aside.\"\n );\n }\n const unit = \" \";\n files.push({\n path: file,\n contents: [\n \"import { customizeTable } from \\\"@rebasepro/cms\\\";\",\n `import { ${componentName} } from \"${relativeImport(cmsDir, viewFile)}\";`,\n \"\",\n `export const ${identifier} = customizeTable(\"${table}\", {`,\n `${unit}entityViews: [`,\n reindent(entityViewEntry(view, unit), unit + unit),\n `${unit}]`,\n \"});\",\n \"\"\n ].join(\"\\n\"),\n action: \"create\"\n });\n // Handed to the admin where the project lists its customizations:\n // a `tableCustomizations` list exported by `cms/index.ts`, else\n // the one `App.tsx` passes to `<RebaseCMS>`.\n const indexFile = path.join(cmsDir, \"index.ts\");\n const appFile = path.join(frontendDir, \"src\", \"App.tsx\");\n const index = readIfExists(indexFile);\n const app = readIfExists(appFile);\n const listedInIndex = index === undefined ? undefined : listCustomization(index, identifier, `./${table}`);\n const listedInApp = listedInIndex === undefined && app !== undefined\n ? listCustomization(app, identifier, `./cms/${table}`)\n : undefined;\n if (listedInIndex !== undefined) {\n if (listedInIndex !== \"already\") files.push({ path: indexFile, contents: listedInIndex, action: \"update\" });\n } else if (listedInApp !== undefined) {\n if (listedInApp !== \"already\") files.push({ path: appFile, contents: listedInApp, action: \"update\" });\n } else {\n manualSteps.push(\n `Hand the customization to the admin: import { ${identifier} } from \"./cms/${table}\" and add it to ` +\n `<RebaseCMS tableCustomizations={[…]}> in ${path.relative(projectRoot, appFile)}.`\n );\n }\n }\n planCmsTypesDependency(frontendDir, files, manualSteps);\n return { kind, componentName, viewFile, files, manualSteps };\n }\n\n files.push({\n path: viewFile,\n contents: appViewSource({ slug, componentName, label, collection: defaultCollectionFor(projectRoot) }),\n action: viewAction\n });\n\n // The list of screens.\n const indexFile = path.join(viewsDir, \"index.ts\");\n const existingIndex = readIfExists(indexFile);\n const icon = options.icon ?? \"LayoutDashboard\";\n if (existingIndex === undefined) {\n const unit = \" \";\n files.push({\n path: indexFile,\n contents: `${viewsIndexHeader()}import { ${componentName} } from \"./${componentName}\";\\n\\n` +\n `export const views: AppView[] = [\\n${reindent(appViewEntry({ slug, label, icon, componentName }, unit), unit)}\\n];\\n`,\n action: \"create\"\n });\n } else {\n const updated = registerAppView(existingIndex, { slug, label, icon, componentName });\n if (updated === undefined) {\n manualSteps.push(\n `Add { slug: ${JSON.stringify(slug)}, name: ${JSON.stringify(label)}, view: ${componentName} } to the views in ${path.relative(projectRoot, indexFile)}.`\n );\n } else if (updated !== \"already\") {\n files.push({ path: indexFile, contents: updated, action: \"update\" });\n }\n }\n\n // App.tsx hands the list to <RebaseCMS>, once.\n const appFile = path.join(frontendDir, \"src\", \"App.tsx\");\n const app = readIfExists(appFile);\n const wired = app === undefined ? undefined : wireViewsIntoApp(app);\n if (wired === undefined) {\n manualSteps.push(\n `Pass the screens to the admin: import { views } from \"./views\" and add views={views} to <RebaseCMS> in ${path.relative(projectRoot, appFile)}` +\n \" (or spread ...views into the views it already passes).\"\n );\n } else if (wired !== \"already\") {\n files.push({ path: appFile, contents: wired, action: \"update\" });\n }\n\n planCmsTypesDependency(frontendDir, files, manualSteps);\n return { kind: \"app\", componentName, viewFile, files, manualSteps };\n}\n\n/**\n * `views/index.ts` with one more entry, `\"already\"` when the slug is listed, or\n * `undefined` when the file has no `export const views … = [`.\n *\n * Exported for its tests.\n */\nexport function registerAppView(\n source: string,\n options: { slug: string; label: string; icon: string; componentName: string }\n): string | \"already\" | undefined {\n const masked = maskCode(source);\n const declaration = /export\\s+const\\s+views\\b[^=]*=\\s*\\[/.exec(masked);\n if (!declaration) return undefined;\n const open = declaration.index + declaration[0].length - 1;\n if (matchClose(masked, open) === -1) return undefined;\n const close = matchClose(masked, open);\n const listed = source.slice(open, close);\n if (new RegExp(`slug\\\\s*:\\\\s*[\"']${options.slug}[\"']`).test(listed)) return \"already\";\n\n const unit = indentUnit(source);\n const indent = indentAt(source, open) + unit;\n const element = reindent(appViewEntry(options, unit), indent);\n const appended = appendToArray(source, masked, open, element);\n return addImport(appended, `import { ${options.componentName} } from \"./${options.componentName}\";`);\n}\n\n/**\n * `App.tsx` with `views={views}` on `<RebaseCMS>` and its import, `\"already\"`\n * when it passes exactly that, or `undefined` when it cannot be done safely:\n * no `<RebaseCMS`, a `views` prop of its own, or a `views` name already in scope.\n *\n * Exported for its tests.\n */\nexport function wireViewsIntoApp(source: string): string | \"already\" | undefined {\n const masked = maskCode(source);\n const tag = /<RebaseCMS\\b/.exec(masked);\n if (!tag) return undefined;\n const tagEnd = masked.indexOf(\">\", tag.index);\n if (tagEnd === -1) return undefined;\n const attributes = masked.slice(tag.index, tagEnd);\n const importsViews = /import\\s*\\{\\s*views\\s*\\}\\s*from\\s*[\"']\\.\\/views(?:\\/index)?[\"']/.test(source);\n if (/\\sviews\\s*=/.test(attributes)) {\n return importsViews && /\\sviews\\s*=\\s*\\{\\s*views\\s*\\}/.test(attributes) ? \"already\" : undefined;\n }\n if (/\\bviews\\b/.test(masked)) return undefined;\n\n const insertAt = tag.index + \"<RebaseCMS\".length;\n const afterTag = source.slice(insertAt);\n const nextLine = /^[ \\t]*\\r?\\n([ \\t]*)\\S/.exec(afterTag);\n const attribute = nextLine ? `\\n${nextLine[1]}views={views}` : \" views={views}\";\n const withProp = source.slice(0, insertAt) + attribute + source.slice(insertAt);\n return addImport(withProp, \"import { views } from \\\"./views\\\";\");\n}\n\n/**\n * The customization file with a `{ key, name, Builder }` entry in the\n * `entityViews` of the `customizeTable(…)` options object whose `{` is at\n * `optionsOpen`; `\"already\"` when that key is there; `undefined` when the\n * shape cannot be read. The component's import is the caller's to add.\n *\n * Exported for its tests.\n */\nexport function registerEntityView(\n source: string,\n optionsOpen: number,\n view: { key: string; name: string; componentName: string }\n): string | \"already\" | undefined {\n const masked = maskCode(source);\n const close = matchClose(masked, optionsOpen);\n if (close === -1) return undefined;\n const unit = indentUnit(source);\n const entry = entityViewEntry(view, unit);\n\n const entityViews = directProperty(masked, optionsOpen, \"entityViews\", \"[\");\n if (entityViews) {\n const listClose = matchClose(masked, entityViews.valueOpen);\n if (listClose === -1) return undefined;\n const listed = source.slice(entityViews.valueOpen, listClose);\n if (new RegExp(`key\\\\s*:\\\\s*[\"']${view.key}[\"']|[\"']${view.key}[\"']`).test(listed)) return \"already\";\n const indent = indentAt(source, entityViews.keyAt) + unit;\n return appendToArray(source, masked, entityViews.valueOpen, reindent(entry, indent));\n }\n\n // `entityViews` as the first property of the options.\n const indent = indentAt(source, optionsOpen) + unit;\n const block = `${indent}entityViews: [\\n${reindent(entry, indent + unit)}\\n${indent}]`;\n const empty = masked.slice(optionsOpen + 1, close).trim() === \"\";\n const insertAt = optionsOpen + 1;\n return empty\n ? `${source.slice(0, insertAt)}\\n${block}\\n${indentAt(source, optionsOpen)}${source.slice(close)}`\n : `${source.slice(0, insertAt)}\\n${block},${source.slice(insertAt)}`;\n}\n\n/**\n * A source with `identifier` imported from `importPath` and appended to its\n * list of table customizations — `export const tableCustomizations = [ … ]`\n * (`cms/index.ts`) or `tableCustomizations={[ … ]}` on `<RebaseCMS>`\n * (`App.tsx`); `\"already\"` when it is listed; `undefined` when the source has\n * no such list.\n *\n * Exported for its tests.\n */\nexport function listCustomization(source: string, identifier: string, importPath: string): string | \"already\" | undefined {\n const masked = maskCode(source);\n const declaration = /export\\s+const\\s+tableCustomizations\\b[^=]*=\\s*\\[/.exec(masked)\n ?? /\\btableCustomizations\\s*=\\s*\\{\\s*\\[/.exec(masked);\n if (!declaration) return undefined;\n const open = declaration.index + declaration[0].length - 1;\n const close = matchClose(masked, open);\n if (close === -1) return undefined;\n if (new RegExp(`\\\\b${identifier}\\\\b`).test(masked.slice(open, close))) return \"already\";\n const inner = masked.slice(open + 1, close);\n let appended: string;\n if (inner.trim() !== \"\" && !inner.includes(\"\\n\")) {\n // A list written on one line stays on one line.\n let last = close - 1;\n while (last > open && /\\s/.test(masked[last])) last--;\n const comma = masked[last] === \",\" ? \" \" : \", \";\n appended = `${source.slice(0, last + 1)}${comma}${identifier}${source.slice(last + 1)}`;\n } else {\n const unit = indentUnit(source);\n appended = appendToArray(source, masked, open, `${indentAt(source, open)}${unit}${identifier}`);\n }\n return addImport(appended, `import { ${identifier} } from \"${importPath}\";`);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The command\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase generate\")} — scaffold code into this project\n\n${chalk.bold(\"Usage\")}\n rebase generate view <slug> A screen of the admin, in the sidebar\n rebase generate view <slug> --collection <slug> A tab on every record of a table\n\n${chalk.bold(\"What it writes\")}\n <frontend>/src/views/<Name>View.tsx The component, drawn with @rebasepro/ui\n <frontend>/src/views/index.ts The screens list (AppView[]), wired into\n <RebaseCMS views> in App.tsx on first run\n With --collection, the table's customizeTable(…) in <frontend>/src/cms gains\n an entityViews entry with the component (a new <slug>.tsx when it has none).\n\n${chalk.bold(\"Options\")}\n --collection <slug> Register as a record tab of the table with this slug\n --name <label> Sidebar or tab label ${chalk.gray(\"(default: the slug in sentence case)\")}\n --icon <Lucide name> Sidebar icon for a screen ${chalk.gray(\"(default: LayoutDashboard)\")}\n --dry-run List what would change, and change nothing\n --force Replace an existing view file\n -h, --help Show this help\n`.trim());\n}\n\nexport async function generateCommand(subcommand: string | undefined, rawArgs: string[] = []): Promise<void> {\n if (subcommand === undefined || subcommand === \"--help\" || (subcommand !== \"view\" && wantsHelp(rawArgs))) {\n printHelp();\n return;\n }\n switch (subcommand) {\n case \"view\":\n await generateViewCommand(rawArgs);\n return;\n default:\n throw new UsageError(`Unknown generate command \"${subcommand}\". Available: ${GENERATE_SUBCOMMANDS.join(\", \")}. See \\`rebase generate --help\\`.`);\n }\n}\n\nasync function generateViewCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) {\n printHelp();\n return;\n }\n const { flags, positionals } = parseCommandArgs({\n spec: VIEW_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"generate view\",\n maxPositionals: 1\n });\n const slug = positionals[0];\n if (!slug) {\n throw new UsageError(\"Name the view: `rebase generate view <slug>`, e.g. `rebase generate view orders-board`.\");\n }\n if (flags[\"--icon\"] && flags[\"--collection\"]) {\n throw new UsageError(\"--icon is for a screen in the sidebar; a record tab (--collection) has no icon here.\");\n }\n\n const projectRoot = requireProjectRoot();\n const plan = planGenerateView({\n projectRoot,\n slug,\n collection: flags[\"--collection\"],\n name: flags[\"--name\"],\n icon: flags[\"--icon\"],\n force: Boolean(flags[\"--force\"])\n });\n const dryRun = Boolean(flags[\"--dry-run\"]);\n\n for (const file of plan.files) {\n if (!dryRun) {\n fs.mkdirSync(path.dirname(file.path), { recursive: true });\n fs.writeFileSync(file.path, file.contents);\n }\n const verb = file.action === \"create\" ? \"created\" : file.action === \"replace\" ? \"replaced\" : \"updated\";\n console.log(`${chalk.green(\"✓\")} ${dryRun ? `would be ${verb}` : verb} ${path.relative(projectRoot, file.path)}`);\n }\n for (const step of plan.manualSteps) {\n console.log(`${chalk.yellow(\"!\")} ${step}`);\n }\n const where = plan.kind === \"app\" ? `/${slug} in the admin` : `a \"${flags[\"--name\"]?.trim() || viewLabel(slug)}\" tab on each ${flags[\"--collection\"]} record`;\n console.log(chalk.gray(` ${plan.componentName} renders at ${where}. Edit ${path.relative(projectRoot, plan.viewFile)} to build the screen.`));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAM,YAAY,KAAK,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC;;AAG7D,IAAa,uBAAuB,CAAC,MAAM;AAE3C,IAAM,aAAa;CACf,gBAAgB;CAChB,UAAU;CACV,UAAU;CACV,aAAa;CACb,WAAW;AACf;;AAGA,IAAM,eAAe;;;;;;;AAQrB,IAAM,wBAA2C;CAAC;CAAK;CAAK;AAAU;;AAoCtE,SAAgB,kBAAkB,MAAsB;CACpD,MAAM,SAAS,KAAK,MAAM,GAAG,CAAC,CAAC,KAAI,SAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE;CAChG,OAAO,OAAO,SAAS,MAAM,IAAI,SAAS,GAAG,OAAO;AACxD;;AAGA,SAAgB,UAAU,MAAsB;CAC5C,MAAM,QAAQ,KAAK,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;CACtC,OAAO,MAAM,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,MAAM,MAAM,CAAC;AACxD;;;;;;;;;AAcA,SAAgB,SAAS,QAAwB;CAC7C,MAAM,MAAM,OAAO,MAAM,EAAE;CAC3B,IAAI,IAAI;CACR,MAAM,SAAS,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AQ,IAAI,MAAM,KAAK,KAAK,KAAK,cAAc,cAAc,MAAM,SAAS,KAAK,SAAS,aAAa,KAAK,QAAQ,EAAE,sBAAsB,CAAC;AACjJ"}
|
|
1
|
+
{"version":3,"file":"generate-view-BMaLQm8H.js","names":[],"sources":["../src/commands/generate-view.ts"],"sourcesContent":["/**\n * `rebase generate view <slug>` — scaffold a custom admin screen and register it.\n *\n * Most back-office screens are a table, a form or a board, and the admin draws\n * those from the table. The rest — a dispatch board, a reconciliation\n * screen, a record's audit trail — are a hundred lines of React. Written inside\n * the admin they inherit the sign-in, the security rules, the sidebar, the UI\n * kit and the data layer; written as a separate app they have to rebuild every\n * one of those. This command writes the first version of that file where the\n * admin will find it, so the screen starts native and registered.\n *\n * Two places, one file each:\n *\n * - **A screen** (default): `<frontend>/src/views/<Name>View.tsx`, listed in\n * `<frontend>/src/views/index.ts` as an `AppView`, which `App.tsx` hands to\n * `<RebaseCMS views>`. The first run wires `App.tsx`; later runs only append\n * to the list.\n * - **A record tab** (`--collection <slug>`, the slug of a table in\n * `backend/schema`): the same file location, with a component that takes\n * `EntityCustomViewParams`, added to the `entityViews` of that table's\n * `customizeTable(…)` in `<frontend>/src/cms/` — imported directly, because\n * that directory is the admin's own code and the backend never reads it. A\n * table with no customization yet gets one, `<frontend>/src/cms/<slug>.tsx`,\n * listed in `cms/index.ts`'s `tableCustomizations` when there is one.\n *\n * The frontend is where `rebase.json` says the CMS is (the static app with a\n * `cms` mount), which is `frontend/` in everything `rebase init` writes. A\n * project with no admin panel (`rebase init --headless`) is refused: there is\n * nowhere for a view to render.\n *\n * Edits to existing files are textual and conservative. When `App.tsx` already\n * passes its own `views`, or a customization's shape is not one this can read, the\n * view file is still written and the command prints the one line to add by\n * hand instead of guessing.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport chalk from \"chalk\";\n\nimport { tableIdentifier } from \"@rebasepro/common\";\nimport { cmsMountOf, loadManifest } from \"../manifest\";\nimport { resolveSchemaDir } from \"../utils/schema-dir\";\nimport { declaredTables } from \"../utils/schema-text\";\nimport { requireProjectRoot } from \"../utils/project\";\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\n/** What `rebase generate` dispatches. Read by `cli.ts` to name the subcommand. */\nexport const GENERATE_SUBCOMMANDS = [\"view\"] as const;\n\nconst VIEW_FLAGS = {\n \"--collection\": String,\n \"--name\": String,\n \"--icon\": String,\n \"--dry-run\": Boolean,\n \"--force\": Boolean\n} as const;\n\n/** A slug is a URL segment and an entity view key: kebab-case, starting with a letter. */\nconst SLUG_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\n\n/**\n * Top-level paths the admin's own routes answer (`RebaseRouteDefs` in\n * `@rebasepro/cms`): `/c/*` the collections, `/s` Studio, `/settings`. They are\n * declared before custom views, so a screen at one of them was listed in the\n * sidebar and opened the built-in page instead.\n */\nconst RESERVED_SCREEN_SLUGS: readonly string[] = [\"c\", \"s\", \"settings\"];\n\nexport interface GenerateViewOptions {\n projectRoot: string;\n slug: string;\n /** Register as a tab on this table's records (its slug) instead of as a screen. */\n collection?: string;\n /** The label in the sidebar or on the tab. Defaults to the slug in sentence case. */\n name?: string;\n /** A Lucide icon name for the sidebar. Screens only. */\n icon?: string;\n /** Replace an existing view file. Registration is never duplicated. */\n force?: boolean;\n}\n\nexport interface PlannedFile {\n /** Absolute path. */\n path: string;\n contents: string;\n action: \"create\" | \"update\" | \"replace\";\n}\n\nexport interface GenerateViewPlan {\n kind: \"app\" | \"entity\";\n componentName: string;\n viewFile: string;\n files: PlannedFile[];\n /** Steps the command could not take itself, as sentences to print. */\n manualSteps: string[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Names\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** `orders-board` → `OrdersBoardView`; `sales-view` → `SalesView`, not `SalesViewView`. */\nexport function viewComponentName(slug: string): string {\n const pascal = slug.split(\"-\").map(part => part.charAt(0).toUpperCase() + part.slice(1)).join(\"\");\n return pascal.endsWith(\"View\") ? pascal : `${pascal}View`;\n}\n\n/** `orders-board` → `Orders board`: labels are sentence case in the admin. */\nexport function viewLabel(slug: string): string {\n const words = slug.split(\"-\").join(\" \");\n return words.charAt(0).toUpperCase() + words.slice(1);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Reading source without a parser\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The source with every string, template literal, regular expression and\n * comment blanked out, character for character, so brackets and keys can be\n * found by position without being fooled by a `{` inside a string. String\n * contents become `_` (they are still \"something\"), comments become spaces.\n *\n * Exported for its tests.\n */\nexport function maskCode(source: string): string {\n const out = source.split(\"\");\n let i = 0;\n const blank = (from: number, to: number, fill: string) => {\n for (let k = from; k < to; k++) if (out[k] !== \"\\n\") out[k] = fill;\n };\n const previousSignificant = (at: number): string => {\n for (let k = at - 1; k >= 0; k--) {\n const ch = out[k];\n if (ch !== \" \" && ch !== \"\\t\" && ch !== \"\\n\" && ch !== \"\\r\") return ch;\n }\n return \"\";\n };\n while (i < source.length) {\n const ch = source[i];\n const next = source[i + 1];\n if (ch === \"/\" && next === \"/\") {\n const end = source.indexOf(\"\\n\", i);\n const stop = end === -1 ? source.length : end;\n blank(i, stop, \" \");\n i = stop;\n } else if (ch === \"/\" && next === \"*\") {\n const end = source.indexOf(\"*/\", i + 2);\n const stop = end === -1 ? source.length : end + 2;\n blank(i, stop, \" \");\n i = stop;\n } else if (ch === \"\\\"\" || ch === \"'\" || ch === \"`\") {\n let k = i + 1;\n while (k < source.length && source[k] !== ch) {\n if (source[k] === \"\\\\\") k++;\n k++;\n }\n blank(i + 1, k, \"_\");\n i = k + 1;\n } else if (ch === \"/\" && (previousSignificant(i) === \"\" || \"(,=:[!&|?{;\".includes(previousSignificant(i)))) {\n // A regular expression literal: `/` where a value is expected. Not\n // after `}`, which in a .tsx file is far more often `{value}/>`.\n let k = i + 1;\n let inClass = false;\n while (k < source.length && source[k] !== \"\\n\") {\n if (source[k] === \"\\\\\") k++;\n else if (source[k] === \"[\") inClass = true;\n else if (source[k] === \"]\") inClass = false;\n else if (source[k] === \"/\" && !inClass) break;\n k++;\n }\n blank(i + 1, k, \"_\");\n i = k + 1;\n } else {\n i++;\n }\n }\n return out.join(\"\");\n}\n\nconst CLOSERS: Record<string, string> = { \"{\": \"}\", \"[\": \"]\", \"(\": \")\" };\n\n/** The index of the bracket closing the one at `open`, in masked source. */\nfunction matchClose(masked: string, open: number): number {\n const stack: string[] = [];\n for (let i = open; i < masked.length; i++) {\n const ch = masked[i];\n if (ch in CLOSERS) stack.push(CLOSERS[ch]);\n else if (ch === \"}\" || ch === \"]\" || ch === \")\") {\n if (stack.pop() !== ch) return -1;\n if (stack.length === 0) return i;\n }\n }\n return -1;\n}\n\n/** The index of the innermost `{` still open at `at`, in masked source. */\nfunction enclosingBrace(masked: string, at: number): number {\n const stack: number[] = [];\n for (let i = 0; i < at; i++) {\n const ch = masked[i];\n if (ch === \"{\" || ch === \"[\" || ch === \"(\") stack.push(i);\n else if (ch === \"}\" || ch === \"]\" || ch === \")\") stack.pop();\n }\n for (let k = stack.length - 1; k >= 0; k--) {\n if (masked[stack[k]] === \"{\") return stack[k];\n }\n return -1;\n}\n\n/**\n * The position of `key:` as a direct property of the object whose `{` is at\n * `open`, followed by `opener` (`{` or `[`) — or -1.\n */\nfunction directProperty(masked: string, open: number, key: string, opener: \"{\" | \"[\"): { keyAt: number; valueOpen: number } | undefined {\n const close = matchClose(masked, open);\n if (close === -1) return undefined;\n const pattern = new RegExp(`(^|[\\\\s,{])${key}\\\\s*:\\\\s*\\\\${opener}`, \"g\");\n const body = masked.slice(open + 1, close);\n for (const match of body.matchAll(pattern)) {\n const keyAt = open + 1 + (match.index ?? 0) + match[1].length;\n if (enclosingBrace(masked, keyAt) !== open) continue;\n return { keyAt, valueOpen: open + 1 + (match.index ?? 0) + match[0].length - 1 };\n }\n return undefined;\n}\n\nfunction lineStart(source: string, at: number): number {\n return source.lastIndexOf(\"\\n\", at - 1) + 1;\n}\n\nfunction indentAt(source: string, at: number): string {\n const start = lineStart(source, at);\n return /^[ \\t]*/.exec(source.slice(start))?.[0] ?? \"\";\n}\n\n/**\n * The indentation step a file uses: the smallest non-zero leading run of\n * spaces, not counting the ` * ` lines of a block comment.\n */\nfunction indentUnit(source: string): string {\n if (/^\\t/m.test(source)) return \"\\t\";\n let unit = Infinity;\n for (const match of source.matchAll(/^( +)[^\\s*]/gm)) unit = Math.min(unit, match[1].length);\n return \" \".repeat(Number.isFinite(unit) ? unit : 4);\n}\n\nfunction reindent(block: string, indent: string): string {\n return block.split(\"\\n\").map(line => (line ? indent + line : line)).join(\"\\n\");\n}\n\n/**\n * Insert `element` (already indented one level past `indent`) as the last item\n * of the array whose `[` is at `open`.\n */\nfunction appendToArray(source: string, masked: string, open: number, element: string): string {\n const close = matchClose(masked, open);\n const inner = masked.slice(open + 1, close);\n const indent = indentAt(source, open);\n if (inner.trim() === \"\") {\n return `${source.slice(0, open + 1)}\\n${element}\\n${indent}${source.slice(close)}`;\n }\n // After the last non-blank character of the content, keeping any comment\n // after it where it was.\n let last = close - 1;\n while (last > open && /\\s/.test(masked[last])) last--;\n const hasTrailingComma = masked[last] === \",\";\n const insertAt = last + 1;\n return `${source.slice(0, insertAt)}${hasTrailingComma ? \"\" : \",\"}\\n${element}${source.slice(insertAt)}`;\n}\n\n/** Add an import line after the file's last import statement. */\nfunction addImport(source: string, line: string): string {\n const masked = maskCode(source);\n let end = 0;\n for (const match of masked.matchAll(/^import\\b[\\s\\S]*?[\"'][^\"'\\n]*[\"'];?[ \\t]*$/gm)) {\n end = (match.index ?? 0) + match[0].length;\n }\n if (end === 0) return `${line}\\n${source}`;\n return `${source.slice(0, end)}\\n${line}${source.slice(end)}`;\n}\n\n/** A path import from `fromDir` to `toFile`, without extension, always starting with `.`. */\nfunction relativeImport(fromDir: string, toFile: string): string {\n const relative = path.relative(fromDir, toFile).split(path.sep).join(\"/\").replace(/\\.tsx?$/, \"\");\n return relative.startsWith(\".\") ? relative : `./${relative}`;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Where things are\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** The admin's frontend directory: the static app that mounts the CMS, or `frontend/`. */\nexport function resolveFrontendDir(projectRoot: string): string | undefined {\n try {\n const cms = cmsMountOf(loadManifest(projectRoot).manifest);\n if (cms) return path.join(projectRoot, cms.app.root);\n } catch {\n // A malformed rebase.json is reported by the commands that own it.\n }\n const fallback = path.join(projectRoot, \"frontend\");\n return fs.existsSync(path.join(fallback, \"src\")) ? fallback : undefined;\n}\n\n/** The tables directory, as the backend app declares it — one resolver for every command. */\nexport { resolveSchemaDir };\n\n/** Every source file under the admin's `src/cms`, sorted: where table customizations live. */\nfunction customizationFiles(dir: string): string[] {\n if (!fs.existsSync(dir)) return [];\n const out: string[] = [];\n const entries = fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name !== \"node_modules\") out.push(...customizationFiles(full));\n } else if (/\\.tsx?$/.test(entry.name) && !/\\.(test|spec|d)\\.tsx?$/.test(entry.name)) {\n out.push(full);\n }\n }\n return out;\n}\n\n/**\n * Every `customizeTable(\"<slug>\", {` of a table, in code (not in a comment or\n * a string): the file, and where the options object opens. Empty when no file\n * under `cmsDir` customizes the table.\n */\nfunction findCustomization(cmsDir: string, slug: string): { file: string; optionsOpen: number }[] {\n const found: { file: string; optionsOpen: number }[] = [];\n const call = /\\bcustomizeTable\\s*(?:<[^>]*>)?\\(\\s*([\"'`])([^\"'`\\n]+)\\1\\s*,\\s*\\{/g;\n for (const file of customizationFiles(cmsDir)) {\n const source = fs.readFileSync(file, \"utf8\");\n const masked = maskCode(source);\n for (const match of source.matchAll(call)) {\n const at = match.index ?? 0;\n if (match[2] !== slug || masked[at] !== \"c\") continue;\n found.push({ file, optionsOpen: at + match[0].length - 1 });\n }\n }\n return found;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The files\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The scaffolds live in `templates/views/` rather than in template literals\n * here: they import React and the admin packages, and this package's sources\n * must not name those, even inside a string (`pnpm check:types-headless`).\n */\nfunction viewTemplate(name: string): string {\n const cliRoot = findCliRoot(__dirname);\n if (!cliRoot) throw new Error(`The CLI's templates/views folder is missing from ${__dirname}.`);\n return fs.readFileSync(path.join(cliRoot, \"templates\", \"views\", name), \"utf8\");\n}\n\n/** Walk up to the package root, which holds `templates/views`. */\nfunction findCliRoot(from: string): string | null {\n const root = path.parse(from).root;\n let dir = from;\n while (dir && dir !== root) {\n if (fs.existsSync(path.join(dir, \"templates\", \"views\"))) return dir;\n dir = path.dirname(dir);\n }\n return null;\n}\n\ntype ViewTemplateOptions = { slug: string; componentName: string; label: string; collection: string };\n\n/** The `{ key, name, Builder }` an entity view is registered as, with `unit` indentation inside. */\nfunction entityViewEntry(view: { key: string; name: string; componentName: string }, unit: string): string {\n return [\n \"{\",\n `${unit}key: ${JSON.stringify(view.key)},`,\n `${unit}name: ${JSON.stringify(view.name)},`,\n `${unit}Builder: ${view.componentName}`,\n \"}\"\n ].join(\"\\n\");\n}\n\n/**\n * A label as JSX text: written as is when it is plain, as a string expression\n * when it holds a character JSX reads — `{`, `}`, `<`, `>`, `&`. Pasted raw,\n * `--name \"KPIs {beta}\"` wrote `<Typography>KPIs {beta}</Typography>`, and the\n * view did not compile (\"Cannot find name 'beta'\").\n */\nfunction jsxText(text: string): string {\n return /[{}<>&]/.test(text) ? `{${JSON.stringify(text)}}` : text;\n}\n\n/** A label inside the leading `/** … *\\/` comment: one line, and no `*\\/` to close it early. */\nfunction commentText(text: string): string {\n return text.replace(/[\\r\\n]+/g, \" \").replaceAll(\"*/\", \"*\\\\/\");\n}\n\nfunction fillViewTemplate(template: string, options: ViewTemplateOptions): string {\n const { slug, componentName, label, collection } = options;\n return template\n .replaceAll(\"\\\"__COLLECTION__\\\"\", JSON.stringify(collection))\n .replaceAll(\"__COLLECTION__\", collection)\n .replaceAll(\"__COMPONENT__\", componentName)\n .replaceAll(\"__label_jsx__\", jsxText(label.toLowerCase()))\n .replaceAll(\"__LABEL_JSX__\", jsxText(label))\n .replaceAll(\"__label__\", commentText(label.toLowerCase()))\n .replaceAll(\"__LABEL__\", commentText(label))\n .replaceAll(\"__SLUG__\", slug);\n}\n\nexport function appViewSource(options: ViewTemplateOptions): string {\n return fillViewTemplate(viewTemplate(\"AppView.tsx.tmpl\"), options);\n}\n\nexport function entityViewSource(options: ViewTemplateOptions): string {\n return fillViewTemplate(viewTemplate(\"EntityView.tsx.tmpl\"), options);\n}\n\nfunction viewsIndexHeader(): string {\n return viewTemplate(\"index.ts.tmpl\");\n}\n\nfunction appViewEntry(options: { slug: string; label: string; icon: string; componentName: string }, unit: string): string {\n return [\n \"{\",\n `${unit}slug: ${JSON.stringify(options.slug)},`,\n `${unit}name: ${JSON.stringify(options.label)},`,\n `${unit}icon: ${JSON.stringify(options.icon)},`,\n `${unit}view: ${options.componentName}`,\n \"}\"\n ].join(\"\\n\");\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Planning\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction readIfExists(file: string): string | undefined {\n return fs.existsSync(file) ? fs.readFileSync(file, \"utf8\") : undefined;\n}\n\n/**\n * The frontend's package.json gains `@rebasepro/cms-types` when it lacks it.\n *\n * The view files import their prop types from it, and under pnpm a package the\n * frontend does not declare does not resolve from the frontend — the frontend's\n * `tsc` would fail on the first generated view. The version is the one the\n * frontend already uses for `@rebasepro/cms`, so the two cannot drift.\n */\nfunction planCmsTypesDependency(frontendDir: string, files: PlannedFile[], manualSteps: string[]): void {\n const manifestFile = path.join(frontendDir, \"package.json\");\n const raw = readIfExists(manifestFile);\n if (raw === undefined) return;\n let manifest: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };\n try {\n manifest = JSON.parse(raw);\n } catch {\n return;\n }\n const declared = { ...manifest.devDependencies, ...manifest.dependencies };\n if (declared[\"@rebasepro/cms-types\"]) return;\n const version = declared[\"@rebasepro/cms\"] ?? declared[\"@rebasepro/app\"];\n if (!version) return;\n const dependencies = { ...manifest.dependencies, \"@rebasepro/cms-types\": version };\n const sorted = Object.fromEntries(Object.entries(dependencies).sort(([a], [b]) => a.localeCompare(b)));\n const indent = /^(\\s+)\"/m.exec(raw)?.[1] ?? \" \";\n files.push({\n path: manifestFile,\n contents: `${JSON.stringify({ ...manifest, dependencies: sorted }, null, indent)}\\n`,\n action: \"update\"\n });\n manualSteps.push(`Run your package manager's install: ${path.basename(frontendDir)}/package.json now depends on @rebasepro/cms-types, which the view imports its types from.`);\n}\n\nfunction defaultCollectionFor(projectRoot: string): string {\n const slugs = declaredTables(resolveSchemaDir(projectRoot)).map(entry => entry.slug);\n return slugs.find(slug => slug !== \"users\") ?? slugs[0] ?? \"users\";\n}\n\n/**\n * Everything `rebase generate view` would write, without writing it.\n *\n * @throws UsageError when the slug is not a slug, there is no admin panel, the\n * view already exists (without `force`), or `--collection` names nothing.\n */\nexport function planGenerateView(options: GenerateViewOptions): GenerateViewPlan {\n const { projectRoot, slug } = options;\n if (!SLUG_PATTERN.test(slug)) {\n throw new UsageError(\n `\"${slug}\" is not a view slug: use lowercase letters, digits and dashes, starting with a letter (e.g. orders-board).`\n );\n }\n if (!options.collection && RESERVED_SCREEN_SLUGS.includes(slug)) {\n throw new UsageError(\n `\"${slug}\" is reserved: the admin's own routes answer /${slug}, so a screen there would never show. ` +\n `Pick another slug (e.g. ${slug === \"settings\" ? \"app-settings\" : `${slug}-view`}).`\n );\n }\n const frontendDir = resolveFrontendDir(projectRoot);\n if (!frontendDir) {\n throw new UsageError(\n \"This project has no admin panel to add a view to: rebase.json declares no app with a `cms` mount, and there is no frontend/src. \" +\n \"A project created with `rebase init --headless` has no admin.\"\n );\n }\n\n const componentName = viewComponentName(slug);\n const label = options.name?.trim() || viewLabel(slug);\n const viewsDir = path.join(frontendDir, \"src\", \"views\");\n const viewFile = path.join(viewsDir, `${componentName}.tsx`);\n const files: PlannedFile[] = [];\n const manualSteps: string[] = [];\n\n const viewExists = fs.existsSync(viewFile);\n if (viewExists && !options.force) {\n throw new UsageError(\n `${path.relative(projectRoot, viewFile)} already exists. Pass --force to replace it; its registration is kept.`\n );\n }\n const viewAction: PlannedFile[\"action\"] = viewExists ? \"replace\" : \"create\";\n\n if (options.collection) {\n const kind = \"entity\" as const;\n const table = options.collection;\n const schemaDir = resolveSchemaDir(projectRoot);\n const declared = declaredTables(schemaDir);\n if (!declared.some(entry => entry.slug === table)) {\n const known = [...new Set(declared.map(entry => entry.slug))].sort();\n throw new UsageError(\n `No table with slug \"${table}\" under ${path.relative(projectRoot, schemaDir) || \".\"}.` +\n (known.length ? ` Declared: ${known.join(\", \")}.` : \"\")\n );\n }\n const cmsDir = path.join(frontendDir, \"src\", \"cms\");\n const customizations = findCustomization(cmsDir, table);\n if (customizations.length > 1) {\n throw new UsageError(\n `More than one customizeTable(\"${table}\", …) under ${path.relative(projectRoot, cmsDir)}: ` +\n `${[...new Set(customizations.map(entry => path.relative(projectRoot, entry.file)))].join(\", \")}.`\n );\n }\n\n files.push({\n path: viewFile,\n contents: entityViewSource({ slug, componentName, label, collection: table }),\n action: viewAction\n });\n\n const view = { key: slug, name: label, componentName };\n if (customizations.length === 1) {\n const [{ file, optionsOpen }] = customizations;\n const importLine = `import { ${componentName} } from \"${relativeImport(path.dirname(file), viewFile)}\";`;\n const source = fs.readFileSync(file, \"utf8\");\n const updated = registerEntityView(source, optionsOpen, view);\n const where = path.relative(projectRoot, file);\n if (updated === \"already\") {\n // Registered on an earlier run: --force replaced the file only.\n } else if (updated === undefined) {\n manualSteps.push(\n `Add this to the entityViews of customizeTable(\"${table}\", …) in ${where}: ` +\n `{ key: ${JSON.stringify(slug)}, name: ${JSON.stringify(label)}, Builder: ${componentName} }, and ${importLine}`\n );\n } else {\n files.push({ path: file, contents: addImport(updated, importLine), action: \"update\" });\n }\n } else {\n const identifier = `${tableIdentifier(table)}Cms`;\n const file = path.join(cmsDir, `${table}.tsx`);\n if (fs.existsSync(file)) {\n throw new UsageError(\n `${path.relative(projectRoot, file)} exists but holds no customizeTable(\"${table}\", …): ` +\n \"add the record tab to the table's customization by hand, or move that file aside.\"\n );\n }\n const unit = \" \";\n files.push({\n path: file,\n contents: [\n \"import { customizeTable } from \\\"@rebasepro/cms\\\";\",\n `import { ${componentName} } from \"${relativeImport(cmsDir, viewFile)}\";`,\n \"\",\n `export const ${identifier} = customizeTable(\"${table}\", {`,\n `${unit}entityViews: [`,\n reindent(entityViewEntry(view, unit), unit + unit),\n `${unit}]`,\n \"});\",\n \"\"\n ].join(\"\\n\"),\n action: \"create\"\n });\n // Handed to the admin where the project lists its customizations:\n // a `tableCustomizations` list exported by `cms/index.ts`, else\n // the one `App.tsx` passes to `<RebaseCMS>`.\n const indexFile = path.join(cmsDir, \"index.ts\");\n const appFile = path.join(frontendDir, \"src\", \"App.tsx\");\n const index = readIfExists(indexFile);\n const app = readIfExists(appFile);\n const listedInIndex = index === undefined ? undefined : listCustomization(index, identifier, `./${table}`);\n const listedInApp = listedInIndex === undefined && app !== undefined\n ? listCustomization(app, identifier, `./cms/${table}`)\n : undefined;\n if (listedInIndex !== undefined) {\n if (listedInIndex !== \"already\") files.push({ path: indexFile, contents: listedInIndex, action: \"update\" });\n } else if (listedInApp !== undefined) {\n if (listedInApp !== \"already\") files.push({ path: appFile, contents: listedInApp, action: \"update\" });\n } else {\n manualSteps.push(\n `Hand the customization to the admin: import { ${identifier} } from \"./cms/${table}\" and add it to ` +\n `<RebaseCMS tableCustomizations={[…]}> in ${path.relative(projectRoot, appFile)}.`\n );\n }\n }\n planCmsTypesDependency(frontendDir, files, manualSteps);\n return { kind, componentName, viewFile, files, manualSteps };\n }\n\n files.push({\n path: viewFile,\n contents: appViewSource({ slug, componentName, label, collection: defaultCollectionFor(projectRoot) }),\n action: viewAction\n });\n\n // The list of screens.\n const indexFile = path.join(viewsDir, \"index.ts\");\n const existingIndex = readIfExists(indexFile);\n const icon = options.icon ?? \"LayoutDashboard\";\n if (existingIndex === undefined) {\n const unit = \" \";\n files.push({\n path: indexFile,\n contents: `${viewsIndexHeader()}import { ${componentName} } from \"./${componentName}\";\\n\\n` +\n `export const views: AppView[] = [\\n${reindent(appViewEntry({ slug, label, icon, componentName }, unit), unit)}\\n];\\n`,\n action: \"create\"\n });\n } else {\n const updated = registerAppView(existingIndex, { slug, label, icon, componentName });\n if (updated === undefined) {\n manualSteps.push(\n `Add { slug: ${JSON.stringify(slug)}, name: ${JSON.stringify(label)}, view: ${componentName} } to the views in ${path.relative(projectRoot, indexFile)}.`\n );\n } else if (updated !== \"already\") {\n files.push({ path: indexFile, contents: updated, action: \"update\" });\n }\n }\n\n // App.tsx hands the list to <RebaseCMS>, once.\n const appFile = path.join(frontendDir, \"src\", \"App.tsx\");\n const app = readIfExists(appFile);\n const wired = app === undefined ? undefined : wireViewsIntoApp(app);\n if (wired === undefined) {\n manualSteps.push(\n `Pass the screens to the admin: import { views } from \"./views\" and add views={views} to <RebaseCMS> in ${path.relative(projectRoot, appFile)}` +\n \" (or spread ...views into the views it already passes).\"\n );\n } else if (wired !== \"already\") {\n files.push({ path: appFile, contents: wired, action: \"update\" });\n }\n\n planCmsTypesDependency(frontendDir, files, manualSteps);\n return { kind: \"app\", componentName, viewFile, files, manualSteps };\n}\n\n/**\n * `views/index.ts` with one more entry, `\"already\"` when the slug is listed, or\n * `undefined` when the file has no `export const views … = [`.\n *\n * Exported for its tests.\n */\nexport function registerAppView(\n source: string,\n options: { slug: string; label: string; icon: string; componentName: string }\n): string | \"already\" | undefined {\n const masked = maskCode(source);\n const declaration = /export\\s+const\\s+views\\b[^=]*=\\s*\\[/.exec(masked);\n if (!declaration) return undefined;\n const open = declaration.index + declaration[0].length - 1;\n if (matchClose(masked, open) === -1) return undefined;\n const close = matchClose(masked, open);\n const listed = source.slice(open, close);\n if (new RegExp(`slug\\\\s*:\\\\s*[\"']${options.slug}[\"']`).test(listed)) return \"already\";\n\n const unit = indentUnit(source);\n const indent = indentAt(source, open) + unit;\n const element = reindent(appViewEntry(options, unit), indent);\n const appended = appendToArray(source, masked, open, element);\n return addImport(appended, `import { ${options.componentName} } from \"./${options.componentName}\";`);\n}\n\n/**\n * `App.tsx` with `views={views}` on `<RebaseCMS>` and its import, `\"already\"`\n * when it passes exactly that, or `undefined` when it cannot be done safely:\n * no `<RebaseCMS`, a `views` prop of its own, or a `views` name already in scope.\n *\n * Exported for its tests.\n */\nexport function wireViewsIntoApp(source: string): string | \"already\" | undefined {\n const masked = maskCode(source);\n const tag = /<RebaseCMS\\b/.exec(masked);\n if (!tag) return undefined;\n const tagEnd = masked.indexOf(\">\", tag.index);\n if (tagEnd === -1) return undefined;\n const attributes = masked.slice(tag.index, tagEnd);\n const importsViews = /import\\s*\\{\\s*views\\s*\\}\\s*from\\s*[\"']\\.\\/views(?:\\/index)?[\"']/.test(source);\n if (/\\sviews\\s*=/.test(attributes)) {\n return importsViews && /\\sviews\\s*=\\s*\\{\\s*views\\s*\\}/.test(attributes) ? \"already\" : undefined;\n }\n if (/\\bviews\\b/.test(masked)) return undefined;\n\n const insertAt = tag.index + \"<RebaseCMS\".length;\n const afterTag = source.slice(insertAt);\n const nextLine = /^[ \\t]*\\r?\\n([ \\t]*)\\S/.exec(afterTag);\n const attribute = nextLine ? `\\n${nextLine[1]}views={views}` : \" views={views}\";\n const withProp = source.slice(0, insertAt) + attribute + source.slice(insertAt);\n return addImport(withProp, \"import { views } from \\\"./views\\\";\");\n}\n\n/**\n * The customization file with a `{ key, name, Builder }` entry in the\n * `entityViews` of the `customizeTable(…)` options object whose `{` is at\n * `optionsOpen`; `\"already\"` when that key is there; `undefined` when the\n * shape cannot be read. The component's import is the caller's to add.\n *\n * Exported for its tests.\n */\nexport function registerEntityView(\n source: string,\n optionsOpen: number,\n view: { key: string; name: string; componentName: string }\n): string | \"already\" | undefined {\n const masked = maskCode(source);\n const close = matchClose(masked, optionsOpen);\n if (close === -1) return undefined;\n const unit = indentUnit(source);\n const entry = entityViewEntry(view, unit);\n\n const entityViews = directProperty(masked, optionsOpen, \"entityViews\", \"[\");\n if (entityViews) {\n const listClose = matchClose(masked, entityViews.valueOpen);\n if (listClose === -1) return undefined;\n const listed = source.slice(entityViews.valueOpen, listClose);\n if (new RegExp(`key\\\\s*:\\\\s*[\"']${view.key}[\"']|[\"']${view.key}[\"']`).test(listed)) return \"already\";\n const indent = indentAt(source, entityViews.keyAt) + unit;\n return appendToArray(source, masked, entityViews.valueOpen, reindent(entry, indent));\n }\n\n // `entityViews` as the first property of the options.\n const indent = indentAt(source, optionsOpen) + unit;\n const block = `${indent}entityViews: [\\n${reindent(entry, indent + unit)}\\n${indent}]`;\n const empty = masked.slice(optionsOpen + 1, close).trim() === \"\";\n const insertAt = optionsOpen + 1;\n return empty\n ? `${source.slice(0, insertAt)}\\n${block}\\n${indentAt(source, optionsOpen)}${source.slice(close)}`\n : `${source.slice(0, insertAt)}\\n${block},${source.slice(insertAt)}`;\n}\n\n/**\n * A source with `identifier` imported from `importPath` and appended to its\n * list of table customizations — `export const tableCustomizations = [ … ]`\n * (`cms/index.ts`) or `tableCustomizations={[ … ]}` on `<RebaseCMS>`\n * (`App.tsx`); `\"already\"` when it is listed; `undefined` when the source has\n * no such list.\n *\n * Exported for its tests.\n */\nexport function listCustomization(source: string, identifier: string, importPath: string): string | \"already\" | undefined {\n const masked = maskCode(source);\n const declaration = /export\\s+const\\s+tableCustomizations\\b[^=]*=\\s*\\[/.exec(masked)\n ?? /\\btableCustomizations\\s*=\\s*\\{\\s*\\[/.exec(masked);\n if (!declaration) return undefined;\n const open = declaration.index + declaration[0].length - 1;\n const close = matchClose(masked, open);\n if (close === -1) return undefined;\n if (new RegExp(`\\\\b${identifier}\\\\b`).test(masked.slice(open, close))) return \"already\";\n const inner = masked.slice(open + 1, close);\n let appended: string;\n if (inner.trim() !== \"\" && !inner.includes(\"\\n\")) {\n // A list written on one line stays on one line.\n let last = close - 1;\n while (last > open && /\\s/.test(masked[last])) last--;\n const comma = masked[last] === \",\" ? \" \" : \", \";\n appended = `${source.slice(0, last + 1)}${comma}${identifier}${source.slice(last + 1)}`;\n } else {\n const unit = indentUnit(source);\n appended = appendToArray(source, masked, open, `${indentAt(source, open)}${unit}${identifier}`);\n }\n return addImport(appended, `import { ${identifier} } from \"${importPath}\";`);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The command\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase generate\")} — scaffold code into this project\n\n${chalk.bold(\"Usage\")}\n rebase generate view <slug> A screen of the admin, in the sidebar\n rebase generate view <slug> --collection <slug> A tab on every record of a table\n\n${chalk.bold(\"What it writes\")}\n <frontend>/src/views/<Name>View.tsx The component, drawn with @rebasepro/ui\n <frontend>/src/views/index.ts The screens list (AppView[]), wired into\n <RebaseCMS views> in App.tsx on first run\n With --collection, the table's customizeTable(…) in <frontend>/src/cms gains\n an entityViews entry with the component (a new <slug>.tsx when it has none).\n\n${chalk.bold(\"Options\")}\n --collection <slug> Register as a record tab of the table with this slug\n --name <label> Sidebar or tab label ${chalk.gray(\"(default: the slug in sentence case)\")}\n --icon <Lucide name> Sidebar icon for a screen ${chalk.gray(\"(default: LayoutDashboard)\")}\n --dry-run List what would change, and change nothing\n --force Replace an existing view file\n -h, --help Show this help\n`.trim());\n}\n\nexport async function generateCommand(subcommand: string | undefined, rawArgs: string[] = []): Promise<void> {\n if (subcommand === undefined || subcommand === \"--help\" || (subcommand !== \"view\" && wantsHelp(rawArgs))) {\n printHelp();\n return;\n }\n switch (subcommand) {\n case \"view\":\n await generateViewCommand(rawArgs);\n return;\n default:\n throw new UsageError(`Unknown generate command \"${subcommand}\". Available: ${GENERATE_SUBCOMMANDS.join(\", \")}. See \\`rebase generate --help\\`.`);\n }\n}\n\nasync function generateViewCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) {\n printHelp();\n return;\n }\n const { flags, positionals } = parseCommandArgs({\n spec: VIEW_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"generate view\",\n maxPositionals: 1\n });\n const slug = positionals[0];\n if (!slug) {\n throw new UsageError(\"Name the view: `rebase generate view <slug>`, e.g. `rebase generate view orders-board`.\");\n }\n if (flags[\"--icon\"] && flags[\"--collection\"]) {\n throw new UsageError(\"--icon is for a screen in the sidebar; a record tab (--collection) has no icon here.\");\n }\n\n const projectRoot = requireProjectRoot();\n const plan = planGenerateView({\n projectRoot,\n slug,\n collection: flags[\"--collection\"],\n name: flags[\"--name\"],\n icon: flags[\"--icon\"],\n force: Boolean(flags[\"--force\"])\n });\n const dryRun = Boolean(flags[\"--dry-run\"]);\n\n for (const file of plan.files) {\n if (!dryRun) {\n fs.mkdirSync(path.dirname(file.path), { recursive: true });\n fs.writeFileSync(file.path, file.contents);\n }\n const verb = file.action === \"create\" ? \"created\" : file.action === \"replace\" ? \"replaced\" : \"updated\";\n console.log(`${chalk.green(\"✓\")} ${dryRun ? `would be ${verb}` : verb} ${path.relative(projectRoot, file.path)}`);\n }\n for (const step of plan.manualSteps) {\n console.log(`${chalk.yellow(\"!\")} ${step}`);\n }\n const where = plan.kind === \"app\" ? `/${slug} in the admin` : `a \"${flags[\"--name\"]?.trim() || viewLabel(slug)}\" tab on each ${flags[\"--collection\"]} record`;\n console.log(chalk.gray(` ${plan.componentName} renders at ${where}. Edit ${path.relative(projectRoot, plan.viewFile)} to build the screen.`));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAM,YAAY,KAAK,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC;;AAG7D,IAAa,uBAAuB,CAAC,MAAM;AAE3C,IAAM,aAAa;CACf,gBAAgB;CAChB,UAAU;CACV,UAAU;CACV,aAAa;CACb,WAAW;AACf;;AAGA,I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AAO;EAC3B,IAAI,CAAC,QAAQ;GACT,GAAG,UAAU,KAAK,QAAQ,KAAK,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;GACzD,GAAG,cAAc,KAAK,MAAM,KAAK,QAAQ;EAC7C;EACA,MAAM,OAAO,KAAK,WAAW,WAAW,YAAY,KAAK,WAAW,YAAY,aAAa;EAC7F,QAAQ,IAAI,GAAG,MAAM,MAAM,GAAG,EAAE,GAAG,SAAS,YAAY,SAAS,KAAK,IAAI,KAAK,SAAS,aAAa,KAAK,IAAI,GAAG;CACrH;CACA,KAAK,MAAM,QAAQ,KAAK,aACpB,QAAQ,IAAI,GAAG,MAAM,OAAO,GAAG,EAAE,GAAG,MAAM;CAE9C,MAAM,QAAQ,KAAK,SAAS,QAAQ,IAAI,KAAK,iBAAiB,MAAM,MAAM,SAAS,EAAE,KAAK,KAAK,UAAU,IAAI,EAAE,gBAAgB,MAAM,gBAAgB;CACrJ,QAAQ,IAAI,MAAM,KAAK,KAAK,KAAK,cAAc,cAAc,MAAM,SAAS,KAAK,SAAS,aAAa,KAAK,QAAQ,EAAE,sBAAsB,CAAC;AACjJ"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { c as findProjectRoot, d as readEnvFile } from "./project-
|
|
2
|
-
import { O as writeManifest, _ as findBackendApp, b as loadManifest, o as GENERATED_DIR, x as manifestExists } from "./manifest-
|
|
3
|
-
import { n as SCHEMA_DIR_FLAG_HELP, t as PATH_RESOLUTION_RULE } from "./path-flags-
|
|
4
|
-
import { t as loadProjectSchema } from "./project-schema-
|
|
5
|
-
import { t as DEV_BACKEND_URL_ENV } from "./dev-server-
|
|
6
|
-
import {
|
|
1
|
+
import { c as findProjectRoot, d as readEnvFile } from "./project-DALmhb5R.js";
|
|
2
|
+
import { O as writeManifest, _ as findBackendApp, b as loadManifest, o as GENERATED_DIR, x as manifestExists } from "./manifest-RjqxfCpb.js";
|
|
3
|
+
import { n as SCHEMA_DIR_FLAG_HELP, t as PATH_RESOLUTION_RULE } from "./path-flags-ekLdkbra.js";
|
|
4
|
+
import { t as loadProjectSchema } from "./project-schema-Dm6Jk0Y_.js";
|
|
5
|
+
import { t as DEV_BACKEND_URL_ENV } from "./dev-server-2XHSHM_q.js";
|
|
6
|
+
import { H as readLink } from "./context-BOMEoKxn.js";
|
|
7
7
|
import { t as Refusal } from "./refusal-ReeeGP8a.js";
|
|
8
8
|
import chalk from "chalk";
|
|
9
9
|
import fs from "fs";
|
|
@@ -505,4 +505,4 @@ export const SCHEMA_VERSION = ${JSON.stringify(schemaVersion)};
|
|
|
505
505
|
//#endregion
|
|
506
506
|
export { generateSdkCommand, writeRegistrationForBuild };
|
|
507
507
|
|
|
508
|
-
//# sourceMappingURL=generate_sdk-
|
|
508
|
+
//# sourceMappingURL=generate_sdk-ByD-gTsK.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate_sdk-De-aLC1L.js","names":[],"sources":["../src/commands/generate_sdk.ts"],"sourcesContent":["/**\n * CLI command: generate-sdk\n *\n * Reads the project's tables — `backend/schema`, through the loader the\n * backend boots from, so the SDK describes exactly the tables served — or,\n * with `--from`, a running project's contract, and writes a typed TypeScript\n * SDK to the output directory (default: ./generated/sdk).\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { computeSchemaVersion, type TableDescriptor } from \"@rebasepro/types\";\nimport { CodegenError, generateSDK, GeneratedFile, toTableAccessor } from \"@rebasepro/codegen\";\nimport { isSchemaDefinitionError } from \"@rebasepro/common\";\nimport { findProjectRoot, readEnvFile } from \"../utils/project\";\nimport { DEV_BACKEND_URL_ENV } from \"../utils/dev-server\";\nimport { Refusal } from \"../utils/refusal\";\nimport { findBackendApp, GENERATED_DIR, loadManifest, manifestExists, writeManifest } from \"../manifest\";\nimport { readLink } from \"./cloud/context\";\nimport { SCHEMA_DIR_FLAG_HELP, PATH_RESOLUTION_RULE } from \"../utils/path-flags\";\nimport { loadProjectSchema, type ModuleAliases } from \"../utils/project-schema\";\n\ninterface GenerateSDKArgs {\n /** The schema directory: the one whose index exports the tables. */\n schemaDir: string;\n output: string;\n cwd: string;\n /**\n * Where to read the schema from instead of local source.\n *\n * `link` uses this checkout's linked project; anything else is treated as\n * the base URL of a Rebase backend. This is what lets a repository that\n * contains no tables — a separate frontend, a second web app — generate\n * a typed client from the project it talks to.\n */\n from?: string;\n /** Bearer token for the contract endpoint. Falls back to REBASE_SERVICE_KEY. */\n token?: string;\n /**\n * Also register the generated `Database` for server-side code: write the\n * types and the `Register` augmentation into `backend/generated/`. See\n * {@link writeRegistration}.\n */\n register?: boolean;\n /**\n * The directory holding `rebase.json`, where `--register` is remembered\n * and under which `backend/generated/` is. Found from `cwd` when not given.\n */\n projectRoot?: string;\n /** Module specifiers mapped to files when importing the schema (in-repo runs and tests). */\n moduleAliases?: ModuleAliases;\n help?: boolean;\n}\n\n/** What `--register` writes, and what marks a project as having opted in. */\nexport const REGISTER_FILE = \"register.ts\";\n\n/** The first line of {@link REGISTER_FILE}: a file without it is the developer's own. */\nconst REGISTER_MARKER = \"// Auto-generated by `rebase generate-sdk --register`. Do not edit.\";\n\nconst REGISTER_SOURCE = `${REGISTER_MARKER}\n//\n// Registers this project's generated \\`Database\\` on \\`@rebasepro/types\\`, so\n// \\`context.data\\` in table hooks, \\`rebase.dataAsAdmin\\`, and the\n// \\`rebase\\` a function or a cron receives are typed from it. Every later\n// \\`rebase generate-sdk\\` (and \\`rebase dev\\`) refreshes this directory; delete\n// it to go back to untyped server-side data.\nimport type { Database } from \"./database.types\";\n\ndeclare module \"@rebasepro/types\" {\n interface Register {\n database: Database;\n }\n}\n`;\n\n/**\n * Where `--register` writes: `backend/generated/` under the project root.\n *\n * Inside `backend/` because that is the program the hooks, functions and\n * crons it types are compiled in. The types are copied in beside the\n * registration rather than imported from `generated/sdk`, which is outside\n * the backend's `rootDir`.\n */\nexport function registrationDir(projectRoot: string): string {\n return path.join(projectRoot, GENERATED_DIR);\n}\n\n/** Whether this project opted in: the registration is there, and it is ours. */\nfunction hasRegistration(dir: string): boolean {\n try {\n return fs.readFileSync(path.join(dir, REGISTER_FILE), \"utf-8\").startsWith(REGISTER_MARKER);\n } catch {\n return false;\n }\n}\n\n/** Write a file only when its content changed, so a watcher on the directory does not restart for nothing. */\nfunction writeIfChanged(filePath: string, content: string): void {\n try {\n if (fs.readFileSync(filePath, \"utf-8\") === content) return;\n } catch {\n // Not there yet.\n }\n fs.writeFileSync(filePath, content, \"utf-8\");\n}\n\n/**\n * Write the generated `Database` and its `Register` augmentation into\n * {@link registrationDir}. Refuses to overwrite a `register.ts` it did not\n * write.\n */\nfunction writeRegistration(dir: string, databaseTypes: string): void {\n const registerPath = path.join(dir, REGISTER_FILE);\n if (fs.existsSync(registerPath) && !hasRegistration(dir)) {\n throw new Error(\n `${registerPath} exists and was not written by \"rebase generate-sdk --register\". ` +\n \"Move it, or register the Database there yourself.\"\n );\n }\n fs.mkdirSync(dir, { recursive: true });\n writeIfChanged(path.join(dir, \"database.types.ts\"), databaseTypes);\n writeIfChanged(registerPath, REGISTER_SOURCE);\n}\n\n/**\n * Write the server-side registration from the build's tables, exactly as\n * `rebase generate-sdk` writes it.\n *\n * Only for a project that asked for it: `registerDatabase` in `rebase.json`,\n * or a registration an earlier `--register` left, which is kept current. The\n * registration lives in gitignored `backend/generated/`, so a fresh clone (a\n * CI job) has none until something writes it, and a bundle compiled without\n * it types `context.data` as untyped rows: hooks that read a typed column fail\n * to compile there while they compile locally.\n *\n * Returns the directory written, or null when there was nothing to do.\n * Throws when a `register.ts` there is not ours, as `generate-sdk` refuses.\n */\nexport async function writeRegistrationForBuild(\n projectRoot: string,\n tables: readonly TableDescriptor[],\n registerDatabase: boolean\n): Promise<string | null> {\n const dir = registrationDir(projectRoot);\n if (!registerDatabase && !hasRegistration(dir)) return null;\n if (tables.length === 0) return null;\n const databaseTypes = generateSDK(sortedBySlug(tables), { includeReadme: false })\n .find((file) => file.path === \"database.types.ts\")?.content;\n if (databaseTypes === undefined) return null;\n writeRegistration(dir, databaseTypes);\n return dir;\n}\n\n/** Tables sorted by slug: the same schema generates the same bytes, whatever order the index lists it in. */\nfunction sortedBySlug(tables: readonly TableDescriptor[]): TableDescriptor[] {\n return [...tables].sort((a, b) => a.slug.localeCompare(b.slug));\n}\n\n/**\n * Whether `rebase.json` asks for the registration (`registerDatabase: true` on\n * the backend app). That is what survives a clone: `generated/` is gitignored,\n * so a `register.ts` from an earlier run is not there to say it.\n *\n * An unreadable manifest answers no; `rebase build` is where it is reported.\n */\nfunction manifestRegisters(projectRoot: string | undefined): boolean {\n if (!projectRoot || !manifestExists(projectRoot)) return false;\n try {\n return findBackendApp(loadManifest(projectRoot).manifest)?.app.registerDatabase === true;\n } catch {\n return false;\n }\n}\n\n/**\n * Remember `--register` in `rebase.json`, so later runs, `rebase dev` and a\n * fresh clone keep registering. Returns where it was written, or why not.\n *\n * Never creates the file: a project without one is synthesized from its\n * layout, and writing one is `rebase apps init`'s decision, not this flag's.\n */\nfunction rememberRegistration(projectRoot: string | undefined): { written: string } | { skipped: string } {\n if (!projectRoot || !manifestExists(projectRoot)) {\n return { skipped: \"No rebase.json here, so the choice lasts as long as the generated files.\" };\n }\n let loaded: ReturnType<typeof loadManifest>;\n try {\n loaded = loadManifest(projectRoot);\n } catch (error) {\n return { skipped: `rebase.json could not be read (${error instanceof Error ? error.message : String(error)}).` };\n }\n const backend = findBackendApp(loaded.manifest);\n if (!backend) return { skipped: \"rebase.json declares no backend app to remember it on.\" };\n if (backend.app.registerDatabase === true) return { written: loaded.filePath ?? projectRoot };\n const manifest = {\n ...loaded.manifest,\n apps: { ...loaded.manifest.apps, [backend.name]: { ...backend.app, registerDatabase: true } }\n };\n return { written: writeManifest(projectRoot, manifest) };\n}\n\n/**\n * The tables the backend serves, read the way it reads them: the schema\n * directory's index, through `loadBackendSchema`, compiled to descriptors.\n *\n * A definition the backend would refuse is fatal here too, as it is at boot:\n * `rebase dev` runs this on every save, and skipping a table would overwrite\n * good types with a `Database` that is silently short one. A missing\n * directory is a `Refusal`: the message says all there is. A module that\n * throws on import is not: that is the project's own code failing, and the\n * stack `--debug` prints points at the line.\n */\nasync function loadTables(projectRoot: string, schemaDir: string, aliases?: ModuleAliases): Promise<TableDescriptor[]> {\n const absDir = path.resolve(schemaDir);\n if (!fs.existsSync(absDir)) {\n throw new Refusal(`Schema directory not found: ${absDir} (${PATH_RESOLUTION_RULE})`);\n }\n const { compiled } = await loadProjectSchema(projectRoot, absDir, aliases);\n return compiled.descriptors;\n}\n\n/**\n * Write generated files to the output directory.\n */\nfunction writeFiles(outputDir: string, files: GeneratedFile[]): void {\n const absOutput = path.resolve(outputDir);\n\n // Create output directory\n fs.mkdirSync(absOutput, { recursive: true });\n\n for (const file of files) {\n const filePath = path.join(absOutput, file.path);\n const dir = path.dirname(filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n fs.writeFileSync(filePath, file.content, \"utf-8\");\n }\n}\n\nfunction printSdkHelp(): void {\n console.log(`\n${chalk.bold(\"rebase generate-sdk\")} — generate a typed client from a project's schema\n\n${chalk.bold(\"Usage\")}\n rebase generate-sdk [options]\n\n${chalk.bold(\"Options\")}\n --schema-dir <dir> ${SCHEMA_DIR_FLAG_HELP}\n -o, --output <dir> Where to write the SDK (default: ./generated/sdk)\n (--out is accepted too, as on 'rebase build')\n --from <link|url> Fetch the schema from a running project instead of\n local source. \"link\" uses this checkout's linked project.\n --token <token> Bearer token for the contract endpoint\n (default: $REBASE_SERVICE_KEY)\n --register Also type server-side data: write the types and the\n Register declaration to backend/generated/, and\n remember it in rebase.json so later runs keep it.\n -h, --help Show this help\n\n${chalk.bold(\"Examples\")}\n rebase generate-sdk From backend/schema\n rebase generate-sdk --from link From the linked project\n rebase generate-sdk --from https://api.acme.com From any Rebase backend\n rebase generate-sdk --register Type context.data and rebase.dataAsAdmin too\n`.trim());\n}\n\n/** What `--from` sent to the contract endpoint, and which keys it left behind. */\ninterface ContractCredential {\n /** The bearer token sent: `--token`, the shell's key, or none. */\n sent: \"token\" | \"ambient\" | null;\n /** `REBASE_SERVICE_KEY` is in the shell environment. */\n shellKey: boolean;\n /** `REBASE_SERVICE_KEY` is in the project's `.env`. */\n envFileKey: boolean;\n}\n\n/**\n * What to say when the contract endpoint refuses, by what was and was not sent.\n *\n * \"Set REBASE_SERVICE_KEY\" is only right when no key exists. The shell's key is\n * withheld from every host but the linked project, and `.env`'s is never read\n * here — it is the local backend's key, and the linked project is usually a\n * deployed one — so telling a reader whose key is in `.env` to set it sends them\n * to fix something that is not broken.\n */\nfunction contractRefusalHint(credential: ContractCredential): string[] {\n if (credential.sent === \"token\") {\n return [\"The token passed with --token was refused: pass a service key, or an admin's token.\"];\n }\n if (credential.sent === \"ambient\") {\n return [\"REBASE_SERVICE_KEY was sent and refused: it is not this project's service key. Pass the right one with --token.\"];\n }\n if (credential.shellKey) {\n return [\n \"REBASE_SERVICE_KEY is set, but it is only sent to this checkout's linked project, and this host is not it.\",\n \"Pass the key with --token to send it here.\"\n ];\n }\n if (credential.envFileKey) {\n return [\n \"REBASE_SERVICE_KEY in .env is not sent: --from sends the shell's REBASE_SERVICE_KEY, and only to this checkout's linked project.\",\n \"Pass the key with --token.\"\n ];\n }\n return [\"Pass --token <key>, a service key or an admin's token. The shell's REBASE_SERVICE_KEY is sent only to this checkout's linked project.\"];\n}\n\n/**\n * Whether one entry of a contract's `tables` is a table descriptor, as far as\n * the generator reads one: a slug, a SQL name, columns and relations.\n */\nfunction isTableDescriptor(value: unknown): value is TableDescriptor {\n return typeof value === \"object\" && value !== null\n && \"slug\" in value && typeof value.slug === \"string\"\n && \"table\" in value && typeof value.table === \"string\"\n && \"columns\" in value && Array.isArray(value.columns)\n && \"relations\" in value && Array.isArray(value.relations);\n}\n\n/**\n * The tables a running project serves, from its contract endpoint\n * (`{ schemaVersion, runtime, tables: TableDescriptor[] }`). The descriptors\n * are plain data — no thunks to rehydrate — so they go to the generator as\n * they arrive.\n */\nasync function fetchRemoteTables(\n baseUrl: string,\n token: string | undefined,\n credential: ContractCredential\n): Promise<{ tables: TableDescriptor[]; schemaVersion: string }> {\n const url = `${baseUrl.replace(/\\/+$/, \"\")}/api/meta/contract`;\n\n const headers: Record<string, string> = { accept: \"application/json\" };\n if (token) headers.authorization = `Bearer ${token}`;\n\n let response: Response;\n try {\n response = await fetch(url, { headers });\n } catch (err) {\n console.log(chalk.red(` ✗ Could not reach ${url}`));\n console.log(chalk.gray(` ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n }\n\n if (response.status === 401 || response.status === 403) {\n console.log(chalk.red(` ✗ Not authorized to read the project contract (${response.status}).`));\n console.log(chalk.gray(\" The contract describes every table and relation, so it is admin-only.\"));\n for (const line of contractRefusalHint(credential)) console.log(chalk.gray(` ${line}`));\n process.exit(1);\n }\n\n if (response.status === 404) {\n console.log(chalk.red(\" ✗ This server has no contract endpoint.\"));\n console.log(chalk.gray(\" It needs to be running Rebase 0.11 or newer.\"));\n process.exit(1);\n }\n\n if (!response.ok) {\n console.log(chalk.red(` ✗ Contract request failed with ${response.status}.`));\n process.exit(1);\n }\n\n const contract: unknown = await response.json();\n const field = (key: string): unknown =>\n typeof contract === \"object\" && contract !== null && key in contract\n ? Object.entries(contract).find(([name]) => name === key)?.[1]\n : undefined;\n const tables = field(\"tables\");\n const schemaVersion = field(\"schemaVersion\");\n\n if (!Array.isArray(tables)) {\n if (Array.isArray(field(\"collections\"))) {\n // A server from before tables: its contract lists collections, a\n // shape this CLI no longer generates from.\n console.log(chalk.red(\" ✗ This server answers the contract with collections: it runs a Rebase release from before tables.\"));\n console.log(chalk.gray(\" Upgrade the server to a release that serves `tables`, or generate from this project's\"));\n console.log(chalk.gray(\" own backend/schema by running `rebase generate-sdk` without --from.\"));\n process.exit(1);\n }\n console.log(chalk.red(\" ✗ The contract response did not contain tables.\"));\n process.exit(1);\n }\n const invalid = tables.findIndex(entry => !isTableDescriptor(entry));\n if (invalid !== -1) {\n console.log(chalk.red(` ✗ The contract's tables[${invalid}] is not a table descriptor (no slug, table, columns or relations).`));\n process.exit(1);\n }\n\n return {\n tables: tables.filter(isTableDescriptor),\n schemaVersion: typeof schemaVersion === \"string\" ? schemaVersion : \"unknown\"\n };\n}\n\n/**\n * Decide whether the ambient service key may be sent to this host.\n *\n * `REBASE_SERVICE_KEY` grants full admin bypass. Attaching it to whatever URL\n * happened to be passed — or, worse, to whatever a committed `.rebase/cloud.json`\n * points at — would hand the project's most powerful credential to a host nobody\n * vetted. An explicit `--token` is a decision the caller made; the ambient\n * variable is not, so it only travels to the project this checkout is linked to.\n */\nfunction mayUseAmbientKey(target: string, cwd: string): boolean {\n const link = readLink(findProjectRoot(cwd) ?? cwd);\n if (!link?.apiUrl) return false;\n try {\n // Origin, not host: with a link recorded as https, an `http://` target\n // for the same host would otherwise pass and send the key in cleartext.\n return new URL(link.apiUrl).origin === new URL(target).origin;\n } catch {\n return false;\n }\n}\n\n/**\n * The base URL to show in the printed usage example.\n *\n * `rebase dev` binds a port derived from the project path, not 3001, and writes\n * the one it actually got to `.rebase/state.json`. Printing a hardcoded\n * `localhost:3001` sent people to a port nothing was listening on — or, with\n * several projects on one machine, to a different project's backend. Prefer the\n * port `rebase dev` says it is starting the backend on (`DEV_BACKEND_URL_ENV`:\n * it regenerates the SDK before the backend binds), then the port this project\n * last ran on; fall back to the literal only when the project has never been\n * started.\n */\nexport function resolveExampleBaseUrl(cwd: string): string {\n const fromDev = process.env[DEV_BACKEND_URL_ENV]?.trim();\n if (fromDev) return fromDev;\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n try {\n const state = JSON.parse(fs.readFileSync(path.join(projectRoot, \".rebase\", \"state.json\"), \"utf-8\"));\n if (typeof state.baseUrl === \"string\" && state.baseUrl) return state.baseUrl;\n if (typeof state.port === \"number\") return `http://localhost:${state.port}`;\n } catch {\n // Never started, or the file is unreadable — fall through.\n }\n return \"http://localhost:3001\";\n}\n\n/** Whether a slug can be written as `rebase.data.<slug>` rather than a lookup. */\nexport function isIdentifierLike(slug: string): boolean {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(slug);\n}\n\n/** Resolve `--from` into a base URL, following the link file when asked. */\nfunction resolveSchemaSource(from: string, cwd: string): string {\n if (from !== \"link\") {\n // A bare hostname or a typo would otherwise be handed to `fetch` and fail\n // with something unhelpful; a non-http scheme has no business here at all.\n let parsed: URL;\n try {\n parsed = new URL(from);\n } catch {\n console.log(chalk.red(` ✗ \"${from}\" is not a valid URL.`));\n console.log(chalk.gray(\" Pass a full URL, e.g. https://api.example.com, or \\\"link\\\".\"));\n process.exit(1);\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n console.log(chalk.red(\" ✗ The project URL must be http or https.\"));\n process.exit(1);\n }\n return from;\n }\n\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n const link = readLink(projectRoot);\n\n if (!link) {\n console.log(chalk.red(\" ✗ This checkout is not linked to a project.\"));\n console.log(chalk.gray(\" Run `rebase cloud link <url>`, or pass --from <url>.\"));\n process.exit(1);\n }\n\n const apiUrl = link.apiUrl;\n if (!apiUrl) {\n console.log(chalk.red(\" ✗ The project link has no API URL.\"));\n console.log(chalk.gray(\" Re-link with `rebase cloud link <url>` to record one.\"));\n process.exit(1);\n }\n\n return apiUrl;\n}\n\n/**\n * Main entry point for the generate-sdk command.\n */\nexport async function generateSdkCommand(args: GenerateSDKArgs): Promise<void> {\n const { schemaDir, output, cwd } = args;\n\n if (args.help) {\n printSdkHelp();\n return;\n }\n\n const resolvedSchemaDir = path.isAbsolute(schemaDir)\n ? schemaDir\n : path.join(cwd, schemaDir);\n const projectRoot = args.projectRoot ?? findProjectRoot(cwd) ?? undefined;\n\n const resolvedOutput = path.isAbsolute(output)\n ? output\n : path.join(cwd, output);\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔧 Rebase SDK Generator\"));\n console.log(\"\");\n\n let tables: TableDescriptor[];\n let remoteSchemaVersion: string | undefined;\n\n if (args.from) {\n const baseUrl = resolveSchemaSource(args.from, cwd);\n console.log(` ${chalk.gray(\"Project:\")} ${baseUrl}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Fetching the project contract...\"));\n\n const ambient = mayUseAmbientKey(baseUrl, cwd)\n ? process.env.REBASE_SERVICE_KEY\n : undefined;\n\n if (!args.token && !ambient && process.env.REBASE_SERVICE_KEY) {\n console.log(chalk.dim(\n \" (not sending REBASE_SERVICE_KEY — this host is not the linked project; pass --token to override)\"\n ));\n }\n\n const remote = await fetchRemoteTables(baseUrl, args.token || ambient, {\n sent: args.token ? \"token\" : ambient ? \"ambient\" : null,\n shellKey: Boolean(process.env.REBASE_SERVICE_KEY),\n envFileKey: Boolean(readEnvFile(findProjectRoot(cwd) ?? cwd).REBASE_SERVICE_KEY)\n });\n tables = remote.tables;\n remoteSchemaVersion = remote.schemaVersion;\n } else {\n // A headless project has no schema directory by design: its API is\n // introspected from the live database at boot, and there is nothing here\n // to generate a client from. The scaffold ships `pnpm generate:sdk`\n // anyway, so the documented headless path had a script that could only\n // ever fail — and it failed with a path, which reads as a broken install\n // rather than a question with an answer.\n if (!fs.existsSync(resolvedSchemaDir)) {\n console.log(chalk.gray(\n \" ○ This project derives its API from the database — \"\n + \"there is no backend/schema to generate a client from.\"\n ));\n console.log(chalk.gray(\n ` Nothing to generate from: ${resolvedSchemaDir} does not exist.`\n ));\n console.log(\"\");\n return;\n }\n console.log(` ${chalk.gray(\"Schema:\")} ${resolvedSchemaDir}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Loading the tables...\"));\n try {\n tables = await loadTables(projectRoot ?? cwd, resolvedSchemaDir, args.moduleAliases);\n } catch (err) {\n // A definition the backend would refuse to boot on: every problem,\n // one per line, each naming its table.\n if (isSchemaDefinitionError(err)) {\n console.log(\"\");\n console.log(chalk.red(` ✗ ${err.message}`));\n process.exit(1);\n }\n throw err;\n }\n }\n\n // Sorted by slug, so the same schema generates the same SDK.\n tables = sortedBySlug(tables);\n\n if (tables.length === 0) {\n console.log(chalk.red(\" ✗ No tables found. Nothing to generate.\"));\n process.exit(1);\n }\n\n console.log(chalk.green(` ✓ Found ${tables.length} table(s): ${tables.map(table => table.slug).join(\", \")}`));\n console.log(\"\");\n\n // 2. Generate SDK files\n console.log(chalk.cyan(\" → Generating SDK files...\"));\n let files: GeneratedFile[];\n try {\n files = generateSDK(tables, { baseUrl: resolveExampleBaseUrl(cwd) });\n } catch (err) {\n // A schema that cannot be expressed as valid TypeScript — two slugs\n // that collide on one accessor, a slug with no usable name. The\n // generator refuses rather than emitting a file that does not compile,\n // or one that silently routes a table's reads to another's.\n if (err instanceof CodegenError) {\n console.log(\"\");\n console.log(chalk.red(` ✗ ${err.message}`));\n process.exit(1);\n }\n throw err;\n }\n\n // Stamp the schema this SDK was built from.\n //\n // Without it, an app in a separate repository has no way to know its client\n // is stale: the backend moves on, the frontend keeps compiling against types\n // captured weeks ago, and the mismatch only surfaces as a runtime error. With\n // it, CI can compare against `/api/meta/schema-version` and say so.\n //\n // No generation timestamp. Tables are sorted above precisely so that\n // the same schema produces the same bytes; a timestamp put that back,\n // turning every regeneration into a diff and making the obvious staleness\n // gate — `rebase generate-sdk && git diff --exit-code` — impossible to pass.\n // `SCHEMA_VERSION` already identifies what this was built from, and does it\n // in a way that can be compared against a running project.\n const schemaVersion = remoteSchemaVersion ?? computeSchemaVersion(tables);\n files.push({\n path: \"schema.meta.ts\",\n content: `// Auto-generated by \\`rebase generate-sdk\\`. Do not edit.\n//\n// The schema version this SDK was generated from. Compare it against the\n// project's current version to detect drift:\n//\n// curl -s <api-url>/api/meta/schema-version\n//\n// Pass it to the client as \\`schemaVersion\\` and every request carries it in\n// the \\`x-rebase-schema\\` header, so the server can name the drift instead of\n// answering a renamed field with a bare 400.\nexport const SCHEMA_VERSION = ${JSON.stringify(schemaVersion)};\n`\n });\n\n console.log(chalk.green(` ✓ Generated ${files.length} file(s)`));\n console.log(chalk.gray(` schema ${schemaVersion}`));\n\n // 3. Write to disk\n console.log(chalk.cyan(` → Writing to ${resolvedOutput}...`));\n writeFiles(resolvedOutput, files);\n\n // 4. The server-side registration: on request, and kept current once a\n // project has it, so `rebase dev` regenerating the SDK never leaves the\n // server typed against an older schema than the client.\n const registerDir = projectRoot ? registrationDir(projectRoot) : undefined;\n if (args.register || (registerDir && hasRegistration(registerDir)) || manifestRegisters(projectRoot)) {\n if (!registerDir || !fs.existsSync(path.dirname(registerDir))) {\n console.log(chalk.red(` ✗ No backend/ directory to register the Database in${registerDir ? ` (${path.dirname(registerDir)})` : \"\"}.`));\n console.log(chalk.gray(\" --register writes backend/generated/register.ts; run it inside a project with a backend.\"));\n process.exit(1);\n return;\n }\n const databaseTypes = files.find((file) => file.path === \"database.types.ts\")?.content;\n if (databaseTypes !== undefined) {\n try {\n writeRegistration(registerDir, databaseTypes);\n } catch (error) {\n console.log(chalk.red(` ✗ ${error instanceof Error ? error.message : String(error)}`));\n process.exit(1);\n return;\n }\n console.log(chalk.green(` ✓ Registered the Database for server-side code in ${registerDir}`));\n if (args.register) {\n const remembered = rememberRegistration(projectRoot);\n if (\"written\" in remembered) {\n console.log(chalk.gray(` Remembered in ${path.relative(cwd, remembered.written) || \"rebase.json\"} (registerDatabase).`));\n } else {\n console.log(chalk.yellow(` ${remembered.skipped}`));\n }\n }\n }\n }\n\n console.log(\"\");\n console.log(chalk.green.bold(\" ✓ SDK generated successfully!\"));\n console.log(\"\");\n const typesImport = `./${path.relative(cwd, path.join(resolvedOutput, \"database.types\"))}`;\n const metaImport = `./${path.relative(cwd, path.join(resolvedOutput, \"schema.meta\"))}`;\n const exampleSlug = tables[0]?.slug || \"my_table\";\n\n console.log(chalk.gray(\" Usage:\"));\n console.log(chalk.gray(\" import { createRebaseClient } from '@rebasepro/client';\"));\n console.log(chalk.gray(` import { tablesDictionary, type Database } from '${typesImport}';`));\n console.log(chalk.gray(` import { SCHEMA_VERSION } from '${metaImport}';`));\n console.log(\"\");\n console.log(chalk.gray(\" const rebase = createRebaseClient<Database>({\"));\n console.log(chalk.gray(` baseUrl: '${resolveExampleBaseUrl(cwd)}',`));\n // Sent as `x-rebase-schema` on every request. Costs one line here and is\n // the difference between a server that can say \"this client is three\n // deploys behind\" and one that can only reject a field it does not know.\n console.log(chalk.gray(\" schemaVersion: SCHEMA_VERSION,\"));\n // Without the dictionary a hyphenated slug is not resolvable from the\n // property name alone, and the request 404s at runtime.\n console.log(chalk.gray(\" tables: tablesDictionary,\"));\n console.log(chalk.gray(\" // token: 'your-jwt-token',\"));\n console.log(chalk.gray(\" });\"));\n console.log(\"\");\n // `rebase.data.<accessor>` is the typed surface, so it is what gets printed.\n // `rebase.data.table(slug)` exists too, but it is generic over\n // `Record<string, unknown>` and has no link to `Database` — it was the\n // headline example here for a while, which advertised the one call shape\n // that throws away the types this command just generated.\n const exampleAccessor = toTableAccessor(exampleSlug);\n const exampleAccess = isIdentifierLike(exampleAccessor)\n ? `rebase.data.${exampleAccessor}`\n : `rebase.data[${JSON.stringify(exampleAccessor)}]`;\n console.log(chalk.gray(` const { data } = await ${exampleAccess}.find();`));\n console.log(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,gBAAgB;;AAG7B,IAAM,kBAAkB;AAExB,IAAM,kBAAkB,GAAG,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;AAwB3C,SAAgB,gBAAgB,aAA6B;CACzD,OAAO,KAAK,KAAK,aAAa,aAAa;AAC/C;;AAGA,SAAS,gBAAgB,KAAsB;CAC3C,IAAI;EACA,OAAO,GAAG,aAAa,KAAK,KAAK,KAAK,aAAa,GAAG,OAAO,CAAC,CAAC,WAAW,eAAe;CAC7F,QAAQ;EACJ,OAAO;CACX;AACJ;;AAGA,SAAS,eAAe,UAAkB,SAAuB;CAC7D,IAAI;EACA,IAAI,GAAG,aAAa,UAAU,OAAO,MAAM,SAAS;CACxD,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MAAM,gBAAgB,iBAAiB,eAAe,IAChD,eAAe,oBACf,eAAe,KAAK,UAAU,eAAe,EAAE;CACrD,QAAQ,IAAI,MAAM,KAAK,8BAA8B,cAAc,SAAS,CAAC;CAC7E,QAAQ,IAAI,EAAE;AAClB"}
|
|
1
|
+
{"version":3,"file":"generate_sdk-ByD-gTsK.js","names":[],"sources":["../src/commands/generate_sdk.ts"],"sourcesContent":["/**\n * CLI command: generate-sdk\n *\n * Reads the project's tables — `backend/schema`, through the loader the\n * backend boots from, so the SDK describes exactly the tables served — or,\n * with `--from`, a running project's contract, and writes a typed TypeScript\n * SDK to the output directory (default: ./generated/sdk).\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { computeSchemaVersion, type TableDescriptor } from \"@rebasepro/types\";\nimport { CodegenError, generateSDK, GeneratedFile, toTableAccessor } from \"@rebasepro/codegen\";\nimport { isSchemaDefinitionError } from \"@rebasepro/common\";\nimport { findProjectRoot, readEnvFile } from \"../utils/project\";\nimport { DEV_BACKEND_URL_ENV } from \"../utils/dev-server\";\nimport { Refusal } from \"../utils/refusal\";\nimport { findBackendApp, GENERATED_DIR, loadManifest, manifestExists, writeManifest } from \"../manifest\";\nimport { readLink } from \"./cloud/context\";\nimport { SCHEMA_DIR_FLAG_HELP, PATH_RESOLUTION_RULE } from \"../utils/path-flags\";\nimport { loadProjectSchema, type ModuleAliases } from \"../utils/project-schema\";\n\ninterface GenerateSDKArgs {\n /** The schema directory: the one whose index exports the tables. */\n schemaDir: string;\n output: string;\n cwd: string;\n /**\n * Where to read the schema from instead of local source.\n *\n * `link` uses this checkout's linked project; anything else is treated as\n * the base URL of a Rebase backend. This is what lets a repository that\n * contains no tables — a separate frontend, a second web app — generate\n * a typed client from the project it talks to.\n */\n from?: string;\n /** Bearer token for the contract endpoint. Falls back to REBASE_SERVICE_KEY. */\n token?: string;\n /**\n * Also register the generated `Database` for server-side code: write the\n * types and the `Register` augmentation into `backend/generated/`. See\n * {@link writeRegistration}.\n */\n register?: boolean;\n /**\n * The directory holding `rebase.json`, where `--register` is remembered\n * and under which `backend/generated/` is. Found from `cwd` when not given.\n */\n projectRoot?: string;\n /** Module specifiers mapped to files when importing the schema (in-repo runs and tests). */\n moduleAliases?: ModuleAliases;\n help?: boolean;\n}\n\n/** What `--register` writes, and what marks a project as having opted in. */\nexport const REGISTER_FILE = \"register.ts\";\n\n/** The first line of {@link REGISTER_FILE}: a file without it is the developer's own. */\nconst REGISTER_MARKER = \"// Auto-generated by `rebase generate-sdk --register`. Do not edit.\";\n\nconst REGISTER_SOURCE = `${REGISTER_MARKER}\n//\n// Registers this project's generated \\`Database\\` on \\`@rebasepro/types\\`, so\n// \\`context.data\\` in table hooks, \\`rebase.dataAsAdmin\\`, and the\n// \\`rebase\\` a function or a cron receives are typed from it. Every later\n// \\`rebase generate-sdk\\` (and \\`rebase dev\\`) refreshes this directory; delete\n// it to go back to untyped server-side data.\nimport type { Database } from \"./database.types\";\n\ndeclare module \"@rebasepro/types\" {\n interface Register {\n database: Database;\n }\n}\n`;\n\n/**\n * Where `--register` writes: `backend/generated/` under the project root.\n *\n * Inside `backend/` because that is the program the hooks, functions and\n * crons it types are compiled in. The types are copied in beside the\n * registration rather than imported from `generated/sdk`, which is outside\n * the backend's `rootDir`.\n */\nexport function registrationDir(projectRoot: string): string {\n return path.join(projectRoot, GENERATED_DIR);\n}\n\n/** Whether this project opted in: the registration is there, and it is ours. */\nfunction hasRegistration(dir: string): boolean {\n try {\n return fs.readFileSync(path.join(dir, REGISTER_FILE), \"utf-8\").startsWith(REGISTER_MARKER);\n } catch {\n return false;\n }\n}\n\n/** Write a file only when its content changed, so a watcher on the directory does not restart for nothing. */\nfunction writeIfChanged(filePath: string, content: string): void {\n try {\n if (fs.readFileSync(filePath, \"utf-8\") === content) return;\n } catch {\n // Not there yet.\n }\n fs.writeFileSync(filePath, content, \"utf-8\");\n}\n\n/**\n * Write the generated `Database` and its `Register` augmentation into\n * {@link registrationDir}. Refuses to overwrite a `register.ts` it did not\n * write.\n */\nfunction writeRegistration(dir: string, databaseTypes: string): void {\n const registerPath = path.join(dir, REGISTER_FILE);\n if (fs.existsSync(registerPath) && !hasRegistration(dir)) {\n throw new Error(\n `${registerPath} exists and was not written by \"rebase generate-sdk --register\". ` +\n \"Move it, or register the Database there yourself.\"\n );\n }\n fs.mkdirSync(dir, { recursive: true });\n writeIfChanged(path.join(dir, \"database.types.ts\"), databaseTypes);\n writeIfChanged(registerPath, REGISTER_SOURCE);\n}\n\n/**\n * Write the server-side registration from the build's tables, exactly as\n * `rebase generate-sdk` writes it.\n *\n * Only for a project that asked for it: `registerDatabase` in `rebase.json`,\n * or a registration an earlier `--register` left, which is kept current. The\n * registration lives in gitignored `backend/generated/`, so a fresh clone (a\n * CI job) has none until something writes it, and a bundle compiled without\n * it types `context.data` as untyped rows: hooks that read a typed column fail\n * to compile there while they compile locally.\n *\n * Returns the directory written, or null when there was nothing to do.\n * Throws when a `register.ts` there is not ours, as `generate-sdk` refuses.\n */\nexport async function writeRegistrationForBuild(\n projectRoot: string,\n tables: readonly TableDescriptor[],\n registerDatabase: boolean\n): Promise<string | null> {\n const dir = registrationDir(projectRoot);\n if (!registerDatabase && !hasRegistration(dir)) return null;\n if (tables.length === 0) return null;\n const databaseTypes = generateSDK(sortedBySlug(tables), { includeReadme: false })\n .find((file) => file.path === \"database.types.ts\")?.content;\n if (databaseTypes === undefined) return null;\n writeRegistration(dir, databaseTypes);\n return dir;\n}\n\n/** Tables sorted by slug: the same schema generates the same bytes, whatever order the index lists it in. */\nfunction sortedBySlug(tables: readonly TableDescriptor[]): TableDescriptor[] {\n return [...tables].sort((a, b) => a.slug.localeCompare(b.slug));\n}\n\n/**\n * Whether `rebase.json` asks for the registration (`registerDatabase: true` on\n * the backend app). That is what survives a clone: `generated/` is gitignored,\n * so a `register.ts` from an earlier run is not there to say it.\n *\n * An unreadable manifest answers no; `rebase build` is where it is reported.\n */\nfunction manifestRegisters(projectRoot: string | undefined): boolean {\n if (!projectRoot || !manifestExists(projectRoot)) return false;\n try {\n return findBackendApp(loadManifest(projectRoot).manifest)?.app.registerDatabase === true;\n } catch {\n return false;\n }\n}\n\n/**\n * Remember `--register` in `rebase.json`, so later runs, `rebase dev` and a\n * fresh clone keep registering. Returns where it was written, or why not.\n *\n * Never creates the file: a project without one is synthesized from its\n * layout, and writing one is `rebase apps init`'s decision, not this flag's.\n */\nfunction rememberRegistration(projectRoot: string | undefined): { written: string } | { skipped: string } {\n if (!projectRoot || !manifestExists(projectRoot)) {\n return { skipped: \"No rebase.json here, so the choice lasts as long as the generated files.\" };\n }\n let loaded: ReturnType<typeof loadManifest>;\n try {\n loaded = loadManifest(projectRoot);\n } catch (error) {\n return { skipped: `rebase.json could not be read (${error instanceof Error ? error.message : String(error)}).` };\n }\n const backend = findBackendApp(loaded.manifest);\n if (!backend) return { skipped: \"rebase.json declares no backend app to remember it on.\" };\n if (backend.app.registerDatabase === true) return { written: loaded.filePath ?? projectRoot };\n const manifest = {\n ...loaded.manifest,\n apps: { ...loaded.manifest.apps, [backend.name]: { ...backend.app, registerDatabase: true } }\n };\n return { written: writeManifest(projectRoot, manifest) };\n}\n\n/**\n * The tables the backend serves, read the way it reads them: the schema\n * directory's index, through `loadBackendSchema`, compiled to descriptors.\n *\n * A definition the backend would refuse is fatal here too, as it is at boot:\n * `rebase dev` runs this on every save, and skipping a table would overwrite\n * good types with a `Database` that is silently short one. A missing\n * directory is a `Refusal`: the message says all there is. A module that\n * throws on import is not: that is the project's own code failing, and the\n * stack `--debug` prints points at the line.\n */\nasync function loadTables(projectRoot: string, schemaDir: string, aliases?: ModuleAliases): Promise<TableDescriptor[]> {\n const absDir = path.resolve(schemaDir);\n if (!fs.existsSync(absDir)) {\n throw new Refusal(`Schema directory not found: ${absDir} (${PATH_RESOLUTION_RULE})`);\n }\n const { compiled } = await loadProjectSchema(projectRoot, absDir, aliases);\n return compiled.descriptors;\n}\n\n/**\n * Write generated files to the output directory.\n */\nfunction writeFiles(outputDir: string, files: GeneratedFile[]): void {\n const absOutput = path.resolve(outputDir);\n\n // Create output directory\n fs.mkdirSync(absOutput, { recursive: true });\n\n for (const file of files) {\n const filePath = path.join(absOutput, file.path);\n const dir = path.dirname(filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n fs.writeFileSync(filePath, file.content, \"utf-8\");\n }\n}\n\nfunction printSdkHelp(): void {\n console.log(`\n${chalk.bold(\"rebase generate-sdk\")} — generate a typed client from a project's schema\n\n${chalk.bold(\"Usage\")}\n rebase generate-sdk [options]\n\n${chalk.bold(\"Options\")}\n --schema-dir <dir> ${SCHEMA_DIR_FLAG_HELP}\n -o, --output <dir> Where to write the SDK (default: ./generated/sdk)\n (--out is accepted too, as on 'rebase build')\n --from <link|url> Fetch the schema from a running project instead of\n local source. \"link\" uses this checkout's linked project.\n --token <token> Bearer token for the contract endpoint\n (default: $REBASE_SERVICE_KEY)\n --register Also type server-side data: write the types and the\n Register declaration to backend/generated/, and\n remember it in rebase.json so later runs keep it.\n -h, --help Show this help\n\n${chalk.bold(\"Examples\")}\n rebase generate-sdk From backend/schema\n rebase generate-sdk --from link From the linked project\n rebase generate-sdk --from https://api.acme.com From any Rebase backend\n rebase generate-sdk --register Type context.data and rebase.dataAsAdmin too\n`.trim());\n}\n\n/** What `--from` sent to the contract endpoint, and which keys it left behind. */\ninterface ContractCredential {\n /** The bearer token sent: `--token`, the shell's key, or none. */\n sent: \"token\" | \"ambient\" | null;\n /** `REBASE_SERVICE_KEY` is in the shell environment. */\n shellKey: boolean;\n /** `REBASE_SERVICE_KEY` is in the project's `.env`. */\n envFileKey: boolean;\n}\n\n/**\n * What to say when the contract endpoint refuses, by what was and was not sent.\n *\n * \"Set REBASE_SERVICE_KEY\" is only right when no key exists. The shell's key is\n * withheld from every host but the linked project, and `.env`'s is never read\n * here — it is the local backend's key, and the linked project is usually a\n * deployed one — so telling a reader whose key is in `.env` to set it sends them\n * to fix something that is not broken.\n */\nfunction contractRefusalHint(credential: ContractCredential): string[] {\n if (credential.sent === \"token\") {\n return [\"The token passed with --token was refused: pass a service key, or an admin's token.\"];\n }\n if (credential.sent === \"ambient\") {\n return [\"REBASE_SERVICE_KEY was sent and refused: it is not this project's service key. Pass the right one with --token.\"];\n }\n if (credential.shellKey) {\n return [\n \"REBASE_SERVICE_KEY is set, but it is only sent to this checkout's linked project, and this host is not it.\",\n \"Pass the key with --token to send it here.\"\n ];\n }\n if (credential.envFileKey) {\n return [\n \"REBASE_SERVICE_KEY in .env is not sent: --from sends the shell's REBASE_SERVICE_KEY, and only to this checkout's linked project.\",\n \"Pass the key with --token.\"\n ];\n }\n return [\"Pass --token <key>, a service key or an admin's token. The shell's REBASE_SERVICE_KEY is sent only to this checkout's linked project.\"];\n}\n\n/**\n * Whether one entry of a contract's `tables` is a table descriptor, as far as\n * the generator reads one: a slug, a SQL name, columns and relations.\n */\nfunction isTableDescriptor(value: unknown): value is TableDescriptor {\n return typeof value === \"object\" && value !== null\n && \"slug\" in value && typeof value.slug === \"string\"\n && \"table\" in value && typeof value.table === \"string\"\n && \"columns\" in value && Array.isArray(value.columns)\n && \"relations\" in value && Array.isArray(value.relations);\n}\n\n/**\n * The tables a running project serves, from its contract endpoint\n * (`{ schemaVersion, runtime, tables: TableDescriptor[] }`). The descriptors\n * are plain data — no thunks to rehydrate — so they go to the generator as\n * they arrive.\n */\nasync function fetchRemoteTables(\n baseUrl: string,\n token: string | undefined,\n credential: ContractCredential\n): Promise<{ tables: TableDescriptor[]; schemaVersion: string }> {\n const url = `${baseUrl.replace(/\\/+$/, \"\")}/api/meta/contract`;\n\n const headers: Record<string, string> = { accept: \"application/json\" };\n if (token) headers.authorization = `Bearer ${token}`;\n\n let response: Response;\n try {\n response = await fetch(url, { headers });\n } catch (err) {\n console.log(chalk.red(` ✗ Could not reach ${url}`));\n console.log(chalk.gray(` ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n }\n\n if (response.status === 401 || response.status === 403) {\n console.log(chalk.red(` ✗ Not authorized to read the project contract (${response.status}).`));\n console.log(chalk.gray(\" The contract describes every table and relation, so it is admin-only.\"));\n for (const line of contractRefusalHint(credential)) console.log(chalk.gray(` ${line}`));\n process.exit(1);\n }\n\n if (response.status === 404) {\n console.log(chalk.red(\" ✗ This server has no contract endpoint.\"));\n console.log(chalk.gray(\" It needs to be running Rebase 0.11 or newer.\"));\n process.exit(1);\n }\n\n if (!response.ok) {\n console.log(chalk.red(` ✗ Contract request failed with ${response.status}.`));\n process.exit(1);\n }\n\n const contract: unknown = await response.json();\n const field = (key: string): unknown =>\n typeof contract === \"object\" && contract !== null && key in contract\n ? Object.entries(contract).find(([name]) => name === key)?.[1]\n : undefined;\n const tables = field(\"tables\");\n const schemaVersion = field(\"schemaVersion\");\n\n if (!Array.isArray(tables)) {\n if (Array.isArray(field(\"collections\"))) {\n // A server from before tables: its contract lists collections, a\n // shape this CLI no longer generates from.\n console.log(chalk.red(\" ✗ This server answers the contract with collections: it runs a Rebase release from before tables.\"));\n console.log(chalk.gray(\" Upgrade the server to a release that serves `tables`, or generate from this project's\"));\n console.log(chalk.gray(\" own backend/schema by running `rebase generate-sdk` without --from.\"));\n process.exit(1);\n }\n console.log(chalk.red(\" ✗ The contract response did not contain tables.\"));\n process.exit(1);\n }\n const invalid = tables.findIndex(entry => !isTableDescriptor(entry));\n if (invalid !== -1) {\n console.log(chalk.red(` ✗ The contract's tables[${invalid}] is not a table descriptor (no slug, table, columns or relations).`));\n process.exit(1);\n }\n\n return {\n tables: tables.filter(isTableDescriptor),\n schemaVersion: typeof schemaVersion === \"string\" ? schemaVersion : \"unknown\"\n };\n}\n\n/**\n * Decide whether the ambient service key may be sent to this host.\n *\n * `REBASE_SERVICE_KEY` grants full admin bypass. Attaching it to whatever URL\n * happened to be passed — or, worse, to whatever a committed `.rebase/cloud.json`\n * points at — would hand the project's most powerful credential to a host nobody\n * vetted. An explicit `--token` is a decision the caller made; the ambient\n * variable is not, so it only travels to the project this checkout is linked to.\n */\nfunction mayUseAmbientKey(target: string, cwd: string): boolean {\n const link = readLink(findProjectRoot(cwd) ?? cwd);\n if (!link?.apiUrl) return false;\n try {\n // Origin, not host: with a link recorded as https, an `http://` target\n // for the same host would otherwise pass and send the key in cleartext.\n return new URL(link.apiUrl).origin === new URL(target).origin;\n } catch {\n return false;\n }\n}\n\n/**\n * The base URL to show in the printed usage example.\n *\n * `rebase dev` binds a port derived from the project path, not 3001, and writes\n * the one it actually got to `.rebase/state.json`. Printing a hardcoded\n * `localhost:3001` sent people to a port nothing was listening on — or, with\n * several projects on one machine, to a different project's backend. Prefer the\n * port `rebase dev` says it is starting the backend on (`DEV_BACKEND_URL_ENV`:\n * it regenerates the SDK before the backend binds), then the port this project\n * last ran on; fall back to the literal only when the project has never been\n * started.\n */\nexport function resolveExampleBaseUrl(cwd: string): string {\n const fromDev = process.env[DEV_BACKEND_URL_ENV]?.trim();\n if (fromDev) return fromDev;\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n try {\n const state = JSON.parse(fs.readFileSync(path.join(projectRoot, \".rebase\", \"state.json\"), \"utf-8\"));\n if (typeof state.baseUrl === \"string\" && state.baseUrl) return state.baseUrl;\n if (typeof state.port === \"number\") return `http://localhost:${state.port}`;\n } catch {\n // Never started, or the file is unreadable — fall through.\n }\n return \"http://localhost:3001\";\n}\n\n/** Whether a slug can be written as `rebase.data.<slug>` rather than a lookup. */\nexport function isIdentifierLike(slug: string): boolean {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(slug);\n}\n\n/** Resolve `--from` into a base URL, following the link file when asked. */\nfunction resolveSchemaSource(from: string, cwd: string): string {\n if (from !== \"link\") {\n // A bare hostname or a typo would otherwise be handed to `fetch` and fail\n // with something unhelpful; a non-http scheme has no business here at all.\n let parsed: URL;\n try {\n parsed = new URL(from);\n } catch {\n console.log(chalk.red(` ✗ \"${from}\" is not a valid URL.`));\n console.log(chalk.gray(\" Pass a full URL, e.g. https://api.example.com, or \\\"link\\\".\"));\n process.exit(1);\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n console.log(chalk.red(\" ✗ The project URL must be http or https.\"));\n process.exit(1);\n }\n return from;\n }\n\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n const link = readLink(projectRoot);\n\n if (!link) {\n console.log(chalk.red(\" ✗ This checkout is not linked to a project.\"));\n console.log(chalk.gray(\" Run `rebase cloud link <url>`, or pass --from <url>.\"));\n process.exit(1);\n }\n\n const apiUrl = link.apiUrl;\n if (!apiUrl) {\n console.log(chalk.red(\" ✗ The project link has no API URL.\"));\n console.log(chalk.gray(\" Re-link with `rebase cloud link <url>` to record one.\"));\n process.exit(1);\n }\n\n return apiUrl;\n}\n\n/**\n * Main entry point for the generate-sdk command.\n */\nexport async function generateSdkCommand(args: GenerateSDKArgs): Promise<void> {\n const { schemaDir, output, cwd } = args;\n\n if (args.help) {\n printSdkHelp();\n return;\n }\n\n const resolvedSchemaDir = path.isAbsolute(schemaDir)\n ? schemaDir\n : path.join(cwd, schemaDir);\n const projectRoot = args.projectRoot ?? findProjectRoot(cwd) ?? undefined;\n\n const resolvedOutput = path.isAbsolute(output)\n ? output\n : path.join(cwd, output);\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔧 Rebase SDK Generator\"));\n console.log(\"\");\n\n let tables: TableDescriptor[];\n let remoteSchemaVersion: string | undefined;\n\n if (args.from) {\n const baseUrl = resolveSchemaSource(args.from, cwd);\n console.log(` ${chalk.gray(\"Project:\")} ${baseUrl}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Fetching the project contract...\"));\n\n const ambient = mayUseAmbientKey(baseUrl, cwd)\n ? process.env.REBASE_SERVICE_KEY\n : undefined;\n\n if (!args.token && !ambient && process.env.REBASE_SERVICE_KEY) {\n console.log(chalk.dim(\n \" (not sending REBASE_SERVICE_KEY — this host is not the linked project; pass --token to override)\"\n ));\n }\n\n const remote = await fetchRemoteTables(baseUrl, args.token || ambient, {\n sent: args.token ? \"token\" : ambient ? \"ambient\" : null,\n shellKey: Boolean(process.env.REBASE_SERVICE_KEY),\n envFileKey: Boolean(readEnvFile(findProjectRoot(cwd) ?? cwd).REBASE_SERVICE_KEY)\n });\n tables = remote.tables;\n remoteSchemaVersion = remote.schemaVersion;\n } else {\n // A headless project has no schema directory by design: its API is\n // introspected from the live database at boot, and there is nothing here\n // to generate a client from. The scaffold ships `pnpm generate:sdk`\n // anyway, so the documented headless path had a script that could only\n // ever fail — and it failed with a path, which reads as a broken install\n // rather than a question with an answer.\n if (!fs.existsSync(resolvedSchemaDir)) {\n console.log(chalk.gray(\n \" ○ This project derives its API from the database — \"\n + \"there is no backend/schema to generate a client from.\"\n ));\n console.log(chalk.gray(\n ` Nothing to generate from: ${resolvedSchemaDir} does not exist.`\n ));\n console.log(\"\");\n return;\n }\n console.log(` ${chalk.gray(\"Schema:\")} ${resolvedSchemaDir}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Loading the tables...\"));\n try {\n tables = await loadTables(projectRoot ?? cwd, resolvedSchemaDir, args.moduleAliases);\n } catch (err) {\n // A definition the backend would refuse to boot on: every problem,\n // one per line, each naming its table.\n if (isSchemaDefinitionError(err)) {\n console.log(\"\");\n console.log(chalk.red(` ✗ ${err.message}`));\n process.exit(1);\n }\n throw err;\n }\n }\n\n // Sorted by slug, so the same schema generates the same SDK.\n tables = sortedBySlug(tables);\n\n if (tables.length === 0) {\n console.log(chalk.red(\" ✗ No tables found. Nothing to generate.\"));\n process.exit(1);\n }\n\n console.log(chalk.green(` ✓ Found ${tables.length} table(s): ${tables.map(table => table.slug).join(\", \")}`));\n console.log(\"\");\n\n // 2. Generate SDK files\n console.log(chalk.cyan(\" → Generating SDK files...\"));\n let files: GeneratedFile[];\n try {\n files = generateSDK(tables, { baseUrl: resolveExampleBaseUrl(cwd) });\n } catch (err) {\n // A schema that cannot be expressed as valid TypeScript — two slugs\n // that collide on one accessor, a slug with no usable name. The\n // generator refuses rather than emitting a file that does not compile,\n // or one that silently routes a table's reads to another's.\n if (err instanceof CodegenError) {\n console.log(\"\");\n console.log(chalk.red(` ✗ ${err.message}`));\n process.exit(1);\n }\n throw err;\n }\n\n // Stamp the schema this SDK was built from.\n //\n // Without it, an app in a separate repository has no way to know its client\n // is stale: the backend moves on, the frontend keeps compiling against types\n // captured weeks ago, and the mismatch only surfaces as a runtime error. With\n // it, CI can compare against `/api/meta/schema-version` and say so.\n //\n // No generation timestamp. Tables are sorted above precisely so that\n // the same schema produces the same bytes; a timestamp put that back,\n // turning every regeneration into a diff and making the obvious staleness\n // gate — `rebase generate-sdk && git diff --exit-code` — impossible to pass.\n // `SCHEMA_VERSION` already identifies what this was built from, and does it\n // in a way that can be compared against a running project.\n const schemaVersion = remoteSchemaVersion ?? computeSchemaVersion(tables);\n files.push({\n path: \"schema.meta.ts\",\n content: `// Auto-generated by \\`rebase generate-sdk\\`. Do not edit.\n//\n// The schema version this SDK was generated from. Compare it against the\n// project's current version to detect drift:\n//\n// curl -s <api-url>/api/meta/schema-version\n//\n// Pass it to the client as \\`schemaVersion\\` and every request carries it in\n// the \\`x-rebase-schema\\` header, so the server can name the drift instead of\n// answering a renamed field with a bare 400.\nexport const SCHEMA_VERSION = ${JSON.stringify(schemaVersion)};\n`\n });\n\n console.log(chalk.green(` ✓ Generated ${files.length} file(s)`));\n console.log(chalk.gray(` schema ${schemaVersion}`));\n\n // 3. Write to disk\n console.log(chalk.cyan(` → Writing to ${resolvedOutput}...`));\n writeFiles(resolvedOutput, files);\n\n // 4. The server-side registration: on request, and kept current once a\n // project has it, so `rebase dev` regenerating the SDK never leaves the\n // server typed against an older schema than the client.\n const registerDir = projectRoot ? registrationDir(projectRoot) : undefined;\n if (args.register || (registerDir && hasRegistration(registerDir)) || manifestRegisters(projectRoot)) {\n if (!registerDir || !fs.existsSync(path.dirname(registerDir))) {\n console.log(chalk.red(` ✗ No backend/ directory to register the Database in${registerDir ? ` (${path.dirname(registerDir)})` : \"\"}.`));\n console.log(chalk.gray(\" --register writes backend/generated/register.ts; run it inside a project with a backend.\"));\n process.exit(1);\n return;\n }\n const databaseTypes = files.find((file) => file.path === \"database.types.ts\")?.content;\n if (databaseTypes !== undefined) {\n try {\n writeRegistration(registerDir, databaseTypes);\n } catch (error) {\n console.log(chalk.red(` ✗ ${error instanceof Error ? error.message : String(error)}`));\n process.exit(1);\n return;\n }\n console.log(chalk.green(` ✓ Registered the Database for server-side code in ${registerDir}`));\n if (args.register) {\n const remembered = rememberRegistration(projectRoot);\n if (\"written\" in remembered) {\n console.log(chalk.gray(` Remembered in ${path.relative(cwd, remembered.written) || \"rebase.json\"} (registerDatabase).`));\n } else {\n console.log(chalk.yellow(` ${remembered.skipped}`));\n }\n }\n }\n }\n\n console.log(\"\");\n console.log(chalk.green.bold(\" ✓ SDK generated successfully!\"));\n console.log(\"\");\n const typesImport = `./${path.relative(cwd, path.join(resolvedOutput, \"database.types\"))}`;\n const metaImport = `./${path.relative(cwd, path.join(resolvedOutput, \"schema.meta\"))}`;\n const exampleSlug = tables[0]?.slug || \"my_table\";\n\n console.log(chalk.gray(\" Usage:\"));\n console.log(chalk.gray(\" import { createRebaseClient } from '@rebasepro/client';\"));\n console.log(chalk.gray(` import { tablesDictionary, type Database } from '${typesImport}';`));\n console.log(chalk.gray(` import { SCHEMA_VERSION } from '${metaImport}';`));\n console.log(\"\");\n console.log(chalk.gray(\" const rebase = createRebaseClient<Database>({\"));\n console.log(chalk.gray(` baseUrl: '${resolveExampleBaseUrl(cwd)}',`));\n // Sent as `x-rebase-schema` on every request. Costs one line here and is\n // the difference between a server that can say \"this client is three\n // deploys behind\" and one that can only reject a field it does not know.\n console.log(chalk.gray(\" schemaVersion: SCHEMA_VERSION,\"));\n // Without the dictionary a hyphenated slug is not resolvable from the\n // property name alone, and the request 404s at runtime.\n console.log(chalk.gray(\" tables: tablesDictionary,\"));\n console.log(chalk.gray(\" // token: 'your-jwt-token',\"));\n console.log(chalk.gray(\" });\"));\n console.log(\"\");\n // `rebase.data.<accessor>` is the typed surface, so it is what gets printed.\n // `rebase.data.table(slug)` exists too, but it is generic over\n // `Record<string, unknown>` and has no link to `Database` — it was the\n // headline example here for a while, which advertised the one call shape\n // that throws away the types this command just generated.\n const exampleAccessor = toTableAccessor(exampleSlug);\n const exampleAccess = isIdentifierLike(exampleAccessor)\n ? `rebase.data.${exampleAccessor}`\n : `rebase.data[${JSON.stringify(exampleAccessor)}]`;\n console.log(chalk.gray(` const { data } = await ${exampleAccess}.find();`));\n console.log(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,gBAAgB;;AAG7B,IAAM,kBAAkB;AAExB,IAAM,kBAAkB,GAAG,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;AAwB3C,SAAgB,gBAAgB,aAA6B;CACzD,OAAO,KAAK,KAAK,aAAa,aAAa;AAC/C;;AAGA,SAAS,gBAAgB,KAAsB;CAC3C,IAAI;EACA,OAAO,GAAG,aAAa,KAAK,KAAK,KAAK,aAAa,GAAG,OAAO,CAAC,CAAC,WAAW,eAAe;CAC7F,QAAQ;EACJ,OAAO;CACX;AACJ;;AAGA,SAAS,eAAe,UAAkB,SAAuB;CAC7D,IAAI;EACA,IAAI,GAAG,aAAa,UAAU,OAAO,MAAM,SAAS;CACxD,QAAQ,CAER;CACA,GAAG,cAAc,UAAU,SAAS,OAAO;AAC/C;;;;;;AAOA,SAAS,kBAAkB,KAAa,eAA6B;CACjE,MAAM,eAAe,KAAK,KAAK,KAAK,aAAa;CACjD,IAAI,GAAG,WAAW,YAAY,KAAK,CAAC,gBAAgB,GAAG,GACnD,MAAM,IAAI,MACN,GAAG,aAAa,mHAEpB;CAEJ,GAAG,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;CACrC,eAAe,KAAK,KAAK,KAAK,mBAAmB,GAAG,aAAa;CACjE,eAAe,cAAc,eAAe;A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