@rebasepro/server 0.20.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{admin_block-0Xu0r6eZ.js → admin_block-DxKLmdiv.js} +26 -8
- package/dist/{admin_block-0Xu0r6eZ.js.map → admin_block-DxKLmdiv.js.map} +1 -1
- package/dist/api/ast-schema-editor.d.ts +15 -0
- package/dist/api/rest/api-generator.d.ts +28 -0
- package/dist/{ast-schema-editor-C6mDz0XN.js → ast-schema-editor-CslO8Oje.js} +24 -4
- package/dist/ast-schema-editor-CslO8Oje.js.map +1 -0
- package/dist/auth/jwt.d.ts +67 -0
- package/dist/auth/rls-scope.d.ts +14 -0
- package/dist/{auth-DJsLXsCR.js → auth-gzoRjnuh.js} +24 -12
- package/dist/auth-gzoRjnuh.js.map +1 -0
- package/dist/boot/env.d.ts +8 -2
- package/dist/boot/fetch-bundle.d.ts +19 -0
- package/dist/boot/role.d.ts +2 -0
- package/dist/contract-routes-eLxV0le1.js.map +1 -1
- package/dist/{cron-routes-Bfwni8Zg.js → cron-routes-BamgO0Xr.js} +2 -2
- package/dist/{cron-routes-Bfwni8Zg.js.map → cron-routes-BamgO0Xr.js.map} +1 -1
- package/dist/{cron-store-Bsiw4Q6u.js → cron-store-yXOyIEmn.js} +2 -3
- package/dist/{cron-store-Bsiw4Q6u.js.map → cron-store-yXOyIEmn.js.map} +1 -1
- package/dist/db/ambient-transaction.d.ts +48 -0
- package/dist/ddl-bootstrap-CfNvxMuK.js.map +1 -1
- package/dist/deploy/pod-contract.d.ts +1 -1
- package/dist/errors-DMImyqyR.js.map +1 -1
- package/dist/functions/index.js.map +1 -1
- package/dist/{history-recorder-r5_IzSHK.js → history-recorder-hBGuXcZc.js} +2 -2
- package/dist/{history-recorder-r5_IzSHK.js.map → history-recorder-hBGuXcZc.js.map} +1 -1
- package/dist/{history-store-D4RVK-uZ.js → history-store-C9EtGtoL.js} +5 -6
- package/dist/history-store-C9EtGtoL.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.es.js +2266 -93
- package/dist/index.es.js.map +1 -1
- package/dist/init/callback-client.d.ts +16 -0
- package/dist/init/surfaces.d.ts +37 -7
- package/dist/jobs/types.d.ts +5 -0
- package/dist/{jobs-CW5lm_Ix.js → jobs-DZ8DLLcU.js} +82 -13
- package/dist/jobs-DZ8DLLcU.js.map +1 -0
- package/dist/{jwt-DATvkKB_.js → jwt-C4OW-DNq.js} +136 -4
- package/dist/jwt-C4OW-DNq.js.map +1 -0
- package/dist/logger-DO2PZc4i.js.map +1 -1
- package/dist/mcp/consent-page.d.ts +75 -0
- package/dist/mcp/mcp-routes.d.ts +52 -0
- package/dist/mcp/mcp-tools.d.ts +51 -0
- package/dist/mcp/oauth-metadata.d.ts +123 -0
- package/dist/mcp/oauth-routes.d.ts +52 -0
- package/dist/mcp/oauth-store.d.ts +157 -0
- package/dist/metrics/index.d.ts +16 -1
- package/dist/{openapi-generator-DGyLbISS.js → openapi-generator-CAFKF36E.js} +2 -8
- package/dist/openapi-generator-CAFKF36E.js.map +1 -0
- package/dist/{query-parser-BQiPZrM-.js → query-parser-uqzkZ82i.js} +2 -2
- package/dist/{query-parser-BQiPZrM-.js.map → query-parser-uqzkZ82i.js.map} +1 -1
- package/dist/{schema-editor-routes-C3TLZqAC.js → schema-editor-routes-BKOmdf4M.js} +2 -2
- package/dist/{schema-editor-routes-C3TLZqAC.js.map → schema-editor-routes-BKOmdf4M.js.map} +1 -1
- package/dist/services/webhook-service.d.ts +11 -8
- package/dist/sql-rows-C6GEc2oE.js +45 -0
- package/dist/sql-rows-C6GEc2oE.js.map +1 -0
- package/dist/src-Br6ARbs6.js.map +1 -1
- package/dist/{src-DqZ9YiGA.js → src-DW1cQ_28.js} +261 -17
- package/dist/src-DW1cQ_28.js.map +1 -0
- package/dist/utils/portable-crypto.d.ts +8 -0
- package/package.json +5 -5
- package/dist/ast-schema-editor-C6mDz0XN.js.map +0 -1
- package/dist/auth-DJsLXsCR.js.map +0 -1
- package/dist/history-store-D4RVK-uZ.js.map +0 -1
- package/dist/internal-tables-DYVcFFSv.js +0 -117
- package/dist/internal-tables-DYVcFFSv.js.map +0 -1
- package/dist/jobs-CW5lm_Ix.js.map +0 -1
- package/dist/jwt-DATvkKB_.js.map +0 -1
- package/dist/openapi-generator-DGyLbISS.js.map +0 -1
- package/dist/src-DqZ9YiGA.js.map +0 -1
|
@@ -163,26 +163,44 @@ function nestAdminKeysOf(source, adminKeys) {
|
|
|
163
163
|
function nestAdminCollectionKeys(collection) {
|
|
164
164
|
return nestAdminKeysOf(collection, ADMIN_COLLECTION_KEYS);
|
|
165
165
|
}
|
|
166
|
+
/** A record of properties, keyed by name — a map's `properties`, or a `oneOf` block's. */
|
|
167
|
+
function nestEachProperty(properties) {
|
|
168
|
+
return Object.fromEntries(Object.entries(properties).map(([key, child]) => [key, isNestable(child) ? nestAdminPropertyKeys(child) : child]));
|
|
169
|
+
}
|
|
170
|
+
/** Anything the walk can descend into: a plain object, not an array. */
|
|
171
|
+
function isNestable(value) {
|
|
172
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
173
|
+
}
|
|
166
174
|
/**
|
|
167
175
|
* {@link nestAdminKeysOf} for a property, applied to its children too.
|
|
168
176
|
*
|
|
169
|
-
* A map property carries `properties`, an array property carries `of`, and
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
*
|
|
177
|
+
* A map property carries `properties`, an array property carries `of`, and an
|
|
178
|
+
* array of typed blocks carries `oneOf.properties` — a record of properties like
|
|
179
|
+
* a map's. All of them hold properties with `admin` blocks of their own. A flat
|
|
180
|
+
* `readOnly` left on a child is as dead — and as fatal at the next boot — as one
|
|
181
|
+
* left on the parent, so the walk goes all the way down.
|
|
182
|
+
*
|
|
183
|
+
* `oneOf` was the container this walk did not know about, and it is the one the
|
|
184
|
+
* block-based collection templates are built out of: every block inside them
|
|
185
|
+
* kept its flat `markdown`, and the collection they created would not boot.
|
|
173
186
|
*
|
|
174
187
|
* @group Models
|
|
175
188
|
*/
|
|
176
189
|
function nestAdminPropertyKeys(property) {
|
|
177
190
|
const nested = nestAdminKeysOf(property, ADMIN_PROPERTY_KEYS);
|
|
178
191
|
const children = nested.properties;
|
|
179
|
-
if (
|
|
192
|
+
if (isNestable(children)) nested.properties = nestEachProperty(children);
|
|
193
|
+
const oneOf = nested.oneOf;
|
|
194
|
+
if (isNestable(oneOf) && isNestable(oneOf.properties)) nested.oneOf = {
|
|
195
|
+
...oneOf,
|
|
196
|
+
properties: nestEachProperty(oneOf.properties)
|
|
197
|
+
};
|
|
180
198
|
const of = nested.of;
|
|
181
|
-
if (Array.isArray(of)) nested.of = of.map((entry) =>
|
|
182
|
-
else if (of
|
|
199
|
+
if (Array.isArray(of)) nested.of = of.map((entry) => isNestable(entry) ? nestAdminPropertyKeys(entry) : entry);
|
|
200
|
+
else if (isNestable(of)) nested.of = nestAdminPropertyKeys(of);
|
|
183
201
|
return nested;
|
|
184
202
|
}
|
|
185
203
|
//#endregion
|
|
186
204
|
export { nestAdminPropertyKeys as i, ADMIN_PROPERTY_KEYS as n, nestAdminCollectionKeys as r, ADMIN_COLLECTION_KEYS as t };
|
|
187
205
|
|
|
188
|
-
//# sourceMappingURL=admin_block-
|
|
206
|
+
//# sourceMappingURL=admin_block-DxKLmdiv.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin_block-
|
|
1
|
+
{"version":3,"file":"admin_block-DxKLmdiv.js","names":[],"sources":["../../types/src/types/admin_block.ts"],"sourcesContent":["/**\n * The keys of a collection's admin block, as data.\n *\n * There is no *type* for the block in this package any more, and that is the point:\n * `admin` is not declared on `BaseCollectionConfig` or on any property here, so a\n * BaaS install cannot even write one. `@rebasepro/cms-types` adds the field back by\n * declaration merging, which is why installing it is what makes the admin surface\n * appear.\n *\n * The *list* still has to live here, because three runtime consumers need it and two\n * of them are core — see below.\n */\n\n/**\n * Every key that belongs inside a collection's `admin` block, as data.\n *\n * The type that describes these fields is `AdminCollectionOptions` in\n * `@rebasepro/cms-types`, and it is erased at build time — but three runtime\n * consumers need the list, and two of them are core:\n *\n * - `serializeCollections`, to drop the block from the contract\n * - the ts-morph schema editor in `@rebasepro/server`, which rewrites collection\n * files on disk from the admin panel and has to know where each key goes. A key\n * missing from this list gets written to the *top level* of the file, where the\n * backend ignores it and the panel never finds it again.\n * - the `collections-admin-block` codemod\n *\n * `@rebasepro/cms-types` re-exports this and asserts it names only real option\n * keys; the count is pinned by a test there.\n *\n * @group Models\n */\nexport const ADMIN_COLLECTION_KEYS = [\n \"Actions\",\n \"additionalFields\",\n \"alwaysApplyDefaultValues\",\n \"browserCallbacks\",\n \"components\",\n \"customViews\",\n \"defaultEntityAction\",\n \"defaultFilter\",\n \"defaultSelectedView\",\n \"defaultSize\",\n \"defaultViewMode\",\n \"disableDefaultActions\",\n \"display\",\n \"enabledViews\",\n \"entityActions\",\n \"entityViews\",\n \"exportable\",\n \"filterPresets\",\n \"fixedFilter\",\n \"form\",\n \"formAutoSave\",\n \"formView\",\n \"group\",\n \"hideFromEntityViews\",\n \"hideFromNavigation\",\n \"hideIdFromCollection\",\n \"hideIdFromForm\",\n \"icon\",\n \"includeJsonView\",\n \"inlineEditing\",\n \"kanban\",\n \"listProperties\",\n \"localChangesBackup\",\n \"openEntityMode\",\n \"orderProperty\",\n \"pagination\",\n \"previewProperties\",\n \"propertiesOrder\",\n \"selectionController\",\n \"selectionEnabled\",\n \"sideDialogWidth\",\n \"sort\"\n] as const;\n\n/** A key of a collection's `admin` block. @group Models */\nexport type AdminCollectionKey = typeof ADMIN_COLLECTION_KEYS[number];\n\n/**\n * Every key that belongs inside a *property's* `admin` block, as data.\n *\n * The union of `AdminPropertyOptions` and its per-type extensions\n * (`AdminStringOptions`, `AdminArrayOptions`, …) in `@rebasepro/cms-types`.\n * It lives here for the same reason {@link ADMIN_COLLECTION_KEYS} does: the\n * runtime consumers are core packages that the BaaS guard forbids from\n * importing `@rebasepro/cms-types`. Here it is the boot-time collection\n * validator in `@rebasepro/server`, which has to tell \"you left `readOnly` at\n * the top of the property, where nothing reads it\" apart from \"you invented a\n * key we have never heard of\".\n *\n * `@rebasepro/cms-types` re-exports this and asserts it names only real\n * option keys.\n *\n * @group Models\n */\nexport const ADMIN_PROPERTY_KEYS = [\n \"canAddElements\",\n \"clearable\",\n \"columnWidth\",\n \"customProps\",\n \"disabled\",\n \"expanded\",\n \"Field\",\n \"Filter\",\n \"filterOperators\",\n \"fixedFilter\",\n \"format\",\n \"hideFromCollection\",\n \"includeEntityLink\",\n \"includeId\",\n \"markdown\",\n \"minimalistView\",\n \"multiline\",\n \"Preview\",\n \"previewAsTag\",\n \"previewProperties\",\n \"readOnly\",\n \"renderInForm\",\n \"sortable\",\n \"span\",\n \"spreadChildren\",\n \"urlPreview\",\n \"widget\",\n] as const;\n\n/** A key of a property's `admin` block. @group Models */\nexport type AdminPropertyKey = typeof ADMIN_PROPERTY_KEYS[number];\n\n/**\n * Move flattened admin keys back down into the `admin` block.\n *\n * The admin panel works with a *flat* view model — the block merged onto the\n * collection — so what comes back from a form has `icon` and `defaultViewMode`\n * at the top level while `admin` still holds whatever the file was loaded with.\n * This is the way back.\n *\n * **The top-level value wins.** It is the one the form just wrote; the block is\n * the copy the collection was loaded with, and preferring it resolves every edit\n * in favour of the value the user changed away from.\n *\n * This lives here, next to the key lists, because it had two implementations —\n * `toAdminCollectionConfig` in `@rebasepro/cms-types` and `nestAdminKeys` in\n * `@rebasepro/server`'s schema editor — that agreed on everything except that\n * precedence, which is the only part that decides whether a save is visible.\n *\n * @group Models\n */\nexport function nestAdminKeysOf(\n source: Record<string, unknown>,\n adminKeys: readonly string[]\n): Record<string, unknown> {\n const keys = new Set<string>(adminKeys);\n const top: Record<string, unknown> = {};\n const block: Record<string, unknown> = { ...((source.admin as Record<string, unknown> | undefined) ?? {}) };\n\n for (const [key, value] of Object.entries(source)) {\n if (key === \"admin\") continue;\n if (keys.has(key)) block[key] = value;\n else top[key] = value;\n }\n\n if (Object.keys(block).length > 0) top.admin = block;\n return top;\n}\n\n/**\n * {@link nestAdminKeysOf} for a collection.\n *\n * @group Models\n */\nexport function nestAdminCollectionKeys(collection: Record<string, unknown>): Record<string, unknown> {\n return nestAdminKeysOf(collection, ADMIN_COLLECTION_KEYS);\n}\n\n/** A record of properties, keyed by name — a map's `properties`, or a `oneOf` block's. */\nfunction nestEachProperty(properties: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(properties).map(([key, child]) => [\n key,\n isNestable(child) ? nestAdminPropertyKeys(child) : child\n ])\n );\n}\n\n/** Anything the walk can descend into: a plain object, not an array. */\nfunction isNestable(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * {@link nestAdminKeysOf} for a property, applied to its children too.\n *\n * A map property carries `properties`, an array property carries `of`, and an\n * array of typed blocks carries `oneOf.properties` — a record of properties like\n * a map's. All of them hold properties with `admin` blocks of their own. A flat\n * `readOnly` left on a child is as dead — and as fatal at the next boot — as one\n * left on the parent, so the walk goes all the way down.\n *\n * `oneOf` was the container this walk did not know about, and it is the one the\n * block-based collection templates are built out of: every block inside them\n * kept its flat `markdown`, and the collection they created would not boot.\n *\n * @group Models\n */\nexport function nestAdminPropertyKeys(property: Record<string, unknown>): Record<string, unknown> {\n const nested = nestAdminKeysOf(property, ADMIN_PROPERTY_KEYS);\n\n const children = nested.properties;\n if (isNestable(children)) {\n nested.properties = nestEachProperty(children);\n }\n\n // `oneOf` is not itself a property — it is a block holding `properties`\n // alongside `typeField`, `valueField` and `propertiesOrder`, none of which\n // may be walked as one.\n const oneOf = nested.oneOf;\n if (isNestable(oneOf) && isNestable(oneOf.properties)) {\n nested.oneOf = { ...oneOf, properties: nestEachProperty(oneOf.properties) };\n }\n\n const of = nested.of;\n if (Array.isArray(of)) {\n nested.of = of.map(entry => isNestable(entry) ? nestAdminPropertyKeys(entry) : entry);\n } else if (isNestable(of)) {\n nested.of = nestAdminPropertyKeys(of);\n }\n\n return nested;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,IAAa,wBAAwB;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;;;;;;;;;;;;;;;;;;AAsBA,IAAa,sBAAsB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,gBACZ,QACA,WACuB;CACvB,MAAM,OAAO,IAAI,IAAY,SAAS;CACtC,MAAM,MAA+B,CAAC;CACtC,MAAM,QAAiC,EAAE,GAAK,OAAO,SAAiD,CAAC,EAAG;CAE1G,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAAG;EAC/C,IAAI,QAAQ,SAAS;EACrB,IAAI,KAAK,IAAI,GAAG,GAAG,MAAM,OAAO;OAC3B,IAAI,OAAO;CACpB;CAEA,IAAI,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,GAAG,IAAI,QAAQ;CAC/C,OAAO;AACX;;;;;;AAOA,SAAgB,wBAAwB,YAA8D;CAClG,OAAO,gBAAgB,YAAY,qBAAqB;AAC5D;;AAGA,SAAS,iBAAiB,YAA8D;CACpF,OAAO,OAAO,YACV,OAAO,QAAQ,UAAU,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,CAC7C,KACA,WAAW,KAAK,IAAI,sBAAsB,KAAK,IAAI,KACvD,CAAC,CACL;AACJ;;AAGA,SAAS,WAAW,OAAkD;CAClE,OAAO,QAAQ,KAAK,KAAK,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC9E;;;;;;;;;;;;;;;;AAiBA,SAAgB,sBAAsB,UAA4D;CAC9F,MAAM,SAAS,gBAAgB,UAAU,mBAAmB;CAE5D,MAAM,WAAW,OAAO;CACxB,IAAI,WAAW,QAAQ,GACnB,OAAO,aAAa,iBAAiB,QAAQ;CAMjD,MAAM,QAAQ,OAAO;CACrB,IAAI,WAAW,KAAK,KAAK,WAAW,MAAM,UAAU,GAChD,OAAO,QAAQ;EAAE,GAAG;EAAO,YAAY,iBAAiB,MAAM,UAAU;CAAE;CAG9E,MAAM,KAAK,OAAO;CAClB,IAAI,MAAM,QAAQ,EAAE,GAChB,OAAO,KAAK,GAAG,KAAI,UAAS,WAAW,KAAK,IAAI,sBAAsB,KAAK,IAAI,KAAK;MACjF,IAAI,WAAW,EAAE,GACpB,OAAO,KAAK,sBAAsB,EAAE;CAGxC,OAAO;AACX"}
|
|
@@ -8,6 +8,21 @@
|
|
|
8
8
|
* saved or silently reverted to the value the user had just changed away from.
|
|
9
9
|
*/
|
|
10
10
|
export declare function nestAdminKeys(collectionData: Record<string, unknown>): Record<string, unknown>;
|
|
11
|
+
/**
|
|
12
|
+
* {@link nestAdminKeys} for a whole collection — its properties included.
|
|
13
|
+
*
|
|
14
|
+
* `nestAdminKeys` only ever moved the COLLECTION's presentation keys. A
|
|
15
|
+
* property's — `markdown`, `multiline`, `previewAsTag` — went to disk exactly as
|
|
16
|
+
* the panel sent them, at the top level of the property, which the boot
|
|
17
|
+
* validator treats as fatal. `saveProperty` nests them; `saveCollection` did
|
|
18
|
+
* not, and *creating* a collection is a `saveCollection`.
|
|
19
|
+
*
|
|
20
|
+
* So a collection created from a template wrote a file that could not boot, and
|
|
21
|
+
* took the whole project down with it — the loader imports every collection in
|
|
22
|
+
* the directory, so one bad file stops `rebase dev` from starting at all. The
|
|
23
|
+
* panel reported success.
|
|
24
|
+
*/
|
|
25
|
+
export declare function nestAdminKeysDeep(collectionData: Record<string, unknown>): Record<string, unknown>;
|
|
11
26
|
export declare class AstSchemaEditor {
|
|
12
27
|
private project;
|
|
13
28
|
private collectionsDir;
|
|
@@ -141,6 +141,34 @@ export declare class RestApiGenerator {
|
|
|
141
141
|
* it here would report a resolution failure as a validation failure.
|
|
142
142
|
*/
|
|
143
143
|
private resolveNestedWriteCollection;
|
|
144
|
+
/**
|
|
145
|
+
* `PATCH <collection>/<id>/<relation>/<targetId>` with a `_pivot` body: set
|
|
146
|
+
* the columns that one many-to-many link carries.
|
|
147
|
+
*
|
|
148
|
+
* The membership array on the parent (`PATCH posts/1 { tags: [...] }`) sets
|
|
149
|
+
* *which* links exist; this sets what one of them holds. They are separate
|
|
150
|
+
* because the array cannot express a single-link edit without either
|
|
151
|
+
* unlinking everything it omits or re-sending the whole set — and re-sending
|
|
152
|
+
* the set to change one `role` is exactly the lost update that the
|
|
153
|
+
* membership diff exists to avoid.
|
|
154
|
+
*
|
|
155
|
+
* Validated against the junction's own properties, through the same
|
|
156
|
+
* `assertWriteRequestValid` a row's values go through: `required`, `enum`,
|
|
157
|
+
* `min`/`max`/`matches` and per-field `access.write` mean the same thing on
|
|
158
|
+
* a payload column as on a collection's, or the promise that they are
|
|
159
|
+
* "declared exactly like collection properties" is not one.
|
|
160
|
+
*/
|
|
161
|
+
private updateRelationPivotFromBody;
|
|
162
|
+
/**
|
|
163
|
+
* The synthetic collection standing in for the junction a nested path's last
|
|
164
|
+
* hop reaches through, or `undefined` when that hop is not a `manyToMany`
|
|
165
|
+
* carrying `through.properties`.
|
|
166
|
+
*
|
|
167
|
+
* Built from the relation rather than by walking every collection: the same
|
|
168
|
+
* `getJunctionConfigForRelation` the schema planner and the driver use, so
|
|
169
|
+
* the shape validated here is the shape the columns were emitted from.
|
|
170
|
+
*/
|
|
171
|
+
private resolveJunctionCollection;
|
|
144
172
|
/**
|
|
145
173
|
* Get the request-scoped driver. Throws if none is set — never falls
|
|
146
174
|
* back to the unscoped `this.driver` to avoid bypassing RLS/auth.
|
|
@@ -3,7 +3,7 @@ import __rebaseProcess from "process";
|
|
|
3
3
|
globalThis.process ??= __rebaseProcess;
|
|
4
4
|
__rebaseCreateRequire(import.meta.url);
|
|
5
5
|
import "./src-Br6ARbs6.js";
|
|
6
|
-
import { i as nestAdminPropertyKeys, r as nestAdminCollectionKeys } from "./admin_block-
|
|
6
|
+
import { i as nestAdminPropertyKeys, r as nestAdminCollectionKeys } from "./admin_block-DxKLmdiv.js";
|
|
7
7
|
import * as fs$1 from "fs";
|
|
8
8
|
import * as path$1 from "path";
|
|
9
9
|
import { IndentationText, Node, Project, SyntaxKind } from "ts-morph";
|
|
@@ -58,6 +58,26 @@ var RawExpression = class {
|
|
|
58
58
|
function nestAdminKeys(collectionData) {
|
|
59
59
|
return nestAdminCollectionKeys(collectionData);
|
|
60
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* {@link nestAdminKeys} for a whole collection — its properties included.
|
|
63
|
+
*
|
|
64
|
+
* `nestAdminKeys` only ever moved the COLLECTION's presentation keys. A
|
|
65
|
+
* property's — `markdown`, `multiline`, `previewAsTag` — went to disk exactly as
|
|
66
|
+
* the panel sent them, at the top level of the property, which the boot
|
|
67
|
+
* validator treats as fatal. `saveProperty` nests them; `saveCollection` did
|
|
68
|
+
* not, and *creating* a collection is a `saveCollection`.
|
|
69
|
+
*
|
|
70
|
+
* So a collection created from a template wrote a file that could not boot, and
|
|
71
|
+
* took the whole project down with it — the loader imports every collection in
|
|
72
|
+
* the directory, so one bad file stops `rebase dev` from starting at all. The
|
|
73
|
+
* panel reported success.
|
|
74
|
+
*/
|
|
75
|
+
function nestAdminKeysDeep(collectionData) {
|
|
76
|
+
const nested = nestAdminKeys(collectionData);
|
|
77
|
+
const properties = nested.properties;
|
|
78
|
+
if (properties && typeof properties === "object" && !Array.isArray(properties)) nested.properties = Object.fromEntries(Object.entries(properties).map(([key, property]) => [key, property && typeof property === "object" && !Array.isArray(property) ? nestAdminPropertyKeys(property) : property]));
|
|
79
|
+
return nested;
|
|
80
|
+
}
|
|
61
81
|
var AstSchemaEditor = class AstSchemaEditor {
|
|
62
82
|
project;
|
|
63
83
|
collectionsDir;
|
|
@@ -322,7 +342,7 @@ var AstSchemaEditor = class AstSchemaEditor {
|
|
|
322
342
|
const newFilePath = this.safePath(`${safeId}.ts`);
|
|
323
343
|
if (fs$1.existsSync(newFilePath)) throw new Error(`Refusing to overwrite ${newFilePath}: a file for "${collectionId}" already exists but could not be parsed.`);
|
|
324
344
|
const varName = `${AstSchemaEditor.collectionVarName(safeId)}Collection`;
|
|
325
|
-
file = this.project.createSourceFile(newFilePath, `import { CollectionConfig } from "@rebasepro/types";\n\nconst ${varName}: CollectionConfig = ${this.convertJsonToAstString(
|
|
345
|
+
file = this.project.createSourceFile(newFilePath, `import { CollectionConfig } from "@rebasepro/types";\n\nconst ${varName}: CollectionConfig = ${this.convertJsonToAstString(nestAdminKeysDeep(collectionData))};\n\nexport default ${varName};\n`);
|
|
326
346
|
} else {
|
|
327
347
|
if (!partial) {
|
|
328
348
|
if (!("securityRules" in collectionData) || collectionData.securityRules === void 0 || Array.isArray(collectionData.securityRules) && collectionData.securityRules.length === 0) {
|
|
@@ -331,7 +351,7 @@ var AstSchemaEditor = class AstSchemaEditor {
|
|
|
331
351
|
delete collectionData["securityRules"];
|
|
332
352
|
}
|
|
333
353
|
}
|
|
334
|
-
collectionData =
|
|
354
|
+
collectionData = nestAdminKeysDeep(collectionData);
|
|
335
355
|
for (const key of Object.keys(collectionData)) {
|
|
336
356
|
if (key === "relations") {
|
|
337
357
|
this.writeRelations(collectionId, file, collectionObj, collectionData[key]);
|
|
@@ -442,4 +462,4 @@ var AstSchemaEditor = class AstSchemaEditor {
|
|
|
442
462
|
//#endregion
|
|
443
463
|
export { AstSchemaEditor };
|
|
444
464
|
|
|
445
|
-
//# sourceMappingURL=ast-schema-editor-
|
|
465
|
+
//# sourceMappingURL=ast-schema-editor-CslO8Oje.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ast-schema-editor-CslO8Oje.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 * The only relation-target expression this editor will write through verbatim.\n *\n * A relation's `target` is emitted as SOURCE, not as a string literal, because\n * it has to be `() => otherCollection`. The test for \"is this already a thunk?\"\n * used to be \"does it contain an arrow\", which `() => { require(\"child_process\")\n * .execSync(\"…\") }` also satisfies — and `rebase dev` re-imports the file the\n * moment it changes, so the payload ran without anyone deploying anything.\n *\n * An arrow returning a single identifier is the whole grammar. Anything else is\n * read as a collection name and turned into a thunk by `targetThunk`, which\n * resolves it against the collections directory and refuses a name with no file.\n */\nconst ARROW_TO_IDENTIFIER = /^\\(\\s*\\)\\s*=>\\s*[A-Za-z_$][A-Za-z0-9_$]*$/;\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/cms-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\n/**\n * {@link nestAdminKeys} for a whole collection — its properties included.\n *\n * `nestAdminKeys` only ever moved the COLLECTION's presentation keys. A\n * property's — `markdown`, `multiline`, `previewAsTag` — went to disk exactly as\n * the panel sent them, at the top level of the property, which the boot\n * validator treats as fatal. `saveProperty` nests them; `saveCollection` did\n * not, and *creating* a collection is a `saveCollection`.\n *\n * So a collection created from a template wrote a file that could not boot, and\n * took the whole project down with it — the loader imports every collection in\n * the directory, so one bad file stops `rebase dev` from starting at all. The\n * panel reported success.\n */\nexport function nestAdminKeysDeep(collectionData: Record<string, unknown>): Record<string, unknown> {\n const nested = nestAdminKeys(collectionData);\n const properties = nested.properties;\n if (properties && typeof properties === \"object\" && !Array.isArray(properties)) {\n nested.properties = Object.fromEntries(\n Object.entries(properties as Record<string, unknown>).map(([key, property]) => [\n key,\n property && typeof property === \"object\" && !Array.isArray(property)\n ? nestAdminPropertyKeys(property as Record<string, unknown>)\n : property\n ])\n );\n }\n return nested;\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 === \"browserCallbacks\" || 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(nestAdminKeysDeep(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. A\n // property's presentation keys are worse than ignored: they are fatal\n // at the next boot, which is why this goes all the way down.\n collectionData = nestAdminKeysDeep(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 // `quoteKey`, like every other site that emits a key.\n // This one did not, and ts-morph writes a property name\n // out verbatim — so a top-level key of\n // `injected: (() => { … })(), tail` closed the property\n // and opened an expression, which `rebase dev` then\n // re-imported and ran. The rest of this file has always\n // quoted; this was the one that did not.\n name: AstSchemaEditor.quoteKey(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 const trimmed = rawTarget.trim();\n // A target that already looks like a thunk is written into the\n // file as source, so \"contains an arrow\" is not a good enough\n // reason to trust it: `() => { require(\"child_process\")… }` also\n // contains one. Only the exact shape this emits is accepted —\n // an arrow returning one identifier — and anything else is\n // treated as a collection NAME and turned into a thunk here,\n // which is the path that was always safe.\n targetText = ARROW_TO_IDENTIFIER.test(trimmed)\n ? trimmed\n : this.targetThunk(file, trimmed);\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 }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAcA,IAAM,uCAAuB,IAAI,IAAI,CAAC,kBAAkB,CAAC;;;;;;;;;;;;;;AAezD,IAAM,sBAAsB;;;;;;;;;AAU5B,IAAM,gBAAN,MAAoB;CACY;CAA5B,YAAY,MAA8B;EAAd,KAAA,OAAA;CAC5B;AACJ;;;;;;;;;;AAWA,SAAgB,cAAc,gBAAkE;CAC5F,OAAO,wBAAwB,cAAc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KAAK,iBAAiB,MAAM,UAAU,GAAG;GAC7F,MAAM,WAAW,OAAK,SAAS,OAAK,QAAQ,KAAK,YAAY,CAAC,GAAG,WAAW,YAAY,CAAC,CAAC,CACrF,MAAM,OAAK,GAAG,CAAC,CACf,KAAK,GAAG,CAAC,CACT,QAAQ,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"}
|
package/dist/auth/jwt.d.ts
CHANGED
|
@@ -249,3 +249,70 @@ export declare function generateDownloadToken(path: string, expiresInSeconds?: n
|
|
|
249
249
|
* for a *named* source is refused and the client re-fetches `/metadata`.
|
|
250
250
|
*/
|
|
251
251
|
export declare function verifyDownloadToken(token: string): Promise<DownloadTokenPayload | null>;
|
|
252
|
+
/**
|
|
253
|
+
* Sign a short-lived token that carries state across a redirect.
|
|
254
|
+
*
|
|
255
|
+
* The generalisation of the MFA-pending token: a signed blob the server hands
|
|
256
|
+
* out and expects back, where the point is that the holder cannot edit it. The
|
|
257
|
+
* OAuth authorize flow needs one to carry the authorization request across the
|
|
258
|
+
* sign-in hop — without it, the endpoint the consent page posts to would mint a
|
|
259
|
+
* code for whatever `client_id` and `redirect_uri` its caller typed, skipping
|
|
260
|
+
* every check the authorize endpoint performs.
|
|
261
|
+
*
|
|
262
|
+
* The `purpose` is not decoration. {@link verifyAccessToken} refuses any token
|
|
263
|
+
* that has one, so nothing minted here can be replayed as a session, and
|
|
264
|
+
* {@link verifyPurposeToken} refuses a token whose purpose is not the one the
|
|
265
|
+
* caller named — so a token minted for one hop cannot be spent on another.
|
|
266
|
+
*/
|
|
267
|
+
export declare function signPurposeToken(purpose: string, claims: Record<string, unknown>, expiresInSeconds: number): Promise<string>;
|
|
268
|
+
/** Verify a token minted by {@link signPurposeToken}, for one named purpose. */
|
|
269
|
+
export declare function verifyPurposeToken<T>(purpose: string, token: string): Promise<T | null>;
|
|
270
|
+
/** The `purpose` that marks a token as belonging to the MCP resource. */
|
|
271
|
+
export declare const MCP_ACCESS_PURPOSE = "mcp-access";
|
|
272
|
+
export interface McpAccessTokenPayload {
|
|
273
|
+
purpose: typeof MCP_ACCESS_PURPOSE;
|
|
274
|
+
/** The person the token acts for. Fed straight to `withAuth()`, so RLS sees them. */
|
|
275
|
+
uid: string;
|
|
276
|
+
roles: string[];
|
|
277
|
+
/** Granted OAuth scope, space-separated. */
|
|
278
|
+
scope: string;
|
|
279
|
+
/** Which registered client holds this token — carried for audit and revocation. */
|
|
280
|
+
clientId: string;
|
|
281
|
+
/** The resource this token is bound to (RFC 8707). */
|
|
282
|
+
aud: string;
|
|
283
|
+
iss: string;
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Mint an access token for the MCP endpoint.
|
|
287
|
+
*
|
|
288
|
+
* Deliberately **not** an ordinary session token, and the `purpose` claim is
|
|
289
|
+
* what enforces that: {@link verifyAccessToken} refuses any token carrying one,
|
|
290
|
+
* so a credential issued to a third-party MCP client — Claude, an IDE, anything
|
|
291
|
+
* that completed the OAuth flow — cannot be replayed against `/api/data`,
|
|
292
|
+
* `/api/admin` or the websocket. It buys exactly the one resource it names.
|
|
293
|
+
*
|
|
294
|
+
* That asymmetry matters more than it first looks. These tokens are handed to
|
|
295
|
+
* software the user authorized but the operator never vetted, they live in that
|
|
296
|
+
* software's storage, and they are the only credential in this system minted
|
|
297
|
+
* for a third party. Without the purpose separation, "connect Claude to your
|
|
298
|
+
* data" would silently mean "give Claude a full session".
|
|
299
|
+
*
|
|
300
|
+
* The audience is the canonical resource URI, and {@link verifyMcpAccessToken}
|
|
301
|
+
* requires the caller to say which resource it is checking for. A token minted
|
|
302
|
+
* for another Rebase project — or another path on this one — fails there.
|
|
303
|
+
*
|
|
304
|
+
* HS256 with the shared secret, like the download token: the authorization
|
|
305
|
+
* server and the resource server are the same process, so nothing outside it
|
|
306
|
+
* ever needs to verify one, and an asymmetric key here would be a second key
|
|
307
|
+
* surface bought for nobody.
|
|
308
|
+
*/
|
|
309
|
+
export declare function generateMcpAccessToken(payload: Omit<McpAccessTokenPayload, "purpose">, expiresInSeconds: number): Promise<string>;
|
|
310
|
+
/**
|
|
311
|
+
* Verify an MCP access token **for a specific resource**.
|
|
312
|
+
*
|
|
313
|
+
* `expectedAudience` has no default. The MCP specification requires a resource
|
|
314
|
+
* server to validate that a token was issued for it specifically, and a default
|
|
315
|
+
* would be the thing that quietly turns that check off — the caller has to say
|
|
316
|
+
* what it is, every time, so a new call site cannot forget by omission.
|
|
317
|
+
*/
|
|
318
|
+
export declare function verifyMcpAccessToken(token: string, expectedAudience: string): Promise<McpAccessTokenPayload | null>;
|
package/dist/auth/rls-scope.d.ts
CHANGED
|
@@ -37,6 +37,20 @@ export declare const SERVICE_IDENTITY: {
|
|
|
37
37
|
uid: string;
|
|
38
38
|
roles: string[];
|
|
39
39
|
};
|
|
40
|
+
/**
|
|
41
|
+
* Can this driver run a request as a specific user?
|
|
42
|
+
*
|
|
43
|
+
* The same question `scopeDataDriver` asks internally, exported because one
|
|
44
|
+
* caller must act on the answer BEFORE it has a request to scope.
|
|
45
|
+
*
|
|
46
|
+
* `scopeDataDriver` returns the driver unscoped when the answer is no, which is
|
|
47
|
+
* the right behaviour for `/api/data` — Mongo has no row-level security and
|
|
48
|
+
* never claimed to, and the route's own checks still apply. It is the wrong
|
|
49
|
+
* behaviour for a surface whose entire promise is "this runs as you": there,
|
|
50
|
+
* an unscoped driver silently means "runs as the database owner". So the MCP
|
|
51
|
+
* surface asks this at boot and declines to mount rather than degrade.
|
|
52
|
+
*/
|
|
53
|
+
export declare function supportsRlsScoping(driver: DataDriver): boolean;
|
|
40
54
|
/**
|
|
41
55
|
* Scope a DataDriver via `withAuth()` for RLS.
|
|
42
56
|
*
|
|
@@ -3,14 +3,14 @@ import __rebaseProcess from "process";
|
|
|
3
3
|
globalThis.process ??= __rebaseProcess;
|
|
4
4
|
__rebaseCreateRequire(import.meta.url);
|
|
5
5
|
import { i as __toESM, n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
|
|
6
|
-
import {
|
|
6
|
+
import { P as revokeInternalTableSql, at as isAnonymousUid, it as ANONYMOUS_USER_ID } from "./src-DW1cQ_28.js";
|
|
7
7
|
import "./src-Br6ARbs6.js";
|
|
8
8
|
import { n as createDdlBootstrapper, o as isSQLAdmin } from "./ddl-bootstrap-CfNvxMuK.js";
|
|
9
|
-
import { t as
|
|
9
|
+
import { t as firstSqlRow } from "./sql-rows-C6GEc2oE.js";
|
|
10
10
|
import { r as logger } from "./logger-DO2PZc4i.js";
|
|
11
11
|
import { n as errorHandler, t as ApiError } from "./errors-DMImyqyR.js";
|
|
12
|
-
import { a as resolveListLimitParam } from "./query-parser-
|
|
13
|
-
import {
|
|
12
|
+
import { a as resolveListLimitParam } from "./query-parser-uqzkZ82i.js";
|
|
13
|
+
import { C as require_jsonwebtoken, E as randomInt$1, O as sha256Hex, _ as verifyAccessToken, b as verifyMfaPendingToken, c as getAccessTokenExpiry, d as getRefreshTokenTtlMs, f as hasAsymmetricSigningKey, i as generateDownloadToken, l as getJwks, m as isJwtConfigured, n as configureJwt, o as generateMfaPendingToken, p as hashRefreshToken, r as generateAccessToken, s as generateRefreshToken, t as MAX_COOKIE_AGE_MS, u as getRefreshTokenExpiry, v as verifyDownloadToken, w as constantTimeEqual } from "./jwt-C4OW-DNq.js";
|
|
14
14
|
import { n as hasAdministrativeRole, r as isAdministrativeRole, t as ADMINISTRATIVE_ROLES } from "./admin-roles-vYdp_Pil.js";
|
|
15
15
|
import { c as tryCanonicalStorageKey, i as canonicalStorageId } from "./keys-Qfc4XieN.js";
|
|
16
16
|
import { createHash, randomBytes, randomInt } from "node:crypto";
|
|
@@ -241,6 +241,22 @@ function isRLSScopedDriver(driver) {
|
|
|
241
241
|
return "withAuth" in driver && typeof driver.withAuth === "function";
|
|
242
242
|
}
|
|
243
243
|
/**
|
|
244
|
+
* Can this driver run a request as a specific user?
|
|
245
|
+
*
|
|
246
|
+
* The same question `scopeDataDriver` asks internally, exported because one
|
|
247
|
+
* caller must act on the answer BEFORE it has a request to scope.
|
|
248
|
+
*
|
|
249
|
+
* `scopeDataDriver` returns the driver unscoped when the answer is no, which is
|
|
250
|
+
* the right behaviour for `/api/data` — Mongo has no row-level security and
|
|
251
|
+
* never claimed to, and the route's own checks still apply. It is the wrong
|
|
252
|
+
* behaviour for a surface whose entire promise is "this runs as you": there,
|
|
253
|
+
* an unscoped driver silently means "runs as the database owner". So the MCP
|
|
254
|
+
* surface asks this at boot and declines to mount rather than degrade.
|
|
255
|
+
*/
|
|
256
|
+
function supportsRlsScoping(driver) {
|
|
257
|
+
return isRLSScopedDriver(driver);
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
244
260
|
* Scope a DataDriver via `withAuth()` for RLS.
|
|
245
261
|
*
|
|
246
262
|
* SECURITY: If `withAuth()` is available but fails, the error is re-thrown
|
|
@@ -3544,7 +3560,7 @@ function mountSessionRoutes(opts) {
|
|
|
3544
3560
|
clearRefreshCookie(c, config.cookieAuth);
|
|
3545
3561
|
const accessToken = extractBearerToken(c.req.header("authorization"));
|
|
3546
3562
|
if (ops.afterLogout && accessToken !== void 0) {
|
|
3547
|
-
const { verifyAccessToken } = await import("./jwt-
|
|
3563
|
+
const { verifyAccessToken } = await import("./jwt-C4OW-DNq.js").then((n) => n.h);
|
|
3548
3564
|
const payload = await verifyAccessToken(accessToken);
|
|
3549
3565
|
if (payload) ops.afterLogout(payload.uid).catch((err) => {
|
|
3550
3566
|
logger.error("[AuthHooks] afterLogout error", { error: err instanceof Error ? err.message : err });
|
|
@@ -6572,11 +6588,7 @@ function createSqlRateLimitStore(driver, options = {}) {
|
|
|
6572
6588
|
* being on their first request — a limiter that never limits, with no error
|
|
6573
6589
|
* anywhere. Tolerating both costs one line.
|
|
6574
6590
|
*/
|
|
6575
|
-
|
|
6576
|
-
if (Array.isArray(result)) return result[0];
|
|
6577
|
-
const rows = result?.rows;
|
|
6578
|
-
return Array.isArray(rows) ? rows[0] : void 0;
|
|
6579
|
-
}
|
|
6591
|
+
var firstRow = firstSqlRow;
|
|
6580
6592
|
//#endregion
|
|
6581
6593
|
//#region src/auth/resolve-rate-limit-store.ts
|
|
6582
6594
|
/**
|
|
@@ -7093,6 +7105,6 @@ var auth_exports = /* @__PURE__ */ __exportAll({
|
|
|
7093
7105
|
verifyPassword: () => verifyPassword
|
|
7094
7106
|
});
|
|
7095
7107
|
//#endregion
|
|
7096
|
-
export {
|
|
7108
|
+
export { RawHtml as $, defaultAuthLimiter as A, resolveEmailLinkBase as B, providerVerifiedEmail as C, httpMethodToOperation as Ct, DEFAULT_FUNCTIONS_ANONYMOUS_LIMIT as D, isBootstrapWindowOpen as E, isPublicStoragePath as Et, extractLinks as F, generateSecurePassword as G, hashPassword as H, registerDevEmailSink as I, getMagicLinkTemplate as J, getEmailOtpTemplate as K, SMTPEmailService as L, activeDevEmailSink as M, clearActiveDevEmailSink as N, createDataRateLimiter as O, createDevEmailSink as P, resolveEmailBranding as Q, createEmailService as R, pkceTokenParams as S, supportsRlsScoping as St, createBuiltinAuthAdapter as T, PUBLIC_STORAGE_PREFIX as Tt, validatePasswordStrength as U, resolveAuthHooks as V, verifyPassword as W, getUserInvitationTemplate as X, getPasswordResetTemplate as Y, getWelcomeEmailTemplate as Z, verifyOidcIdToken as _, validateApiKey as _t, resolveRateLimitStoreKind as a, createRequireAuth as at, createGoogleProvider as b, SERVICE_IDENTITY as bt, createSlackProvider as c, optionalAuth as ct, createDiscordProvider as d, requireAdmin as dt, escapeHtml as et, createTwitterProvider as f, requireAuth as ft, tryVerifyOidcIdToken as g, isApiKeyToken as gt, createMicrosoftProvider as h, createStorageApiKeyGuard as ht, createApiKeyStore as i, createAuthMiddleware as it, MemoryRateLimitStore as j, createRateLimiter as k, createBitbucketProvider as l, publicObjectAuth as lt, createAppleProvider as m, createFunctionApiKeyGuard as mt, createCustomAuthAdapter as n, raw as nt, createSqlRateLimitStore as o, extractUserFromToken as ot, createFacebookProvider as p, createApiKeyPreAuth as pt, getEmailVerificationTemplate as q, createApiKeyRoutes as r, createAdapterAuthMiddleware as rt, createSpotifyProvider as s, fileTokenAuth as st, auth_exports as t, html as tt, createGitLabProvider as u, queryTokenAuth as ut, createGitHubProvider as v, extractBearerToken as vt, createJwksRoutes as w, isOperationAllowed as wt, oauthCodeFlowSchema as x, scopeDataDriver as xt, createLinkedinProvider as y, safeCompare as yt, assertEmailLinkBases as z };
|
|
7097
7109
|
|
|
7098
|
-
//# sourceMappingURL=auth-
|
|
7110
|
+
//# sourceMappingURL=auth-gzoRjnuh.js.map
|