@rebasepro/server 0.33.2 → 0.34.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.
Files changed (103) hide show
  1. package/dist/{GCSStorageController-kCv5MH2B.js → GCSStorageController-DKv7oDo7.js} +3 -3
  2. package/dist/{GCSStorageController-kCv5MH2B.js.map → GCSStorageController-DKv7oDo7.js.map} +1 -1
  3. package/dist/{S3StorageController-DqK533Sl.js → S3StorageController-CIQ2_mC5.js} +3 -3
  4. package/dist/{S3StorageController-DqK533Sl.js.map → S3StorageController-CIQ2_mC5.js.map} +1 -1
  5. package/dist/{access-CRQBlEZY.js → access-BdsIXo_L.js} +4 -4
  6. package/dist/{access-CRQBlEZY.js.map → access-BdsIXo_L.js.map} +1 -1
  7. package/dist/api/rest/api-generator.d.ts +11 -1
  8. package/dist/auth/auth-hooks.d.ts +1 -1
  9. package/dist/auth/builtin-auth-adapter.d.ts +2 -0
  10. package/dist/auth/capabilities.d.ts +12 -0
  11. package/dist/auth/platform-signin-routes.d.ts +85 -0
  12. package/dist/auth/platform-token.d.ts +33 -0
  13. package/dist/auth/routes.d.ts +8 -0
  14. package/dist/auth/seed-admin.d.ts +2 -0
  15. package/dist/{auth-BanB_pZj.js → auth-CHOmnYwu.js} +358 -12
  16. package/dist/auth-CHOmnYwu.js.map +1 -0
  17. package/dist/{backup-CVNce2jz.js → backup-M37yPYpz.js} +6 -6
  18. package/dist/{backup-CVNce2jz.js.map → backup-M37yPYpz.js.map} +1 -1
  19. package/dist/boot/bundle.d.ts +12 -0
  20. package/dist/boot/env.d.ts +1 -0
  21. package/dist/{branch-routes-aLDaGOD1.js → branch-routes-Cl-Oa3CL.js} +2 -2
  22. package/dist/{branch-routes-aLDaGOD1.js.map → branch-routes-Cl-Oa3CL.js.map} +1 -1
  23. package/dist/{contract-routes-a4ZbN1h3.js → contract-routes-Dkxl-2B_.js} +3 -3
  24. package/dist/{contract-routes-a4ZbN1h3.js.map → contract-routes-Dkxl-2B_.js.map} +1 -1
  25. package/dist/{cron-loader-CWhyA5eR.js → cron-loader-BWahenzQ.js} +2 -2
  26. package/dist/{cron-loader-CWhyA5eR.js.map → cron-loader-BWahenzQ.js.map} +1 -1
  27. package/dist/{cron-routes-CMGAz1my.js → cron-routes-Cq6O3oPR.js} +4 -4
  28. package/dist/{cron-routes-CMGAz1my.js.map → cron-routes-Cq6O3oPR.js.map} +1 -1
  29. package/dist/{cron-scheduler-DQBdkkfb.js → cron-scheduler-B25NuV7o.js} +2 -2
  30. package/dist/{cron-scheduler-DQBdkkfb.js.map → cron-scheduler-B25NuV7o.js.map} +1 -1
  31. package/dist/{cron-store-CjUydRyp.js → cron-store-B1IStnKM.js} +2 -2
  32. package/dist/{cron-store-CjUydRyp.js.map → cron-store-B1IStnKM.js.map} +1 -1
  33. package/dist/dist-D_R0Khut.js +19354 -0
  34. package/dist/dist-D_R0Khut.js.map +1 -0
  35. package/dist/email/link-base.d.ts +21 -0
  36. package/dist/email/types.d.ts +4 -0
  37. package/dist/{filter-dialect-nsQ2ozPY.js → filter-dialect-DgWkoXt7.js} +2 -2
  38. package/dist/{filter-dialect-nsQ2ozPY.js.map → filter-dialect-DgWkoXt7.js.map} +1 -1
  39. package/dist/{function-loader-Cihj_r86.js → function-loader-C23HVFx8.js} +2 -2
  40. package/dist/{function-loader-Cihj_r86.js.map → function-loader-C23HVFx8.js.map} +1 -1
  41. package/dist/{function-routes-CWaldgEj.js → function-routes-DBKL2azw.js} +2 -2
  42. package/dist/{function-routes-CWaldgEj.js.map → function-routes-DBKL2azw.js.map} +1 -1
  43. package/dist/{history-recorder-B8TJMEfO.js → history-recorder-C5gixsU3.js} +16 -3
  44. package/dist/history-recorder-C5gixsU3.js.map +1 -0
  45. package/dist/history-store-c_cm9R3w.js +459 -0
  46. package/dist/history-store-c_cm9R3w.js.map +1 -0
  47. package/dist/index.d.ts +1 -1
  48. package/dist/index.es.js +273 -236
  49. package/dist/index.es.js.map +1 -1
  50. package/dist/{jobs-IJX3fE3X.js → jobs-uqvEGTfs.js} +2 -2
  51. package/dist/{jobs-IJX3fE3X.js.map → jobs-uqvEGTfs.js.map} +1 -1
  52. package/dist/{jwt-BuEprb39.js → jwt-B_5zx-7y.js} +3 -3
  53. package/dist/{jwt-BuEprb39.js.map → jwt-B_5zx-7y.js.map} +1 -1
  54. package/dist/{keys-C8gpPIOG.js → keys-C0g4vwP5.js} +2 -2
  55. package/dist/{keys-C8gpPIOG.js.map → keys-C0g4vwP5.js.map} +1 -1
  56. package/dist/{load-schema-BvRxAuaD.js → load-schema-aNynBztw.js} +2 -2
  57. package/dist/{load-schema-BvRxAuaD.js.map → load-schema-aNynBztw.js.map} +1 -1
  58. package/dist/{logs-routes-BAq2ZxuY.js → logs-routes-D2NGM5Pa.js} +2 -2
  59. package/dist/{logs-routes-BAq2ZxuY.js.map → logs-routes-D2NGM5Pa.js.map} +1 -1
  60. package/dist/metrics/history-recorder.d.ts +10 -1
  61. package/dist/metrics/history-store.d.ts +122 -7
  62. package/dist/metrics/index.d.ts +24 -2
  63. package/dist/{offline-ET6xI1ZO-CIdB1ilf.js → offline-ET6xI1ZO-Du75S8J1.js} +4 -4
  64. package/dist/{offline-ET6xI1ZO-CIdB1ilf.js.map → offline-ET6xI1ZO-Du75S8J1.js.map} +1 -1
  65. package/dist/{offline-store-DtmBwmKE-CzyvC_Zj.js → offline-store-DtmBwmKE-CEakGPWn.js} +3 -3
  66. package/dist/{offline-store-DtmBwmKE-CzyvC_Zj.js.map → offline-store-DtmBwmKE-CEakGPWn.js.map} +1 -1
  67. package/dist/{openapi-generator-CCLtAJ2s.js → openapi-generator-B7EbCjhN.js} +2 -2
  68. package/dist/{openapi-generator-CCLtAJ2s.js.map → openapi-generator-B7EbCjhN.js.map} +1 -1
  69. package/dist/{project-root-CuCOXvbk.js → project-root-BTQAiPki.js} +2 -2
  70. package/dist/{project-root-CuCOXvbk.js.map → project-root-BTQAiPki.js.map} +1 -1
  71. package/dist/{proxy-DUUXXoQo.js → proxy-0fGXJapt.js} +2 -2
  72. package/dist/{proxy-DUUXXoQo.js.map → proxy-0fGXJapt.js.map} +1 -1
  73. package/dist/{query-parser-C9l1eFov.js → query-parser-DwERE0rm.js} +3 -3
  74. package/dist/{query-parser-C9l1eFov.js.map → query-parser-DwERE0rm.js.map} +1 -1
  75. package/dist/{request-timeout-DOu8ItLQ.js → request-timeout-DdbFS6ef.js} +3 -3
  76. package/dist/{request-timeout-DOu8ItLQ.js.map → request-timeout-DdbFS6ef.js.map} +1 -1
  77. package/dist/{rls-simulator-routes-DIAjffhq.js → rls-simulator-routes-Cjv8yY1V.js} +3 -3
  78. package/dist/{rls-simulator-routes-DIAjffhq.js.map → rls-simulator-routes-Cjv8yY1V.js.map} +1 -1
  79. package/dist/{schema-editor-routes-qWGWBPi0.js → schema-editor-routes-CwdoGYKu.js} +4 -4
  80. package/dist/{schema-editor-routes-qWGWBPi0.js.map → schema-editor-routes-CwdoGYKu.js.map} +1 -1
  81. package/dist/{schema-tables-BneB2KZ7.js → schema-tables-DUThMxen.js} +3 -3
  82. package/dist/{schema-tables-BneB2KZ7.js.map → schema-tables-DUThMxen.js.map} +1 -1
  83. package/dist/{schema-tables-routes-BBZJK8_S.js → schema-tables-routes-Ch52xLqF.js} +4 -4
  84. package/dist/{schema-tables-routes-BBZJK8_S.js.map → schema-tables-routes-Ch52xLqF.js.map} +1 -1
  85. package/dist/{securityRuleToConditions-Cj5ZR7TS.js → securityRuleToConditions-DXPY_Z-x.js} +2 -2
  86. package/dist/{securityRuleToConditions-Cj5ZR7TS.js.map → securityRuleToConditions-DXPY_Z-x.js.map} +1 -1
  87. package/dist/{selection-BB8ejqa2.js → selection-BiTJ-Tiy.js} +2 -2
  88. package/dist/{selection-BB8ejqa2.js.map → selection-BiTJ-Tiy.js.map} +1 -1
  89. package/dist/{sql-export-routes-CPXI3qZ7.js → sql-export-routes-BYt7G2v-.js} +2 -2
  90. package/dist/{sql-export-routes-CPXI3qZ7.js.map → sql-export-routes-BYt7G2v-.js.map} +1 -1
  91. package/dist/{src-BdPKCs9u.js → src--EBfCtYm.js} +2 -2
  92. package/dist/src--EBfCtYm.js.map +1 -0
  93. package/dist/storage/routes.d.ts +6 -0
  94. package/dist/{table-source-editor-D3m_VMwN.js → table-source-editor-P5zp7lOn.js} +3 -3
  95. package/dist/{table-source-editor-D3m_VMwN.js.map → table-source-editor-P5zp7lOn.js.map} +1 -1
  96. package/package.json +5 -5
  97. package/dist/auth-BanB_pZj.js.map +0 -1
  98. package/dist/dist-C1vNURUy.js +0 -19354
  99. package/dist/dist-C1vNURUy.js.map +0 -1
  100. package/dist/history-recorder-B8TJMEfO.js.map +0 -1
  101. package/dist/history-store-DzrJeEKv.js +0 -233
  102. package/dist/history-store-DzrJeEKv.js.map +0 -1
  103. package/dist/src-BdPKCs9u.js.map +0 -1
@@ -2,9 +2,9 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import { wt as summarizeRoles, yt as scopeGrants } from "./src-BdPKCs9u.js";
5
+ import { Tt as summarizeRoles, bt as scopeGrants } from "./src--EBfCtYm.js";
6
6
  import { i as errorHandler, t as ApiError } from "./errors-NVbAQU25.js";
7
- import { B as decideSimulation, Q as scopeDataDriver, V as maskedFieldsFor, r as accessOf, z as callerOf } from "./access-CRQBlEZY.js";
7
+ import { B as decideSimulation, Q as scopeDataDriver, V as maskedFieldsFor, r as accessOf, z as callerOf } from "./access-BdsIXo_L.js";
8
8
  import { Hono } from "hono";
9
9
  //#region src/auth/rls-simulator-routes.ts
10
10
  /**
@@ -178,4 +178,4 @@ function createRlsSimulatorRoutes(config) {
178
178
  //#endregion
179
179
  export { createRlsSimulatorRoutes };
180
180
 
181
- //# sourceMappingURL=rls-simulator-routes-DIAjffhq.js.map
181
+ //# sourceMappingURL=rls-simulator-routes-Cjv8yY1V.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"rls-simulator-routes-DIAjffhq.js","names":[],"sources":["../src/auth/rls-simulator-routes.ts"],"sourcesContent":["/**\n * The RLS simulator's admin surface, under `/api/admin/rls-simulator`.\n *\n * The data API answers one table at a time for a simulated identity\n * (`auth/simulation.ts`). This answers the questions the admin panel's\n * \"Simulate access\" bar asks about all of them at once:\n *\n * - `GET /options` — what can be simulated: the roles the project names (the\n * access model's, the ones its row and field rules mention, and `anon`) and\n * the API keys that are live.\n * - `POST /preview` — for `{ role?, userId?, apiKeyId? }`, each table's\n * rows as that identity sees them against the caller's own view, whether a\n * key's scopes shut it out, and which fields its roles cannot read.\n *\n * The same decision as the data API: only an administrator's own session, a\n * 403 for anyone else.\n *\n * @module\n */\n\nimport { Hono, type Context } from \"hono\";\nimport {\n scopeGrants,\n summarizeRoles,\n type AccessSimulation,\n type DataDriver,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport type { HonoEnv } from \"../api/types\";\nimport { ApiError, errorHandler } from \"../api/errors\";\nimport { scopeDataDriver } from \"./rls-scope\";\nimport { accessOf } from \"./access\";\nimport type { ApiKeyStore } from \"./api-keys/api-key-store\";\nimport type { ImpersonationCredential, ImpersonationUserResolver } from \"./impersonation\";\nimport { callerOf, decideSimulation, maskedFieldsFor } from \"./simulation\";\n\nexport interface RlsSimulatorRouteConfig {\n /** The tables this backend serves, as they are now. */\n tables(): readonly TableDescriptor[];\n /** The unscoped driver a table's rows live in. */\n driverFor(table: TableDescriptor): DataDriver;\n resolveUser?: ImpersonationUserResolver;\n apiKeyStore?: ApiKeyStore;\n}\n\n/** One table, as the simulated identity reaches it (the response keeps its wire field names). */\nexport interface SimulatedCollectionView {\n slug: string;\n name: string;\n /**\n * Why the identity sees nothing here: its key's scopes, row policies\n * hiding every row, or a read that fails for it (`error` says why).\n */\n hiddenBy?: \"scope\" | \"rls\" | \"error\";\n /** Rows the simulated identity reads. Absent when not counted. */\n visibleRows?: number;\n /** Rows the administrator asking reads. */\n totalRows?: number;\n /** Fields the identity's roles cannot read. */\n maskedColumns: string[];\n /** Why the rows could not be counted. */\n error?: string;\n}\n\n/** How the caller authenticated, read off what the admin gate left on the context. */\nfunction credentialOf(c: Context<HonoEnv>): ImpersonationCredential {\n const caller = callerOf(c);\n if (!caller) return \"none\";\n if (c.get(\"apiKey\") || c.get(\"scopes\") !== undefined) return \"api-key\";\n if (caller.uid === \"service\") return \"service-key\";\n return \"session\";\n}\n\nfunction readSimulation(body: unknown): AccessSimulation {\n if (typeof body !== \"object\" || body === null) {\n throw ApiError.badRequest(\"Send { role?, userId?, apiKeyId? } naming what to simulate.\", \"SIMULATION_INVALID\");\n }\n const field = (name: string): string | undefined => {\n if (!(name in body)) return undefined;\n const value: unknown = Reflect.get(body, name);\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"string\") throw ApiError.badRequest(`${name} must be a string.`, \"SIMULATION_INVALID\");\n return value;\n };\n const role = field(\"role\");\n const userId = field(\"userId\");\n const apiKeyId = field(\"apiKeyId\");\n if (role === undefined && userId === undefined && apiKeyId === undefined) {\n throw ApiError.badRequest(\"Name a role, a user id or an API key id to simulate.\", \"SIMULATION_INVALID\");\n }\n return {\n ...(role !== undefined ? { role } : {}),\n ...(userId !== undefined ? { userId } : {}),\n ...(apiKeyId !== undefined ? { apiKeyId } : {})\n };\n}\n\n/** Every role the project's rules name — row rules and column access — beyond the access model's own. */\nfunction rolesNamedByRules(tables: readonly TableDescriptor[]): string[] {\n const named = new Set<string>();\n for (const table of tables) {\n for (const rule of table.rls.rules) {\n for (const role of rule.roles ?? []) named.add(role);\n }\n for (const target of [...table.columns, ...table.relations]) {\n for (const role of [...(target.access?.read ?? []), ...(target.access?.write ?? [])]) named.add(role);\n }\n }\n return [...named];\n}\n\nexport function createRlsSimulatorRoutes(config: RlsSimulatorRouteConfig): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n router.onError(errorHandler);\n\n /** The caller, refused unless an administrator's own session. */\n const decide = async (c: Context<HonoEnv>, simulation: AccessSimulation) => {\n const decision = await decideSimulation({\n simulation,\n credential: credentialOf(c),\n caller: callerOf(c),\n resolveUser: config.resolveUser,\n apiKeyStore: config.apiKeyStore,\n access: accessOf(c),\n audit: { door: \"rls-simulator\", method: c.req.method, path: c.req.path, requestId: c.get(\"requestId\") }\n });\n if (\"refused\" in decision) throw decision.refused;\n return decision;\n };\n\n router.get(\"/options\", async (c) => {\n // The same gate as a preview, with a role that is always there.\n await decide(c, { role: \"anon\" });\n const declared = summarizeRoles(accessOf(c).model).map(role => ({ id: role.id, name: role.name }));\n const seen = new Set(declared.map(role => role.id));\n const roles = [\n { id: \"anon\", name: \"anon\" },\n ...declared,\n ...rolesNamedByRules(config.tables())\n .filter(role => !seen.has(role) && role !== \"anon\")\n .map(role => ({ id: role, name: role }))\n ];\n const now = Date.now();\n const apiKeys = config.apiKeyStore\n ? (await config.apiKeyStore.listApiKeys({ kind: \"service\" }))\n .filter(key => !key.revoked_at && !(key.expires_at && new Date(key.expires_at).getTime() < now))\n .map(key => ({ id: key.id, name: key.name, keyPrefix: key.key_prefix, roles: key.roles, scopes: key.scopes }))\n : [];\n return c.json({ roles, apiKeys });\n });\n\n router.post(\"/preview\", async (c) => {\n const simulation = readSimulation(await c.req.json().catch(() => undefined));\n const { granted: identity, simulator } = await decide(c, simulation);\n const callerIdentity = { uid: simulator, roles: callerOf(c)?.roles ?? [] };\n\n const countRows = async (driver: DataDriver, table: TableDescriptor): Promise<number> => {\n if (driver.count) return driver.count({ path: table.slug });\n return (await driver.fetchCollection({ path: table.slug })).length;\n };\n const collections: SimulatedCollectionView[] = [];\n for (const table of config.tables()) {\n const view: SimulatedCollectionView = {\n slug: table.slug,\n name: table.name,\n maskedColumns: maskedFieldsFor(table, identity.roles)\n };\n if (identity.scopes && !scopeGrants(identity.scopes, \"data:read\", table.slug)) {\n view.hiddenBy = \"scope\";\n collections.push(view);\n continue;\n }\n try {\n const driver = config.driverFor(table);\n const [visible, total] = await Promise.all([\n scopeDataDriver(driver, {\n uid: identity.uid,\n roles: identity.roles,\n isAnonymous: identity.isAnonymous,\n ...(identity.claims ? { claims: identity.claims } : {})\n }).then(scoped => countRows(scoped, table)),\n scopeDataDriver(driver, callerIdentity).then(scoped => countRows(scoped, table))\n ]);\n view.visibleRows = visible;\n view.totalRows = total;\n if (total > 0 && visible === 0) view.hiddenBy = \"rls\";\n } catch (error: unknown) {\n // A read that fails for this identity — a policy that casts\n // its uid, a grant it lacks — shows it nothing either.\n view.hiddenBy = \"error\";\n view.error = error instanceof Error ? error.message : String(error);\n }\n collections.push(view);\n }\n\n return c.json({\n simulation: {\n role: identity.role,\n sub: identity.uid,\n roles: identity.roles,\n ...(identity.apiKey\n ? { apiKey: { id: identity.apiKey.id, name: identity.apiKey.name, keyPrefix: identity.apiKey.key_prefix } }\n : {})\n },\n collections,\n summary: {\n hiddenCollections: collections.filter(view => view.hiddenBy).length,\n maskedColumns: collections.reduce((sum, view) => sum + view.maskedColumns.length, 0)\n }\n });\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,SAAS,aAAa,GAA8C;CAChE,MAAM,SAAS,SAAS,CAAC;CACzB,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,EAAE,IAAI,QAAQ,KAAK,EAAE,IAAI,QAAQ,MAAM,KAAA,GAAW,OAAO;CAC7D,IAAI,OAAO,QAAQ,WAAW,OAAO;CACrC,OAAO;AACX;AAEA,SAAS,eAAe,MAAiC;CACrD,IAAI,OAAO,SAAS,YAAY,SAAS,MACrC,MAAM,SAAS,WAAW,+DAA+D,oBAAoB;CAEjH,MAAM,SAAS,SAAqC;EAChD,IAAI,EAAE,QAAQ,OAAO,OAAO,KAAA;EAC5B,MAAM,QAAiB,QAAQ,IAAI,MAAM,IAAI;EAC7C,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO,KAAA;EAClD,IAAI,OAAO,UAAU,UAAU,MAAM,SAAS,WAAW,GAAG,KAAK,qBAAqB,oBAAoB;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P,EAAE,QAAQ;KAAE,IAAI,SAAS,OAAO;KAAI,MAAM,SAAS,OAAO;KAAM,WAAW,SAAS,OAAO;IAAW,EAAE,IACxG,CAAC;GACX;GACA;GACA,SAAS;IACL,mBAAmB,YAAY,QAAO,SAAQ,KAAK,QAAQ,CAAC,CAAC;IAC7D,eAAe,YAAY,QAAQ,KAAK,SAAS,MAAM,KAAK,cAAc,QAAQ,CAAC;GACvF;EACJ,CAAC;CACL,CAAC;CAED,OAAO;AACX"}
1
+ {"version":3,"file":"rls-simulator-routes-Cjv8yY1V.js","names":[],"sources":["../src/auth/rls-simulator-routes.ts"],"sourcesContent":["/**\n * The RLS simulator's admin surface, under `/api/admin/rls-simulator`.\n *\n * The data API answers one table at a time for a simulated identity\n * (`auth/simulation.ts`). This answers the questions the admin panel's\n * \"Simulate access\" bar asks about all of them at once:\n *\n * - `GET /options` — what can be simulated: the roles the project names (the\n * access model's, the ones its row and field rules mention, and `anon`) and\n * the API keys that are live.\n * - `POST /preview` — for `{ role?, userId?, apiKeyId? }`, each table's\n * rows as that identity sees them against the caller's own view, whether a\n * key's scopes shut it out, and which fields its roles cannot read.\n *\n * The same decision as the data API: only an administrator's own session, a\n * 403 for anyone else.\n *\n * @module\n */\n\nimport { Hono, type Context } from \"hono\";\nimport {\n scopeGrants,\n summarizeRoles,\n type AccessSimulation,\n type DataDriver,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport type { HonoEnv } from \"../api/types\";\nimport { ApiError, errorHandler } from \"../api/errors\";\nimport { scopeDataDriver } from \"./rls-scope\";\nimport { accessOf } from \"./access\";\nimport type { ApiKeyStore } from \"./api-keys/api-key-store\";\nimport type { ImpersonationCredential, ImpersonationUserResolver } from \"./impersonation\";\nimport { callerOf, decideSimulation, maskedFieldsFor } from \"./simulation\";\n\nexport interface RlsSimulatorRouteConfig {\n /** The tables this backend serves, as they are now. */\n tables(): readonly TableDescriptor[];\n /** The unscoped driver a table's rows live in. */\n driverFor(table: TableDescriptor): DataDriver;\n resolveUser?: ImpersonationUserResolver;\n apiKeyStore?: ApiKeyStore;\n}\n\n/** One table, as the simulated identity reaches it (the response keeps its wire field names). */\nexport interface SimulatedCollectionView {\n slug: string;\n name: string;\n /**\n * Why the identity sees nothing here: its key's scopes, row policies\n * hiding every row, or a read that fails for it (`error` says why).\n */\n hiddenBy?: \"scope\" | \"rls\" | \"error\";\n /** Rows the simulated identity reads. Absent when not counted. */\n visibleRows?: number;\n /** Rows the administrator asking reads. */\n totalRows?: number;\n /** Fields the identity's roles cannot read. */\n maskedColumns: string[];\n /** Why the rows could not be counted. */\n error?: string;\n}\n\n/** How the caller authenticated, read off what the admin gate left on the context. */\nfunction credentialOf(c: Context<HonoEnv>): ImpersonationCredential {\n const caller = callerOf(c);\n if (!caller) return \"none\";\n if (c.get(\"apiKey\") || c.get(\"scopes\") !== undefined) return \"api-key\";\n if (caller.uid === \"service\") return \"service-key\";\n return \"session\";\n}\n\nfunction readSimulation(body: unknown): AccessSimulation {\n if (typeof body !== \"object\" || body === null) {\n throw ApiError.badRequest(\"Send { role?, userId?, apiKeyId? } naming what to simulate.\", \"SIMULATION_INVALID\");\n }\n const field = (name: string): string | undefined => {\n if (!(name in body)) return undefined;\n const value: unknown = Reflect.get(body, name);\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"string\") throw ApiError.badRequest(`${name} must be a string.`, \"SIMULATION_INVALID\");\n return value;\n };\n const role = field(\"role\");\n const userId = field(\"userId\");\n const apiKeyId = field(\"apiKeyId\");\n if (role === undefined && userId === undefined && apiKeyId === undefined) {\n throw ApiError.badRequest(\"Name a role, a user id or an API key id to simulate.\", \"SIMULATION_INVALID\");\n }\n return {\n ...(role !== undefined ? { role } : {}),\n ...(userId !== undefined ? { userId } : {}),\n ...(apiKeyId !== undefined ? { apiKeyId } : {})\n };\n}\n\n/** Every role the project's rules name — row rules and column access — beyond the access model's own. */\nfunction rolesNamedByRules(tables: readonly TableDescriptor[]): string[] {\n const named = new Set<string>();\n for (const table of tables) {\n for (const rule of table.rls.rules) {\n for (const role of rule.roles ?? []) named.add(role);\n }\n for (const target of [...table.columns, ...table.relations]) {\n for (const role of [...(target.access?.read ?? []), ...(target.access?.write ?? [])]) named.add(role);\n }\n }\n return [...named];\n}\n\nexport function createRlsSimulatorRoutes(config: RlsSimulatorRouteConfig): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n router.onError(errorHandler);\n\n /** The caller, refused unless an administrator's own session. */\n const decide = async (c: Context<HonoEnv>, simulation: AccessSimulation) => {\n const decision = await decideSimulation({\n simulation,\n credential: credentialOf(c),\n caller: callerOf(c),\n resolveUser: config.resolveUser,\n apiKeyStore: config.apiKeyStore,\n access: accessOf(c),\n audit: { door: \"rls-simulator\", method: c.req.method, path: c.req.path, requestId: c.get(\"requestId\") }\n });\n if (\"refused\" in decision) throw decision.refused;\n return decision;\n };\n\n router.get(\"/options\", async (c) => {\n // The same gate as a preview, with a role that is always there.\n await decide(c, { role: \"anon\" });\n const declared = summarizeRoles(accessOf(c).model).map(role => ({ id: role.id, name: role.name }));\n const seen = new Set(declared.map(role => role.id));\n const roles = [\n { id: \"anon\", name: \"anon\" },\n ...declared,\n ...rolesNamedByRules(config.tables())\n .filter(role => !seen.has(role) && role !== \"anon\")\n .map(role => ({ id: role, name: role }))\n ];\n const now = Date.now();\n const apiKeys = config.apiKeyStore\n ? (await config.apiKeyStore.listApiKeys({ kind: \"service\" }))\n .filter(key => !key.revoked_at && !(key.expires_at && new Date(key.expires_at).getTime() < now))\n .map(key => ({ id: key.id, name: key.name, keyPrefix: key.key_prefix, roles: key.roles, scopes: key.scopes }))\n : [];\n return c.json({ roles, apiKeys });\n });\n\n router.post(\"/preview\", async (c) => {\n const simulation = readSimulation(await c.req.json().catch(() => undefined));\n const { granted: identity, simulator } = await decide(c, simulation);\n const callerIdentity = { uid: simulator, roles: callerOf(c)?.roles ?? [] };\n\n const countRows = async (driver: DataDriver, table: TableDescriptor): Promise<number> => {\n if (driver.count) return driver.count({ path: table.slug });\n return (await driver.fetchCollection({ path: table.slug })).length;\n };\n const collections: SimulatedCollectionView[] = [];\n for (const table of config.tables()) {\n const view: SimulatedCollectionView = {\n slug: table.slug,\n name: table.name,\n maskedColumns: maskedFieldsFor(table, identity.roles)\n };\n if (identity.scopes && !scopeGrants(identity.scopes, \"data:read\", table.slug)) {\n view.hiddenBy = \"scope\";\n collections.push(view);\n continue;\n }\n try {\n const driver = config.driverFor(table);\n const [visible, total] = await Promise.all([\n scopeDataDriver(driver, {\n uid: identity.uid,\n roles: identity.roles,\n isAnonymous: identity.isAnonymous,\n ...(identity.claims ? { claims: identity.claims } : {})\n }).then(scoped => countRows(scoped, table)),\n scopeDataDriver(driver, callerIdentity).then(scoped => countRows(scoped, table))\n ]);\n view.visibleRows = visible;\n view.totalRows = total;\n if (total > 0 && visible === 0) view.hiddenBy = \"rls\";\n } catch (error: unknown) {\n // A read that fails for this identity — a policy that casts\n // its uid, a grant it lacks — shows it nothing either.\n view.hiddenBy = \"error\";\n view.error = error instanceof Error ? error.message : String(error);\n }\n collections.push(view);\n }\n\n return c.json({\n simulation: {\n role: identity.role,\n sub: identity.uid,\n roles: identity.roles,\n ...(identity.apiKey\n ? { apiKey: { id: identity.apiKey.id, name: identity.apiKey.name, keyPrefix: identity.apiKey.key_prefix } }\n : {})\n },\n collections,\n summary: {\n hiddenCollections: collections.filter(view => view.hiddenBy).length,\n maskedColumns: collections.reduce((sum, view) => sum + view.maskedColumns.length, 0)\n }\n });\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,SAAS,aAAa,GAA8C;CAChE,MAAM,SAAS,SAAS,CAAC;CACzB,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,EAAE,IAAI,QAAQ,KAAK,EAAE,IAAI,QAAQ,MAAM,KAAA,GAAW,OAAO;CAC7D,IAAI,OAAO,QAAQ,WAAW,OAAO;CACrC,OAAO;AACX;AAEA,SAAS,eAAe,MAAiC;CACrD,IAA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AK,cAAc;IACnB,KAAK,YAAY;IACjB,IAAI,QAAQ,KAAK,YAAY,GAAG,KAAK,WAAW;GACpD,SAAS,OAAgB;IAGrB,KAAK,WAAW;IAChB,KAAK,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACtE;GACA,YAAY,KAAK,IAAI;EACzB;EAEA,OAAO,EAAE,KAAK;GACV,YAAY;IACR,MAAM,SAAS;IACf,KAAK,SAAS;IACd,OAAO,SAAS;IAChB,GAAI,SAAS,SACP,EAAE,QAAQ;KAAE,IAAI,SAAS,OAAO;KAAI,MAAM,SAAS,OAAO;KAAM,WAAW,SAAS,OAAO;IAAW,EAAE,IACxG,CAAC;GACX;GACA;GACA,SAAS;IACL,mBAAmB,YAAY,QAAO,SAAQ,KAAK,QAAQ,CAAC,CAAC;IAC7D,eAAe,YAAY,QAAQ,KAAK,SAAS,MAAM,KAAK,cAAc,QAAQ,CAAC;GACvF;EACJ,CAAC;CACL,CAAC;CAED,OAAO;AACX"}
@@ -2,10 +2,10 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import { i as parseTablePatches, n as TablePatchError } from "./src-BdPKCs9u.js";
6
- import { _ as replaceNode, a as literalString, c as opaqueMembers, d as unwrapExpression, f as applyEdits, g as removeListItem, h as listShape, i as isData, l as printKey, m as itemText, n as TableSourceEditError, o as member, p as insertListItem, r as TableSourceEditor, s as memberName, t as IDENTIFIER, v as printSchemaValue } from "./table-source-editor-D3m_VMwN.js";
5
+ import { i as parseTablePatches, n as TablePatchError } from "./src--EBfCtYm.js";
6
+ import { _ as replaceNode, a as literalString, c as opaqueMembers, d as unwrapExpression, f as applyEdits, g as removeListItem, h as listShape, i as isData, l as printKey, m as itemText, n as TableSourceEditError, o as member, p as insertListItem, r as TableSourceEditor, s as memberName, t as IDENTIFIER, v as printSchemaValue } from "./table-source-editor-P5zp7lOn.js";
7
7
  import { i as errorHandler, t as ApiError } from "./errors-NVbAQU25.js";
8
- import { r as findProjectRoot } from "./project-root-CuCOXvbk.js";
8
+ import { r as findProjectRoot } from "./project-root-BTQAiPki.js";
9
9
  import crypto from "node:crypto";
10
10
  import path from "node:path";
11
11
  import fs from "node:fs";
@@ -872,4 +872,4 @@ function createSchemaEditorRoutes(editor, options = {}) {
872
872
  //#endregion
873
873
  export { createSchemaEditorRoutes, createTableSourceEditor };
874
874
 
875
- //# sourceMappingURL=schema-editor-routes-qWGWBPi0.js.map
875
+ //# sourceMappingURL=schema-editor-routes-CwdoGYKu.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema-editor-routes-qWGWBPi0.js","names":[],"sources":["../src/schema-edit/frontend-source-editor.ts","../src/api/frontend-source-routes.ts","../src/api/schema-editor-routes.ts"],"sourcesContent":["import crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Node, Project, ts, type CallExpression, type ObjectLiteralExpression, type SourceFile } from \"ts-morph\";\nimport { printSchemaValue } from \"@rebasepro/common\";\n\nimport { IDENTIFIER, isData, member, memberName, opaqueMembers, printKey, unwrapExpression, literalString, type SchemaEditRefusalCode } from \"../api/table-source-editor\";\nimport { applyEdits, insertListItem, itemText, listShape, removeListItem, replaceNode, type TextEdit } from \"./source-text\";\n\n/**\n * Edits to the object-literal argument of one call in the project's frontend\n * source, from the admin panel, in development.\n *\n * The backend knows nothing about what the call means. A request names a\n * callee (`defineFirestoreCollection`), the key and string value that pick\n * one call out (`slug: \"fs_events\"`), and a list of operations on paths into\n * the call's object argument: set a value, remove a key, rename a key, move a\n * key. What those calls are — a Firestore collection, its fields — is the\n * admin panel's business, which translates its own edits into these.\n *\n * The safety model is the table source editor's ({@link TableSourceEditor}):\n *\n * - **Byte-preserving.** It parses with ts-morph to find positions and writes\n * by splicing printed text at them (`source-text.ts`), so comments, imports,\n * functions, JSX and every key it was not asked to touch stay byte for byte.\n * - **Never executes the wire.** Every value is JSON, printed as a literal\n * (`printSchemaValue`); every key is printed as an identifier only when it\n * is one, quoted otherwise. Nothing a request carries is evaluated, imported\n * or spliced as code.\n * - **Edited in code is left alone.** A value that is not plain data — a\n * function, a component, a variable, a call — is never overwritten; an object\n * that spreads another, or has a computed key, is never written into. The\n * edit is refused with the reason, and {@link FrontendSourceEditor.describe}\n * reports those places so the panel shows them read-only.\n * - **Preview, check, write, roll back.** An edit is applied to a copy of the\n * text, the result parsed and read back (each value set must read back as\n * exactly that value), and only then written — refused if the file changed\n * on disk since the edit read it (the panel's `version`, or another save in\n * between). The optional `check` runs over the written files (a project's\n * own compile); when it fails, every file is restored as it was.\n *\n * @group Schema\n */\nexport class FrontendSourceEditor {\n private settled: Promise<unknown> = Promise.resolve();\n /** The directory searched for calls, absolute: the project's `frontend/src`. */\n readonly sourceDir: string;\n /** The directory paths are reported relative to: the project root. */\n readonly root: string;\n private readonly check?: FrontendSourceCheck;\n\n /**\n * @param sourceDir the directory searched for calls: the project's `frontend/src`\n * @param options.root what paths are reported relative to (default: two levels above `sourceDir`)\n * @param options.check a compile over the written files; problems roll the edit back\n */\n constructor(sourceDir: string, options: { root?: string; check?: FrontendSourceCheck } = {}) {\n this.sourceDir = path.resolve(sourceDir);\n this.root = path.resolve(options.root ?? path.dirname(path.dirname(this.sourceDir)));\n this.check = options.check;\n }\n\n /** Run `work` once every edit queued before it has finished. */\n run<T>(work: () => Promise<T>): Promise<T> {\n const result = this.settled.then(work);\n this.settled = result.then(() => undefined, () => undefined);\n return result;\n }\n\n /**\n * Every call to `callee` in the source directory, picked out by its `key`\n * member, as the editor reads it: its file, its `version`, and where it\n * is edited in code. `lists` names paths into the argument whose members\n * are each reported (`[[\"fields\"]]`: each field, and whether it is an\n * object literal the editor can write).\n */\n describe(callee: string, key: string, lists: readonly (readonly string[])[] = []): FrontendCallSummary[] {\n assertIdentifier(callee, \"callee\");\n const out: FrontendCallSummary[] = [];\n for (const file of sourceFiles(this.sourceDir)) {\n const text = fs.readFileSync(file, \"utf8\");\n if (!text.includes(callee)) continue;\n const source = parse(file, text);\n for (const call of callsTo(source, callee)) {\n const located = locateArgument(call, key);\n if (!located) continue;\n const summary: FrontendCallSummary = {\n value: located.value,\n file: this.relative(file),\n version: versionOf(text),\n members: {}\n };\n if (located.editedInCode) summary.editedInCode = located.editedInCode;\n else if (located.object) {\n for (const list of lists) {\n const reached = reach(located.object, list);\n if (reached.kind === \"code\") {\n summary.members[list.join(\".\")] = reached.reason;\n continue;\n }\n if (reached.kind !== \"object\") continue;\n const opaque = opaqueMembers(reached.object, `\\`${list.join(\".\")}\\``);\n for (const each of reached.object.getProperties()) {\n const name = memberName(each);\n if (name === undefined) continue;\n const where = [...list, name].join(\".\");\n if (opaque) {\n summary.members[where] = opaque;\n continue;\n }\n const value = Node.isPropertyAssignment(each) ? unwrapExpression(each.getInitializer()) : undefined;\n if (!value) summary.members[where] = `\\`${where}\\` is ${Node.isShorthandPropertyAssignment(each) ? \"a variable\" : \"a method\"}.`;\n else if (!Node.isObjectLiteralExpression(value)) summary.members[where] = `\\`${where}\\` is \\`${clip(value.getText())}\\`, not an object written in the call.`;\n else {\n const inner = opaqueMembers(value, `\\`${where}\\``);\n if (inner) summary.members[where] = inner;\n }\n }\n }\n }\n out.push(summary);\n }\n }\n return out;\n }\n\n /**\n * Apply `request` to a copy of its file and read the result back. Writes\n * nothing: the edit is refused (a {@link FrontendSourceEditError}) or\n * returned, with the file it changes.\n */\n async preview(request: FrontendSourceEditRequest): Promise<FrontendSourceEdit> {\n const { target } = request;\n const found = this.locate(target);\n if (request.version !== undefined && request.version !== versionOf(found.text)) {\n throw new FrontendSourceEditError(\"SCHEMA_EDIT_STALE_FILE\",\n `${this.relative(found.file)} changed since the edit was prepared (it was saved by something else meanwhile). ` +\n \"Nothing was written: reload, and make the edit again against the file as it is now.\",\n [{ table: target.value, message: \"The file changed on disk.\" }]);\n }\n let text = found.text;\n for (const [index, operation] of request.operations.entries()) {\n try {\n text = applyOperation(found.file, text, target, operation);\n } catch (error) {\n throw asRefusal(error, index, operation, target);\n }\n }\n if (text === found.text) {\n throw new FrontendSourceEditError(\"SCHEMA_EDIT_REFUSED\", `The edit changes nothing in ${this.relative(found.file)}.`, []);\n }\n verify(found.file, text, target, request.operations);\n return { files: [{ path: found.file, contents: text, before: found.text }] };\n }\n\n /** {@link preview}, then write, check and — when the check fails — roll back. Queued behind every other edit. */\n apply(request: FrontendSourceEditRequest): Promise<FrontendSourceEdit> {\n return this.run(async () => {\n const edit = await this.preview(request);\n await this.write(edit);\n return edit;\n });\n }\n\n /**\n * Write a previewed edit, refusing when a file changed on disk since the\n * preview read it. A file that does not read back as written, a failure\n * on the way, or a `check` that reports problems restores every file as\n * it was before the write.\n */\n async write(edit: FrontendSourceEdit): Promise<void> {\n for (const file of edit.files) {\n const now = fs.existsSync(file.path) ? fs.readFileSync(file.path, \"utf8\") : undefined;\n if (now !== file.before) {\n throw new FrontendSourceEditError(\"SCHEMA_EDIT_STALE_FILE\",\n `${this.relative(file.path)} changed since the edit was prepared (it was saved by something else meanwhile). ` +\n \"Nothing was written: reload, and make the edit again against the file as it is now.\", []);\n }\n }\n const written: FrontendSourceFile[] = [];\n try {\n for (const file of edit.files) {\n await writeWhole(file.path, file.contents);\n written.push(file);\n if (fs.readFileSync(file.path, \"utf8\") !== file.contents) throw new Error(`${file.path} does not read back as written.`);\n }\n const problems = this.check ? await this.check(edit.files) : [];\n if (problems.length > 0) {\n throw new FrontendSourceEditError(\"SCHEMA_EDIT_DOES_NOT_COMPILE\",\n `The edit was not kept: it does not compile. ${problems.map(problem => problem.message).join(\" \")}`, problems);\n }\n } catch (error) {\n for (const file of written.reverse()) {\n if (file.before === undefined) await fsp.rm(file.path, { force: true });\n else await writeWhole(file.path, file.before);\n }\n throw error;\n }\n }\n\n /** A path as the panel reads it: relative to the project root, with forward slashes. */\n relative(file: string): string {\n return path.relative(this.root, file).split(path.sep).join(\"/\");\n }\n\n /** The one call `target` names, or a refusal. */\n private locate(target: FrontendCallTarget): { file: string; text: string } {\n const found: { file: string; text: string }[] = [];\n for (const file of sourceFiles(this.sourceDir)) {\n const text = fs.readFileSync(file, \"utf8\");\n if (!text.includes(target.callee)) continue;\n const source = parse(file, text);\n for (const call of callsTo(source, target.callee)) {\n if (locateArgument(call, target.key)?.value === target.value) found.push({ file, text });\n }\n }\n if (found.length === 0) {\n throw refusal(\n `No \\`${target.callee}({ ${target.key}: ${JSON.stringify(target.value)}, … })\\` in ${this.relative(this.sourceDir) || \".\"}. ` +\n `If it is built by a helper or its \\`${target.key}\\` is not a string written in the call, it is edited in code.`,\n target.value\n );\n }\n if (found.length > 1) {\n throw refusal(\n `More than one \\`${target.callee}\\` call has \\`${target.key}: ${JSON.stringify(target.value)}\\` ` +\n `(${found.map(each => this.relative(each.file)).join(\", \")}): edit it in code.`,\n target.value\n );\n }\n return found[0];\n }\n}\n\n/**\n * A check over the files an edit wrote, with the edit on disk: a project's\n * own compile. Problems roll the edit back.\n *\n * @group Schema\n */\nexport type FrontendSourceCheck = (files: readonly FrontendSourceFile[]) => Promise<FrontendSourceProblem[]>;\n\n/**\n * JSON, the only thing a frontend source edit writes as a value.\n *\n * @group Schema\n */\nexport type FrontendSourceValue = null | boolean | number | string | FrontendSourceValue[] | { [key: string]: FrontendSourceValue };\n\n/**\n * One operation on the object argument of a call, at a path of keys into it.\n *\n * - `set` — write `value` at `path`, replacing what is there (which must be\n * plain data) or inserting it (before the member `before`, else last),\n * creating the objects on the way that do not exist yet.\n * - `remove` — remove the key at `path`; nothing when it is absent. With\n * `prune`, an object the removal leaves empty is removed too.\n * - `rename` — give the key at `path` the name `to`; its value is untouched.\n * - `move` — move the key at `path` before its sibling `before`, else last.\n *\n * @group Schema\n */\nexport type FrontendSourceOperation =\n | { op: \"set\"; path: string[]; value: FrontendSourceValue; before?: string }\n | { op: \"remove\"; path: string[]; prune?: boolean }\n | { op: \"rename\"; path: string[]; to: string }\n | { op: \"move\"; path: string[]; before?: string };\n\n/**\n * Which call an edit is about: the call to `callee` whose object argument has\n * the member `key` written as the string `value`.\n *\n * @group Schema\n */\nexport interface FrontendCallTarget {\n callee: string;\n key: string;\n value: string;\n}\n\n/**\n * A frontend source edit, as `POST /api/admin/schema-editor/frontend/apply`\n * takes it.\n *\n * @group Schema\n */\nexport interface FrontendSourceEditRequest {\n target: FrontendCallTarget;\n /** The file's `version` as the panel read it; a different file is refused as stale. */\n version?: string;\n operations: FrontendSourceOperation[];\n}\n\n/**\n * One file an edit changes.\n *\n * @group Schema\n */\nexport interface FrontendSourceFile {\n /** Absolute path. */\n path: string;\n /** The new text. */\n contents: string;\n /** The text the edit was made against. */\n before?: string;\n}\n\n/**\n * An edit, applied to a copy and read back.\n *\n * @group Schema\n */\nexport interface FrontendSourceEdit {\n files: FrontendSourceFile[];\n}\n\n/**\n * How the editor reads one call.\n *\n * @group Schema\n */\nexport interface FrontendCallSummary {\n /** The value of the key it was picked out by (a collection's slug). */\n value: string;\n /** Its file, relative to the project root. */\n file: string;\n /** A hash of the file's text: sent back with an edit, a changed file is refused. */\n version: string;\n /** Why the whole call is read-only, when it is. */\n editedInCode?: string;\n /** Why a member of a listed path is read-only, by dotted path (`fields.customerId`). */\n members: Record<string, string>;\n}\n\n/**\n * What is wrong with an edit. `table` names the call by the value it was\n * picked out by — the shape the panel reads every schema-edit problem in.\n *\n * @group Schema\n */\nexport interface FrontendSourceProblem {\n table: string;\n /** The dotted path, when there is one. */\n key?: string;\n message: string;\n}\n\n/**\n * An edit the frontend source editor will not make. Nothing was written (or\n * what was written was restored). The codes are the table editor's\n * ({@link SchemaEditRefusalCode}) — a file changed on disk since the panel\n * read it is `SCHEMA_EDIT_STALE_FILE` — and `INVALID_INPUT`.\n *\n * @group Schema\n */\nexport class FrontendSourceEditError extends Error {\n constructor(\n readonly code: SchemaEditRefusalCode | \"INVALID_INPUT\",\n message: string,\n readonly problems: readonly FrontendSourceProblem[]\n ) {\n super(message);\n this.name = \"FrontendSourceEditError\";\n }\n}\n\n// ── The wire ────────────────────────────────────────────────────────────────\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nfunction isValue(value: unknown, depth = 0): value is FrontendSourceValue {\n if (depth > 32) return false;\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") return true;\n if (typeof value === \"number\") return Number.isFinite(value);\n if (Array.isArray(value)) return value.every(item => isValue(item, depth + 1));\n if (isRecord(value) && Object.getPrototypeOf(value) === Object.prototype) {\n return Object.values(value).every(item => isValue(item, depth + 1));\n }\n return false;\n}\n\nconst isKeyPath = (value: unknown): value is string[] =>\n Array.isArray(value) && value.length > 0 && value.every(segment => typeof segment === \"string\" && segment.length > 0);\n\nfunction assertIdentifier(value: string, what: string): void {\n if (!IDENTIFIER.test(value)) throw new FrontendSourceEditError(\"INVALID_INPUT\", `\\`${what}\\` must be an identifier, not ${JSON.stringify(value)}.`, []);\n}\n\n/**\n * The edit a request body describes, or an `INVALID_INPUT` refusal naming\n * every problem. Values must be JSON; the callee an identifier; paths\n * non-empty lists of keys.\n *\n * @group Schema\n */\nexport function parseFrontendSourceEdit(body: unknown): FrontendSourceEditRequest {\n const problems: string[] = [];\n if (!isRecord(body)) throw new FrontendSourceEditError(\"INVALID_INPUT\", \"Expected `{ target, operations }`.\", []);\n const target = body.target;\n if (!isRecord(target) || typeof target.callee !== \"string\" || typeof target.key !== \"string\" || typeof target.value !== \"string\") {\n problems.push(\"`target` must be `{ callee, key, value }`, three strings.\");\n } else if (!IDENTIFIER.test(target.callee)) {\n problems.push(`\\`target.callee\\` must be an identifier, not ${JSON.stringify(target.callee)}.`);\n }\n if (body.version !== undefined && typeof body.version !== \"string\") problems.push(\"`version` must be a string.\");\n const operations: FrontendSourceOperation[] = [];\n if (!Array.isArray(body.operations) || body.operations.length === 0) {\n problems.push(\"`operations` must be a non-empty list.\");\n } else {\n body.operations.forEach((operation: unknown, index) => {\n const where = `operations[${index}]`;\n if (!isRecord(operation) || !isKeyPath(operation.path)) {\n problems.push(`${where} needs a \\`path\\`: a non-empty list of keys.`);\n return;\n }\n const before = operation.before;\n if (before !== undefined && typeof before !== \"string\") {\n problems.push(`${where}.before must be a key.`);\n return;\n }\n switch (operation.op) {\n case \"set\":\n if (!(\"value\" in operation) || !isValue(operation.value)) {\n problems.push(`${where}.value must be JSON: strings, finite numbers, booleans, null, arrays and plain objects.`);\n return;\n }\n operations.push({ op: \"set\", path: operation.path, value: operation.value, ...(before !== undefined ? { before } : {}) });\n return;\n case \"remove\":\n operations.push({ op: \"remove\", path: operation.path, ...(operation.prune === true ? { prune: true } : {}) });\n return;\n case \"rename\":\n if (typeof operation.to !== \"string\" || operation.to.length === 0) {\n problems.push(`${where}.to must be a key.`);\n return;\n }\n operations.push({ op: \"rename\", path: operation.path, to: operation.to });\n return;\n case \"move\":\n operations.push({ op: \"move\", path: operation.path, ...(before !== undefined ? { before } : {}) });\n return;\n default:\n problems.push(`${where}.op must be one of set, remove, rename, move.`);\n }\n });\n }\n if (problems.length > 0 || !isRecord(target)) {\n throw new FrontendSourceEditError(\"INVALID_INPUT\", `The frontend source edit is not well formed: ${problems.join(\" \")}`,\n problems.map(message => ({ table: \"\", message })));\n }\n return {\n target: { callee: String(target.callee), key: String(target.key), value: String(target.value) },\n ...(typeof body.version === \"string\" ? { version: body.version } : {}),\n operations\n };\n}\n\n// ── Reading ─────────────────────────────────────────────────────────────────\n\nconst SOURCE_EXTENSIONS = [\".ts\", \".tsx\", \".mts\", \".js\", \".jsx\", \".mjs\"];\n\n/** The module files of the frontend source, in path order. */\nfunction sourceFiles(dir: string): string[] {\n const out: string[] = [];\n if (!fs.existsSync(dir)) return out;\n const walk = (current: string): void => {\n for (const entry of fs.readdirSync(current, { withFileTypes: true })) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\" || entry.name === \"__tests__\") continue;\n const full = path.join(current, entry.name);\n if (entry.isDirectory()) walk(full);\n else if (entry.isFile() && SOURCE_EXTENSIONS.some(ext => entry.name.endsWith(ext))\n && !/\\.d\\.[mc]?ts$/.test(entry.name) && !/\\.(test|spec)\\./.test(entry.name)) {\n out.push(full);\n }\n }\n };\n walk(dir);\n return out.sort();\n}\n\n/** The text of a file parsed on its own, JSX by its extension. */\nfunction parse(file: string, text: string): SourceFile {\n const project = new Project({ useInMemoryFileSystem: true, compilerOptions: { allowJs: true, noLib: true, jsx: ts.JsxEmit.Preserve } });\n return project.createSourceFile(file, text, { overwrite: true });\n}\n\n/** The syntax errors of a text, as messages. */\nfunction syntaxErrors(file: string, text: string): string[] {\n const result = ts.transpileModule(text, {\n fileName: file,\n reportDiagnostics: true,\n compilerOptions: { jsx: ts.JsxEmit.Preserve, target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext }\n });\n return (result.diagnostics ?? []).map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, \"\\n\"));\n}\n\n/** Every call whose callee ends in `callee`: `defineX(…)`, `lib.defineX(…)`. */\nfunction callsTo(source: SourceFile, callee: string): CallExpression[] {\n return source.getDescendants().filter((node): node is CallExpression => {\n if (!Node.isCallExpression(node)) return false;\n const expression = node.getExpression();\n if (Node.isIdentifier(expression)) return expression.getText() === callee;\n return Node.isPropertyAccessExpression(expression) && expression.getName() === callee;\n });\n}\n\n/** The call's object argument, picked out by its `key` member, and whether it can be written. */\nfunction locateArgument(call: CallExpression, key: string): { value: string; object?: ObjectLiteralExpression; editedInCode?: string } | undefined {\n const argument = unwrapExpression(call.getArguments()[0]);\n if (!argument || !Node.isObjectLiteralExpression(argument)) return undefined;\n const found = member(argument, key, \"the call's argument\");\n if (found.kind !== \"written\") return undefined;\n const value = literalString(unwrapExpression(found.value));\n if (value === undefined) return undefined;\n const opaque = opaqueMembers(argument, \"its argument\");\n return opaque ? { value, editedInCode: opaque } : { value, object: argument };\n}\n\ntype Reached =\n | { kind: \"object\"; object: ObjectLiteralExpression }\n | { kind: \"absent\"; object: ObjectLiteralExpression; depth: number }\n | { kind: \"code\"; reason: string };\n\n/** Walk `keys` down from `root` through object literals written in place. */\nfunction reach(root: ObjectLiteralExpression, keys: readonly string[]): Reached {\n let object = root;\n for (const [depth, key] of keys.entries()) {\n const where = keys.slice(0, depth + 1).join(\".\");\n const found = member(object, key, `\\`${keys.slice(0, depth).join(\".\") || \"the argument\"}\\``);\n if (found.kind === \"absent\") return { kind: \"absent\", object, depth };\n if (found.kind === \"code\") return { kind: \"code\", reason: found.reason };\n const value = unwrapExpression(found.value);\n if (!value || !Node.isObjectLiteralExpression(value)) {\n return { kind: \"code\", reason: `\\`${where}\\` is \\`${clip(found.value.getText())}\\`, not an object written in the call.` };\n }\n const opaque = opaqueMembers(value, `\\`${where}\\``);\n if (opaque) return { kind: \"code\", reason: opaque };\n object = value;\n }\n return { kind: \"object\", object };\n}\n\nconst clip = (text: string): string => (text.length > 40 ? `${text.slice(0, 40)}…` : text);\n\n/**\n * The version of a file's text the panel sends back with an edit: a short\n * hash, so a file changed since the panel read it is refused as stale.\n *\n * @group Schema\n */\nexport function versionOf(text: string): string {\n return crypto.createHash(\"sha256\").update(text).digest(\"hex\").slice(0, 16);\n}\n\n/** The JSON a plain-data literal denotes; `undefined` for anything else. */\nfunction literalValue(node: Node | undefined): FrontendSourceValue | undefined {\n const value = unwrapExpression(node);\n if (!value) return undefined;\n if (Node.isStringLiteral(value) || Node.isNoSubstitutionTemplateLiteral(value)) return value.getLiteralValue();\n if (Node.isNumericLiteral(value)) return value.getLiteralValue();\n if (Node.isTrueLiteral(value)) return true;\n if (Node.isFalseLiteral(value)) return false;\n if (Node.isNullLiteral(value)) return null;\n if (Node.isPrefixUnaryExpression(value) && value.getOperatorToken() === ts.SyntaxKind.MinusToken) {\n const operand = value.getOperand();\n return Node.isNumericLiteral(operand) ? -operand.getLiteralValue() : undefined;\n }\n if (Node.isArrayLiteralExpression(value)) {\n const items: FrontendSourceValue[] = [];\n for (const element of value.getElements()) {\n const item = literalValue(element);\n if (item === undefined) return undefined;\n items.push(item);\n }\n return items;\n }\n if (Node.isObjectLiteralExpression(value)) {\n const out: { [key: string]: FrontendSourceValue } = {};\n for (const each of value.getProperties()) {\n const name = memberName(each);\n if (name === undefined || !Node.isPropertyAssignment(each)) return undefined;\n const item = literalValue(each.getInitializer());\n if (item === undefined) return undefined;\n out[name] = item;\n }\n return out;\n }\n return undefined;\n}\n\nfunction sameJson(a: FrontendSourceValue | undefined, b: FrontendSourceValue | undefined): boolean {\n if (a === b) return true;\n if (Array.isArray(a) || Array.isArray(b)) {\n return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, index) => sameJson(item, b[index]));\n }\n if (a === null || b === null || typeof a !== \"object\" || typeof b !== \"object\") return false;\n const keys = Object.keys(a);\n return keys.length === Object.keys(b).length && keys.every(key => key in b && sameJson(a[key], b[key]));\n}\n\n// ── Writing ─────────────────────────────────────────────────────────────────\n\nfunction refusal(message: string, table: string, key?: string): FrontendSourceEditError {\n return new FrontendSourceEditError(\"SCHEMA_EDIT_REFUSED\", message, [{ table, ...(key !== undefined ? { key } : {}), message }]);\n}\n\nfunction asRefusal(error: unknown, index: number, operation: FrontendSourceOperation, target: FrontendCallTarget): FrontendSourceEditError {\n if (error instanceof FrontendSourceEditError) return error;\n const message = error instanceof Error ? error.message : String(error);\n return refusal(`Edit ${index} (${operation.op} \\`${operation.path.join(\".\")}\\` of \"${target.value}\"): ${message}`, target.value, operation.path.join(\".\"));\n}\n\n/** The writable argument of the target call in `text`. */\nfunction argumentIn(file: string, text: string, target: FrontendCallTarget): ObjectLiteralExpression {\n const source = parse(file, text);\n for (const call of callsTo(source, target.callee)) {\n const located = locateArgument(call, target.key);\n if (located?.value !== target.value) continue;\n if (!located.object) throw refusal(`\"${target.value}\" is edited in code: ${located.editedInCode}`, target.value);\n return located.object;\n }\n throw refusal(`The call for \"${target.value}\" is no longer in ${path.basename(file)}.`, target.value);\n}\n\n/** The object holding the last key of `keys`, which must exist and be writable. */\nfunction parentOf(root: ObjectLiteralExpression, keys: readonly string[], target: FrontendCallTarget): ObjectLiteralExpression {\n const reached = reach(root, keys.slice(0, -1));\n const where = keys.join(\".\");\n if (reached.kind === \"code\") throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: ${reached.reason}`, target.value, where);\n if (reached.kind === \"absent\") throw refusal(`\"${target.value}\" has no \\`${keys.slice(0, reached.depth + 1).join(\".\")}\\`.`, target.value, where);\n const opaque = opaqueMembers(reached.object, `\\`${keys.slice(0, -1).join(\".\") || \"the argument\"}\\``);\n if (opaque) throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: ${opaque}`, target.value, where);\n return reached.object;\n}\n\n/** `value` nested under `keys`: `{ a: { b: value } }` for `[\"a\", \"b\"]`. */\nfunction nestedValue(keys: readonly string[], value: FrontendSourceValue): FrontendSourceValue {\n return keys.reduceRight<FrontendSourceValue>((inner, key) => ({ [key]: inner }), value);\n}\n\nfunction printed(value: FrontendSourceValue, where: string): string {\n return printSchemaValue(value, where);\n}\n\nfunction applyOperation(file: string, text: string, target: FrontendCallTarget, operation: FrontendSourceOperation): string {\n const root = argumentIn(file, text, target);\n const keys = operation.path;\n const where = keys.join(\".\");\n if (keys.length === 1 && keys[0] === target.key && operation.op !== \"set\") {\n throw refusal(`\\`${target.key}\\` is what the call is found by: it cannot be ${operation.op === \"remove\" ? \"removed\" : operation.op === \"rename\" ? \"renamed\" : \"moved\"}.`, target.value, where);\n }\n switch (operation.op) {\n case \"set\": {\n if (keys.length === 1 && keys[0] === target.key && operation.value !== target.value) {\n throw refusal(`\\`${target.key}\\` is what the call is found by, and other code refers to it: change it in code.`, target.value, where);\n }\n const reached = reach(root, keys.slice(0, -1));\n if (reached.kind === \"code\") throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: ${reached.reason}`, target.value, where);\n if (reached.kind === \"absent\") {\n // Create the objects on the way: insert the first missing key with the rest nested in it.\n const missing = keys.slice(reached.depth);\n return insertMember(text, reached.object, missing[0], nestedValue(missing.slice(1), operation.value), `${target.value}.${where}`,\n reached.depth === keys.length - 1 ? operation.before : undefined, target);\n }\n const object = reached.object;\n const last = keys[keys.length - 1];\n const found = member(object, last, `\\`${keys.slice(0, -1).join(\".\") || \"the argument\"}\\``);\n if (found.kind === \"code\") throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: ${found.reason}`, target.value, where);\n if (found.kind === \"absent\") return insertMember(text, object, last, operation.value, `${target.value}.${where}`, operation.before, target);\n if (!isData(found.value)) {\n throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: it is \\`${clip(found.value.getText())}\\`, not plain data.`, target.value, where);\n }\n return applyEdits(text, [replaceNode(text, found.value, printed(operation.value, `${target.value}.${where}`))]);\n }\n case \"remove\": {\n const reached = reach(root, keys.slice(0, -1));\n if (reached.kind === \"absent\") return text;\n if (reached.kind === \"code\") throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: ${reached.reason}`, target.value, where);\n const object = reached.object;\n const found = member(object, keys[keys.length - 1], `\\`${keys.slice(0, -1).join(\".\") || \"the argument\"}\\``);\n if (found.kind === \"absent\") return text;\n if (found.kind === \"code\") throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: ${found.reason}`, target.value, where);\n const value = unwrapExpression(found.value);\n if (!value || !(isData(value) || Node.isObjectLiteralExpression(value))) {\n throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: it is \\`${clip(found.value.getText())}\\`.`, target.value, where);\n }\n const next = applyEdits(text, removeListItem(text, listShape(object, object.getProperties()), found.index));\n if (operation.prune && keys.length > 1 && object.getProperties().length === 1) {\n return applyOperation(file, next, target, { op: \"remove\", path: keys.slice(0, -1), prune: true });\n }\n return next;\n }\n case \"rename\": {\n const object = parentOf(root, keys, target);\n const last = keys[keys.length - 1];\n const found = member(object, last, `\\`${keys.slice(0, -1).join(\".\") || \"the argument\"}\\``);\n if (found.kind === \"absent\") throw refusal(`\"${target.value}\" has no \\`${where}\\`.`, target.value, where);\n if (found.kind === \"code\") throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: ${found.reason}`, target.value, where);\n if (operation.to === last) return text;\n if (member(object, operation.to, \"it\").kind !== \"absent\") {\n throw refusal(`\"${target.value}\" already has \\`${[...keys.slice(0, -1), operation.to].join(\".\")}\\`.`, target.value, where);\n }\n const assignment = found.node;\n if (!Node.isPropertyAssignment(assignment)) throw refusal(`\\`${where}\\` is not written as \\`key: value\\`.`, target.value, where);\n const nameNode = assignment.getNameNode();\n return applyEdits(text, [{ start: nameNode.getStart(), end: nameNode.getEnd(), text: printKey(operation.to) }]);\n }\n case \"move\": {\n const object = parentOf(root, keys, target);\n const last = keys[keys.length - 1];\n const found = member(object, last, \"it\");\n if (found.kind !== \"written\") throw refusal(`\"${target.value}\" has no \\`${where}\\` written in the call.`, target.value, where);\n if (operation.before === last) return text;\n if (operation.before !== undefined && member(object, operation.before, \"it\").kind !== \"written\") {\n throw refusal(`\"${target.value}\" has no \\`${[...keys.slice(0, -1), operation.before].join(\".\")}\\` to move before.`, target.value, where);\n }\n const moved = itemText(text, listShape(object, object.getProperties()), found.index);\n const removed = applyEdits(text, removeListItem(text, listShape(object, object.getProperties()), found.index));\n const again = parentOf(argumentIn(file, removed, target), keys, target);\n const members = again.getProperties();\n const index = operation.before !== undefined ? members.findIndex(each => memberName(each) === operation.before) : members.length;\n return applyEdits(removed, insertListItem(removed, listShape(again, members), index, moved, \"lines\"));\n }\n }\n}\n\nfunction insertMember(\n text: string,\n object: ObjectLiteralExpression,\n key: string,\n value: FrontendSourceValue,\n where: string,\n before: string | undefined,\n target: FrontendCallTarget\n): string {\n const members = object.getProperties();\n let index = members.length;\n if (before !== undefined) {\n index = members.findIndex(each => memberName(each) === before);\n if (index === -1) throw refusal(`There is no \\`${before}\\` to insert \\`${key}\\` before.`, target.value, where);\n }\n const edits: TextEdit[] = insertListItem(text, listShape(object, members), index, `${printKey(key)}: ${printed(value, where)}`, \"lines\");\n return applyEdits(text, edits);\n}\n\n/** The edited text parses, and every value set reads back as that value; every key removed is gone. */\nfunction verify(file: string, text: string, target: FrontendCallTarget, operations: readonly FrontendSourceOperation[]): void {\n const errors = syntaxErrors(file, text);\n if (errors.length > 0) {\n throw new FrontendSourceEditError(\"SCHEMA_EDIT_DOES_NOT_COMPILE\",\n `The edit was not written: ${path.basename(file)} would not parse: ${errors.join(\" \")}`,\n errors.map(message => ({ table: target.value, message })));\n }\n const root = argumentIn(file, text, target);\n const expected = new Map<string, { path: string[]; value?: FrontendSourceValue }>();\n for (const operation of operations) {\n if (operation.op === \"set\") expected.set(operation.path.join(\"\\u0000\"), { path: operation.path, value: operation.value });\n else if (operation.op === \"remove\") expected.set(operation.path.join(\"\\u0000\"), { path: operation.path });\n else if (operation.op === \"rename\") {\n // What was set under the old key is now under the new one.\n const from = operation.path;\n const to = [...from.slice(0, -1), operation.to];\n for (const [id, entry] of [...expected]) {\n if (entry.path.length < from.length || !from.every((key, index) => entry.path[index] === key)) continue;\n expected.delete(id);\n const moved = [...to, ...entry.path.slice(from.length)];\n expected.set(moved.join(\"\\u0000\"), { ...entry, path: moved });\n }\n }\n }\n for (const { path: keys, value } of expected.values()) {\n const reached = reach(root, keys.slice(0, -1));\n const where = keys.join(\".\");\n const found = reached.kind === \"object\" ? member(reached.object, keys[keys.length - 1], \"it\") : undefined;\n if (value === undefined) {\n if (found?.kind === \"written\") throw refusal(`\\`${where}\\` is still there after the edit removed it.`, target.value, where);\n continue;\n }\n const read = found?.kind === \"written\" ? literalValue(found.value) : undefined;\n if (!sameJson(read, value)) throw refusal(`\\`${where}\\` does not read back as the value written.`, target.value, where);\n }\n}\n\nasync function writeWhole(file: string, contents: string): Promise<void> {\n await fsp.writeFile(file, contents, \"utf8\");\n}\n\n/**\n * Where a project keeps its frontend source: `<project root>/frontend/src`.\n *\n * @group Schema\n */\nexport function frontendSourceDirOf(projectRoot: string): string {\n return path.join(projectRoot, \"frontend\", \"src\");\n}\n","import { Hono } from \"hono\";\nimport path from \"node:path\";\nimport {\n FrontendSourceEditError,\n FrontendSourceEditor,\n frontendSourceDirOf,\n parseFrontendSourceEdit,\n type FrontendSourceEdit\n} from \"../schema-edit/frontend-source-editor\";\nimport { findProjectRoot } from \"../schema-edit/project-root\";\nimport { ApiError, errorHandler } from \"./errors\";\nimport { HonoEnv } from \"./types\";\n\n/**\n * Editing the project's frontend source from the admin panel, in\n * development: `/api/admin/schema-editor/frontend/*`, mounted inside the\n * source-only schema editor, so behind the same gate (`schema:read` to read,\n * `schema:write` to write) and present exactly where that editor is — a\n * `schemaDir` on disk, `schemaEditor` not false, never under\n * `NODE_ENV=production` unless the server opted in.\n *\n * It edits the object argument of one call in `frontend/src` — the admin\n * panel uses it for the `defineFirestoreCollection({...})` calls of a hybrid\n * project — and knows nothing about what the call means:\n *\n * - `GET /calls?callee=<identifier>&key=<key>&list=<dotted path>…` — every\n * call to `callee` picked out by its `key` member, with its file, version\n * and what is edited in code.\n * - `POST /preview` `{ target, version?, operations }` — the file the edit\n * would write; nothing is written.\n * - `POST /apply` — the same, written.\n *\n * Refusals carry the problems in `details.problems`, in the codes the table\n * routes use: 400 `SCHEMA_EDIT_REFUSED`, `SCHEMA_EDIT_DOES_NOT_COMPILE`,\n * `INVALID_INPUT`, and 409 `SCHEMA_EDIT_STALE_FILE` for a file changed on disk\n * since the panel read it.\n */\n\n/** The process's frontend source editor for the project `schemaDir` belongs to. */\nexport function createFrontendSourceEditor(schemaDir: string): FrontendSourceEditor {\n const root = findProjectRoot(schemaDir) ?? path.dirname(path.dirname(path.resolve(schemaDir)));\n return new FrontendSourceEditor(frontendSourceDirOf(root), { root });\n}\n\n/** A refusal as the answer that carries it: 409 for a file changed on disk since it was read, 400 otherwise. */\nfunction refusalsAsBadRequest<T>(run: () => Promise<T>): Promise<T> {\n return run().catch((error: unknown) => {\n if (error instanceof FrontendSourceEditError) {\n throw new ApiError(error.code === \"SCHEMA_EDIT_STALE_FILE\" ? 409 : 400, error.code, error.message, { problems: error.problems });\n }\n throw error;\n });\n}\n\nasync function requestOf(c: { req: { json: () => Promise<unknown> } }) {\n const body: unknown = await c.req.json().catch(() => undefined);\n try {\n return parseFrontendSourceEdit(body);\n } catch (error) {\n if (error instanceof FrontendSourceEditError) throw ApiError.badRequest(error.message, error.code, { problems: error.problems });\n throw error;\n }\n}\n\nfunction describeEdit(editor: FrontendSourceEditor, edit: FrontendSourceEdit) {\n return { files: edit.files.map(file => ({ path: editor.relative(file.path), contents: file.contents })) };\n}\n\n/** The frontend source editor's routes, over one editor. */\nexport function createFrontendSourceRoutes(editor: FrontendSourceEditor): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n router.onError(errorHandler);\n\n router.get(\"/calls\", async (c) => {\n const callee = c.req.query(\"callee\");\n const key = c.req.query(\"key\");\n if (!callee || !key) throw ApiError.badRequest(\"Expected `?callee=<identifier>&key=<key>`.\", \"INVALID_INPUT\");\n const lists = (c.req.queries(\"list\") ?? []).filter(list => list.length > 0).map(list => list.split(\".\"));\n const calls = await refusalsAsBadRequest(async () => editor.describe(callee, key, lists));\n return c.json({ calls });\n });\n\n router.post(\"/preview\", async (c) => {\n const request = await requestOf(c);\n const edit = await refusalsAsBadRequest(() => editor.run(() => editor.preview(request)));\n return c.json(describeEdit(editor, edit));\n });\n\n router.post(\"/apply\", async (c) => {\n const request = await requestOf(c);\n const edit = await refusalsAsBadRequest(() => editor.apply(request));\n return c.json({ success: true, ...describeEdit(editor, edit) });\n });\n\n return router;\n}\n","import { Hono } from \"hono\";\nimport path from \"node:path\";\nimport { TablePatchError, parseTablePatches, type DatabaseAdmin, type TablePatch, type UnmappedTable } from \"@rebasepro/types\";\nimport { TableSourceEditError, TableSourceEditor, type TableSourceEdit } from \"./table-source-editor\";\nimport { ApiError, errorHandler } from \"./errors\";\nimport { createFrontendSourceEditor, createFrontendSourceRoutes } from \"./frontend-source-routes\";\nimport { HonoEnv } from \"./types\";\n\n/**\n * Editing `backend/schema` from the Studio, on this machine, without touching\n * the database: `/api/admin/schema-editor/*`.\n *\n * - `GET /tables` — every table the index exports as the editor reads it,\n * with what is edited in code (read-only) and why.\n * - `POST /preview` `{ patches }` — the files the edit would write, compiled;\n * nothing is written.\n * - `POST /apply` `{ patches }` — the same, written to disk.\n * - `GET /unmapped-tables` — the database's tables no declared table maps\n * (\"Import an existing table\"): `{ tables: [{ schema, table, rlsEnabled,\n * policies, unimportable? }] }`.\n * - `GET /unmapped-tables/:schema/:table` — one of them as introspection\n * describes it, `{ table: { …, descriptor, rlsRaised?, notes } }`: the\n * `TableDescriptor` an `adoptTable` edit writes as its source. Its `rls` is\n * never weaker than what the database enforces — with row-level security\n * off or no policy it is `\"admin-only\"`, and `rlsRaised` says so.\n *\n * Every refusal says what to do, with the problems in `details.problems`: a\n * 400 for an edit the editor will not make (`SCHEMA_EDIT_REFUSED`), one whose\n * result does not compile (`SCHEMA_EDIT_DOES_NOT_COMPILE`) or a list of edits\n * that is not well formed (`INVALID_INPUT`), and a 409 when a file the edit\n * rewrites changed on disk since it was read (`SCHEMA_EDIT_STALE_FILE`).\n * Nothing is written on any of them.\n *\n * Changing the database is live schema editing's job (`/api/admin/schema`),\n * which commits the same edits and runs the DDL.\n *\n * `/frontend/*` edits the project's frontend source the same way — the\n * object argument of one call in `frontend/src`, which the admin panel uses\n * for its Firestore collections — under the same gate\n * (see `frontend-source-routes.ts`).\n */\n\n/** The process's one editor of `schemaDir`, shared with live schema editing. */\nexport function createTableSourceEditor(schemaDir: string): TableSourceEditor {\n return new TableSourceEditor(schemaDir);\n}\n\n/** The `{ patches }` of a request, or a 400 naming every problem. */\nasync function patchesOf(c: { req: { json: () => Promise<unknown> } }): Promise<TablePatch[]> {\n const body: unknown = await c.req.json().catch(() => undefined);\n if (typeof body !== \"object\" || body === null || !(\"patches\" in body)) {\n throw ApiError.badRequest(\"Expected `{ patches: [...] }`: the schema edits to make.\", \"INVALID_INPUT\");\n }\n try {\n return parseTablePatches(body.patches);\n } catch (error) {\n if (error instanceof TablePatchError) throw ApiError.badRequest(error.message, \"INVALID_INPUT\", { problems: error.problems });\n throw error;\n }\n}\n\n/** An edit, as the panel reads it: each file by its path in the project, with its new text. */\nfunction describeEdit(editor: TableSourceEditor, edit: TableSourceEdit) {\n const root = path.dirname(path.dirname(editor.schemaDir));\n return {\n files: edit.files.map(file => ({\n path: path.relative(root, file.path).split(path.sep).join(\"/\"),\n ...(file.deleted ? { deleted: true } : { contents: file.contents })\n })),\n tables: edit.schema.descriptors.map(descriptor => descriptor.slug)\n };\n}\n\n/** The editor's refusal, as the answer that carries its reason and its problems: 409 for a stale file, 400 otherwise. */\nfunction refusalsAsBadRequest<T>(run: () => Promise<T>): Promise<T> {\n return run().catch((error: unknown) => {\n if (error instanceof TableSourceEditError) {\n throw new ApiError(error.code === \"SCHEMA_EDIT_STALE_FILE\" ? 409 : 400, error.code, error.message, { problems: error.problems });\n }\n throw error;\n });\n}\n\n/** What the schema editor's routes read besides the editor. */\nexport interface SchemaEditorRoutesOptions {\n /** The default database's admin, read at request time: what describes the tables \"Import an existing table\" offers. */\n getAdmin?: () => DatabaseAdmin | undefined;\n}\n\n/** A table as the import list shows it: everything but its description. */\nfunction summaryOf(table: UnmappedTable): Omit<UnmappedTable, \"descriptor\" | \"notes\" | \"rlsRaised\"> {\n return {\n schema: table.schema,\n table: table.table,\n rlsEnabled: table.rlsEnabled,\n policies: table.policies,\n ...(table.unimportable ? { unimportable: table.unimportable } : {})\n };\n}\n\n/**\n * The tables of the database no table of `backend/schema` maps, described,\n * with each `belongsTo` naming its target by the declared table's slug.\n */\nasync function unmappedTables(editor: TableSourceEditor, admin: DatabaseAdmin | undefined, onlySchema?: string): Promise<UnmappedTable[]> {\n const describe = admin?.describeUnmappedTables;\n if (!describe) {\n throw new ApiError(503, \"SCHEMA_EDITING_UNSUPPORTED\", \"This database driver cannot describe its tables, so none can be imported from here.\");\n }\n const declared = (await refusalsAsBadRequest(() => editor.compileCurrent())).descriptors;\n const schemas = onlySchema !== undefined ? [onlySchema] : [...new Set([\"public\", ...declared.map(descriptor => descriptor.schema)])];\n const out: UnmappedTable[] = [];\n for (const schema of schemas) {\n const inSchema = declared.filter(descriptor => descriptor.schema === schema);\n const slugOf = new Map(inSchema.map(descriptor => [descriptor.table, descriptor.slug]));\n for (const table of await describe.call(admin, schema, new Set(inSchema.map(descriptor => descriptor.table)))) {\n if (!table.descriptor) {\n out.push(table);\n continue;\n }\n const self = table.descriptor;\n const relations = self.relations.map(relation => ({\n ...relation,\n target: relation.target === self.table ? self.slug : slugOf.get(relation.target) ?? relation.target\n }));\n out.push({ ...table, descriptor: { ...self, relations } });\n }\n }\n return out;\n}\n\n/** The source-only schema editor's routes, over one editor. */\nexport function createSchemaEditorRoutes(editor: TableSourceEditor, options: SchemaEditorRoutesOptions = {}): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n router.onError(errorHandler);\n\n router.get(\"/unmapped-tables\", async (c) => {\n const tables = await unmappedTables(editor, options.getAdmin?.());\n return c.json({ tables: tables.map(summaryOf) });\n });\n\n router.get(\"/unmapped-tables/:schema/:table\", async (c) => {\n const schema = c.req.param(\"schema\");\n const name = c.req.param(\"table\");\n const found = (await unmappedTables(editor, options.getAdmin?.(), schema)).find(table => table.table === name);\n if (!found) {\n throw ApiError.notFound(`The database has no table \"${schema}\".\"${name}\" that backend/schema does not declare already.`, \"NOT_FOUND\");\n }\n if (!found.descriptor) {\n throw ApiError.badRequest(`\"${schema}\".\"${name}\" cannot be imported: ${found.unimportable ?? \"introspection could not describe it.\"}`, \"SCHEMA_EDIT_REFUSED\", {\n problems: [{ table: name, message: found.unimportable ?? \"introspection could not describe it.\" }]\n });\n }\n return c.json({ table: found });\n });\n\n router.get(\"/tables\", async (c) => c.json({ tables: await editor.describe() }));\n\n router.post(\"/preview\", async (c) => {\n const patches = await patchesOf(c);\n const edit = await refusalsAsBadRequest(() => editor.run(() => editor.preview(patches)));\n return c.json(describeEdit(editor, edit));\n });\n\n router.post(\"/apply\", async (c) => {\n const patches = await patchesOf(c);\n const edit = await refusalsAsBadRequest(() => editor.apply(patches));\n return c.json({ success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wdoGYKu.js","names":[],"sources":["../src/schema-edit/frontend-source-editor.ts","../src/api/frontend-source-routes.ts","../src/api/schema-editor-routes.ts"],"sourcesContent":["import crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Node, Project, ts, type CallExpression, type ObjectLiteralExpression, type SourceFile } from \"ts-morph\";\nimport { printSchemaValue } from \"@rebasepro/common\";\n\nimport { IDENTIFIER, isData, member, memberName, opaqueMembers, printKey, unwrapExpression, literalString, type SchemaEditRefusalCode } from \"../api/table-source-editor\";\nimport { applyEdits, insertListItem, itemText, listShape, removeListItem, replaceNode, type TextEdit } from \"./source-text\";\n\n/**\n * Edits to the object-literal argument of one call in the project's frontend\n * source, from the admin panel, in development.\n *\n * The backend knows nothing about what the call means. A request names a\n * callee (`defineFirestoreCollection`), the key and string value that pick\n * one call out (`slug: \"fs_events\"`), and a list of operations on paths into\n * the call's object argument: set a value, remove a key, rename a key, move a\n * key. What those calls are — a Firestore collection, its fields — is the\n * admin panel's business, which translates its own edits into these.\n *\n * The safety model is the table source editor's ({@link TableSourceEditor}):\n *\n * - **Byte-preserving.** It parses with ts-morph to find positions and writes\n * by splicing printed text at them (`source-text.ts`), so comments, imports,\n * functions, JSX and every key it was not asked to touch stay byte for byte.\n * - **Never executes the wire.** Every value is JSON, printed as a literal\n * (`printSchemaValue`); every key is printed as an identifier only when it\n * is one, quoted otherwise. Nothing a request carries is evaluated, imported\n * or spliced as code.\n * - **Edited in code is left alone.** A value that is not plain data — a\n * function, a component, a variable, a call — is never overwritten; an object\n * that spreads another, or has a computed key, is never written into. The\n * edit is refused with the reason, and {@link FrontendSourceEditor.describe}\n * reports those places so the panel shows them read-only.\n * - **Preview, check, write, roll back.** An edit is applied to a copy of the\n * text, the result parsed and read back (each value set must read back as\n * exactly that value), and only then written — refused if the file changed\n * on disk since the edit read it (the panel's `version`, or another save in\n * between). The optional `check` runs over the written files (a project's\n * own compile); when it fails, every file is restored as it was.\n *\n * @group Schema\n */\nexport class FrontendSourceEditor {\n private settled: Promise<unknown> = Promise.resolve();\n /** The directory searched for calls, absolute: the project's `frontend/src`. */\n readonly sourceDir: string;\n /** The directory paths are reported relative to: the project root. */\n readonly root: string;\n private readonly check?: FrontendSourceCheck;\n\n /**\n * @param sourceDir the directory searched for calls: the project's `frontend/src`\n * @param options.root what paths are reported relative to (default: two levels above `sourceDir`)\n * @param options.check a compile over the written files; problems roll the edit back\n */\n constructor(sourceDir: string, options: { root?: string; check?: FrontendSourceCheck } = {}) {\n this.sourceDir = path.resolve(sourceDir);\n this.root = path.resolve(options.root ?? path.dirname(path.dirname(this.sourceDir)));\n this.check = options.check;\n }\n\n /** Run `work` once every edit queued before it has finished. */\n run<T>(work: () => Promise<T>): Promise<T> {\n const result = this.settled.then(work);\n this.settled = result.then(() => undefined, () => undefined);\n return result;\n }\n\n /**\n * Every call to `callee` in the source directory, picked out by its `key`\n * member, as the editor reads it: its file, its `version`, and where it\n * is edited in code. `lists` names paths into the argument whose members\n * are each reported (`[[\"fields\"]]`: each field, and whether it is an\n * object literal the editor can write).\n */\n describe(callee: string, key: string, lists: readonly (readonly string[])[] = []): FrontendCallSummary[] {\n assertIdentifier(callee, \"callee\");\n const out: FrontendCallSummary[] = [];\n for (const file of sourceFiles(this.sourceDir)) {\n const text = fs.readFileSync(file, \"utf8\");\n if (!text.includes(callee)) continue;\n const source = parse(file, text);\n for (const call of callsTo(source, callee)) {\n const located = locateArgument(call, key);\n if (!located) continue;\n const summary: FrontendCallSummary = {\n value: located.value,\n file: this.relative(file),\n version: versionOf(text),\n members: {}\n };\n if (located.editedInCode) summary.editedInCode = located.editedInCode;\n else if (located.object) {\n for (const list of lists) {\n const reached = reach(located.object, list);\n if (reached.kind === \"code\") {\n summary.members[list.join(\".\")] = reached.reason;\n continue;\n }\n if (reached.kind !== \"object\") continue;\n const opaque = opaqueMembers(reached.object, `\\`${list.join(\".\")}\\``);\n for (const each of reached.object.getProperties()) {\n const name = memberName(each);\n if (name === undefined) continue;\n const where = [...list, name].join(\".\");\n if (opaque) {\n summary.members[where] = opaque;\n continue;\n }\n const value = Node.isPropertyAssignment(each) ? unwrapExpression(each.getInitializer()) : undefined;\n if (!value) summary.members[where] = `\\`${where}\\` is ${Node.isShorthandPropertyAssignment(each) ? \"a variable\" : \"a method\"}.`;\n else if (!Node.isObjectLiteralExpression(value)) summary.members[where] = `\\`${where}\\` is \\`${clip(value.getText())}\\`, not an object written in the call.`;\n else {\n const inner = opaqueMembers(value, `\\`${where}\\``);\n if (inner) summary.members[where] = inner;\n }\n }\n }\n }\n out.push(summary);\n }\n }\n return out;\n }\n\n /**\n * Apply `request` to a copy of its file and read the result back. Writes\n * nothing: the edit is refused (a {@link FrontendSourceEditError}) or\n * returned, with the file it changes.\n */\n async preview(request: FrontendSourceEditRequest): Promise<FrontendSourceEdit> {\n const { target } = request;\n const found = this.locate(target);\n if (request.version !== undefined && request.version !== versionOf(found.text)) {\n throw new FrontendSourceEditError(\"SCHEMA_EDIT_STALE_FILE\",\n `${this.relative(found.file)} changed since the edit was prepared (it was saved by something else meanwhile). ` +\n \"Nothing was written: reload, and make the edit again against the file as it is now.\",\n [{ table: target.value, message: \"The file changed on disk.\" }]);\n }\n let text = found.text;\n for (const [index, operation] of request.operations.entries()) {\n try {\n text = applyOperation(found.file, text, target, operation);\n } catch (error) {\n throw asRefusal(error, index, operation, target);\n }\n }\n if (text === found.text) {\n throw new FrontendSourceEditError(\"SCHEMA_EDIT_REFUSED\", `The edit changes nothing in ${this.relative(found.file)}.`, []);\n }\n verify(found.file, text, target, request.operations);\n return { files: [{ path: found.file, contents: text, before: found.text }] };\n }\n\n /** {@link preview}, then write, check and — when the check fails — roll back. Queued behind every other edit. */\n apply(request: FrontendSourceEditRequest): Promise<FrontendSourceEdit> {\n return this.run(async () => {\n const edit = await this.preview(request);\n await this.write(edit);\n return edit;\n });\n }\n\n /**\n * Write a previewed edit, refusing when a file changed on disk since the\n * preview read it. A file that does not read back as written, a failure\n * on the way, or a `check` that reports problems restores every file as\n * it was before the write.\n */\n async write(edit: FrontendSourceEdit): Promise<void> {\n for (const file of edit.files) {\n const now = fs.existsSync(file.path) ? fs.readFileSync(file.path, \"utf8\") : undefined;\n if (now !== file.before) {\n throw new FrontendSourceEditError(\"SCHEMA_EDIT_STALE_FILE\",\n `${this.relative(file.path)} changed since the edit was prepared (it was saved by something else meanwhile). ` +\n \"Nothing was written: reload, and make the edit again against the file as it is now.\", []);\n }\n }\n const written: FrontendSourceFile[] = [];\n try {\n for (const file of edit.files) {\n await writeWhole(file.path, file.contents);\n written.push(file);\n if (fs.readFileSync(file.path, \"utf8\") !== file.contents) throw new Error(`${file.path} does not read back as written.`);\n }\n const problems = this.check ? await this.check(edit.files) : [];\n if (problems.length > 0) {\n throw new FrontendSourceEditError(\"SCHEMA_EDIT_DOES_NOT_COMPILE\",\n `The edit was not kept: it does not compile. ${problems.map(problem => problem.message).join(\" \")}`, problems);\n }\n } catch (error) {\n for (const file of written.reverse()) {\n if (file.before === undefined) await fsp.rm(file.path, { force: true });\n else await writeWhole(file.path, file.before);\n }\n throw error;\n }\n }\n\n /** A path as the panel reads it: relative to the project root, with forward slashes. */\n relative(file: string): string {\n return path.relative(this.root, file).split(path.sep).join(\"/\");\n }\n\n /** The one call `target` names, or a refusal. */\n private locate(target: FrontendCallTarget): { file: string; text: string } {\n const found: { file: string; text: string }[] = [];\n for (const file of sourceFiles(this.sourceDir)) {\n const text = fs.readFileSync(file, \"utf8\");\n if (!text.includes(target.callee)) continue;\n const source = parse(file, text);\n for (const call of callsTo(source, target.callee)) {\n if (locateArgument(call, target.key)?.value === target.value) found.push({ file, text });\n }\n }\n if (found.length === 0) {\n throw refusal(\n `No \\`${target.callee}({ ${target.key}: ${JSON.stringify(target.value)}, … })\\` in ${this.relative(this.sourceDir) || \".\"}. ` +\n `If it is built by a helper or its \\`${target.key}\\` is not a string written in the call, it is edited in code.`,\n target.value\n );\n }\n if (found.length > 1) {\n throw refusal(\n `More than one \\`${target.callee}\\` call has \\`${target.key}: ${JSON.stringify(target.value)}\\` ` +\n `(${found.map(each => this.relative(each.file)).join(\", \")}): edit it in code.`,\n target.value\n );\n }\n return found[0];\n }\n}\n\n/**\n * A check over the files an edit wrote, with the edit on disk: a project's\n * own compile. Problems roll the edit back.\n *\n * @group Schema\n */\nexport type FrontendSourceCheck = (files: readonly FrontendSourceFile[]) => Promise<FrontendSourceProblem[]>;\n\n/**\n * JSON, the only thing a frontend source edit writes as a value.\n *\n * @group Schema\n */\nexport type FrontendSourceValue = null | boolean | number | string | FrontendSourceValue[] | { [key: string]: FrontendSourceValue };\n\n/**\n * One operation on the object argument of a call, at a path of keys into it.\n *\n * - `set` — write `value` at `path`, replacing what is there (which must be\n * plain data) or inserting it (before the member `before`, else last),\n * creating the objects on the way that do not exist yet.\n * - `remove` — remove the key at `path`; nothing when it is absent. With\n * `prune`, an object the removal leaves empty is removed too.\n * - `rename` — give the key at `path` the name `to`; its value is untouched.\n * - `move` — move the key at `path` before its sibling `before`, else last.\n *\n * @group Schema\n */\nexport type FrontendSourceOperation =\n | { op: \"set\"; path: string[]; value: FrontendSourceValue; before?: string }\n | { op: \"remove\"; path: string[]; prune?: boolean }\n | { op: \"rename\"; path: string[]; to: string }\n | { op: \"move\"; path: string[]; before?: string };\n\n/**\n * Which call an edit is about: the call to `callee` whose object argument has\n * the member `key` written as the string `value`.\n *\n * @group Schema\n */\nexport interface FrontendCallTarget {\n callee: string;\n key: string;\n value: string;\n}\n\n/**\n * A frontend source edit, as `POST /api/admin/schema-editor/frontend/apply`\n * takes it.\n *\n * @group Schema\n */\nexport interface FrontendSourceEditRequest {\n target: FrontendCallTarget;\n /** The file's `version` as the panel read it; a different file is refused as stale. */\n version?: string;\n operations: FrontendSourceOperation[];\n}\n\n/**\n * One file an edit changes.\n *\n * @group Schema\n */\nexport interface FrontendSourceFile {\n /** Absolute path. */\n path: string;\n /** The new text. */\n contents: string;\n /** The text the edit was made against. */\n before?: string;\n}\n\n/**\n * An edit, applied to a copy and read back.\n *\n * @group Schema\n */\nexport interface FrontendSourceEdit {\n files: FrontendSourceFile[];\n}\n\n/**\n * How the editor reads one call.\n *\n * @group Schema\n */\nexport interface FrontendCallSummary {\n /** The value of the key it was picked out by (a collection's slug). */\n value: string;\n /** Its file, relative to the project root. */\n file: string;\n /** A hash of the file's text: sent back with an edit, a changed file is refused. */\n version: string;\n /** Why the whole call is read-only, when it is. */\n editedInCode?: string;\n /** Why a member of a listed path is read-only, by dotted path (`fields.customerId`). */\n members: Record<string, string>;\n}\n\n/**\n * What is wrong with an edit. `table` names the call by the value it was\n * picked out by — the shape the panel reads every schema-edit problem in.\n *\n * @group Schema\n */\nexport interface FrontendSourceProblem {\n table: string;\n /** The dotted path, when there is one. */\n key?: string;\n message: string;\n}\n\n/**\n * An edit the frontend source editor will not make. Nothing was written (or\n * what was written was restored). The codes are the table editor's\n * ({@link SchemaEditRefusalCode}) — a file changed on disk since the panel\n * read it is `SCHEMA_EDIT_STALE_FILE` — and `INVALID_INPUT`.\n *\n * @group Schema\n */\nexport class FrontendSourceEditError extends Error {\n constructor(\n readonly code: SchemaEditRefusalCode | \"INVALID_INPUT\",\n message: string,\n readonly problems: readonly FrontendSourceProblem[]\n ) {\n super(message);\n this.name = \"FrontendSourceEditError\";\n }\n}\n\n// ── The wire ────────────────────────────────────────────────────────────────\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nfunction isValue(value: unknown, depth = 0): value is FrontendSourceValue {\n if (depth > 32) return false;\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") return true;\n if (typeof value === \"number\") return Number.isFinite(value);\n if (Array.isArray(value)) return value.every(item => isValue(item, depth + 1));\n if (isRecord(value) && Object.getPrototypeOf(value) === Object.prototype) {\n return Object.values(value).every(item => isValue(item, depth + 1));\n }\n return false;\n}\n\nconst isKeyPath = (value: unknown): value is string[] =>\n Array.isArray(value) && value.length > 0 && value.every(segment => typeof segment === \"string\" && segment.length > 0);\n\nfunction assertIdentifier(value: string, what: string): void {\n if (!IDENTIFIER.test(value)) throw new FrontendSourceEditError(\"INVALID_INPUT\", `\\`${what}\\` must be an identifier, not ${JSON.stringify(value)}.`, []);\n}\n\n/**\n * The edit a request body describes, or an `INVALID_INPUT` refusal naming\n * every problem. Values must be JSON; the callee an identifier; paths\n * non-empty lists of keys.\n *\n * @group Schema\n */\nexport function parseFrontendSourceEdit(body: unknown): FrontendSourceEditRequest {\n const problems: string[] = [];\n if (!isRecord(body)) throw new FrontendSourceEditError(\"INVALID_INPUT\", \"Expected `{ target, operations }`.\", []);\n const target = body.target;\n if (!isRecord(target) || typeof target.callee !== \"string\" || typeof target.key !== \"string\" || typeof target.value !== \"string\") {\n problems.push(\"`target` must be `{ callee, key, value }`, three strings.\");\n } else if (!IDENTIFIER.test(target.callee)) {\n problems.push(`\\`target.callee\\` must be an identifier, not ${JSON.stringify(target.callee)}.`);\n }\n if (body.version !== undefined && typeof body.version !== \"string\") problems.push(\"`version` must be a string.\");\n const operations: FrontendSourceOperation[] = [];\n if (!Array.isArray(body.operations) || body.operations.length === 0) {\n problems.push(\"`operations` must be a non-empty list.\");\n } else {\n body.operations.forEach((operation: unknown, index) => {\n const where = `operations[${index}]`;\n if (!isRecord(operation) || !isKeyPath(operation.path)) {\n problems.push(`${where} needs a \\`path\\`: a non-empty list of keys.`);\n return;\n }\n const before = operation.before;\n if (before !== undefined && typeof before !== \"string\") {\n problems.push(`${where}.before must be a key.`);\n return;\n }\n switch (operation.op) {\n case \"set\":\n if (!(\"value\" in operation) || !isValue(operation.value)) {\n problems.push(`${where}.value must be JSON: strings, finite numbers, booleans, null, arrays and plain objects.`);\n return;\n }\n operations.push({ op: \"set\", path: operation.path, value: operation.value, ...(before !== undefined ? { before } : {}) });\n return;\n case \"remove\":\n operations.push({ op: \"remove\", path: operation.path, ...(operation.prune === true ? { prune: true } : {}) });\n return;\n case \"rename\":\n if (typeof operation.to !== \"string\" || operation.to.length === 0) {\n problems.push(`${where}.to must be a key.`);\n return;\n }\n operations.push({ op: \"rename\", path: operation.path, to: operation.to });\n return;\n case \"move\":\n operations.push({ op: \"move\", path: operation.path, ...(before !== undefined ? { before } : {}) });\n return;\n default:\n problems.push(`${where}.op must be one of set, remove, rename, move.`);\n }\n });\n }\n if (problems.length > 0 || !isRecord(target)) {\n throw new FrontendSourceEditError(\"INVALID_INPUT\", `The frontend source edit is not well formed: ${problems.join(\" \")}`,\n problems.map(message => ({ table: \"\", message })));\n }\n return {\n target: { callee: String(target.callee), key: String(target.key), value: String(target.value) },\n ...(typeof body.version === \"string\" ? { version: body.version } : {}),\n operations\n };\n}\n\n// ── Reading ─────────────────────────────────────────────────────────────────\n\nconst SOURCE_EXTENSIONS = [\".ts\", \".tsx\", \".mts\", \".js\", \".jsx\", \".mjs\"];\n\n/** The module files of the frontend source, in path order. */\nfunction sourceFiles(dir: string): string[] {\n const out: string[] = [];\n if (!fs.existsSync(dir)) return out;\n const walk = (current: string): void => {\n for (const entry of fs.readdirSync(current, { withFileTypes: true })) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\" || entry.name === \"__tests__\") continue;\n const full = path.join(current, entry.name);\n if (entry.isDirectory()) walk(full);\n else if (entry.isFile() && SOURCE_EXTENSIONS.some(ext => entry.name.endsWith(ext))\n && !/\\.d\\.[mc]?ts$/.test(entry.name) && !/\\.(test|spec)\\./.test(entry.name)) {\n out.push(full);\n }\n }\n };\n walk(dir);\n return out.sort();\n}\n\n/** The text of a file parsed on its own, JSX by its extension. */\nfunction parse(file: string, text: string): SourceFile {\n const project = new Project({ useInMemoryFileSystem: true, compilerOptions: { allowJs: true, noLib: true, jsx: ts.JsxEmit.Preserve } });\n return project.createSourceFile(file, text, { overwrite: true });\n}\n\n/** The syntax errors of a text, as messages. */\nfunction syntaxErrors(file: string, text: string): string[] {\n const result = ts.transpileModule(text, {\n fileName: file,\n reportDiagnostics: true,\n compilerOptions: { jsx: ts.JsxEmit.Preserve, target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext }\n });\n return (result.diagnostics ?? []).map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, \"\\n\"));\n}\n\n/** Every call whose callee ends in `callee`: `defineX(…)`, `lib.defineX(…)`. */\nfunction callsTo(source: SourceFile, callee: string): CallExpression[] {\n return source.getDescendants().filter((node): node is CallExpression => {\n if (!Node.isCallExpression(node)) return false;\n const expression = node.getExpression();\n if (Node.isIdentifier(expression)) return expression.getText() === callee;\n return Node.isPropertyAccessExpression(expression) && expression.getName() === callee;\n });\n}\n\n/** The call's object argument, picked out by its `key` member, and whether it can be written. */\nfunction locateArgument(call: CallExpression, key: string): { value: string; object?: ObjectLiteralExpression; editedInCode?: string } | undefined {\n const argument = unwrapExpression(call.getArguments()[0]);\n if (!argument || !Node.isObjectLiteralExpression(argument)) return undefined;\n const found = member(argument, key, \"the call's argument\");\n if (found.kind !== \"written\") return undefined;\n const value = literalString(unwrapExpression(found.value));\n if (value === undefined) return undefined;\n const opaque = opaqueMembers(argument, \"its argument\");\n return opaque ? { value, editedInCode: opaque } : { value, object: argument };\n}\n\ntype Reached =\n | { kind: \"object\"; object: ObjectLiteralExpression }\n | { kind: \"absent\"; object: ObjectLiteralExpression; depth: number }\n | { kind: \"code\"; reason: string };\n\n/** Walk `keys` down from `root` through object literals written in place. */\nfunction reach(root: ObjectLiteralExpression, keys: readonly string[]): Reached {\n let object = root;\n for (const [depth, key] of keys.entries()) {\n const where = keys.slice(0, depth + 1).join(\".\");\n const found = member(object, key, `\\`${keys.slice(0, depth).join(\".\") || \"the argument\"}\\``);\n if (found.kind === \"absent\") return { kind: \"absent\", object, depth };\n if (found.kind === \"code\") return { kind: \"code\", reason: found.reason };\n const value = unwrapExpression(found.value);\n if (!value || !Node.isObjectLiteralExpression(value)) {\n return { kind: \"code\", reason: `\\`${where}\\` is \\`${clip(found.value.getText())}\\`, not an object written in the call.` };\n }\n const opaque = opaqueMembers(value, `\\`${where}\\``);\n if (opaque) return { kind: \"code\", reason: opaque };\n object = value;\n }\n return { kind: \"object\", object };\n}\n\nconst clip = (text: string): string => (text.length > 40 ? `${text.slice(0, 40)}…` : text);\n\n/**\n * The version of a file's text the panel sends back with an edit: a short\n * hash, so a file changed since the panel read it is refused as stale.\n *\n * @group Schema\n */\nexport function versionOf(text: string): string {\n return crypto.createHash(\"sha256\").update(text).digest(\"hex\").slice(0, 16);\n}\n\n/** The JSON a plain-data literal denotes; `undefined` for anything else. */\nfunction literalValue(node: Node | undefined): FrontendSourceValue | undefined {\n const value = unwrapExpression(node);\n if (!value) return undefined;\n if (Node.isStringLiteral(value) || Node.isNoSubstitutionTemplateLiteral(value)) return value.getLiteralValue();\n if (Node.isNumericLiteral(value)) return value.getLiteralValue();\n if (Node.isTrueLiteral(value)) return true;\n if (Node.isFalseLiteral(value)) return false;\n if (Node.isNullLiteral(value)) return null;\n if (Node.isPrefixUnaryExpression(value) && value.getOperatorToken() === ts.SyntaxKind.MinusToken) {\n const operand = value.getOperand();\n return Node.isNumericLiteral(operand) ? -operand.getLiteralValue() : undefined;\n }\n if (Node.isArrayLiteralExpression(value)) {\n const items: FrontendSourceValue[] = [];\n for (const element of value.getElements()) {\n const item = literalValue(element);\n if (item === undefined) return undefined;\n items.push(item);\n }\n return items;\n }\n if (Node.isObjectLiteralExpression(value)) {\n const out: { [key: string]: FrontendSourceValue } = {};\n for (const each of value.getProperties()) {\n const name = memberName(each);\n if (name === undefined || !Node.isPropertyAssignment(each)) return undefined;\n const item = literalValue(each.getInitializer());\n if (item === undefined) return undefined;\n out[name] = item;\n }\n return out;\n }\n return undefined;\n}\n\nfunction sameJson(a: FrontendSourceValue | undefined, b: FrontendSourceValue | undefined): boolean {\n if (a === b) return true;\n if (Array.isArray(a) || Array.isArray(b)) {\n return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, index) => sameJson(item, b[index]));\n }\n if (a === null || b === null || typeof a !== \"object\" || typeof b !== \"object\") return false;\n const keys = Object.keys(a);\n return keys.length === Object.keys(b).length && keys.every(key => key in b && sameJson(a[key], b[key]));\n}\n\n// ── Writing ─────────────────────────────────────────────────────────────────\n\nfunction refusal(message: string, table: string, key?: string): FrontendSourceEditError {\n return new FrontendSourceEditError(\"SCHEMA_EDIT_REFUSED\", message, [{ table, ...(key !== undefined ? { key } : {}), message }]);\n}\n\nfunction asRefusal(error: unknown, index: number, operation: FrontendSourceOperation, target: FrontendCallTarget): FrontendSourceEditError {\n if (error instanceof FrontendSourceEditError) return error;\n const message = error instanceof Error ? error.message : String(error);\n return refusal(`Edit ${index} (${operation.op} \\`${operation.path.join(\".\")}\\` of \"${target.value}\"): ${message}`, target.value, operation.path.join(\".\"));\n}\n\n/** The writable argument of the target call in `text`. */\nfunction argumentIn(file: string, text: string, target: FrontendCallTarget): ObjectLiteralExpression {\n const source = parse(file, text);\n for (const call of callsTo(source, target.callee)) {\n const located = locateArgument(call, target.key);\n if (located?.value !== target.value) continue;\n if (!located.object) throw refusal(`\"${target.value}\" is edited in code: ${located.editedInCode}`, target.value);\n return located.object;\n }\n throw refusal(`The call for \"${target.value}\" is no longer in ${path.basename(file)}.`, target.value);\n}\n\n/** The object holding the last key of `keys`, which must exist and be writable. */\nfunction parentOf(root: ObjectLiteralExpression, keys: readonly string[], target: FrontendCallTarget): ObjectLiteralExpression {\n const reached = reach(root, keys.slice(0, -1));\n const where = keys.join(\".\");\n if (reached.kind === \"code\") throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: ${reached.reason}`, target.value, where);\n if (reached.kind === \"absent\") throw refusal(`\"${target.value}\" has no \\`${keys.slice(0, reached.depth + 1).join(\".\")}\\`.`, target.value, where);\n const opaque = opaqueMembers(reached.object, `\\`${keys.slice(0, -1).join(\".\") || \"the argument\"}\\``);\n if (opaque) throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: ${opaque}`, target.value, where);\n return reached.object;\n}\n\n/** `value` nested under `keys`: `{ a: { b: value } }` for `[\"a\", \"b\"]`. */\nfunction nestedValue(keys: readonly string[], value: FrontendSourceValue): FrontendSourceValue {\n return keys.reduceRight<FrontendSourceValue>((inner, key) => ({ [key]: inner }), value);\n}\n\nfunction printed(value: FrontendSourceValue, where: string): string {\n return printSchemaValue(value, where);\n}\n\nfunction applyOperation(file: string, text: string, target: FrontendCallTarget, operation: FrontendSourceOperation): string {\n const root = argumentIn(file, text, target);\n const keys = operation.path;\n const where = keys.join(\".\");\n if (keys.length === 1 && keys[0] === target.key && operation.op !== \"set\") {\n throw refusal(`\\`${target.key}\\` is what the call is found by: it cannot be ${operation.op === \"remove\" ? \"removed\" : operation.op === \"rename\" ? \"renamed\" : \"moved\"}.`, target.value, where);\n }\n switch (operation.op) {\n case \"set\": {\n if (keys.length === 1 && keys[0] === target.key && operation.value !== target.value) {\n throw refusal(`\\`${target.key}\\` is what the call is found by, and other code refers to it: change it in code.`, target.value, where);\n }\n const reached = reach(root, keys.slice(0, -1));\n if (reached.kind === \"code\") throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: ${reached.reason}`, target.value, where);\n if (reached.kind === \"absent\") {\n // Create the objects on the way: insert the first missing key with the rest nested in it.\n const missing = keys.slice(reached.depth);\n return insertMember(text, reached.object, missing[0], nestedValue(missing.slice(1), operation.value), `${target.value}.${where}`,\n reached.depth === keys.length - 1 ? operation.before : undefined, target);\n }\n const object = reached.object;\n const last = keys[keys.length - 1];\n const found = member(object, last, `\\`${keys.slice(0, -1).join(\".\") || \"the argument\"}\\``);\n if (found.kind === \"code\") throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: ${found.reason}`, target.value, where);\n if (found.kind === \"absent\") return insertMember(text, object, last, operation.value, `${target.value}.${where}`, operation.before, target);\n if (!isData(found.value)) {\n throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: it is \\`${clip(found.value.getText())}\\`, not plain data.`, target.value, where);\n }\n return applyEdits(text, [replaceNode(text, found.value, printed(operation.value, `${target.value}.${where}`))]);\n }\n case \"remove\": {\n const reached = reach(root, keys.slice(0, -1));\n if (reached.kind === \"absent\") return text;\n if (reached.kind === \"code\") throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: ${reached.reason}`, target.value, where);\n const object = reached.object;\n const found = member(object, keys[keys.length - 1], `\\`${keys.slice(0, -1).join(\".\") || \"the argument\"}\\``);\n if (found.kind === \"absent\") return text;\n if (found.kind === \"code\") throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: ${found.reason}`, target.value, where);\n const value = unwrapExpression(found.value);\n if (!value || !(isData(value) || Node.isObjectLiteralExpression(value))) {\n throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: it is \\`${clip(found.value.getText())}\\`.`, target.value, where);\n }\n const next = applyEdits(text, removeListItem(text, listShape(object, object.getProperties()), found.index));\n if (operation.prune && keys.length > 1 && object.getProperties().length === 1) {\n return applyOperation(file, next, target, { op: \"remove\", path: keys.slice(0, -1), prune: true });\n }\n return next;\n }\n case \"rename\": {\n const object = parentOf(root, keys, target);\n const last = keys[keys.length - 1];\n const found = member(object, last, `\\`${keys.slice(0, -1).join(\".\") || \"the argument\"}\\``);\n if (found.kind === \"absent\") throw refusal(`\"${target.value}\" has no \\`${where}\\`.`, target.value, where);\n if (found.kind === \"code\") throw refusal(`\\`${where}\\` of \"${target.value}\" is edited in code: ${found.reason}`, target.value, where);\n if (operation.to === last) return text;\n if (member(object, operation.to, \"it\").kind !== \"absent\") {\n throw refusal(`\"${target.value}\" already has \\`${[...keys.slice(0, -1), operation.to].join(\".\")}\\`.`, target.value, where);\n }\n const assignment = found.node;\n if (!Node.isPropertyAssignment(assignment)) throw refusal(`\\`${where}\\` is not written as \\`key: value\\`.`, target.value, where);\n const nameNode = assignment.getNameNode();\n return applyEdits(text, [{ start: nameNode.getStart(), end: nameNode.getEnd(), text: printKey(operation.to) }]);\n }\n case \"move\": {\n const object = parentOf(root, keys, target);\n const last = keys[keys.length - 1];\n const found = member(object, last, \"it\");\n if (found.kind !== \"written\") throw refusal(`\"${target.value}\" has no \\`${where}\\` written in the call.`, target.value, where);\n if (operation.before === last) return text;\n if (operation.before !== undefined && member(object, operation.before, \"it\").kind !== \"written\") {\n throw refusal(`\"${target.value}\" has no \\`${[...keys.slice(0, -1), operation.before].join(\".\")}\\` to move before.`, target.value, where);\n }\n const moved = itemText(text, listShape(object, object.getProperties()), found.index);\n const removed = applyEdits(text, removeListItem(text, listShape(object, object.getProperties()), found.index));\n const again = parentOf(argumentIn(file, removed, target), keys, target);\n const members = again.getProperties();\n const index = operation.before !== undefined ? members.findIndex(each => memberName(each) === operation.before) : members.length;\n return applyEdits(removed, insertListItem(removed, listShape(again, members), index, moved, \"lines\"));\n }\n }\n}\n\nfunction insertMember(\n text: string,\n object: ObjectLiteralExpression,\n key: string,\n value: FrontendSourceValue,\n where: string,\n before: string | undefined,\n target: FrontendCallTarget\n): string {\n const members = object.getProperties();\n let index = members.length;\n if (before !== undefined) {\n index = members.findIndex(each => memberName(each) === before);\n if (index === -1) throw refusal(`There is no \\`${before}\\` to insert \\`${key}\\` before.`, target.value, where);\n }\n const edits: TextEdit[] = insertListItem(text, listShape(object, members), index, `${printKey(key)}: ${printed(value, where)}`, \"lines\");\n return applyEdits(text, edits);\n}\n\n/** The edited text parses, and every value set reads back as that value; every key removed is gone. */\nfunction verify(file: string, text: string, target: FrontendCallTarget, operations: readonly FrontendSourceOperation[]): void {\n const errors = syntaxErrors(file, text);\n if (errors.length > 0) {\n throw new FrontendSourceEditError(\"SCHEMA_EDIT_DOES_NOT_COMPILE\",\n `The edit was not written: ${path.basename(file)} would not parse: ${errors.join(\" \")}`,\n errors.map(message => ({ table: target.value, message })));\n }\n const root = argumentIn(file, text, target);\n const expected = new Map<string, { path: string[]; value?: FrontendSourceValue }>();\n for (const operation of operations) {\n if (operation.op === \"set\") expected.set(operation.path.join(\"\\u0000\"), { path: operation.path, value: operation.value });\n else if (operation.op === \"remove\") expected.set(operation.path.join(\"\\u0000\"), { path: operation.path });\n else if (operation.op === \"rename\") {\n // What was set under the old key is now under the new one.\n const from = operation.path;\n const to = [...from.slice(0, -1), operation.to];\n for (const [id, entry] of [...expected]) {\n if (entry.path.length < from.length || !from.every((key, index) => entry.path[index] === key)) continue;\n expected.delete(id);\n const moved = [...to, ...entry.path.slice(from.length)];\n expected.set(moved.join(\"\\u0000\"), { ...entry, path: moved });\n }\n }\n }\n for (const { path: keys, value } of expected.values()) {\n const reached = reach(root, keys.slice(0, -1));\n const where = keys.join(\".\");\n const found = reached.kind === \"object\" ? member(reached.object, keys[keys.length - 1], \"it\") : undefined;\n if (value === undefined) {\n if (found?.kind === \"written\") throw refusal(`\\`${where}\\` is still there after the edit removed it.`, target.value, where);\n continue;\n }\n const read = found?.kind === \"written\" ? literalValue(found.value) : undefined;\n if (!sameJson(read, value)) throw refusal(`\\`${where}\\` does not read back as the value written.`, target.value, where);\n }\n}\n\nasync function writeWhole(file: string, contents: string): Promise<void> {\n await fsp.writeFile(file, contents, \"utf8\");\n}\n\n/**\n * Where a project keeps its frontend source: `<project root>/frontend/src`.\n *\n * @group Schema\n */\nexport function frontendSourceDirOf(projectRoot: string): string {\n return path.join(projectRoot, \"frontend\", \"src\");\n}\n","import { Hono } from \"hono\";\nimport path from \"node:path\";\nimport {\n FrontendSourceEditError,\n FrontendSourceEditor,\n frontendSourceDirOf,\n parseFrontendSourceEdit,\n type FrontendSourceEdit\n} from \"../schema-edit/frontend-source-editor\";\nimport { findProjectRoot } from \"../schema-edit/project-root\";\nimport { ApiError, errorHandler } from \"./errors\";\nimport { HonoEnv } from \"./types\";\n\n/**\n * Editing the project's frontend source from the admin panel, in\n * development: `/api/admin/schema-editor/frontend/*`, mounted inside the\n * source-only schema editor, so behind the same gate (`schema:read` to read,\n * `schema:write` to write) and present exactly where that editor is — a\n * `schemaDir` on disk, `schemaEditor` not false, never under\n * `NODE_ENV=production` unless the server opted in.\n *\n * It edits the object argument of one call in `frontend/src` — the admin\n * panel uses it for the `defineFirestoreCollection({...})` calls of a hybrid\n * project — and knows nothing about what the call means:\n *\n * - `GET /calls?callee=<identifier>&key=<key>&list=<dotted path>…` — every\n * call to `callee` picked out by its `key` member, with its file, version\n * and what is edited in code.\n * - `POST /preview` `{ target, version?, operations }` — the file the edit\n * would write; nothing is written.\n * - `POST /apply` — the same, written.\n *\n * Refusals carry the problems in `details.problems`, in the codes the table\n * routes use: 400 `SCHEMA_EDIT_REFUSED`, `SCHEMA_EDIT_DOES_NOT_COMPILE`,\n * `INVALID_INPUT`, and 409 `SCHEMA_EDIT_STALE_FILE` for a file changed on disk\n * since the panel read it.\n */\n\n/** The process's frontend source editor for the project `schemaDir` belongs to. */\nexport function createFrontendSourceEditor(schemaDir: string): FrontendSourceEditor {\n const root = findProjectRoot(schemaDir) ?? path.dirname(path.dirname(path.resolve(schemaDir)));\n return new FrontendSourceEditor(frontendSourceDirOf(root), { root });\n}\n\n/** A refusal as the answer that carries it: 409 for a file changed on disk since it was read, 400 otherwise. */\nfunction refusalsAsBadRequest<T>(run: () => Promise<T>): Promise<T> {\n return run().catch((error: unknown) => {\n if (error instanceof FrontendSourceEditError) {\n throw new ApiError(error.code === \"SCHEMA_EDIT_STALE_FILE\" ? 409 : 400, error.code, error.message, { problems: error.problems });\n }\n throw error;\n });\n}\n\nasync function requestOf(c: { req: { json: () => Promise<unknown> } }) {\n const body: unknown = await c.req.json().catch(() => undefined);\n try {\n return parseFrontendSourceEdit(body);\n } catch (error) {\n if (error instanceof FrontendSourceEditError) throw ApiError.badRequest(error.message, error.code, { problems: error.problems });\n throw error;\n }\n}\n\nfunction describeEdit(editor: FrontendSourceEditor, edit: FrontendSourceEdit) {\n return { files: edit.files.map(file => ({ path: editor.relative(file.path), contents: file.contents })) };\n}\n\n/** The frontend source editor's routes, over one editor. */\nexport function createFrontendSourceRoutes(editor: FrontendSourceEditor): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n router.onError(errorHandler);\n\n router.get(\"/calls\", async (c) => {\n const callee = c.req.query(\"callee\");\n const key = c.req.query(\"key\");\n if (!callee || !key) throw ApiError.badRequest(\"Expected `?callee=<identifier>&key=<key>`.\", \"INVALID_INPUT\");\n const lists = (c.req.queries(\"list\") ?? []).filter(list => list.length > 0).map(list => list.split(\".\"));\n const calls = await refusalsAsBadRequest(async () => editor.describe(callee, key, lists));\n return c.json({ calls });\n });\n\n router.post(\"/preview\", async (c) => {\n const request = await requestOf(c);\n const edit = await refusalsAsBadRequest(() => editor.run(() => editor.preview(request)));\n return c.json(describeEdit(editor, edit));\n });\n\n router.post(\"/apply\", async (c) => {\n const request = await requestOf(c);\n const edit = await refusalsAsBadRequest(() => editor.apply(request));\n return c.json({ success: true, ...describeEdit(editor, edit) });\n });\n\n return router;\n}\n","import { Hono } from \"hono\";\nimport path from \"node:path\";\nimport { TablePatchError, parseTablePatches, type DatabaseAdmin, type TablePatch, type UnmappedTable } from \"@rebasepro/types\";\nimport { TableSourceEditError, TableSourceEditor, type TableSourceEdit } from \"./table-source-editor\";\nimport { ApiError, errorHandler } from \"./errors\";\nimport { createFrontendSourceEditor, createFrontendSourceRoutes } from \"./frontend-source-routes\";\nimport { HonoEnv } from \"./types\";\n\n/**\n * Editing `backend/schema` from the Studio, on this machine, without touching\n * the database: `/api/admin/schema-editor/*`.\n *\n * - `GET /tables` — every table the index exports as the editor reads it,\n * with what is edited in code (read-only) and why.\n * - `POST /preview` `{ patches }` — the files the edit would write, compiled;\n * nothing is written.\n * - `POST /apply` `{ patches }` — the same, written to disk.\n * - `GET /unmapped-tables` — the database's tables no declared table maps\n * (\"Import an existing table\"): `{ tables: [{ schema, table, rlsEnabled,\n * policies, unimportable? }] }`.\n * - `GET /unmapped-tables/:schema/:table` — one of them as introspection\n * describes it, `{ table: { …, descriptor, rlsRaised?, notes } }`: the\n * `TableDescriptor` an `adoptTable` edit writes as its source. Its `rls` is\n * never weaker than what the database enforces — with row-level security\n * off or no policy it is `\"admin-only\"`, and `rlsRaised` says so.\n *\n * Every refusal says what to do, with the problems in `details.problems`: a\n * 400 for an edit the editor will not make (`SCHEMA_EDIT_REFUSED`), one whose\n * result does not compile (`SCHEMA_EDIT_DOES_NOT_COMPILE`) or a list of edits\n * that is not well formed (`INVALID_INPUT`), and a 409 when a file the edit\n * rewrites changed on disk since it was read (`SCHEMA_EDIT_STALE_FILE`).\n * Nothing is written on any of them.\n *\n * Changing the database is live schema editing's job (`/api/admin/schema`),\n * which commits the same edits and runs the DDL.\n *\n * `/frontend/*` edits the project's frontend source the same way — the\n * object argument of one call in `frontend/src`, which the admin panel uses\n * for its Firestore collections — under the same gate\n * (see `frontend-source-routes.ts`).\n */\n\n/** The process's one editor of `schemaDir`, shared with live schema editing. */\nexport function createTableSourceEditor(schemaDir: string): TableSourceEditor {\n return new TableSourceEditor(schemaDir);\n}\n\n/** The `{ patches }` of a request, or a 400 naming every problem. */\nasync function patchesOf(c: { req: { json: () => Promise<unknown> } }): Promise<TablePatch[]> {\n const body: unknown = await c.req.json().catch(() => undefined);\n if (typeof body !== \"object\" || body === null || !(\"patches\" in body)) {\n throw ApiError.badRequest(\"Expected `{ patches: [...] }`: the schema edits to make.\", \"INVALID_INPUT\");\n }\n try {\n return parseTablePatches(body.patches);\n } catch (error) {\n if (error instanceof TablePatchError) throw ApiError.badRequest(error.message, \"INVALID_INPUT\", { problems: error.problems });\n throw error;\n }\n}\n\n/** An edit, as the panel reads it: each file by its path in the project, with its new text. */\nfunction describeEdit(editor: TableSourceEditor, edit: TableSourceEdit) {\n const root = path.dirname(path.dirname(editor.schemaDir));\n return {\n files: edit.files.map(file => ({\n path: path.relative(root, file.path).split(path.sep).join(\"/\"),\n ...(file.deleted ? { deleted: true } : { contents: file.contents })\n })),\n tables: edit.schema.descriptors.map(descriptor => descriptor.slug)\n };\n}\n\n/** The editor's refusal, as the answer that carries its reason and its problems: 409 for a stale file, 400 otherwise. */\nfunction refusalsAsBadRequest<T>(run: () => Promise<T>): Promise<T> {\n return run().catch((error: unknown) => {\n if (error instanceof TableSourceEditError) {\n throw new ApiError(error.code === \"SCHEMA_EDIT_STALE_FILE\" ? 409 : 400, error.code, error.message, { problems: error.problems });\n }\n throw error;\n });\n}\n\n/** What the schema editor's routes read besides the editor. */\nexport interface SchemaEditorRoutesOptions {\n /** The default database's admin, read at request time: what describes the tables \"Import an existing table\" offers. */\n getAdmin?: () => DatabaseAdmin | undefined;\n}\n\n/** A table as the import list shows it: everything but its description. */\nfunction summaryOf(table: UnmappedTable): Omit<UnmappedTable, \"descriptor\" | \"notes\" | \"rlsRaised\"> {\n return {\n schema: table.schema,\n table: table.table,\n rlsEnabled: table.rlsEnabled,\n policies: table.policies,\n ...(table.unimportable ? { unimportable: table.unimportable } : {})\n };\n}\n\n/**\n * The tables of the database no table of `backend/schema` maps, described,\n * with each `belongsTo` naming its target by the declared table's slug.\n */\nasync function unmappedTables(editor: TableSourceEditor, admin: DatabaseAdmin | undefined, onlySchema?: string): Promise<UnmappedTable[]> {\n const describe = admin?.describeUnmappedTables;\n if (!describe) {\n throw new ApiError(503, \"SCHEMA_EDITING_UNSUPPORTED\", \"This database driver cannot describe its tables, so none can be imported from here.\");\n }\n const declared = (await refusalsAsBadRequest(() => editor.compileCurrent())).descriptors;\n const schemas = onlySchema !== undefined ? [onlySchema] : [...new Set([\"public\", ...declared.map(descriptor => descriptor.schema)])];\n const out: UnmappedTable[] = [];\n for (const schema of schemas) {\n const inSchema = declared.filter(descriptor => descriptor.schema === schema);\n const slugOf = new Map(inSchema.map(descriptor => [descriptor.table, descriptor.slug]));\n for (const table of await describe.call(admin, schema, new Set(inSchema.map(descriptor => descriptor.table)))) {\n if (!table.descriptor) {\n out.push(table);\n continue;\n }\n const self = table.descriptor;\n const relations = self.relations.map(relation => ({\n ...relation,\n target: relation.target === self.table ? self.slug : slugOf.get(relation.target) ?? relation.target\n }));\n out.push({ ...table, descriptor: { ...self, relations } });\n }\n }\n return out;\n}\n\n/** The source-only schema editor's routes, over one editor. */\nexport function createSchemaEditorRoutes(editor: TableSourceEditor, options: SchemaEditorRoutesOptions = {}): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n router.onError(errorHandler);\n\n router.get(\"/unmapped-tables\", async (c) => {\n const tables = await unmappedTables(editor, options.getAdmin?.());\n return c.json({ tables: tables.map(summaryOf) });\n });\n\n router.get(\"/unmapped-tables/:schema/:table\", async (c) => {\n const schema = c.req.param(\"schema\");\n const name = c.req.param(\"table\");\n const found = (await unmappedTables(editor, options.getAdmin?.(), schema)).find(table => table.table === name);\n if (!found) {\n throw ApiError.notFound(`The database has no table \"${schema}\".\"${name}\" that backend/schema does not declare already.`, \"NOT_FOUND\");\n }\n if (!found.descriptor) {\n throw ApiError.badRequest(`\"${schema}\".\"${name}\" cannot be imported: ${found.unimportable ?? \"introspection could not describe it.\"}`, \"SCHEMA_EDIT_REFUSED\", {\n problems: [{ table: name, message: found.unimportable ?? \"introspection could not describe it.\" }]\n });\n }\n return c.json({ table: found });\n });\n\n router.get(\"/tables\", async (c) => c.json({ tables: await editor.describe() }));\n\n router.post(\"/preview\", async (c) => {\n const patches = await patchesOf(c);\n const edit = await refusalsAsBadRequest(() => editor.run(() => editor.preview(patches)));\n return c.json(describeEdit(editor, edit));\n });\n\n router.post(\"/apply\", async (c) => {\n const patches = await patchesOf(c);\n const edit = await refusalsAsBadRequest(() => editor.apply(patches));\n return c.json({ success: true, ...describeEdit(editor, edit) });\n });\n\n router.route(\"/frontend\", createFrontendSourceRoutes(createFrontendSourceEditor(editor.schemaDir)));\n\n return router;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,uBAAb,MAAkC;CAC9B,UAAoC,QAAQ,QAAQ;;CAEpD;;CAEA;CACA;;;;;;CAOA,YAAY,WAAmB,UAA0D,CAAC,GAAG;EACzF,KAAK,YAAY,KAAK,QAAQ,SAAS;EACvC,KAAK,OAAO,KAAK,QAAQ,QAAQ,QAAQ,KAAK,QAAQ,KAAK,QAAQ,KAAK,SAAS,CAAC,CAAC;EACnF,KA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0CAA0C,uBAAuB,EAC1J,UAAU,CAAC;GAAE,OAAO;GAAM,SAAS,MAAM,gBAAgB;EAAuC,CAAC,EACrG,CAAC;EAEL,OAAO,EAAE,KAAK,EAAE,OAAO,MAAM,CAAC;CAClC,CAAC;CAED,OAAO,IAAI,WAAW,OAAO,MAAM,EAAE,KAAK,EAAE,QAAQ,MAAM,OAAO,SAAS,EAAE,CAAC,CAAC;CAE9E,OAAO,KAAK,YAAY,OAAO,MAAM;EACjC,MAAM,UAAU,MAAM,UAAU,CAAC;EACjC,MAAM,OAAO,MAAM,2BAA2B,OAAO,UAAU,OAAO,QAAQ,OAAO,CAAC,CAAC;EACvF,OAAO,EAAE,KAAK,aAAa,QAAQ,IAAI,CAAC;CAC5C,CAAC;CAED,OAAO,KAAK,UAAU,OAAO,MAAM;EAC/B,MAAM,UAAU,MAAM,UAAU,CAAC;EACjC,MAAM,OAAO,MAAM,2BAA2B,OAAO,MAAM,OAAO,CAAC;EACnE,OAAO,EAAE,KAAK;GAAE,SAAS;GAAM,GAAG,aAAa,QAAQ,IAAI;EAAE,CAAC;CAClE,CAAC;CAED,OAAO,MAAM,aAAa,2BAA2B,2BAA2B,OAAO,SAAS,CAAC,CAAC;CAElG,OAAO;AACX"}
@@ -2,11 +2,11 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import { Rt as declaredRlsPolicyShape, an as isTenantClaimSource, bn as policy, bt as scopeGrantsAny, cn as REBASE_ADMIN_ROLE, dn as RLS_JWT_SQL, fn as RLS_ROLES_SQL, gn as ANONYMOUS_USER_IDS, in as DEFAULT_TENANT_BYPASS_ROLES, ln as RLS_IS_ANONYMOUS_SQL, mn as rewriteLegacyRlsFunctions, on as isRedactedSecurityRule, pn as RLS_UID_SQL, sn as REBASE_ADMIN_REQUEST_ROLE, un as RLS_IS_REQUEST_ROLE_SQL, x as isNumericColumnType, xt as scopeTargets, yn as isPolicyShorthand, yt as scopeGrants } from "./src-BdPKCs9u.js";
5
+ import { St as scopeTargets, _n as ANONYMOUS_USER_IDS, an as DEFAULT_TENANT_BYPASS_ROLES, bn as isPolicyShorthand, bt as scopeGrants, cn as REBASE_ADMIN_REQUEST_ROLE, dn as RLS_IS_REQUEST_ROLE_SQL, fn as RLS_JWT_SQL, hn as rewriteLegacyRlsFunctions, ln as REBASE_ADMIN_ROLE, mn as RLS_UID_SQL, on as isTenantClaimSource, pn as RLS_ROLES_SQL, sn as isRedactedSecurityRule, un as RLS_IS_ANONYMOUS_SQL, x as isNumericColumnType, xn as policy, xt as scopeGrantsAny, zt as declaredRlsPolicyShape } from "./src--EBfCtYm.js";
6
6
  import { a as logger } from "./logger-SigQ2oZJ.js";
7
7
  import { r as toSnakeCase } from "./strings.es-k0kjzQBh.js";
8
8
  import { i as truncateToBytes, n as toPostgresIdentifier } from "./names.es-PUE02OBV.js";
9
- import { n as policyShorthandColumns, t as securityRuleToConditions } from "./securityRuleToConditions-Cj5ZR7TS.js";
9
+ import { n as policyShorthandColumns, t as securityRuleToConditions } from "./securityRuleToConditions-DXPY_Z-x.js";
10
10
  import { a as canReadRelation, d as canReadWithAccess } from "./access-D1CTJSLK.js";
11
11
  import { createHash } from "node:crypto";
12
12
  //#region ../utils/dist/sha1.es.js
@@ -1886,4 +1886,4 @@ function serializeTables(tables, view, policies) {
1886
1886
  //#endregion
1887
1887
  export { serializeTables as a, policyTableFromDescriptor as c, schemaViewKey as i, compileServedPolicies as n, servedTableSlugs as o, schemaViewFor as r, tableEffectiveRules as s, ADMIN_SCHEMA_VIEW as t };
1888
1888
 
1889
- //# sourceMappingURL=schema-tables-BneB2KZ7.js.map
1889
+ //# sourceMappingURL=schema-tables-DUThMxen.js.map