@rebasepro/server 0.16.0 → 0.16.1-canary.g0d7af95

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 (219) hide show
  1. package/dist/{GCSStorageController-BEmDYFKc.js → GCSStorageController-Bl7nmhdv.js} +7 -6
  2. package/dist/{GCSStorageController-BEmDYFKc.js.map → GCSStorageController-Bl7nmhdv.js.map} +1 -1
  3. package/dist/{S3StorageController-B2EDXXMH.js → S3StorageController-CWvvrRpF.js} +7 -6
  4. package/dist/{S3StorageController-B2EDXXMH.js.map → S3StorageController-CWvvrRpF.js.map} +1 -1
  5. package/dist/{admin_block-DLILvzle.js → admin_block-BeypnEfb.js} +6 -6
  6. package/dist/admin_block-BeypnEfb.js.map +1 -0
  7. package/dist/api/ast-schema-editor.d.ts +23 -0
  8. package/dist/api/contract-routes.d.ts +1 -1
  9. package/dist/api/errors.d.ts +1 -1
  10. package/dist/api/index.d.ts +3 -3
  11. package/dist/api/live-schema-routes.d.ts +122 -0
  12. package/dist/api/logs-routes.d.ts +1 -1
  13. package/dist/api/mount.d.ts +41 -0
  14. package/dist/api/rest/api-generator.d.ts +2 -2
  15. package/dist/api/rest/index.d.ts +1 -1
  16. package/dist/api/rest/query-parser.d.ts +1 -1
  17. package/dist/api/schema-editor-routes.d.ts +1 -1
  18. package/dist/api/types.d.ts +12 -4
  19. package/dist/{schema-editor-routes-CV9k0w3G.js → ast-schema-editor-BrarYZCq.js} +37 -45
  20. package/dist/ast-schema-editor-BrarYZCq.js.map +1 -0
  21. package/dist/auth/adapter-middleware.d.ts +2 -2
  22. package/dist/auth/admin-roles-route.d.ts +2 -2
  23. package/dist/auth/admin-user-ops.d.ts +3 -3
  24. package/dist/auth/admin-users-route.d.ts +4 -6
  25. package/dist/auth/api-keys/api-key-middleware.d.ts +2 -2
  26. package/dist/auth/api-keys/api-key-permission-guard.d.ts +1 -1
  27. package/dist/auth/api-keys/api-key-routes.d.ts +2 -2
  28. package/dist/auth/api-keys/api-key-store.d.ts +1 -1
  29. package/dist/auth/api-keys/index.d.ts +9 -9
  30. package/dist/auth/apple-oauth.d.ts +2 -2
  31. package/dist/auth/auth-hooks.d.ts +4 -4
  32. package/dist/auth/bitbucket-oauth.d.ts +2 -2
  33. package/dist/auth/builtin-auth-adapter.d.ts +8 -4
  34. package/dist/auth/capabilities.d.ts +51 -0
  35. package/dist/auth/captcha.d.ts +86 -0
  36. package/dist/auth/cookie-utils.d.ts +2 -2
  37. package/dist/auth/discord-oauth.d.ts +2 -2
  38. package/dist/auth/facebook-oauth.d.ts +2 -2
  39. package/dist/auth/github-oauth.d.ts +2 -2
  40. package/dist/auth/gitlab-oauth.d.ts +2 -2
  41. package/dist/auth/google-oauth.d.ts +1 -1
  42. package/dist/auth/index.d.ts +58 -54
  43. package/dist/auth/jwks-routes.d.ts +1 -1
  44. package/dist/auth/jwt.d.ts +1 -1
  45. package/dist/auth/linkedin-oauth.d.ts +2 -2
  46. package/dist/auth/magic-link-routes.d.ts +10 -3
  47. package/dist/auth/mfa-gate.d.ts +1 -1
  48. package/dist/auth/mfa-routes.d.ts +3 -3
  49. package/dist/auth/microsoft-oauth.d.ts +2 -2
  50. package/dist/auth/middleware.d.ts +6 -7
  51. package/dist/auth/otp-routes.d.ts +89 -0
  52. package/dist/auth/rate-limiter.d.ts +2 -2
  53. package/dist/auth/require-auth.d.ts +1 -1
  54. package/dist/auth/reset-password-admin.d.ts +4 -4
  55. package/dist/auth/routes.d.ts +18 -10
  56. package/dist/auth/session-routes.d.ts +3 -3
  57. package/dist/auth/slack-oauth.d.ts +2 -2
  58. package/dist/auth/spotify-oauth.d.ts +2 -2
  59. package/dist/auth/token-revocation.d.ts +2 -2
  60. package/dist/auth/twitter-oauth.d.ts +2 -2
  61. package/dist/{auth-5Et5mnUA.js → auth-DU-nUjPp.js} +604 -4376
  62. package/dist/auth-DU-nUjPp.js.map +1 -0
  63. package/dist/backup/backup-common.d.ts +1 -1
  64. package/dist/backup/backup-routes.d.ts +3 -3
  65. package/dist/backup/index.d.ts +3 -3
  66. package/dist/{backup-C6ljYVTp.js → backup-CRdZkA6c.js} +7 -6
  67. package/dist/{backup-C6ljYVTp.js.map → backup-CRdZkA6c.js.map} +1 -1
  68. package/dist/boot/boot.d.ts +5 -5
  69. package/dist/boot/bundle.d.ts +10 -1
  70. package/dist/boot/driver.d.ts +1 -1
  71. package/dist/boot/env.d.ts +28 -1
  72. package/dist/boot/fetch-bundle.d.ts +144 -1
  73. package/dist/boot/options.d.ts +30 -6
  74. package/dist/boot/resource-adapters.d.ts +31 -0
  75. package/dist/boot/resource-loading.d.ts +10 -0
  76. package/dist/boot/role.d.ts +3 -2
  77. package/dist/boot/sources.d.ts +8 -2
  78. package/dist/boot/version-skew.d.ts +1 -1
  79. package/dist/collections/BackendCollectionRegistry.d.ts +1 -1
  80. package/dist/collections/loader.d.ts +1 -1
  81. package/dist/collections/validate-config.d.ts +13 -0
  82. package/dist/{contract-routes-DZ-LBpSL.js → contract-routes-D8TvxPLo.js} +8 -7
  83. package/dist/contract-routes-D8TvxPLo.js.map +1 -0
  84. package/dist/cron/cron-routes.d.ts +2 -2
  85. package/dist/cron/cron-scheduler.d.ts +3 -3
  86. package/dist/cron/index.d.ts +8 -8
  87. package/dist/{cron-loader-YhhQeVBM.js → cron-loader-d9WMFENB.js} +8 -7
  88. package/dist/{cron-loader-YhhQeVBM.js.map → cron-loader-d9WMFENB.js.map} +1 -1
  89. package/dist/{cron-routes-maM_RlUu.js → cron-routes-BsukhMGm.js} +9 -8
  90. package/dist/cron-routes-BsukhMGm.js.map +1 -0
  91. package/dist/{cron-scheduler-DIpYBmZP.js → cron-scheduler-BB82dWuU.js} +9 -9
  92. package/dist/cron-scheduler-BB82dWuU.js.map +1 -0
  93. package/dist/{cron-store-DfH_4Cd9.js → cron-store-CbFfQhbg.js} +11 -9
  94. package/dist/{cron-store-DfH_4Cd9.js.map → cron-store-CbFfQhbg.js.map} +1 -1
  95. package/dist/ddl-bootstrap-5YZCZ8qk.js +146 -0
  96. package/dist/ddl-bootstrap-5YZCZ8qk.js.map +1 -0
  97. package/dist/deploy/pod-contract.d.ts +139 -0
  98. package/dist/dev-secrets.d.ts +52 -0
  99. package/dist/{dynamic-import-Dvh-K5fl.js → dynamic-import-X40pTZUQ.js} +5 -4
  100. package/dist/{dynamic-import-Dvh-K5fl.js.map → dynamic-import-X40pTZUQ.js.map} +1 -1
  101. package/dist/email/dev-sink.d.ts +88 -0
  102. package/dist/email/index.d.ts +9 -7
  103. package/dist/email/link-base.d.ts +1 -1
  104. package/dist/email/smtp-email-service.d.ts +2 -2
  105. package/dist/email/templates.d.ts +12 -0
  106. package/dist/email/types.d.ts +18 -6
  107. package/dist/env.d.ts +1 -1
  108. package/dist/{errors-EBYiaJ2E.js → errors-DBwpj9N8.js} +8 -7
  109. package/dist/errors-DBwpj9N8.js.map +1 -0
  110. package/dist/{function-loader-DDS1v7YX.js → function-loader-LLdmBFoL.js} +9 -8
  111. package/dist/{function-loader-DDS1v7YX.js.map → function-loader-LLdmBFoL.js.map} +1 -1
  112. package/dist/{function-routes-Btcez1T-.js → function-routes-ClT6UQpD.js} +8 -7
  113. package/dist/function-routes-ClT6UQpD.js.map +1 -0
  114. package/dist/functions/context.d.ts +141 -0
  115. package/dist/functions/define-function.d.ts +1 -1
  116. package/dist/functions/function-routes.d.ts +9 -3
  117. package/dist/functions/guards.d.ts +76 -0
  118. package/dist/functions/index.d.ts +96 -5
  119. package/dist/functions/index.js +919 -0
  120. package/dist/functions/index.js.map +1 -0
  121. package/dist/functions/internal.d.ts +26 -0
  122. package/dist/functions/proxy.d.ts +1 -1
  123. package/dist/functions/request-timeout.d.ts +9 -1
  124. package/dist/functions/runtime-env.d.ts +92 -0
  125. package/dist/functions/wait-until.d.ts +74 -0
  126. package/dist/history/history-routes.d.ts +2 -2
  127. package/dist/history/index.d.ts +1 -1
  128. package/dist/history-recorder-B67maiTi.js +76 -0
  129. package/dist/history-recorder-B67maiTi.js.map +1 -0
  130. package/dist/history-store-oiqhb3HU.js +210 -0
  131. package/dist/history-store-oiqhb3HU.js.map +1 -0
  132. package/dist/index.d.ts +65 -54
  133. package/dist/index.es.js +3667 -328
  134. package/dist/index.es.js.map +1 -1
  135. package/dist/init/docs.d.ts +1 -1
  136. package/dist/init/middlewares.d.ts +1 -1
  137. package/dist/init/shutdown.d.ts +4 -0
  138. package/dist/init/storage.d.ts +1 -1
  139. package/dist/init/surfaces.d.ts +10 -0
  140. package/dist/init.d.ts +179 -22
  141. package/dist/internal-tables-DpxfPaEB.js +97 -0
  142. package/dist/internal-tables-DpxfPaEB.js.map +1 -0
  143. package/dist/jobs/index.d.ts +5 -5
  144. package/dist/{jobs-CyOKXXlu.js → jobs-B2ELModo.js} +11 -9
  145. package/dist/{jobs-CyOKXXlu.js.map → jobs-B2ELModo.js.map} +1 -1
  146. package/dist/{jwt-DxH9fLPt.js → jwt-DoHkMMWF.js} +9 -8
  147. package/dist/jwt-DoHkMMWF.js.map +1 -0
  148. package/dist/{logger-DfvF_8r-.js → logger-DS03e908.js} +104 -10
  149. package/dist/logger-DS03e908.js.map +1 -0
  150. package/dist/{logs-routes-CWBLQj2l.js → logs-routes-DB72iQSr.js} +36 -9
  151. package/dist/logs-routes-DB72iQSr.js.map +1 -0
  152. package/dist/metrics/history-recorder.d.ts +18 -0
  153. package/dist/metrics/history-store.d.ts +123 -0
  154. package/dist/metrics/index.d.ts +10 -2
  155. package/dist/{openapi-generator-BCKJRUS4.js → openapi-generator-FFGT0H6O.js} +7 -11
  156. package/dist/{openapi-generator-BCKJRUS4.js.map → openapi-generator-FFGT0H6O.js.map} +1 -1
  157. package/dist/{proxy-Bj5DVllb.js → proxy-CMymhnwG.js} +9 -6
  158. package/dist/{proxy-Bj5DVllb.js.map → proxy-CMymhnwG.js.map} +1 -1
  159. package/dist/query-parser--nstjRCh.js +355 -0
  160. package/dist/query-parser--nstjRCh.js.map +1 -0
  161. package/dist/{request-timeout-BuFoEKwT.js → request-timeout-C8gkc-j7.js} +21 -6
  162. package/dist/request-timeout-C8gkc-j7.js.map +1 -0
  163. package/dist/rls-audit/index.d.ts +111 -0
  164. package/dist/{rolldown-runtime-DSJWtz9O.js → rolldown-runtime-dW7B1o5h.js} +4 -3
  165. package/dist/schema-edit/apply-schema-change.d.ts +141 -0
  166. package/dist/schema-edit/github-repository.d.ts +67 -0
  167. package/dist/schema-edit/local-git-repository.d.ts +28 -0
  168. package/dist/schema-edit/project-root.d.ts +43 -0
  169. package/dist/schema-edit/remote-source.d.ts +25 -0
  170. package/dist/schema-edit/schema-edit-permissions.d.ts +129 -0
  171. package/dist/schema-editor-routes-Bf5h5Emf.js +87 -0
  172. package/dist/schema-editor-routes-Bf5h5Emf.js.map +1 -0
  173. package/dist/schemas-DBxgjM9A.js +4153 -0
  174. package/dist/schemas-DBxgjM9A.js.map +1 -0
  175. package/dist/{selection-_z6TM1DB.js → selection-CRpqKUbt.js} +6 -5
  176. package/dist/{selection-_z6TM1DB.js.map → selection-CRpqKUbt.js.map} +1 -1
  177. package/dist/services/webhook-service.d.ts +1 -1
  178. package/dist/singleton.d.ts +7 -0
  179. package/dist/{src-BPfYOeN4.js → src-B-CmIFMr.js} +8 -6
  180. package/dist/src-B-CmIFMr.js.map +1 -0
  181. package/dist/{src-CrCxd8km.js → src-Cdsw7DqV.js} +126 -5
  182. package/dist/src-Cdsw7DqV.js.map +1 -0
  183. package/dist/storage/GCSStorageController.d.ts +1 -1
  184. package/dist/storage/LocalStorageController.d.ts +1 -1
  185. package/dist/storage/S3StorageController.d.ts +1 -1
  186. package/dist/storage/cache-headers.d.ts +87 -0
  187. package/dist/storage/index.d.ts +11 -11
  188. package/dist/storage/path-pattern.d.ts +58 -0
  189. package/dist/storage/policies.d.ts +88 -0
  190. package/dist/storage/range.d.ts +63 -0
  191. package/dist/storage/rendition-cache.d.ts +45 -0
  192. package/dist/storage/routes.d.ts +17 -5
  193. package/dist/storage/storage-registry.d.ts +1 -1
  194. package/dist/storage/triggers.d.ts +66 -0
  195. package/dist/storage/tus-handler.d.ts +34 -3
  196. package/dist/topics/runtime.d.ts +68 -0
  197. package/dist/{types-DSnOC4mF.js → types-BfKcm9do.js} +5 -4
  198. package/dist/{types-DSnOC4mF.js.map → types-BfKcm9do.js.map} +1 -1
  199. package/dist/utils/host.d.ts +58 -0
  200. package/dist/utils/logger.d.ts +0 -15
  201. package/dist/utils/request-id.d.ts +1 -1
  202. package/functions/package.json +24 -0
  203. package/package.json +13 -7
  204. package/dist/admin_block-DLILvzle.js.map +0 -1
  205. package/dist/auth-5Et5mnUA.js.map +0 -1
  206. package/dist/contract-routes-DZ-LBpSL.js.map +0 -1
  207. package/dist/cron-routes-maM_RlUu.js.map +0 -1
  208. package/dist/cron-scheduler-DIpYBmZP.js.map +0 -1
  209. package/dist/ddl-bootstrap-Cywoj8Ta.js +0 -221
  210. package/dist/ddl-bootstrap-Cywoj8Ta.js.map +0 -1
  211. package/dist/errors-EBYiaJ2E.js.map +0 -1
  212. package/dist/function-routes-Btcez1T-.js.map +0 -1
  213. package/dist/jwt-DxH9fLPt.js.map +0 -1
  214. package/dist/logger-DfvF_8r-.js.map +0 -1
  215. package/dist/logs-routes-CWBLQj2l.js.map +0 -1
  216. package/dist/request-timeout-BuFoEKwT.js.map +0 -1
  217. package/dist/schema-editor-routes-CV9k0w3G.js.map +0 -1
  218. package/dist/src-BPfYOeN4.js.map +0 -1
  219. package/dist/src-CrCxd8km.js.map +0 -1
@@ -1,12 +1,11 @@
1
- import { createRequire as __createRequire } from "module";
2
- import "process";
3
- __createRequire(import.meta.url);
4
- import "./src-CrCxd8km.js";
5
- import { i as nestAdminPropertyKeys, r as nestAdminCollectionKeys } from "./admin_block-DLILvzle.js";
6
- import { n as errorHandler } from "./errors-EBYiaJ2E.js";
1
+ import { createRequire as __rebaseCreateRequire } from "module";
2
+ import __rebaseProcess from "process";
3
+ globalThis.process ??= __rebaseProcess;
4
+ __rebaseCreateRequire(import.meta.url);
5
+ import "./src-Cdsw7DqV.js";
6
+ import { i as nestAdminPropertyKeys, r as nestAdminCollectionKeys } from "./admin_block-BeypnEfb.js";
7
7
  import * as fs$1 from "fs";
8
8
  import * as path$1 from "path";
9
- import { Hono } from "hono";
10
9
  import { IndentationText, Node, Project, SyntaxKind } from "ts-morph";
11
10
  //#region src/api/ast-schema-editor.ts
12
11
  /**
@@ -57,6 +56,33 @@ var AstSchemaEditor = class AstSchemaEditor {
57
56
  * Sanitize collectionId to prevent path traversal attacks.
58
57
  * Only allows alphanumeric characters, underscores, and hyphens.
59
58
  */
59
+ /**
60
+ * The variable name the generated file binds the collection to.
61
+ *
62
+ * `sanitizeCollectionId` guards the FILENAME, and permits hyphens and a
63
+ * leading digit — both legal in a filename and neither legal in a
64
+ * JavaScript identifier. So a collection created from the admin panel as
65
+ * `my-notes` (the documented slug shape) or `2024 Archive` (auto-slugged to
66
+ * `2024_archive`) wrote:
67
+ *
68
+ * const my-notesCollection: CollectionConfig = … "',' expected"
69
+ * const 2024_archiveCollection: CollectionConfig = … "Numeric separators
70
+ * are not allowed here"
71
+ *
72
+ * The panel reported success, and the next boot failed for EVERY collection
73
+ * in the directory — the loader imports all of them — while the editor could
74
+ * no longer parse the file it had just written, so it could not fix itself.
75
+ *
76
+ * Separators camel-case rather than vanish, so `my-notes` and `my_notes`
77
+ * stay distinct; a leading digit is prefixed rather than stripped, so
78
+ * `2024_archive` stays distinct from `archive`. Byte-identical for every
79
+ * slug that already produced a valid identifier.
80
+ */
81
+ static collectionVarName(safeId) {
82
+ const camel = safeId.replace(/[-_]+([a-zA-Z0-9])/g, (_, char) => char.toUpperCase());
83
+ const identifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(camel) ? camel : `c${camel.replace(/^[0-9]/, (d) => d)}`;
84
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(identifier) ? identifier : `c${identifier.replace(/[^A-Za-z0-9_$]/g, "")}`;
85
+ }
60
86
  sanitizeCollectionId(collectionId) {
61
87
  const sanitized = collectionId.replace(/[^a-zA-Z0-9_-]/g, "");
62
88
  if (!sanitized || sanitized !== collectionId) throw new Error(`Invalid collection ID: "${collectionId}". Only alphanumeric characters, underscores, and hyphens are allowed.`);
@@ -281,7 +307,8 @@ var AstSchemaEditor = class AstSchemaEditor {
281
307
  const safeId = this.sanitizeCollectionId(collectionId);
282
308
  const newFilePath = this.safePath(`${safeId}.ts`);
283
309
  if (fs$1.existsSync(newFilePath)) throw new Error(`Refusing to overwrite ${newFilePath}: a file for "${collectionId}" already exists but could not be parsed.`);
284
- file = this.project.createSourceFile(newFilePath, `import { CollectionConfig } from "@rebasepro/types";\n\nconst ${safeId}Collection: CollectionConfig = ${this.convertJsonToAstString(nestAdminKeys(collectionData))};\n\nexport default ${safeId}Collection;\n`);
310
+ const varName = `${AstSchemaEditor.collectionVarName(safeId)}Collection`;
311
+ file = this.project.createSourceFile(newFilePath, `import { CollectionConfig } from "@rebasepro/types";\n\nconst ${varName}: CollectionConfig = ${this.convertJsonToAstString(nestAdminKeys(collectionData))};\n\nexport default ${varName};\n`);
285
312
  } else {
286
313
  if (!partial) {
287
314
  if (!("securityRules" in collectionData) || collectionData.securityRules === void 0 || Array.isArray(collectionData.securityRules) && collectionData.securityRules.length === 0) {
@@ -397,41 +424,6 @@ var AstSchemaEditor = class AstSchemaEditor {
397
424
  }
398
425
  };
399
426
  //#endregion
400
- //#region src/api/schema-editor-routes.ts
401
- function createSchemaEditorRoutes(collectionsDir) {
402
- const router = new Hono();
403
- router.onError(errorHandler);
404
- const editor = new AstSchemaEditor(collectionsDir);
405
- router.post("/property/save", async (c) => {
406
- const { collectionId, propertyKey, propertyConfig } = await c.req.json();
407
- await editor.saveProperty(collectionId, propertyKey, propertyConfig);
408
- return c.json({ success: true });
409
- });
410
- router.post("/property/delete", async (c) => {
411
- const { collectionId, propertyKey } = await c.req.json();
412
- await editor.deleteProperty(collectionId, propertyKey);
413
- return c.json({ success: true });
414
- });
415
- /**
416
- * `partial: true` means "this payload is what changed", not "this is the
417
- * collection". Without it a one-key patch — which is what adding a column
418
- * posts — is read as a whole-collection save and deletes everything it does
419
- * not mention, `securityRules` included. Absent, it defaults to a full save,
420
- * so an older panel keeps the behaviour it was written against.
421
- */
422
- router.post("/collection/save", async (c) => {
423
- const { collectionId, collectionData, partial } = await c.req.json();
424
- await editor.saveCollection(collectionId, collectionData, { partial: partial === true });
425
- return c.json({ success: true });
426
- });
427
- router.post("/collection/delete", async (c) => {
428
- const { collectionId } = await c.req.json();
429
- await editor.deleteCollection(collectionId);
430
- return c.json({ success: true });
431
- });
432
- return router;
433
- }
434
- //#endregion
435
- export { createSchemaEditorRoutes };
427
+ export { AstSchemaEditor };
436
428
 
437
- //# sourceMappingURL=schema-editor-routes-CV9k0w3G.js.map
429
+ //# sourceMappingURL=ast-schema-editor-BrarYZCq.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ast-schema-editor-BrarYZCq.js","names":[],"sources":["../src/api/ast-schema-editor.ts"],"sourcesContent":["import { Project, SyntaxKind, Node, ObjectLiteralExpression, ObjectLiteralElementLike, PropertyAssignment, SourceFile, IndentationText } from \"ts-morph\";\nimport { nestAdminCollectionKeys, nestAdminPropertyKeys } from \"@rebasepro/types\";\nimport * as path from \"path\";\nimport * as fs from \"fs\";\n\n/**\n * The helpers a collection file may be wrapped in.\n *\n * `rebase init` scaffolds every collection as\n * `const postsCollection = defineCollection({ … })` — a call expression, not the\n * bare object literal `rebase introspect` emits. An editor that only understood\n * the bare form found nothing to patch in any stock project, and then rewrote the\n * file from the panel's JSON: no wrapper, no imports, no relation thunks.\n */\nconst COLLECTION_FACTORIES = new Set([\"defineCollection\"]);\n\n/**\n * A value that must be emitted as source code rather than as JSON.\n *\n * Everything reaching the writer has been through `JSON.stringify` on the wire,\n * so a function-valued key arrives either missing or as a string. A relation's\n * `target` is a thunk in the file and a slug in the payload; this is how the\n * thunk gets written back.\n */\nclass RawExpression {\n constructor(public readonly text: string) {\n }\n}\n\n/**\n * Move presentation keys into the `admin` block.\n *\n * The rule itself lives in `@rebasepro/types`, next to `ADMIN_COLLECTION_KEYS`,\n * because `@rebasepro/admin-types` has to apply the identical one on the panel's\n * side and this package cannot import that one. Two copies used to exist and\n * they disagreed about precedence, which decided whether a presentation edit was\n * saved or silently reverted to the value the user had just changed away from.\n */\nexport function nestAdminKeys(collectionData: Record<string, unknown>): Record<string, unknown> {\n return nestAdminCollectionKeys(collectionData);\n}\n\nexport class AstSchemaEditor {\n private project: Project;\n private collectionsDir: string;\n\n constructor(collectionsDir: string) {\n this.project = new Project({\n manipulationSettings: {\n indentationText: IndentationText.FourSpaces\n }\n });\n if (fs.existsSync(collectionsDir)) {\n this.project.addSourceFilesAtPaths(`${collectionsDir}/**/*.ts`);\n }\n this.collectionsDir = path.resolve(collectionsDir);\n }\n\n /**\n * Sanitize collectionId to prevent path traversal attacks.\n * Only allows alphanumeric characters, underscores, and hyphens.\n */\n /**\n * The variable name the generated file binds the collection to.\n *\n * `sanitizeCollectionId` guards the FILENAME, and permits hyphens and a\n * leading digit — both legal in a filename and neither legal in a\n * JavaScript identifier. So a collection created from the admin panel as\n * `my-notes` (the documented slug shape) or `2024 Archive` (auto-slugged to\n * `2024_archive`) wrote:\n *\n * const my-notesCollection: CollectionConfig = … \"',' expected\"\n * const 2024_archiveCollection: CollectionConfig = … \"Numeric separators\n * are not allowed here\"\n *\n * The panel reported success, and the next boot failed for EVERY collection\n * in the directory — the loader imports all of them — while the editor could\n * no longer parse the file it had just written, so it could not fix itself.\n *\n * Separators camel-case rather than vanish, so `my-notes` and `my_notes`\n * stay distinct; a leading digit is prefixed rather than stripped, so\n * `2024_archive` stays distinct from `archive`. Byte-identical for every\n * slug that already produced a valid identifier.\n */\n private static collectionVarName(safeId: string): string {\n const camel = safeId.replace(/[-_]+([a-zA-Z0-9])/g, (_, char: string) => char.toUpperCase());\n const identifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(camel) ? camel : `c${camel.replace(/^[0-9]/, (d) => d)}`;\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(identifier) ? identifier : `c${identifier.replace(/[^A-Za-z0-9_$]/g, \"\")}`;\n }\n\n private sanitizeCollectionId(collectionId: string): string {\n const sanitized = collectionId.replace(/[^a-zA-Z0-9_-]/g, \"\");\n if (!sanitized || sanitized !== collectionId) {\n throw new Error(`Invalid collection ID: \"${collectionId}\". Only alphanumeric characters, underscores, and hyphens are allowed.`);\n }\n return sanitized;\n }\n\n /**\n * Resolve a file path and ensure it falls within the collectionsDir.\n */\n private safePath(filename: string): string {\n const resolved = path.resolve(this.collectionsDir, filename);\n if (!resolved.startsWith(this.collectionsDir + path.sep) && resolved !== this.collectionsDir) {\n throw new Error(\"Path traversal detected: resolved path is outside the collections directory.\");\n }\n return resolved;\n }\n\n private getCollectionFile(collectionId: string) {\n const safeId = this.sanitizeCollectionId(collectionId);\n const filePath = this.safePath(`${safeId}.ts`);\n let file = this.project.getSourceFile(filePath);\n if (!file && fs.existsSync(filePath)) {\n this.project.addSourceFilesAtPaths(`${this.collectionsDir}/**/*.ts`);\n file = this.project.getSourceFile(filePath);\n }\n return file;\n }\n\n /**\n * Find the object literal a collection is declared with, through whatever\n * wraps it.\n *\n * `defineCollection({ … })` is the shape `rebase init` writes and the one the\n * docs recommend; `satisfies` / `as` / parentheses are the other ways an\n * author can dress the same literal. Returning `null` for any of them meant\n * the three callers below each failed differently, and the worst of them\n * overwrote the file.\n */\n private unwrapCollectionObject(node: Node | undefined): ObjectLiteralExpression | null {\n if (!node) return null;\n if (Node.isObjectLiteralExpression(node)) return node;\n if (Node.isParenthesizedExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isSatisfiesExpression(node) ||\n Node.isTypeAssertion(node) ||\n Node.isNonNullExpression(node)) {\n return this.unwrapCollectionObject(node.getExpression());\n }\n if (Node.isCallExpression(node)) {\n // `defineCollection`, `admin.defineCollection`, `defineCollection<Post>`\n const callee = node.getExpression().getText().split(\".\").pop();\n if (callee && COLLECTION_FACTORIES.has(callee)) {\n return this.unwrapCollectionObject(node.getArguments()[0]);\n }\n }\n return null;\n }\n\n private getCollectionObject(collectionId: string): ObjectLiteralExpression | null {\n const file = this.getCollectionFile(collectionId);\n if (!file) return null;\n\n const defaultExport = file.getDefaultExportSymbol();\n if (defaultExport) {\n const declaration = defaultExport.getDeclarations()[0];\n if (declaration && declaration.getKind() === SyntaxKind.ExportAssignment) {\n const expr = declaration.asKind(SyntaxKind.ExportAssignment)?.getExpression();\n if (expr && expr.getKind() === SyntaxKind.Identifier) {\n const varName = expr.getText();\n const varDecl = file.getVariableDeclaration(varName);\n const unwrapped = this.unwrapCollectionObject(varDecl?.getInitializer());\n if (unwrapped) return unwrapped;\n } else {\n // `export default defineCollection({ … })`\n const unwrapped = this.unwrapCollectionObject(expr);\n if (unwrapped) return unwrapped;\n }\n }\n }\n // Fallback: the first VariableDeclaration that holds a collection literal\n for (const varDecl of file.getVariableDeclarations()) {\n const init = this.unwrapCollectionObject(varDecl.getInitializer());\n if (init) return init;\n }\n return null;\n }\n\n /**\n * The collection's object literal, or a refusal that says what to do.\n *\n * Every caller needs this to be all-or-nothing: a missing object literal used\n * to mean \"throw\", \"report success and do nothing\" and \"recreate the file\n * from scratch\" depending on which method you called.\n */\n private requireCollectionObject(collectionId: string): ObjectLiteralExpression {\n const file = this.getCollectionFile(collectionId);\n if (!file) {\n throw new Error(`Collection \"${collectionId}\" has no file at ${path.join(this.collectionsDir, `${collectionId}.ts`)}.`);\n }\n const collectionObj = this.getCollectionObject(collectionId);\n if (!collectionObj) {\n throw new Error(this.unreadableFileMessage(collectionId, file));\n }\n return collectionObj;\n }\n\n private unreadableFileMessage(collectionId: string, file: SourceFile): string {\n return `Could not find the collection object in ${file.getFilePath()}. ` +\n \"The schema editor can only edit a collection declared as `const x = defineCollection({ … })` \" +\n \"or `const x: CollectionConfig = { … }` and exported as the file's default. \" +\n `Edit \"${collectionId}\" in code instead.`;\n }\n\n /** Look a key up on an object literal, quoted or not. */\n private findProperty(obj: ObjectLiteralExpression, name: string): ObjectLiteralElementLike | undefined {\n return obj.getProperty((p: ObjectLiteralElementLike) =>\n \"getName\" in p &&\n typeof (p as PropertyAssignment).getName === \"function\" &&\n ((p as PropertyAssignment).getName() === name ||\n (p as PropertyAssignment).getName() === `\"${name}\"` ||\n (p as PropertyAssignment).getName() === `'${name}'`));\n }\n\n private static quoteKey(key: string): string {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key);\n }\n\n private static isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value) && !(value instanceof RawExpression);\n }\n\n private convertJsonToAstString(obj: unknown, indentLevel = 0, oldAstNode?: ObjectLiteralExpression): string {\n // Base TS-morph parses arrays as 2 levels deep from the property key:\n // PropertiesObject = level 1, PropertyConfig = level 2.\n // We calibrate the spacing multiples to keep the items flush with standard TS format.\n const indentStr = \" \";\n const indent = indentStr.repeat(indentLevel);\n const innerIndent = indentStr.repeat(indentLevel + 1);\n\n if (obj instanceof RawExpression) {\n return obj.text;\n }\n if (obj === null || obj === undefined) {\n return \"undefined\";\n }\n if (typeof obj === \"string\") {\n return JSON.stringify(obj);\n }\n if (typeof obj === \"number\" || typeof obj === \"boolean\") {\n return String(obj);\n }\n if (Array.isArray(obj)) {\n if (obj.length === 0) return \"[]\";\n const items = obj.map(item => this.convertJsonToAstString(item, indentLevel + 1));\n return `[\\n${innerIndent}${items.join(`,\\n${innerIndent}`)}\\n${indent}]`;\n }\n if (typeof obj === \"object\") {\n const record = obj as Record<string, unknown>;\n const keys = Object.keys(record);\n\n // Collect preserved AST properties\n const preservedProps: string[] = [];\n if (oldAstNode) {\n const oldProps = oldAstNode.getProperties();\n for (const oldProp of oldProps) {\n if (oldProp.isKind(SyntaxKind.PropertyAssignment)) {\n const nameNode = oldProp.getNameNode();\n let name = nameNode.getText();\n if (name.startsWith('\"') && name.endsWith('\"')) name = name.slice(1, -1);\n if (name.startsWith(\"'\") && name.endsWith(\"'\")) name = name.slice(1, -1);\n\n // If the JSON object doesn't have this key, check if we should preserve it\n if (!(name in record)) {\n const init = oldProp.getInitializer();\n if (init) {\n const kind = init.getKind();\n const isCode = kind === SyntaxKind.ArrowFunction ||\n kind === SyntaxKind.FunctionExpression ||\n kind === SyntaxKind.Identifier ||\n kind === SyntaxKind.CallExpression ||\n kind === SyntaxKind.JsxElement;\n\n if (isCode || name === \"target\" || name === \"callbacks\" || name === \"permissions\" || name === \"securityRules\") {\n // Preserve this property exactly as it was\n preservedProps.push(`${AstSchemaEditor.quoteKey(name)}: ${init.getText()}`);\n }\n }\n }\n }\n }\n }\n\n if (keys.length === 0 && preservedProps.length === 0) return \"{}\";\n\n const props = keys.map(key => {\n const keyStr = AstSchemaEditor.quoteKey(key);\n\n // If the value is an object, pass the old AST node to recurse\n let childAstNode: ObjectLiteralExpression | undefined;\n if (oldAstNode && AstSchemaEditor.isPlainObject(record[key])) {\n const oldProp = this.findProperty(oldAstNode, key);\n if (oldProp && oldProp.isKind(SyntaxKind.PropertyAssignment)) {\n childAstNode = oldProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);\n }\n }\n\n return `${keyStr}: ${this.convertJsonToAstString(record[key], indentLevel + 1, childAstNode)}`;\n });\n\n const allProps = [...props, ...preservedProps];\n return `{\\n${innerIndent}${allProps.join(`,\\n${innerIndent}`)}\\n${indent}}`;\n }\n return \"undefined\";\n }\n\n /**\n * Write only the keys the patch names, leaving every sibling alone.\n *\n * A patch says what changed, not what the collection is. The panel sends one\n * — `{ propertiesOrder }` is what adding a column posts — and rewriting the\n * `admin` block from it deleted the collection's icon, group, list columns\n * and kanban config in the same write.\n */\n private mergeIntoObjectLiteral(target: ObjectLiteralExpression, data: Record<string, unknown>, indentLevel: number): void {\n for (const [key, value] of Object.entries(data)) {\n const existing = this.findProperty(target, key);\n const existingObj = existing && existing.isKind(SyntaxKind.PropertyAssignment)\n ? existing.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression)\n : undefined;\n\n if (existingObj && AstSchemaEditor.isPlainObject(value)) {\n this.mergeIntoObjectLiteral(existingObj, value, indentLevel + 1);\n continue;\n }\n\n const initializer = this.convertJsonToAstString(value, indentLevel, existingObj);\n if (existing && existing.isKind(SyntaxKind.PropertyAssignment)) {\n existing.setInitializer(initializer);\n } else {\n target.addPropertyAssignment({\n name: AstSchemaEditor.quoteKey(key),\n initializer\n });\n }\n }\n }\n\n public async saveProperty(collectionId: string, propertyKey: string, propertyConfig: Record<string, unknown>) {\n const collectionObj = this.requireCollectionObject(collectionId);\n\n // The panel's property forms bind to the flat names — `readOnly`,\n // `hideFromCollection` — while on disk they belong inside the property's\n // own `admin` block. Written flat they are not merely ignored: the boot\n // validator treats a moved key as fatal.\n const nestedConfig = nestAdminPropertyKeys(propertyConfig);\n\n let propertiesProp = collectionObj.getProperty(\"properties\") as PropertyAssignment;\n if (!propertiesProp) {\n propertiesProp = collectionObj.addPropertyAssignment({\n name: \"properties\",\n initializer: \"{}\"\n });\n }\n\n const propsObj = propertiesProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);\n if (propsObj) {\n const existingProp = this.findProperty(propsObj, propertyKey);\n\n let oldPropAstNode: ObjectLiteralExpression | undefined;\n if (existingProp && existingProp.isKind(SyntaxKind.PropertyAssignment)) {\n oldPropAstNode = existingProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);\n }\n\n const newInitializer = this.convertJsonToAstString(nestedConfig, 2, oldPropAstNode);\n\n if (existingProp) {\n if (existingProp.isKind(SyntaxKind.PropertyAssignment)) {\n existingProp.setInitializer(newInitializer);\n }\n } else {\n propsObj.addPropertyAssignment({\n name: AstSchemaEditor.quoteKey(propertyKey),\n initializer: newInitializer\n });\n }\n\n const file = this.getCollectionFile(collectionId);\n if (file) {\n file.formatText();\n }\n await this.project.save();\n }\n }\n\n public async deleteProperty(collectionId: string, propertyKey: string) {\n const collectionObj = this.requireCollectionObject(collectionId);\n\n const propertiesProp = collectionObj.getProperty(\"properties\") as PropertyAssignment;\n if (propertiesProp) {\n const propsObj = propertiesProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);\n if (propsObj) {\n const existingProp = this.findProperty(propsObj, propertyKey);\n if (existingProp) {\n existingProp.remove();\n const file = this.getCollectionFile(collectionId);\n if (file) {\n file.formatText();\n }\n await this.project.save();\n }\n }\n }\n }\n\n /**\n * Write a collection back to its file.\n *\n * `partial` is the difference between \"this is the collection\" and \"this is\n * what changed about it\". The panel sends both — a full save from the editor\n * dialog, and a one-key patch whenever a property is added, deleted or\n * reordered — and they cannot be told apart by looking at the payload. Read\n * as a full save, a patch deletes everything it does not mention, including\n * `securityRules`; the loader then hands the collection the directory\n * default, which in the scaffold is `access: \"public\"`.\n */\n public async saveCollection(collectionId: string, collectionData: Record<string, unknown>, options: { partial?: boolean } = {}) {\n const partial = options.partial === true;\n let file = this.getCollectionFile(collectionId);\n const collectionObj = file ? this.getCollectionObject(collectionId) : null;\n\n if (file && !collectionObj) {\n // The file is there and we could not read it. Recreating it from the\n // panel's JSON would drop the imports, the callbacks and the relation\n // thunks that JSON cannot carry.\n throw new Error(this.unreadableFileMessage(collectionId, file));\n }\n\n if (!file || !collectionObj) {\n if (partial) {\n throw new Error(`Cannot apply a partial update to \"${collectionId}\": it has no collection file yet.`);\n }\n // Create a new file\n const safeId = this.sanitizeCollectionId(collectionId);\n const newFilePath = this.safePath(`${safeId}.ts`);\n if (fs.existsSync(newFilePath)) {\n throw new Error(`Refusing to overwrite ${newFilePath}: a file for \"${collectionId}\" already exists but could not be parsed.`);\n }\n const varName = `${AstSchemaEditor.collectionVarName(safeId)}Collection`;\n file = this.project.createSourceFile(newFilePath, `import { CollectionConfig } from \"@rebasepro/types\";\\n\\nconst ${varName}: CollectionConfig = ${this.convertJsonToAstString(nestAdminKeys(collectionData))};\\n\\nexport default ${varName};\\n`);\n } else {\n // Update root level properties gracefully\n\n if (!partial) {\n // Force delete securityRules if empty or undefined to handle Formex / serialization stripping\n if (!(\"securityRules\" in collectionData) || collectionData.securityRules === undefined || (Array.isArray(collectionData.securityRules) && collectionData.securityRules.length === 0)) {\n const srProp = collectionObj.getProperty(\"securityRules\");\n if (srProp) {\n srProp.remove();\n }\n\n // If it was in collectionData as an empty array, delete it so the loop below doesn't add it back as \"[]\"\n // Actually, if it's \"[]\", omitting it entirely from the TS file achieves the same logical effect (no RLS rules)\n // and correctly triggers \"unmapped policies\" if the DB still has them.\n delete collectionData[\"securityRules\"];\n }\n }\n\n // The panel works with a flat view model — presentation merged onto the\n // collection — so what arrives here has `icon` and `listProperties` at\n // the top level. On disk they belong inside `admin`. Writing them flat\n // would produce a file the backend loads and ignores and the panel\n // never reads back, which looks exactly like the edit not saving.\n collectionData = nestAdminKeys(collectionData);\n\n for (const key of Object.keys(collectionData)) {\n if (key === \"relations\") {\n this.writeRelations(collectionId, file, collectionObj, collectionData[key]);\n continue;\n }\n\n const prop = collectionObj.getProperty(key) as PropertyAssignment;\n\n let oldAstNode: ObjectLiteralExpression | undefined;\n if (prop && prop.isKind(SyntaxKind.PropertyAssignment)) {\n oldAstNode = prop.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);\n }\n\n if (partial && oldAstNode && AstSchemaEditor.isPlainObject(collectionData[key])) {\n this.mergeIntoObjectLiteral(oldAstNode, collectionData[key] as Record<string, unknown>, 2);\n continue;\n }\n\n const newInit = this.convertJsonToAstString(collectionData[key], 1, oldAstNode);\n if (prop) {\n prop.setInitializer(newInit);\n } else {\n collectionObj.addPropertyAssignment({\n name: key,\n initializer: newInit\n });\n }\n }\n }\n if (file) {\n file.formatText();\n }\n await this.project.save();\n }\n\n /**\n * Write the collection-level `relations` array.\n *\n * Relations are the one key whose values are not all data: `target` is a\n * thunk in the file, and the panel sends the target collection's slug (or,\n * for a relation it did not touch, nothing at all — `JSON.stringify` drops\n * the function). So each entry's target is resolved in that order: a slug\n * becomes `() => xCollection` plus the import it needs, and anything else\n * falls back to the thunk already in the file.\n *\n * This used to be a `continue` with a comment saying relations were handled\n * elsewhere. Nothing handled them; every edit in the Relations tab was\n * dropped without a word.\n */\n private writeRelations(collectionId: string, file: SourceFile, collectionObj: ObjectLiteralExpression, value: unknown): void {\n if (!Array.isArray(value)) return;\n\n const existing = this.findProperty(collectionObj, \"relations\");\n const oldArray = existing && existing.isKind(SyntaxKind.PropertyAssignment)\n ? existing.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression)\n : undefined;\n\n const oldElements = oldArray?.getElements() ?? [];\n const oldTargetsByName = new Map<string, string>();\n // Only for entries the file left unnamed — `relationName` is optional, and\n // those cannot be matched any other way. Positional matching is off the\n // moment the array's length changes, because then a position no longer\n // means the same relation.\n const anonymousTargetsByIndex: (string | undefined)[] = [];\n oldElements.forEach((element, index) => {\n const elementObj = element.asKind(SyntaxKind.ObjectLiteralExpression);\n if (!elementObj) return;\n const targetProp = this.findProperty(elementObj, \"target\");\n const targetInit = targetProp && targetProp.isKind(SyntaxKind.PropertyAssignment)\n ? targetProp.getInitializer()\n : undefined;\n if (!targetInit) return;\n\n const nameProp = this.findProperty(elementObj, \"relationName\");\n const nameInit = nameProp && nameProp.isKind(SyntaxKind.PropertyAssignment)\n ? nameProp.getInitializerIfKind(SyntaxKind.StringLiteral)\n : undefined;\n if (nameInit) oldTargetsByName.set(nameInit.getLiteralValue(), targetInit.getText());\n else anonymousTargetsByIndex[index] = targetInit.getText();\n });\n\n const items = value.map((entry, index) => {\n if (!AstSchemaEditor.isPlainObject(entry)) return entry;\n const relation: Record<string, unknown> = { ...entry };\n const relationName = typeof relation.relationName === \"string\" ? relation.relationName : undefined;\n const rawTarget = relation.target;\n\n let targetText: string | undefined;\n if (typeof rawTarget === \"string\" && rawTarget.trim().length > 0) {\n targetText = rawTarget.includes(\"=>\")\n ? rawTarget.trim()\n : this.targetThunk(file, rawTarget.trim());\n } else if (relationName && oldTargetsByName.has(relationName)) {\n targetText = oldTargetsByName.get(relationName);\n } else if (value.length === oldElements.length) {\n targetText = anonymousTargetsByIndex[index];\n }\n\n if (!targetText) {\n throw new Error(`Relation \"${relationName ?? `#${index}`}\" on collection \"${collectionId}\" has no target collection. Pick one before saving.`);\n }\n\n relation.target = new RawExpression(targetText);\n return relation;\n });\n\n const initializer = this.convertJsonToAstString(items, 1);\n if (existing && existing.isKind(SyntaxKind.PropertyAssignment)) {\n existing.setInitializer(initializer);\n } else {\n collectionObj.addPropertyAssignment({ name: \"relations\", initializer });\n }\n }\n\n /**\n * `() => targetCollection` for a target named by its slug, importing it if\n * the file does not already.\n */\n private targetThunk(file: SourceFile, targetSlug: string): string {\n const targetFile = this.getCollectionFile(targetSlug);\n if (!targetFile) {\n throw new Error(`Cannot link to collection \"${targetSlug}\": no file for it in ${this.collectionsDir}.`);\n }\n\n const identifier = this.getDefaultExportName(targetFile);\n if (!identifier) {\n throw new Error(`Cannot link to collection \"${targetSlug}\": ${targetFile.getFilePath()} has no default export to import.`);\n }\n\n if (targetFile.getFilePath() !== file.getFilePath() && !this.hasDefaultImport(file, identifier)) {\n const relative = path.relative(path.dirname(file.getFilePath()), targetFile.getFilePath())\n .split(path.sep)\n .join(\"/\")\n .replace(/\\.tsx?$/, \".js\");\n file.addImportDeclaration({\n defaultImport: identifier,\n moduleSpecifier: relative.startsWith(\".\") ? relative : `./${relative}`\n });\n }\n\n return `() => ${identifier}`;\n }\n\n private hasDefaultImport(file: SourceFile, identifier: string): boolean {\n return file.getImportDeclarations().some(decl => decl.getDefaultImport()?.getText() === identifier);\n }\n\n private getDefaultExportName(file: SourceFile): string | undefined {\n const declaration = file.getDefaultExportSymbol()?.getDeclarations()[0];\n const expr = declaration?.asKind(SyntaxKind.ExportAssignment)?.getExpression();\n if (expr && expr.getKind() === SyntaxKind.Identifier) return expr.getText();\n\n for (const varDecl of file.getVariableDeclarations()) {\n if (this.unwrapCollectionObject(varDecl.getInitializer())) return varDecl.getName();\n }\n return undefined;\n }\n\n public async deleteCollection(collectionId: string) {\n const file = this.getCollectionFile(collectionId);\n if (file) {\n file.deleteImmediatelySync();\n }\n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WAAW,KAAK;GAC7B,KAAK,qBAAqB;IACtB,eAAe;IACf,iBAAiB,SAAS,WAAW,GAAG,IAAI,WAAW,KAAK;GAChE,CAAC;EACL;EAEA,OAAO,SAAS;CACpB;CAEA,iBAAyB,MAAkB,YAA6B;EACpE,OAAO,KAAK,sBAAsB,CAAC,CAAC,MAAK,SAAQ,KAAK,iBAAiB,CAAC,EAAE,QAAQ,MAAM,UAAU;CACtG;CAEA,qBAA6B,MAAsC;EAE/D,MAAM,QADc,KAAK,uBAAuB,CAAC,EAAE,gBAAgB,CAAC,CAAC,GAAA,EAC3C,OAAO,WAAW,gBAAgB,CAAC,EAAE,cAAc;EAC7E,IAAI,QAAQ,KAAK,QAAQ,MAAM,WAAW,YAAY,OAAO,KAAK,QAAQ;EAE1E,KAAK,MAAM,WAAW,KAAK,wBAAwB,GAC/C,IAAI,KAAK,uBAAuB,QAAQ,eAAe,CAAC,GAAG,OAAO,QAAQ,QAAQ;CAG1F;CAEA,MAAa,iBAAiB,cAAsB;EAChD,MAAM,OAAO,KAAK,kBAAkB,YAAY;EAChD,IAAI,MACA,KAAK,sBAAsB;CAEnC;AACJ"}
@@ -18,8 +18,8 @@
18
18
  */
19
19
  import type { MiddlewareHandler, Context } from "hono";
20
20
  import type { DataDriver, AuthAdapter } from "@rebasepro/types";
21
- import type { HonoEnv } from "../api/types";
22
- import type { ApiKeyStore } from "./api-keys/api-key-store";
21
+ import type { HonoEnv } from "../api/types.js";
22
+ import type { ApiKeyStore } from "./api-keys/api-key-store.js";
23
23
  export interface AdapterAuthMiddlewareOptions {
24
24
  /** The auth adapter to delegate verification to. */
25
25
  adapter: AuthAdapter;
@@ -4,8 +4,8 @@
4
4
  * Mounts: GET /roles
5
5
  */
6
6
  import { Hono } from "hono";
7
- import type { AuthRepository } from "./interfaces";
8
- import type { HonoEnv } from "../api/types";
7
+ import type { AuthRepository } from "./interfaces.js";
8
+ import type { HonoEnv } from "../api/types.js";
9
9
  export interface AdminRolesRouteConfig {
10
10
  authRepo: AuthRepository;
11
11
  serviceKey?: string;
@@ -9,9 +9,9 @@
9
9
  * 2. Backend-level hook (`AuthHooks.onAdminCreateUser`) — global override
10
10
  * 3. Built-in default — framework fallback
11
11
  */
12
- import type { AuthRepository } from "./interfaces";
13
- import type { EmailService, EmailConfig } from "../email";
14
- import type { ResolvedAuthHooks } from "./auth-hooks";
12
+ import type { AuthRepository } from "./interfaces.js";
13
+ import type { EmailService, EmailConfig } from "../email/index.js";
14
+ import type { ResolvedAuthHooks } from "./auth-hooks.js";
15
15
  import type { AuthCollectionConfig } from "@rebasepro/types";
16
16
  /**
17
17
  * Generate a cryptographically secure random password that meets strength requirements.
@@ -10,10 +10,10 @@
10
10
  * POST /bootstrap
11
11
  */
12
12
  import { Hono } from "hono";
13
- import type { AuthRepository } from "./interfaces";
14
- import type { AuthHooks } from "./auth-hooks";
15
- import type { EmailService, EmailConfig } from "../email";
16
- import type { HonoEnv } from "../api/types";
13
+ import type { AuthRepository } from "./interfaces.js";
14
+ import type { AuthHooks } from "./auth-hooks.js";
15
+ import type { EmailService, EmailConfig } from "../email/index.js";
16
+ import type { HonoEnv } from "../api/types.js";
17
17
  import type { AuthCollectionConfig } from "@rebasepro/types";
18
18
  export interface AdminUsersRouteConfig {
19
19
  authRepo: AuthRepository;
@@ -22,7 +22,5 @@ export interface AdminUsersRouteConfig {
22
22
  serviceKey?: string;
23
23
  authHooks?: AuthHooks;
24
24
  collectionAuthConfig?: AuthCollectionConfig;
25
- isBootstrapCompleted?: () => Promise<boolean>;
26
- setBootstrapCompleted?: () => Promise<void>;
27
25
  }
28
26
  export declare function createAdminUsersRoute(config: AdminUsersRouteConfig): Hono<HonoEnv>;
@@ -23,8 +23,8 @@
23
23
  */
24
24
  import type { Context, MiddlewareHandler } from "hono";
25
25
  import type { DataDriver } from "@rebasepro/types";
26
- import type { HonoEnv } from "../../api/types";
27
- import type { ApiKeyStore } from "./api-key-store";
26
+ import type { HonoEnv } from "../../api/types.js";
27
+ import type { ApiKeyStore } from "./api-key-store.js";
28
28
  /**
29
29
  * Check whether a token looks like a Rebase API key.
30
30
  */
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * @module
9
9
  */
10
- import type { ApiKeyPermission } from "./api-key-types";
10
+ import type { ApiKeyPermission } from "./api-key-types.js";
11
11
  /** Operations that map to HTTP methods. */
12
12
  export type ApiKeyOperation = "read" | "write" | "delete";
13
13
  /**
@@ -8,8 +8,8 @@
8
8
  * @module
9
9
  */
10
10
  import { Hono } from "hono";
11
- import type { HonoEnv } from "../../api/types";
12
- import type { ApiKeyStore } from "./api-key-store";
11
+ import type { HonoEnv } from "../../api/types.js";
12
+ import type { ApiKeyStore } from "./api-key-store.js";
13
13
  export interface ApiKeyRouteOptions {
14
14
  store: ApiKeyStore;
15
15
  serviceKey?: string;
@@ -8,7 +8,7 @@
8
8
  * @module
9
9
  */
10
10
  import type { DataDriver } from "@rebasepro/types";
11
- import type { ApiKey, ApiKeyMasked, ApiKeyWithSecret, CreateApiKeyRequest, UpdateApiKeyRequest } from "./api-key-types";
11
+ import type { ApiKey, ApiKeyMasked, ApiKeyWithSecret, CreateApiKeyRequest, UpdateApiKeyRequest } from "./api-key-types.js";
12
12
  export interface ApiKeyStore {
13
13
  /** Ensure the `rebase.api_keys` table exists. Called once on startup. */
14
14
  ensureTable(): Promise<void>;
@@ -6,12 +6,12 @@
6
6
  *
7
7
  * @module
8
8
  */
9
- export type { ApiKey, ApiKeyMasked, ApiKeyPermission, ApiKeyWithSecret, CreateApiKeyRequest, UpdateApiKeyRequest } from "./api-key-types";
10
- export { createApiKeyStore } from "./api-key-store";
11
- export type { ApiKeyStore } from "./api-key-store";
12
- export { isApiKeyToken, validateApiKey, createApiKeyPreAuth, createFunctionApiKeyGuard, createStorageApiKeyGuard } from "./api-key-middleware";
13
- export type { ApiKeyAuthOptions } from "./api-key-middleware";
14
- export { httpMethodToOperation, isOperationAllowed, isFunctionAllowed, isStorageAllowed } from "./api-key-permission-guard";
15
- export type { ApiKeyOperation } from "./api-key-permission-guard";
16
- export { createApiKeyRoutes } from "./api-key-routes";
17
- export type { ApiKeyRouteOptions } from "./api-key-routes";
9
+ export type { ApiKey, ApiKeyMasked, ApiKeyPermission, ApiKeyWithSecret, CreateApiKeyRequest, UpdateApiKeyRequest } from "./api-key-types.js";
10
+ export { createApiKeyStore } from "./api-key-store.js";
11
+ export type { ApiKeyStore } from "./api-key-store.js";
12
+ export { isApiKeyToken, validateApiKey, createApiKeyPreAuth, createFunctionApiKeyGuard, createStorageApiKeyGuard } from "./api-key-middleware.js";
13
+ export type { ApiKeyAuthOptions } from "./api-key-middleware.js";
14
+ export { httpMethodToOperation, isOperationAllowed, isFunctionAllowed, isStorageAllowed } from "./api-key-permission-guard.js";
15
+ export type { ApiKeyOperation } from "./api-key-permission-guard.js";
16
+ export { createApiKeyRoutes } from "./api-key-routes.js";
17
+ export type { ApiKeyRouteOptions } from "./api-key-routes.js";
@@ -1,5 +1,5 @@
1
- import type { OAuthProvider } from "./interfaces";
2
- import { type OAuthCodeFlowPayload } from "./oauth-code-flow";
1
+ import type { OAuthProvider } from "./interfaces.js";
2
+ import { type OAuthCodeFlowPayload } from "./oauth-code-flow.js";
3
3
  /** Extra field Apple's client sends that no other provider has. */
4
4
  export interface AppleCodeFlowPayload extends OAuthCodeFlowPayload {
5
5
  /**
@@ -36,14 +36,14 @@
36
36
  * };
37
37
  * ```
38
38
  */
39
- import type { PasswordValidationResult } from "./password";
40
- import type { AuthRepository, UserData, CreateUserData } from "./interfaces";
41
- import type { EmailService, EmailConfig } from "../email";
39
+ import type { PasswordValidationResult } from "./password.js";
40
+ import type { AuthRepository, UserData, CreateUserData } from "./interfaces.js";
41
+ import type { EmailService, EmailConfig } from "../email/index.js";
42
42
  import type { AuthResponsePayload, TransformAuthResponseContext } from "@rebasepro/types";
43
43
  /**
44
44
  * Authentication method identifier for lifecycle hooks.
45
45
  */
46
- export type AuthMethod = "login" | "register" | "oauth" | "refresh" | "password-reset" | "anonymous" | "magic-link" | "mfa";
46
+ export type AuthMethod = "login" | "register" | "oauth" | "refresh" | "password-reset" | "anonymous" | "magic-link" | "otp" | "mfa";
47
47
  /**
48
48
  * Hook specific parts of the built-in Rebase auth implementation.
49
49
  *
@@ -1,5 +1,5 @@
1
- import type { OAuthProvider } from "./interfaces";
2
- import { type OAuthCodeFlowPayload } from "./oauth-code-flow";
1
+ import type { OAuthProvider } from "./interfaces.js";
2
+ import { type OAuthCodeFlowPayload } from "./oauth-code-flow.js";
3
3
  /**
4
4
  * Creates a Bitbucket OAuth Provider integration (OAuth 2.0 consumer).
5
5
  */
@@ -10,9 +10,10 @@
10
10
  * present the same functionality through the pluggable `AuthAdapter` contract.
11
11
  */
12
12
  import type { AuthAdapter } from "@rebasepro/types";
13
- import type { AuthRepository, OAuthProvider } from "./interfaces";
14
- import type { AuthHooks } from "./auth-hooks";
15
- import type { EmailService, EmailConfig } from "../email";
13
+ import type { CaptchaConfig } from "./captcha.js";
14
+ import type { AuthRepository, OAuthProvider } from "./interfaces.js";
15
+ import type { AuthHooks } from "./auth-hooks.js";
16
+ import type { EmailService, EmailConfig } from "../email/index.js";
16
17
  /**
17
18
  * Configuration for the built-in Rebase auth adapter.
18
19
  *
@@ -50,6 +51,8 @@ export interface BuiltinAuthAdapterConfig {
50
51
  allowAnonymous?: boolean;
51
52
  /** Whether to expose the authenticated email→minimal-profile lookup route. */
52
53
  allowUserLookup?: boolean;
54
+ /** Bot protection for the auth routes. See `captcha.ts`. */
55
+ captcha?: CaptchaConfig;
53
56
  /** Default role to assign to new users. */
54
57
  defaultRole?: string;
55
58
  /** OAuth providers to register. */
@@ -64,8 +67,9 @@ export interface BuiltinAuthAdapterConfig {
64
67
  collectionAuthConfig?: import("@rebasepro/types").AuthCollectionConfig;
65
68
  /** Enable magic link (passwordless email) login. Requires email service. */
66
69
  enableMagicLink?: boolean;
70
+ enableEmailOtp?: boolean;
67
71
  /** Opt-in httpOnly cookie mode for refresh tokens. */
68
- cookieAuth?: import("./routes").CookieAuthConfig;
72
+ cookieAuth?: import("./routes.js").CookieAuthConfig;
69
73
  }
70
74
  /**
71
75
  * Create the built-in Rebase auth adapter.
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The `GET /auth/config` payload, assembled in exactly one place.
3
+ *
4
+ * Two handlers used to claim that path — `init.ts` registers it directly and
5
+ * only afterwards mounts the auth router, so the router's copy never ran — and
6
+ * they returned *different shapes*: one reported `emailServiceEnabled` and
7
+ * `magicLinkEnabled`, the other `passwordReset` and `magicLink`. A fix applied
8
+ * to the shadowed copy therefore changed nothing, twice.
9
+ *
10
+ * The router's copy is gone. This module is what the surviving handler calls,
11
+ * so the payload has one definition and one set of rules — the same move
12
+ * `registration-policy.ts` makes for the predicate itself.
13
+ */
14
+ import type { AuthAdapterCapabilities } from "@rebasepro/types";
15
+ /** Everything the built-in payload is derived from. */
16
+ export interface BuiltinAuthCapabilityInputs {
17
+ /**
18
+ * True when the user table is empty — the first-user bootstrap window.
19
+ *
20
+ * The caller resolves this, because how you count users is the adapter's
21
+ * business and it is also reported verbatim as `needsSetup`.
22
+ */
23
+ needsSetup: boolean;
24
+ /** Steady-state self-registration. */
25
+ allowRegistration?: boolean;
26
+ /** The hard kill switch: blocks registration and anonymous sign-in alike. */
27
+ disableSelfRegistration?: boolean;
28
+ /** Opt-in `POST /auth/anonymous`. */
29
+ allowAnonymous?: boolean;
30
+ /** Magic-link login. Needs an email service to be of any use. */
31
+ enableMagicLink?: boolean;
32
+ /** Email one-time codes. Needs an email service, as magic link does. */
33
+ enableEmailOtp?: boolean;
34
+ /**
35
+ * Whether an email service is configured.
36
+ *
37
+ * Every email-borne flow hangs off this — password reset, verification and
38
+ * magic link are advertised only when a message can actually be sent.
39
+ */
40
+ emailConfigured: boolean;
41
+ /** OAuth provider ids the backend has wired, e.g. `["google", "github"]`. */
42
+ enabledProviders: string[];
43
+ }
44
+ /**
45
+ * Build the capability document for the built-in auth adapter.
46
+ *
47
+ * Every flag is a *runtime* answer, not a compile-time feature list: what this
48
+ * advertises, the matching route must accept. `registrationEnabled` and
49
+ * `anonymousLogin` go through the shared predicates for exactly that reason.
50
+ */
51
+ export declare function buildBuiltinAuthCapabilities(inputs: BuiltinAuthCapabilityInputs): AuthAdapterCapabilities;
@@ -0,0 +1,86 @@
1
+ import type { MiddlewareHandler } from "hono";
2
+ import { HonoEnv } from "../api/types.js";
3
+ /** The two providers whose verify endpoints share this exact shape. */
4
+ export type CaptchaProvider = "turnstile" | "hcaptcha";
5
+ export interface CaptchaVerifyRequest {
6
+ token: string;
7
+ /** The caller's address, which both providers accept as a cross-check. */
8
+ remoteIp?: string;
9
+ }
10
+ export interface CaptchaVerifyResult {
11
+ success: boolean;
12
+ /** Provider error codes, for the log line. Never returned to the caller. */
13
+ errorCodes?: string[];
14
+ }
15
+ export type CaptchaVerifier = (request: CaptchaVerifyRequest) => Promise<CaptchaVerifyResult>;
16
+ export interface CaptchaConfig {
17
+ /** Off unless set. */
18
+ enabled?: boolean;
19
+ provider?: CaptchaProvider;
20
+ /** The provider's secret. Required when enabled, unless `verify` is given. */
21
+ secret?: string;
22
+ /**
23
+ * Which routes to protect. Defaults to the three that send mail or create
24
+ * accounts: `register`, `forgotPassword`, `magicLink`.
25
+ *
26
+ * `login` is deliberately not on by default. A challenge on every sign-in is
27
+ * a tax on every real user, and credential stuffing is what the rate limiter
28
+ * and account lockout are for.
29
+ */
30
+ routes?: CaptchaRoute[];
31
+ /**
32
+ * Where the token is read from. Defaults to the `captchaToken` field of the
33
+ * JSON body, with the `cf-turnstile-response` / `h-captcha-response` header
34
+ * accepted as a fallback.
35
+ */
36
+ tokenField?: string;
37
+ /** Override the verifier. Supplying it makes `secret` unnecessary. */
38
+ verify?: CaptchaVerifier;
39
+ /** Milliseconds before a verification attempt is abandoned. Default 5000. */
40
+ timeoutMs?: number;
41
+ }
42
+ export type CaptchaRoute = "register" | "login" | "forgotPassword" | "magicLink" | "emailOtp";
43
+ export declare const DEFAULT_CAPTCHA_ROUTES: CaptchaRoute[];
44
+ /**
45
+ * The built-in verifier: a form post, which is the whole protocol.
46
+ *
47
+ * A non-200, a timeout or a malformed body are all "not verified" rather than
48
+ * exceptions — the caller cannot distinguish them and should not be told which
49
+ * one happened.
50
+ */
51
+ export declare function createHttpCaptchaVerifier(options: {
52
+ provider: CaptchaProvider;
53
+ secret: string;
54
+ timeoutMs?: number;
55
+ fetchImpl?: typeof fetch;
56
+ }): CaptchaVerifier;
57
+ /**
58
+ * Resolve a config into a verifier, or explain why it cannot be used.
59
+ *
60
+ * Returns `undefined` when the feature is off. Throws when it is on but
61
+ * unusable — a misconfigured challenge must not boot as an absent one, because
62
+ * the whole point is that it is there.
63
+ */
64
+ export declare function resolveCaptchaVerifier(config: CaptchaConfig | undefined): CaptchaVerifier | undefined;
65
+ /** Read the challenge token out of a request, body field first, then headers. */
66
+ export declare function extractCaptchaToken(c: Parameters<MiddlewareHandler<HonoEnv>>[0], field: string): Promise<string | undefined>;
67
+ /**
68
+ * Middleware refusing a request whose challenge is missing or unverified.
69
+ *
70
+ * The response says only that the challenge failed. Which of "absent",
71
+ * "malformed", "already used" or "provider unreachable" it was is a log line,
72
+ * because telling a script which one it hit is telling it how to get closer.
73
+ */
74
+ export declare function createCaptchaMiddleware(options: {
75
+ verify: CaptchaVerifier;
76
+ tokenField?: string;
77
+ /** Named in the log so a failure says which route refused. */
78
+ route: CaptchaRoute;
79
+ }): MiddlewareHandler<HonoEnv>;
80
+ /**
81
+ * A middleware per protected route, or an empty map when the feature is off.
82
+ *
83
+ * Routes not named get nothing at all rather than a pass-through, so an unnamed
84
+ * route costs exactly what it did before.
85
+ */
86
+ export declare function buildCaptchaMiddlewares(config: CaptchaConfig | undefined): Partial<Record<CaptchaRoute, MiddlewareHandler<HonoEnv>>>;
@@ -1,7 +1,7 @@
1
1
  import type { Context } from "hono";
2
2
  import type { AuthResponsePayload } from "@rebasepro/types";
3
- import type { HonoEnv } from "../api/types";
4
- import type { CookieAuthConfig } from "./routes";
3
+ import type { HonoEnv } from "../api/types.js";
4
+ import type { CookieAuthConfig } from "./routes.js";
5
5
  /**
6
6
  * Cookie auth helpers for httpOnly refresh tokens.
7
7
  */
@@ -1,5 +1,5 @@
1
- import type { OAuthProvider } from "./interfaces";
2
- import { type OAuthCodeFlowPayload } from "./oauth-code-flow";
1
+ import type { OAuthProvider } from "./interfaces.js";
2
+ import { type OAuthCodeFlowPayload } from "./oauth-code-flow.js";
3
3
  /**
4
4
  * Creates a Discord OAuth2 Provider integration.
5
5
  *
@@ -1,5 +1,5 @@
1
- import type { OAuthProvider } from "./interfaces";
2
- import { type OAuthCodeFlowPayload } from "./oauth-code-flow";
1
+ import type { OAuthProvider } from "./interfaces.js";
2
+ import { type OAuthCodeFlowPayload } from "./oauth-code-flow.js";
3
3
  /**
4
4
  * Creates a Facebook / Meta OAuth Provider integration.
5
5
  *
@@ -1,5 +1,5 @@
1
- import type { OAuthProvider } from "./interfaces";
2
- import { type OAuthCodeFlowPayload } from "./oauth-code-flow";
1
+ import type { OAuthProvider } from "./interfaces.js";
2
+ import { type OAuthCodeFlowPayload } from "./oauth-code-flow.js";
3
3
  /**
4
4
  * Creates a GitHub OAuth Provider integration.
5
5
  *
@@ -1,5 +1,5 @@
1
- import type { OAuthProvider } from "./interfaces";
2
- import { type OAuthCodeFlowPayload } from "./oauth-code-flow";
1
+ import type { OAuthProvider } from "./interfaces.js";
2
+ import { type OAuthCodeFlowPayload } from "./oauth-code-flow.js";
3
3
  /**
4
4
  * Creates a GitLab OAuth Provider integration.
5
5
  * Works with both GitLab.com and self-hosted instances.
@@ -1,4 +1,4 @@
1
- import type { OAuthProvider } from "./interfaces";
1
+ import type { OAuthProvider } from "./interfaces.js";
2
2
  export interface GoogleUserInfo {
3
3
  googleId: string;
4
4
  email: string;