@lpdjs/firestore-repo-service 3.0.16 → 3.0.17
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/{create-servers-DSXdPM6o.d.ts → create-servers-BQ7pxnG0.d.ts} +2 -2
- package/dist/{create-servers-BMpE8oAc.d.cts → create-servers-DKg5Yg2d.d.cts} +2 -2
- package/dist/effects-B8aIXMZ2.d.ts +158 -0
- package/dist/effects-CqJSneNZ.d.cts +158 -0
- package/dist/index.cjs +92 -92
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +92 -92
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +110 -2
- package/dist/llms.txt +1 -1
- package/dist/servers/admin/index.d.cts +1 -1
- package/dist/servers/admin/index.d.ts +1 -1
- package/dist/servers/crud/index.cjs +2 -2
- package/dist/servers/crud/index.cjs.map +1 -1
- package/dist/servers/crud/index.d.cts +4 -5
- package/dist/servers/crud/index.d.ts +4 -5
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/index.cjs +101 -101
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +4 -5
- package/dist/servers/index.d.ts +4 -5
- package/dist/servers/index.js +101 -101
- package/dist/servers/index.js.map +1 -1
- package/dist/{types-mKcJozu4.d.cts → types-DgzPoPvx.d.cts} +282 -2
- package/dist/{types-CaCBG76r.d.ts → types-wMBgnYjH.d.ts} +282 -2
- package/package.json +1 -1
- package/dist/openapi-CKTuB2Yz.d.ts +0 -70
- package/dist/openapi-Cb3QMU0Q.d.cts +0 -70
- package/dist/rules-DY5f_wPw.d.ts +0 -30
- package/dist/rules-DhNUzbIl.d.cts +0 -30
package/dist/llms-full.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# @lpdjs/firestore-repo-service (v3.0.
|
|
1
|
+
# @lpdjs/firestore-repo-service (v3.0.17) — full documentation
|
|
2
2
|
|
|
3
3
|
> ⚡ Type-safe Firestore ORM with auto-generated repositories, advanced queries, relations with typed select, pagination with include, batch/bulk operations, aggregations and transactions.
|
|
4
4
|
|
|
@@ -1316,6 +1316,7 @@ Send complex filter conditions including `where` (AND), `orWhere` (simple OR), a
|
|
|
1316
1316
|
| `middlewares` | `MiddlewareHandler[]` | Custom Hono middleware array |
|
|
1317
1317
|
| `repos` | `Record<string, CrudRepoConfig>` | Per-repository configuration mapping |
|
|
1318
1318
|
| `indexesError` | `(err: { repoName, error, indexUrl, c }) => void` | Callback triggered when a Firestore missing-index error occurs |
|
|
1319
|
+
| `onHookError` | `(ctx: CrudHookErrorContext) => void \| Promise<void>` | Callback invoked when a post-write hook (or `changesNeeded` follow-up update) throws |
|
|
1319
1320
|
| `openapi` | `OpenAPISpecOptions` | OpenAPI 3.1 documentation settings |
|
|
1320
1321
|
| `verbose` | `boolean` | Include detailed error messages in HTTP 500 responses |
|
|
1321
1322
|
|
|
@@ -1330,7 +1331,8 @@ Send complex filter conditions including `where` (AND), `orWhere` (simple OR), a
|
|
|
1330
1331
|
| `orderableFields` | `string[]` | List of allowed fields for ordering |
|
|
1331
1332
|
| `allowedIncludes` | `string[]` | List of relation keys allowed in `includes` |
|
|
1332
1333
|
| `allowDelete` | `boolean` | Whether `DELETE /:id` is enabled |
|
|
1333
|
-
| `rules` | `
|
|
1334
|
+
| `rules` | `CrudRules<TRepo>` | Per-operation authorization, before-rules & `preWrite` mutations |
|
|
1335
|
+
| `hooks` | `CrudHooks<TRepo>` | Post-write lifecycle hooks (`afterCreate`, `afterUpdate`, `afterDelete`, `afterBatch`) |
|
|
1334
1336
|
| `pageSize` | `number` | Default page size for list requests |
|
|
1335
1337
|
|
|
1336
1338
|
---
|
|
@@ -1372,6 +1374,112 @@ If a rule returns `false` or a string error message, the mutation is rejected wi
|
|
|
1372
1374
|
|
|
1373
1375
|
---
|
|
1374
1376
|
|
|
1377
|
+
## Lifecycle Hooks, Mutations & Effects (`hooks`)
|
|
1378
|
+
|
|
1379
|
+
While `rules` govern authorization and before-validation checks, `hooks` manage both **pre-write mutations** and **post-write reactive side effects** with full model type inference from each repository:
|
|
1380
|
+
|
|
1381
|
+
- **`beforeCreate`** (`POST /:repoName` & batch `create`): runs after validation and `rules.create`. Mutate `ctx.body` in place to normalize or inject server-derived fields.
|
|
1382
|
+
- **`beforeUpdate`** (`PUT/PATCH /:repoName/:id` & batch `update`): runs after validation and `rules.update`. Mutate `ctx.body` in place; `diff` is **recomputed afterward** so mutated fields are captured by `afterUpdate` / `afterBatch`.
|
|
1383
|
+
- **`afterCreate`** (`POST /:repoName`): receives `{ user, doc, id, pathArgs, params, c }`. May optionally return a non-empty `Partial<T>` to patch the newly created document via `repo.update(...pathArgs, changes)` and return the patched document in the HTTP 201 response.
|
|
1384
|
+
- **`afterUpdate`** (`PUT/PATCH /:repoName/:id`): receives `{ user, before, after, body, diff, id, pathArgs, params, c }`. The `diff` is **recomputed after `rules.update` and `beforeUpdate`**, so fields added or modified during pre-write are present in `diff.changes` and `diff.after`. May optionally return a non-empty `Partial<T>` to apply follow-up changes to the current document and return the final document in the HTTP 200 response.
|
|
1385
|
+
- **`afterDelete`** (`DELETE /:repoName/:id`): receives `{ user, doc, id, pathArgs, params, c }` where `doc` is the snapshot captured prior to deletion.
|
|
1386
|
+
- **`afterBatch`** (`POST /:repoName/batch`): called **once after `batch.commit()`** with `{ user, created, updated, deleted, params, c }` (each `updated` item carries its `diff` recomputed after pre-write mutations). If `afterBatch` is omitted, the server automatically falls back to invoking `afterCreate` / `afterUpdate` / `afterDelete` sequentially on each committed item.
|
|
1387
|
+
- **`onAfterError`**: per-repo error callback `(err, phase) => void` invoked when any `after*` hook fails (in addition to server-wide `onHookError`).
|
|
1388
|
+
|
|
1389
|
+
### Built-in helpers (`mutations` & `effects`)
|
|
1390
|
+
|
|
1391
|
+
Aligned with `createRules` / `applyRules` / `createBeforeRules`, the package exports declarative builders ready to plug into `hooks`:
|
|
1392
|
+
|
|
1393
|
+
- **Pre-write mutations**: `createMutations`, `applyMutations`, `createBeforeCreateMutations`, `createBeforeUpdateMutations` (indexed by model field key plus `"*"` wildcard, with optional `operations: ["create"] | ["update"]` filter).
|
|
1394
|
+
- **Post-write effects**: `createEffects`, `applyEffects`, `createAfterUpdateEffects` (indexed by model field key plus `"*"` wildcard, with isolated per-rule error capture via `onRuleError` and automatic `changesNeeded` aggregation).
|
|
1395
|
+
|
|
1396
|
+
```typescript
|
|
1397
|
+
import {
|
|
1398
|
+
createAfterUpdateEffects,
|
|
1399
|
+
createBeforeCreateMutations,
|
|
1400
|
+
createBeforeUpdateMutations,
|
|
1401
|
+
createEffects,
|
|
1402
|
+
createMutations,
|
|
1403
|
+
withActor,
|
|
1404
|
+
} from "@lpdjs/firestore-repo-service";
|
|
1405
|
+
|
|
1406
|
+
const eventMutations = createMutations<PreventionEvent>({
|
|
1407
|
+
proId: [
|
|
1408
|
+
{
|
|
1409
|
+
description: "Auto-accept when a pro is assigned",
|
|
1410
|
+
operations: ["update"],
|
|
1411
|
+
mutation: ({ body, diff }) => {
|
|
1412
|
+
if (diff.changes.proId) {
|
|
1413
|
+
body.status = "accepted";
|
|
1414
|
+
body.publicationStatus = "toRepublish";
|
|
1415
|
+
}
|
|
1416
|
+
},
|
|
1417
|
+
},
|
|
1418
|
+
],
|
|
1419
|
+
"*": [
|
|
1420
|
+
({ body }) => {
|
|
1421
|
+
if (typeof body.title === "string") body.title = body.title.trim();
|
|
1422
|
+
},
|
|
1423
|
+
],
|
|
1424
|
+
});
|
|
1425
|
+
|
|
1426
|
+
const eventEffects = createEffects<PreventionEvent, { after: PreventionEvent }>({
|
|
1427
|
+
status: [
|
|
1428
|
+
{
|
|
1429
|
+
description: "Notify when accepted",
|
|
1430
|
+
rule: ({ diff }) => diff.changes.status === "accepted",
|
|
1431
|
+
handler: async ({ after }) => {
|
|
1432
|
+
await notifyAssignment(after);
|
|
1433
|
+
return { notifiedAt: new Date() }; // optional follow-up patch
|
|
1434
|
+
},
|
|
1435
|
+
},
|
|
1436
|
+
],
|
|
1437
|
+
});
|
|
1438
|
+
|
|
1439
|
+
export const api = servers.crud({
|
|
1440
|
+
basePath: "/api",
|
|
1441
|
+
onHookError: ({ hook, repoName, id, error }) => {
|
|
1442
|
+
logger.error(`[CRUD ${hook}] failed on ${repoName}/${id ?? "batch"}`, error);
|
|
1443
|
+
},
|
|
1444
|
+
repos: {
|
|
1445
|
+
preventionEvents: {
|
|
1446
|
+
path: "prevention/prev_rules/prev_workshops/{workshopId}/prev_events",
|
|
1447
|
+
hooks: {
|
|
1448
|
+
beforeCreate: createBeforeCreateMutations(eventMutations),
|
|
1449
|
+
beforeUpdate: createBeforeUpdateMutations(eventMutations),
|
|
1450
|
+
afterUpdate: createAfterUpdateEffects(
|
|
1451
|
+
eventEffects,
|
|
1452
|
+
(ctx) => ({ after: ctx.after }),
|
|
1453
|
+
{
|
|
1454
|
+
onRuleError: (r) =>
|
|
1455
|
+
logger.error(`[afterUpdate] Effect failed: ${r.description}`, r.error),
|
|
1456
|
+
},
|
|
1457
|
+
),
|
|
1458
|
+
afterBatch: async ({ updated }) => {
|
|
1459
|
+
// Runs ONCE after batch.commit() — ideal for deduplicating recalculations
|
|
1460
|
+
const workshopIds = new Set(updated.map((u) => u.pathArgs[0]));
|
|
1461
|
+
await withActor({ userId: "system" }, async () => {
|
|
1462
|
+
for (const wid of workshopIds) {
|
|
1463
|
+
await recalculateWorkshop(wid);
|
|
1464
|
+
}
|
|
1465
|
+
});
|
|
1466
|
+
},
|
|
1467
|
+
onAfterError: (err, phase) => {
|
|
1468
|
+
logger.error(`[preventionEvents:${phase}]`, err);
|
|
1469
|
+
},
|
|
1470
|
+
},
|
|
1471
|
+
},
|
|
1472
|
+
},
|
|
1473
|
+
});
|
|
1474
|
+
```
|
|
1475
|
+
|
|
1476
|
+
**Execution guarantees:**
|
|
1477
|
+
- Every hook is **`await`ed before sending the HTTP response** (safe on Cloud Functions v2, where CPU is throttled once the response finishes).
|
|
1478
|
+
- Post-write hook errors (and errors from follow-up `changesNeeded` patches) are **caught and routed to `hooks.onAfterError` / `onHookError`** (falling back to the Hono `logger` or `console.error`) so a committed write never returns a misleading HTTP 500.
|
|
1479
|
+
- The `actorResolver` `AsyncLocalStorage` scope remains active during hook execution: cascading repository writes automatically inherit the HTTP actor's `_historyMeta`, or can override it with `withActor({ userId: "system" }, ...)`.
|
|
1480
|
+
|
|
1481
|
+
---
|
|
1482
|
+
|
|
1375
1483
|
## Missing Index Detection (`indexesError` & HTTP 424)
|
|
1376
1484
|
|
|
1377
1485
|
When a complex filter or compound query requires a composite index that has not yet been built in Firestore, the CRUD server automatically catches the Firestore `FAILED_PRECONDITION` error:
|
package/dist/llms.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# @lpdjs/firestore-repo-service (v3.0.
|
|
1
|
+
# @lpdjs/firestore-repo-service (v3.0.17)
|
|
2
2
|
|
|
3
3
|
> ⚡ Type-safe Firestore ORM with auto-generated repositories, advanced queries, relations with typed select, pagination with include, batch/bulk operations, aggregations and transactions.
|
|
4
4
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { HttpsOptions } from 'firebase-functions/v2/https';
|
|
3
|
-
import {
|
|
3
|
+
import { V as RelationalFieldMeta } from '../../types-DgzPoPvx.cjs';
|
|
4
4
|
import { ConfiguredRepository, FieldRole } from '../../index.cjs';
|
|
5
5
|
import { SecurityHeadersOptions } from '../index.cjs';
|
|
6
6
|
import { RepositoryConfig, FieldPath } from '../../index.cjs';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { HttpsOptions } from 'firebase-functions/v2/https';
|
|
3
|
-
import {
|
|
3
|
+
import { V as RelationalFieldMeta } from '../../types-wMBgnYjH.js';
|
|
4
4
|
import { ConfiguredRepository, FieldRole } from '../../index.js';
|
|
5
5
|
import { SecurityHeadersOptions } from '../index.js';
|
|
6
6
|
import { RepositoryConfig, FieldPath } from '../../index.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var zod=require('zod'),firestore=require('firebase-admin/firestore'),crypto=require('crypto'),zodToOpenapi=require('@asteasolutions/zod-to-openapi'),hono=require('hono'),nodeServer=require('@hono/node-server'),async_hooks=require('async_hooks');var he=Object.defineProperty;var vt=Object.getOwnPropertyDescriptor;var kt=Object.getOwnPropertyNames;var Ot=Object.prototype.hasOwnProperty;var Ct=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Et=(e,t)=>{for(var n in t)he(e,n,{get:t[n],enumerable:true});},It=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of kt(t))!Ot.call(e,o)&&o!==n&&he(e,o,{get:()=>t[o],enumerable:!(r=vt(t,o))||r.enumerable});return e};var Pt=e=>It(he({},"__esModule",{value:true}),e);var St={};Et(St,{DEFAULT_HTML_CSP:()=>Rt,securityHeaders:()=>On});function On(e={}){let t=e.csp===void 0?Rt:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,r=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,o=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(i,c,u)=>{typeof c?.setHeader=="function"&&(c.setHeader("X-Content-Type-Options","nosniff"),n&&c.setHeader("X-Frame-Options",n),r&&c.setHeader("Referrer-Policy",r),o&&c.setHeader("Cache-Control",o),t&&c.setHeader("Content-Security-Policy",t)),await u();}}var bt,xt,Rt,At=Ct(()=>{"use strict";bt="https://cdn.jsdelivr.net",xt="https://www.gstatic.com",Rt=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${bt} ${xt}`,`style-src 'self' 'unsafe-inline' ${bt}`,`connect-src 'self' ${xt} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,"img-src 'self' data:","font-src 'self' data:","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");});var Fe="preserve";function be(){return Fe}function Dt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Ne(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof firestore.Timestamp)return e.toDate();if(Dt(e))return new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));if(typeof e=="string"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function $e(e){return e}var xe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Re(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=xe.length*4||(e+=xe.charAt(r%xe.length));}}return e}function Ze(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function He(e,t="docId",n=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=e.split("/").map(y=>y.trim()).filter(Boolean);if(r.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let y=r[0];return {rawPath:e,collectionId:y,collectionPath:y,parentKeys:[],documentPathTemplate:n?null:`${y}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let o=r.length%2===0,i=o?r.slice(0,-1):r,c=i[i.length-1],u=i.join("/"),p=i.slice(0,-1).map(Ze).filter(y=>y!==null),m=o?r.join("/"):`${u}/{${t}}`;return {rawPath:e,collectionId:c,collectionPath:u,parentKeys:p,documentPathTemplate:m,hasTemplate:true}}function Me(e,t={}){if(!e||typeof e!="object")return;let{pathKey:n,documentKey:r="docId",parentKeys:o,documentPathTemplate:i,isGroup:c}=t,u=n&&typeof e[n]=="string"&&e[n]?e[n]:void 0;if(u&&i){let d=u.split("/").filter(Boolean),p=i.split("/").filter(Boolean);if(d.length===p.length){let m=[];for(let y=0;y<p.length;y++)Ze(p[y])!==null&&m.push(d[y]);if(m.length>0)return m}}if(o&&o.length>0){let d=o.length+1;if(u){let m=u.split("/").filter(Boolean),y=[];for(let b=1;b<m.length;b+=2)y.push(m[b]);if(y.length>=d)return y.slice(y.length-d)}let p=r?e[r]:void 0;if(typeof p=="string"&&p.trim()!==""){let m=[],y=true;for(let b of o){let O=e[b];if(typeof O=="string"&&O.trim()!=="")m.push(O);else {y=false;break}}if(y)return [...m,p]}}if(u){let d=u.split("/").filter(Boolean),p=[];for(let m=1;m<d.length;m+=2)p.push(d[m]);if(p.length>0)return !c&&(!o||o.length===0)?[p[p.length-1]]:p}}function Be(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}var _t=new Set(["<","<=",">",">=","!="]),qt=new Set(["array-contains","array-contains-any"]);function Se(e){return e==="desc"?"DESCENDING":"ASCENDING"}function Ft(e){return He(e).collectionId||e}function Nt(e,t,n,r,o){let i=[],c=new Set;for(let d of r)if(d.op==="=="||d.op==="in"||d.op==="not-in"){if(c.has(d.field))continue;c.add(d.field),i.push({fieldPath:d.field,order:"ASCENDING"});}for(let d of r)if(qt.has(d.op)){if(c.has(d.field))continue;c.add(d.field),i.push({fieldPath:d.field,arrayConfig:"CONTAINS"});}for(let d of r)if(_t.has(d.op)){if(c.has(d.field))continue;c.add(d.field);let p=o?.field===d.field?Se(o.dir):"ASCENDING";i.push({fieldPath:d.field,order:p});}if(o&&!c.has(o.field)&&i.push({fieldPath:o.field,order:Se(o.dir)}),i.length===1&&n)return Ht(e,t,i[0]);let u=o&&i.some(d=>d.fieldPath===o.field)?Se(o.dir):"ASCENDING";return i.push({fieldPath:"__name__",order:u}),$t(e,t,n,i)}function $t(e,t,n,r,o="(default)"){let i=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,c=[...ve(1,i),...ce(2,n?2:1)];for(let p of r)c.push(...Ue(3,Ke(p)));let u=o==="(default)"?"-default-":o,d=encodeURIComponent(Le(c));return `https://console.firebase.google.com/project/${e}/firestore/databases/${u}/indexes?create_composite=${d}`}function Zt(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Ae(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function Te(e,t){return e<<3|t}function ve(e,t){let n=Array.from(new TextEncoder().encode(t));return [Te(e,2),...Ae(n.length),...n]}function ce(e,t){return [Te(e,0),...Ae(t)]}function Ue(e,t){return [Te(e,2),...Ae(t.length),...t]}function Ke(e){let t=[...ve(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...ce(3,1)):t.push(...ce(2,e.order==="DESCENDING"?2:1)),t}function Le(e){let t=String.fromCharCode(...e),n;if(typeof Buffer<"u")n=Buffer.from(e).toString("base64");else if(typeof btoa<"u")n=btoa(t);else throw new Error("No base64 encoder available");return n.replace(/=+$/,"")}function Ht(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,i=[...ve(1,o),...ce(2,2),...Ue(3,Ke(n))],c=r==="(default)"?"-default-":r,u=encodeURIComponent(Le(i));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes/automatic?create_exemption=${u}`}function Mt(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let o of n)if(typeof o=="string"&&o.length>0)return o;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function Bt(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Ge(e,t){let n=e??{},r=Bt(e),o;if(r&&(o=n.message?Zt(n.message):void 0,!o)){let i=Mt(t.ref);if(i){let c=Ft(t.path);o=Nt(i,c,t.isGroup,t.filters,t.sort);}}return {type:r?"index":"error",message:r?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}function de(e,t,n=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof firestore.Timestamp&&t instanceof firestore.Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(n.get(e)===t)return true;n.set(e,t);for(let r=0;r<e.length;r++)if(!de(e[r],t[r],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof firestore.Timestamp||t instanceof firestore.Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return false;for(let i of r)if(!Object.prototype.hasOwnProperty.call(t,i)||!de(e[i],t[i],n))return false;return true}return false}function le(e,t){let n=e||{},r={},o={...n};for(let[i,c]of Object.entries(t||{})){let u=n[i];de(u,c)||(r[i]=c,o[i]=c);}return {before:n,after:o,changes:r}}function Ut(e){return e}async function We(e,t,n){let r=e.changes||{};for(let o of Object.keys(r)){let i=t[o];if(i&&i.length>0){for(let c of i)if(await c.rule({diff:e,key:o,user:n,authenticatedUser:n})===false)return {allowed:false,reason:c.description}}}return {allowed:true}}function Kt(e){return async t=>We(t.diff,e,t.user)}var ke=1e3;function Ve(e,t){if(e===void 0)return {success:true,value:Math.min(Math.max(1,t),ke)};let n=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return !Number.isInteger(n)||n<=0||n>ke?{success:false,error:`Invalid pageSize: must be an integer between 1 and ${ke}`}:{success:true,value:n}}function Ee(e,t,n=200){let r=$e(t);return e.json(r,n)}function V(e,t,n,r=200){return Ee(e,{success:true,data:t,meta:n},r)}function x(e,t,n=400){return Ee(e,{success:false,error:t},n)}async function Oe(e,t,n,r,o,i){let c=Ge(t,n),u=c.type==="index",d=u?424:500,m={success:false,error:u?c.message:o&&t instanceof Error?t.message:r};if(u&&(m.errorType="index",c.indexUrl&&(m.indexUrl=c.indexUrl,i)))try{let y=i({indexUrl:c.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});y instanceof Promise&&await y;}catch(y){o&&console.error("[crudServer] Error in indexesError callback:",y);}return Ee(e,m,d)}function J(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return zod.z.preprocess(r=>Ne(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[i,c]of Object.entries(r))o[i]=J(c);return zod.z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return zod.z.array(J(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return J(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return J(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let i=J(r);return typeof o=="function"?i.default(o()):i.default(o)}}return e}function Lt(e,t,n=[]){let r=e.shape,o={},i=t&&t.length>0?t:Object.keys(r);for(let c of i){if(n.includes(c))continue;let u=c.split(".")[0];u&&r[u]&&(o[u]=r[u]);}return zod.z.object(o)}function Ce(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function Xe(e,t){let n=t.split("."),r=Ce(e);for(let o=0;o<n.length;o++){let i=n[o];if(!i)continue;let c=r?.shape;if(!c||!c[i])return;let u=c[i];if(o===n.length-1)return u;r=Ce(u);}return r}function Q(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type;if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[i,c]of Object.entries(r))o[i]=Q(c);return zod.z.object(o).partial()}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let o=Q(r);return o===r?e:o.optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let o=Q(r);return o===r?e:o.nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?Q(r).optional():e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let o=r.map(c=>Q(c));return o.some((c,u)=>c!==r[u])?zod.z.union(o):e}return e}function pe(e,t,n,r=false,o=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let i=t,c={},u={};for(let[d,p]of Object.entries(i))if(d.includes(".")){let m=d.split(".")[0];if(o.includes(d)||o.includes(m))continue;if(n&&n.length>0&&!n.includes(d)&&!n.includes(m))return {success:!1,error:`Field '${d}' is not allowed for this operation`};let y=Xe(e,d);if(!y)return {success:!1,error:`Field '${d}' does not exist in schema`};let b=r?Q(y):y,N=(be()==="normalize"?J(b):b).parse(p);c[d]=N;}else u[d]=p;if(Object.keys(u).length>0||Object.keys(c).length===0){let d=Lt(e,n,o),p=r?Q(d):d,y=(be()==="normalize"?J(p):p).parse(u);Object.assign(c,y);}return {success:!0,data:c}}catch(i){return i instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${i.issues.map(u=>`${u.path.join(".")}: ${u.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var Ye={eq:"==","==":"==",ne:"!=","!=":"!=",lt:"<","<":"<",lte:"<=","<=":"<=",gt:">",">":">",gte:">=",">=":">=",in:"in",nin:"not-in","not-in":"not-in",not_in:"not-in",contains:"array-contains","array-contains":"array-contains",array_contains:"array-contains",arrayContains:"array-contains",containsAny:"array-contains-any","array-contains-any":"array-contains-any",array_contains_any:"array-contains-any",arrayContainsAny:"array-contains-any"};function re(e){return Ye[e]??e}function Gt(e){return e in Ye}function fe(e,t,n,r){let o=Xe(e,t);if(!o||typeof o.safeParse!="function")return {success:true,data:n};let i=r?re(r):void 0,c=Ce(o),u=Be(c);if(i==="array-contains"){let m=u??o;if(typeof m.safeParse=="function"){let y=m.safeParse(n);return y.success?{success:true,data:y.data}:{success:false,error:y.error.issues.map(O=>O.message).join(", ")}}return {success:true,data:n}}if(i==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let m=u??o,y=[];for(let b of n)if(typeof m.safeParse=="function"){let O=m.safeParse(b);if(O.success)y.push(O.data);else return {success:false,error:O.error.issues.map(C=>C.message).join(", ")}}else y.push(b);return {success:true,data:y}}let d=o.safeParse(n);if(d.success)return {success:true,data:d.data};if(Array.isArray(n)){let m=u??o,y=[];for(let b of n)if(typeof m.safeParse=="function"){let O=m.safeParse(b);if(O.success)y.push(O.data);else return {success:false,error:O.error.issues.map(C=>C.message).join(", ")}}else y.push(b);return {success:true,data:y}}return {success:false,error:d.error.issues.map(m=>m.message).join(", ")}}function Wt(e,t){let n=[],r=t?new Set(t):null;for(let[o,i]of Object.entries(e)){if(i===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(o))continue;let c=Array.isArray(i)?i[0]:i;if(c===void 0||c==="")continue;let u=o.lastIndexOf("__"),d,p="==";if(u!==-1){let y=o.slice(0,u),b=o.slice(u+2);Gt(b)?(d=y,p=re(b)):(d=o,p="==");}else d=o;if(r&&!r.has(d))continue;let m=c;p==="in"||p==="not-in"||p==="array-contains-any"?m=c.split(",").map(y=>Je(y.trim())):m=Je(c),n.push({field:d,op:p,value:m});}return n}function Je(e){if(e==="true")return true;if(e==="false")return false;if(e==="null"||e==="__null__")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function ye(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Qe(e,t){if(!t)return;let n;if(typeof t=="string")try{n=JSON.parse(t);}catch{n=t.includes("/")?{docPath:t}:{docId:t};}else typeof t=="object"&&(n=t);if(!n)return;let r=typeof n.docPath=="string"?n.docPath:void 0,o=typeof n.docId=="string"?n.docId:void 0;try{let i=e.repo.ref,c=i?.firestore;if(r&&c&&typeof c.doc=="function"){let u=await c.doc(r).get();if(u.exists)return u}if(o&&o.includes("/")&&c&&typeof c.doc=="function"){let u=await c.doc(o).get();if(u.exists)return u}if(o&&typeof i.doc=="function"){let u=await i.doc(o).get();if(u.exists)return u}return}catch{return}}function et(e,t,n,r){async function o(f,s,g,a){if(!s.rules)return {allowed:true};let w=s.rules?.[g];if(!w)return {allowed:false,errorResponse:x(f,`Operation "${g}" is not allowed for this repository`,403)};try{let h=await w(a);return h===!1?{allowed:!1,errorResponse:x(f,"Forbidden",403)}:typeof h=="string"?{allowed:!1,errorResponse:x(f,h,403)}:typeof h=="object"&&h!==null&&!h.allowed?{allowed:!1,errorResponse:x(f,h.reason||"Forbidden",403)}:{allowed:!0}}catch(h){let R=n&&h instanceof Error?h.message:"Forbidden";return {allowed:false,errorResponse:x(f,R,403)}}}async function i(f,s,g,a){if(!f.rules)return a;let w=f.rules?.filter;if(!w)return a;let h=[];for(let R of a)try{await w({user:s,doc:R,params:g})&&h.push(R);}catch{}return h}function c(f){return f.get("user")??f.get("docsUser")??null}function u(f,s){if(!f){let g=s.req.path.split("/");for(let a of g)if(e[a]){f=a;break}}return !f||!e[f]?null:e[f]??null}function d(f,s){return Me(f,{pathKey:s.pathKey,documentKey:s.documentKey,parentKeys:s.parentKeys,documentPathTemplate:s.documentPathTemplate,isGroup:s.isGroup})}async function p(f,s){let g=`by${f.documentKey.charAt(0).toUpperCase()}${f.documentKey.slice(1)}`,a=f.repo.get[g];if(typeof a=="function")try{let h=await a(s);if(h)return h}catch{}return (await f.repo.query.by({where:[[f.documentKey,"==",s]],limit:1}))[0]??null}async function m(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);let w=c(s),h=await o(s,a,"list",{user:w,query:s.req.query(),params:g});if(!h.allowed)return h.errorResponse;let R=[],v;try{let l=s.req.query(),T=Ve(l.pageSize,a.pageSize);if(!T.success)return x(s,T.error,400);let P=T.value,D=l.cursor,_=l.direction?.toLowerCase()==="prev"?"prev":"next",E=l.orderBy,A=l.orderDir?.toLowerCase()==="desc"?"desc":"asc",$=l.select,L=$?$.split(",").map(M=>M.trim()):void 0,I=l.withTotal,k=I==="true"||I==="1"||I===!0,j;a.allowedIncludes&&l.includes&&(j=(typeof l.includes=="string"?l.includes.split(",").map(G=>G.trim()):Array.isArray(l.includes)?l.includes:[]).filter(G=>typeof G=="string"&&a.allowedIncludes.includes(G)),j?.length===0&&(j=void 0));let q=Wt(l,a.filterableFields);R=q.map(M=>({field:M.field,op:M.op,value:String(M.value??"")})),E&&(v={field:E,dir:A});let U={pageSize:P,direction:_,...k?{withTotal:!0}:{}};if(D)try{let M=typeof D=="string"?JSON.parse(D):D;U.cursor=await Qe(a,M);}catch{}if(E){if(a.orderableFields&&!a.orderableFields.includes(E))return x(s,`Field not orderable: ${E}`,400);U.orderBy=[{field:E,direction:A}];}if(q.length>0){U.where=[];for(let M of q){let G=fe(a.schema,M.field,M.value,M.op);if(!G.success)return x(s,`Invalid filter value for '${M.field}': ${G.error}`,400);U.where.push([M.field,M.op,G.data]);}}L&&(U.select=L),j&&(U.include=j);let Z=await a.repo.query.paginate(U),Tt={items:await i(a,c(s),g,Z.data),hasNextPage:Z.hasNextPage,hasPrevPage:Z.hasPrevPage,nextCursor:ye(Z.nextCursor),prevCursor:ye(Z.prevCursor),...Z.totalCount!==void 0?{totalCount:Z.totalCount,totalCountIsExact:Z.totalCountIsExact}:{}};return V(s,Tt,{pageSize:P,hasMore:Z.hasNextPage,...Z.totalCount!==void 0?{totalCount:Z.totalCount,totalCountIsExact:Z.totalCountIsExact}:{}})}catch(l){return await Oe(s,l,{repoName:g.repoName||a.name,ref:a.repo.ref,path:a.path,isGroup:!!a.isGroup,filters:R,sort:v},"Failed to fetch documents",n,r)}}async function y(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);let w=c(s),h=await o(s,a,"list",{user:w,query:f.input||{},params:g});if(!h.allowed)return h.errorResponse;let R=[],v;try{let l=f.input||{},T=Ve(l.pageSize,a.pageSize);if(!T.success)return x(s,T.error,400);let P=T.value,D=l.direction==="prev"?"prev":"next";l.where&&(R=l.where.map(I=>({field:String(I[0]),op:I[1],value:String(I[2]??"")}))),l.orderBy&&l.orderBy[0]&&(v={field:l.orderBy[0].field,dir:l.orderBy[0].direction==="desc"?"desc":"asc"});let _=l.withTotal===!0||String(l.withTotal)==="true",E={pageSize:P,direction:D,..._?{withTotal:!0}:{}};if(l.cursor)try{let I=typeof l.cursor=="string"?JSON.parse(l.cursor):l.cursor;E.cursor=await Qe(a,I);}catch{}if(a.allowedIncludes&&l.includes&&l.includes.length>0){let I=l.includes.filter(k=>typeof k=="string"?a.allowedIncludes.includes(k):typeof k=="object"&&k!==null&&"relation"in k&&typeof k.relation=="string"?a.allowedIncludes.includes(k.relation):!1);I.length>0&&(E.include=I);}if(l.where&&l.where.length>0){if(a.filterableFields){let k=new Set(a.filterableFields),j=l.where.filter(q=>!k.has(q[0]));if(j.length>0){x(s,`Fields not filterable: ${j.map(q=>q[0]).join(", ")}`,400);return}}let I=[];for(let k of l.where){let j=re(k[1]),q=fe(a.schema,k[0],k[2],j);if(!q.success){x(s,`Invalid filter value for '${k[0]}': ${q.error}`,400);return}I.push([k[0],j,q.data]);}E.where=I;}if(l.orWhere&&l.orWhere.length>0){if(a.filterableFields){let k=new Set(a.filterableFields),j=l.orWhere.filter(q=>!k.has(q[0]));if(j.length>0){x(s,`Fields not filterable: ${j.map(q=>q[0]).join(", ")}`,400);return}}let I=[];for(let k of l.orWhere){let j=re(k[1]),q=fe(a.schema,k[0],k[2],j);if(!q.success){x(s,`Invalid filter value for '${k[0]}': ${q.error}`,400);return}I.push([k[0],j,q.data]);}E.orWhere=I;}if(l.orWhereGroups&&l.orWhereGroups.length>0){if(a.filterableFields){let k=new Set(a.filterableFields);for(let j of l.orWhereGroups){let q=j.filter(U=>!k.has(U[0]));if(q.length>0){x(s,`Fields not filterable: ${q.map(U=>U[0]).join(", ")}`,400);return}}}let I=[];for(let k of l.orWhereGroups){let j=[];for(let q of k){let U=re(q[1]),Z=fe(a.schema,q[0],q[2],U);if(!Z.success){x(s,`Invalid filter value for '${q[0]}': ${Z.error}`,400);return}j.push([q[0],U,Z.data]);}I.push(j);}E.orWhereGroups=I;}if(l.orderBy&&l.orderBy.length>0){if(a.orderableFields){let I=new Set(a.orderableFields),k=l.orderBy.filter(j=>!I.has(j.field));if(k.length>0){x(s,`Fields not orderable: ${k.map(j=>j.field).join(", ")}`,400);return}}E.orderBy=l.orderBy;}l.select&&l.select.length>0&&(E.select=l.select);let A=await a.repo.query.paginate(E),L={items:await i(a,c(s),g,A.data),hasNextPage:A.hasNextPage,hasPrevPage:A.hasPrevPage,nextCursor:ye(A.nextCursor),prevCursor:ye(A.prevCursor),...A.totalCount!==void 0?{totalCount:A.totalCount,totalCountIsExact:A.totalCountIsExact}:{}};return V(s,L,{pageSize:P,hasMore:A.hasNextPage,...A.totalCount!==void 0?{totalCount:A.totalCount,totalCountIsExact:A.totalCountIsExact}:{}})}catch(l){return await Oe(s,l,{repoName:g.repoName||a.name,ref:a.repo.ref,path:a.path,isGroup:!!a.isGroup,filters:R,sort:v},"Failed to query documents",n,r)}}async function b(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);let w=g.id;if(!w)return x(s,"Document ID required",400);try{let h=await p(a,w);if(!h)return x(s,"Document not found",404);let R=c(s),v=await o(s,a,"get",{user:R,doc:h,params:g});if(!v.allowed)return v.errorResponse;if(a.rules?.filter)try{if(!await a.rules.filter({user:R,doc:h,params:g}))return x(s,"Document not found",404)}catch{return x(s,"Document not found",404)}return V(s,h)}catch(h){return await Oe(s,h,{repoName:g.repoName||a.name,ref:a.repo.ref,path:a.path,isGroup:!!a.isGroup,filters:[{field:a.documentKey,op:"==",value:w}]},"Failed to fetch document",n,r)}}async function O(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);try{let w=f.input||{},h=c(s),R=await o(s,a,"create",{user:h,body:w,params:g});if(!R.allowed)return R.errorResponse;let v=pe(a.schema,w,a.createFields,!1,a.systemKeys);if(!v.success)return x(s,v.error,400);if(a.validate){let T=await a.validate(v.data,"create");if(T)return x(s,T,400)}let l;if(a.isGroup&&a.parentKeys&&a.parentKeys.length>0){let T={...v.data},P=a.parentKeys.filter(D=>T[D]===void 0||T[D]===null||typeof T[D]=="string"&&T[D].trim()==="");if(P.length>0){x(s,`Missing parent key(s) for subcollection create: ${P.join(", ")}`,400);return}if(typeof a.repo.create=="function")l=await a.repo.create(T);else {let D=a.parentKeys.map(E=>String(T[E])),_=T[a.documentKey]||Re();l=await a.repo.set(...D,_,T);}}else l=await a.repo.create(v.data);return V(s,l,void 0,201)}catch(w){let h=n&&w instanceof Error?w.message:"Failed to create document";return x(s,h,500)}}async function N(f,s){let g=f.c,a=g.req.param(),w=u(a.repoName,g);if(!w)return x(g,"Repository not found",404);let h=a.id;if(!h)return x(g,"Document ID required",400);try{let R=f.input||{},v=await p(w,h);if(!v)return x(g,"Document not found",404);let l=pe(w.schema,R,w.mutableFields,s,w.systemKeys);if(!l.success)return x(g,l.error,400);if(w.validate){let A=await w.validate(l.data,"update");if(A)return x(g,A,400)}let T=le(v,l.data),P=c(g),D=await o(g,w,"update",{user:P,doc:v,body:l.data,diff:T,params:a});if(!D.allowed)return D.errorResponse;let _=d(v,w)??[h],E=await w.repo.update(..._,l.data);return V(g,E)}catch(R){let v=n&&R instanceof Error?R.message:"Failed to update document";return x(g,v,500)}}async function C(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);if(!a.allowDelete)return x(s,"Delete not allowed for this repository",403);let w=g.id;if(!w)return x(s,"Document ID required",400);try{let h=await p(a,w);if(!h)return x(s,"Document not found",404);let R=c(s),v=await o(s,a,"delete",{user:R,doc:h,params:g});if(!v.allowed)return v.errorResponse;let l=d(h,a)??[w];return await a.repo.delete(...l),V(s,{deleted:!0})}catch(h){let R=n&&h instanceof Error?h.message:"Failed to delete document";return x(s,R,500)}}function S(f){return f.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-History-Reason, X-History-Comment","Access-Control-Max-Age":"86400"})}async function z(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);try{let w=f.input||{};if(!Array.isArray(w.operations))return x(s,"operations array is required",400);let h=c(s),R=a.repo.batch.create(),v=[];for(let l of w.operations){if(!l.type||!["create","update","delete"].includes(l.type))return x(s,"Invalid operation type",400);if(l.type==="create"){let T=await o(s,a,"create",{user:h,body:l.data,params:g});if(!T.allowed)return T.errorResponse;let P=pe(a.schema,l.data,a.createFields,!1,a.systemKeys);if(!P.success)return x(s,P.error,400);let D=l.data[a.documentKey]||Re(),_={...P.data};if(a.createdKey&&_[a.createdKey]===void 0&&(_[a.createdKey]=new Date),a.isGroup&&a.parentKeys){let E=a.parentKeys.map(A=>_[A]);R.set(...E,D,_);}else R.set(D,_);v.push({op:"create",id:D});}else if(l.type==="update"){if(!l.id)return x(s,"id required for update",400);let T=await p(a,l.id);if(!T)return x(s,`Document ${l.id} not found`,404);let P=pe(a.schema,l.data,a.mutableFields,!0,a.systemKeys);if(!P.success)return x(s,P.error,400);if(a.validate){let A=await a.validate(P.data,"update");if(A)return x(s,A,400)}let D=le(T,P.data),_=await o(s,a,"update",{user:h,doc:T,body:P.data,diff:D,params:g});if(!_.allowed)return _.errorResponse;let E=d(T,a)??[l.id];R.update(...E,P.data),v.push({op:"update",id:l.id});}else if(l.type==="delete"){if(!a.allowDelete)return x(s,"Delete not allowed",403);if(!l.id)return x(s,"id required for delete",400);let T=await p(a,l.id);if(!T)return x(s,`Document ${l.id} not found`,404);let P=await o(s,a,"delete",{user:h,doc:T,params:g});if(!P.allowed)return P.errorResponse;let D=d(T,a)??[l.id];R.delete(...D),v.push({op:"delete",id:l.id});}}return await R.commit(),V(s,{results:v})}catch(w){let h=n&&w instanceof Error?w.message:"Batch operation failed";return x(s,h,500)}}return {handleList:m,handleQuery:y,handleGet:b,handleCreate:O,handleUpdate:N,handleDelete:C,handleBatch:z,handleOptions:S}}function te(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=zodToOpenapi.getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function H(e){return {$ref:`#/components/schemas/${e}`}}function F(e){return {description:e,content:{"application/json":{schema:H("ErrorResponse")}}}}function ee(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Vt(e){return {description:"Paginated list of documents",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:{type:"object",properties:{items:{type:"array",items:e},nextCursor:{oneOf:[{type:"object"},{type:"null"}]},prevCursor:{oneOf:[{type:"object"},{type:"null"}]},hasNextPage:{type:"boolean"},hasPrevPage:{type:"boolean"},totalCount:{type:"integer",description:"Total count of matching documents (when requested with withTotal=true)"},totalCountIsExact:{type:"boolean",description:"Whether totalCount is exact (true) or estimated due to OR conditions (false)"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},totalCount:{type:"integer"},totalCountIsExact:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function se(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function Jt(e,t){let n=t.split("."),r=se(e);for(let o=0;o<n.length;o++){let i=n[o];if(!i)continue;let c=r?.shape;if(!c||!c[i])return;let u=c[i];if(o===n.length-1)return u;r=se(u);}return r}function Y(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,r=o=>{let i=zodToOpenapi.getOpenApiMetadata(e);return i&&typeof o.openapi=="function"?o.openapi(i):o};if(n==="ZodObject"||n==="object"){let o=e.shape,i={};for(let[c,u]of Object.entries(o))i[c]=Y(u);return r(zod.z.object(i).partial())}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let i=Y(o);return i===o?e:r(i.optional())}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let i=Y(o);return i===o?e:r(i.nullable())}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?r(Y(o).optional()):e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let i=o.map(u=>Y(u));return i.some((u,d)=>u!==o[d])?r(zod.z.union(i)):e}return e}function Ie(e,t="",n=0){if(n>5)return [];let o=se(e)?.shape;if(!o)return [];let i=[];for(let[c,u]of Object.entries(o)){let d=t?`${t}.${c}`:c,p=se(u);p?.shape&&typeof p.shape=="object"?(i.push({path:d,zodSchema:u}),i.push(...Ie(p,d,n+1))):i.push({path:d,zodSchema:u});}return i}function Qt(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:Jt(e.schema,t)})):Ie(e.schema)}function tt(e){if(!e)return {type:"string"};let t=te(e);return delete t.$schema,delete t.title,t}function rt(){return {type:"object",properties:{where:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3}},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string"},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string"},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function Xt(e){let t=Qt(e),n=e.orderableFields??t.map(c=>c.path),r=t.map(c=>c.path);if(t.length===0)return rt();let o=[];for(let{path:c,zodSchema:u}of t){let d=tt(u),p=se(u),y=p?._zod?.def?.type==="array"||p?._def?.typeName==="ZodArray"||p?._def?.type==="array"?tt(p?._zod?.def?.element??p?._def?.type??p?._def?.element):d;o.push({type:"array",description:`Condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},d],minItems:3,maxItems:3}),o.push({type:"array",description:`List condition on '${c}' (in, not-in)`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:d}],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["array-contains","contains"]},y],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains-any condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:y}],minItems:3,maxItems:3});}let i={oneOf:o};return {type:"object",properties:{where:{type:"array",items:i,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:i,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:i},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string",enum:n},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string",enum:r},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:e.allowedIncludes&&e.allowedIncludes.length>0?{oneOf:[{type:"string",enum:e.allowedIncludes},{type:"object",properties:{relation:{type:"string",enum:e.allowedIncludes},select:{type:"array",items:{type:"string"}}},required:["relation"]}]}:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function Yt(e,t,n,r,o,i=null,c="QueryRequestBody"){let u={},d=e.name,p=`${t}/${e.name}`,m=`${p}/{${e.documentKey}}`,y={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};u[p]={post:{operationId:`create${W(e.name)}`,summary:`Create a ${K(e.name)}`,tags:[d],requestBody:{required:true,content:{"application/json":{schema:H(r??n)}}},responses:{201:ee("Document created",H(n)),400:F("Validation error"),403:F("Forbidden"),500:F("Internal server error")}}},u[`${p}/query`]={post:{operationId:`query${W(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[d],requestBody:{required:true,content:{"application/json":{schema:H(c)}}},responses:{200:Vt(H(n)),400:F("Invalid query"),403:F("Forbidden"),424:F("Missing composite index (includes indexUrl in response)"),500:F("Internal server error")}}},u[`${p}/batch`]={post:{operationId:`batch${W(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[d],requestBody:{required:true,content:{"application/json":{schema:H(`${n}BatchRequest`)}}},responses:{200:ee("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:F("Validation error"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}}};let b={};return b.get={operationId:`get${W(K(e.name))}`,summary:`Get a single ${K(e.name)}`,tags:[d],parameters:[y],responses:{200:ee("Document found",H(n)),400:F("Document ID required"),403:F("Forbidden"),404:F("Document not found"),424:F("Missing composite index (includes indexUrl in response)"),500:F("Internal server error")}},b.put={operationId:`update${W(K(e.name))}`,summary:`Update a ${K(e.name)} (full replace)`,tags:[d],parameters:[y],requestBody:{required:true,content:{"application/json":{schema:H(o??n)}}},responses:{200:ee("Document updated",H(n)),400:F("Validation error"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}},b.patch={operationId:`patch${W(K(e.name))}`,summary:`Partially update a ${K(e.name)}`,tags:[d],parameters:[y],requestBody:{required:true,content:{"application/json":{schema:H(i??o??n)}}},responses:{200:ee("Document patched",H(n)),400:F("Validation error"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}},e.allowDelete&&(b.delete={operationId:`delete${W(K(e.name))}`,summary:`Delete a ${K(e.name)}`,tags:[d],parameters:[y],responses:{200:ee("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:F("Document ID required"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}}),u[m]=b,u}function Pe(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:i,servers:c,auth:u=false}=n,d=t==="/"?"":t.replace(/\/$/,""),p={},m={},y=[];p.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string",description:"Human-readable error description"},errorType:{type:"string",enum:["index"],description:"Error category discriminator. Set to 'index' when a Firestore composite index is missing."},indexUrl:{type:"string",format:"uri",description:"Direct Firebase Console URL to create the required composite index (when errorType is 'index')."}},required:["success","error"]},p.QueryRequestBody=rt();for(let[C,S]of Object.entries(e)){let z=W(K(C)),f=`${z}Create`,s=`${z}Update`,g=`${z}Patch`,a=`${z}QueryRequestBody`;p[z]=te(S.schema),p[a]=Xt(S);let w=A=>{let $={},L=Ie(S.schema);for(let{path:I,zodSchema:k}of L){let j=I.split(".")[0];S.systemKeys.includes(j)||S.systemKeys.includes(I)||A&&A.length>0&&!A.includes(I)&&!A.includes(j)||(I.includes(".")?$[I]=k.optional():$[I]=k);}return $},h=null,R=w(S.createFields);if(S.isGroup&&S.parentKeys&&S.parentKeys.length>0){let A=S.schema?.shape??{};for(let $ of S.parentKeys)!R[$]&&A[$]&&(R[$]=A[$]);}if(Object.keys(R).length>0){let A=te(zod.z.object(R));if(S.isGroup&&S.parentKeys&&S.parentKeys.length>0){let $=new Set(Array.isArray(A.required)?A.required:[]);for(let L of S.parentKeys)A.properties?.[L]&&$.add(L);$.size>0&&(A.required=Array.from($));}p[f]=A,h=f;}let v=null,l=null,T=w(S.mutableFields);if(Object.keys(T).length>0){let A=zod.z.object(T);p[s]=te(A),v=s,p[g]=te(Y(A)),l=g;}else p[g]=te(Y(S.schema)),l=g;let P=`${z}BatchCreateOperation`,D=`${z}BatchUpdateOperation`,_=`${z}BatchDeleteOperation`;p[P]={type:"object",title:`${z} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:H(h??z)},required:["type","data"]},p[D]={type:"object",title:`${z} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:H(l??v??z)},required:["type","id","data"]},S.allowDelete&&(p[_]={type:"object",title:`${z} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),p[`${z}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[H(P),H(D),...S.allowDelete?[H(_)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let E=Yt(S,d,z,h,v,l,a);Object.assign(m,E),y.push({name:C,description:`Operations on ${C} (collection: ${S.path})`});}let b={},O;return u==="basic"?(b.basicAuth={type:"http",scheme:"basic"},O=[{basicAuth:[]}]):u==="bearer"&&(b.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},O=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...i?{description:i}:{}},...c&&c.length>0?{servers:c}:{},paths:m,components:{schemas:p,...Object.keys(b).length>0?{securitySchemes:b}:{}},...O?{security:O}:{},tags:y}}function W(e){return e.charAt(0).toUpperCase()+e.slice(1)}function K(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var ne=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var ie=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},ae=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function ot(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function st(e,t){return t instanceof ne?e.json({success:false,error:"Validation failed",issues:ot(t.zodError)},400):t instanceof ie?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof ae?e.json({success:false,error:"Output validation failed",issues:ot(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var it="Successful response",at="Error response";function B(e,t=new Set){if(!e||typeof e!="object"||t.has(e))return;t.add(e);let n=e,r=n._zod?.def??n.def;if(!r)return;if(r.type==="custom"){let i=zodToOpenapi.getOpenApiMetadata(n);i?.type||zod.z.globalRegistry.add(n,{...i??{},type:"object"});return}if(r.innerType&&B(r.innerType,t),r.element&&B(r.element,t),r.valueType&&B(r.valueType,t),r.keyType&&B(r.keyType,t),r.left&&B(r.left,t),r.right&&B(r.right,t),r.in&&B(r.in,t),r.out&&B(r.out,t),typeof r.getter=="function")try{B(r.getter(),t);}catch{}if(Array.isArray(r.options))for(let i of r.options)B(i,t);if(Array.isArray(r.items))for(let i of r.items)B(i,t);let o=typeof r.shape=="function"?r.shape():r.shape;if(o&&typeof o=="object")for(let i of Object.values(o))B(i,t);}function De(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)De(n);return}let t=e;(Array.isArray(t.anyOf)||Array.isArray(t.oneOf))&&"type"in t&&delete t.type;for(let n of Object.values(t))De(n);}function on(e){return e==="get"?"query":"json"}function sn(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function an(e){if(typeof e.safeParse=="function")return {description:at,schema:e};let t=e;return {description:t.description??at,schema:t.schema}}function dt(e,t,n,r){let o=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[u,d]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",u,d);for(let u of e){let d=u.method,p=u.source??on(d),m=dn(t,u.path??"/"),y=u.status??200;u.input&&B(u.input);let b=cn(d,p,u.input),O=ct(p,u.input,"query"),N=ct(p,u.input,"param"),C=ln(d,m),S=sn(u.output,r);S&&B(S);let z={[y]:S?{description:it,content:{"application/json":{schema:S}}}:{description:it}};if(r?.errors)for(let[f,s]of Object.entries(r.errors)){let{description:g,schema:a}=an(s);a&&B(a),z[f]=a?{description:g,content:{"application/json":{schema:a}}}:{description:g};}o.registerPath({method:d,path:un(m),operationId:C,summary:u.summary,description:u.description,tags:u.tags,deprecated:u.deprecated,security:u.security,request:{...O?{query:O}:{},...N?{params:N}:{},...b?{body:b}:{}},responses:z});}let c=new zodToOpenapi.OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return De(c),c}function cn(e,t,n){return !n||e==="get"?null:t==="json"?{content:{"application/json":{schema:n}}}:t==="form"?{content:{"application/x-www-form-urlencoded":{schema:n}}}:null}function ct(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function un(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function dn(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function ln(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function lt(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
1
|
+
'use strict';var zod=require('zod'),firestore=require('firebase-admin/firestore'),crypto=require('crypto'),zodToOpenapi=require('@asteasolutions/zod-to-openapi'),hono=require('hono'),nodeServer=require('@hono/node-server'),async_hooks=require('async_hooks');var xe=Object.defineProperty;var Dt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var zt=Object.prototype.hasOwnProperty;var _t=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var qt=(e,t)=>{for(var n in t)xe(e,n,{get:t[n],enumerable:true});},Nt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of jt(t))!zt.call(e,o)&&o!==n&&xe(e,o,{get:()=>t[o],enumerable:!(r=Dt(t,o))||r.enumerable});return e};var Ft=e=>Nt(xe({},"__esModule",{value:true}),e);var Ot={};qt(Ot,{DEFAULT_HTML_CSP:()=>Et,securityHeaders:()=>Hn});function Hn(e={}){let t=e.csp===void 0?Et:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,r=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,o=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(i,a,d)=>{typeof a?.setHeader=="function"&&(a.setHeader("X-Content-Type-Options","nosniff"),n&&a.setHeader("X-Frame-Options",n),r&&a.setHeader("Referrer-Policy",r),o&&a.setHeader("Cache-Control",o),t&&a.setHeader("Content-Security-Policy",t)),await d();}}var Ct,vt,Et,Pt=_t(()=>{"use strict";Ct="https://cdn.jsdelivr.net",vt="https://www.gstatic.com",Et=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Ct} ${vt}`,`style-src 'self' 'unsafe-inline' ${Ct}`,`connect-src 'self' ${vt} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,"img-src 'self' data:","font-src 'self' data:","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");});var Ze="preserve";function Ae(){return Ze}function Ht(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Me(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof firestore.Timestamp)return e.toDate();if(Ht(e))return new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));if(typeof e=="string"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function Be(e){return e}var Te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ke(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=Te.length*4||(e+=Te.charAt(r%Te.length));}}return e}function Ue(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function Ke(e,t="docId",n=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=e.split("/").map(y=>y.trim()).filter(Boolean);if(r.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let y=r[0];return {rawPath:e,collectionId:y,collectionPath:y,parentKeys:[],documentPathTemplate:n?null:`${y}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let o=r.length%2===0,i=o?r.slice(0,-1):r,a=i[i.length-1],d=i.join("/"),l=i.slice(0,-1).map(Ue).filter(y=>y!==null),g=o?r.join("/"):`${d}/{${t}}`;return {rawPath:e,collectionId:a,collectionPath:d,parentKeys:l,documentPathTemplate:g,hasTemplate:true}}function Le(e,t={}){if(!e||typeof e!="object")return;let{pathKey:n,documentKey:r="docId",parentKeys:o,documentPathTemplate:i,isGroup:a}=t,d=n&&typeof e[n]=="string"&&e[n]?e[n]:void 0;if(d&&i){let u=d.split("/").filter(Boolean),l=i.split("/").filter(Boolean);if(u.length===l.length){let g=[];for(let y=0;y<l.length;y++)Ue(l[y])!==null&&g.push(u[y]);if(g.length>0)return g}}if(o&&o.length>0){let u=o.length+1;if(d){let g=d.split("/").filter(Boolean),y=[];for(let R=1;R<g.length;R+=2)y.push(g[R]);if(y.length>=u)return y.slice(y.length-u)}let l=r?e[r]:void 0;if(typeof l=="string"&&l.trim()!==""){let g=[],y=true;for(let R of o){let _=e[R];if(typeof _=="string"&&_.trim()!=="")g.push(_);else {y=false;break}}if(y)return [...g,l]}}if(d){let u=d.split("/").filter(Boolean),l=[];for(let g=1;g<u.length;g+=2)l.push(u[g]);if(l.length>0)return !a&&(!o||o.length===0)?[l[l.length-1]]:l}}function We(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}var Mt=new Set(["<","<=",">",">=","!="]),Bt=new Set(["array-contains","array-contains-any"]);function Se(e){return e==="desc"?"DESCENDING":"ASCENDING"}function Ut(e){return Ke(e).collectionId||e}function Kt(e,t,n,r,o){let i=[],a=new Set;for(let u of r)if(u.op==="=="||u.op==="in"||u.op==="not-in"){if(a.has(u.field))continue;a.add(u.field),i.push({fieldPath:u.field,order:"ASCENDING"});}for(let u of r)if(Bt.has(u.op)){if(a.has(u.field))continue;a.add(u.field),i.push({fieldPath:u.field,arrayConfig:"CONTAINS"});}for(let u of r)if(Mt.has(u.op)){if(a.has(u.field))continue;a.add(u.field);let l=o?.field===u.field?Se(o.dir):"ASCENDING";i.push({fieldPath:u.field,order:l});}if(o&&!a.has(o.field)&&i.push({fieldPath:o.field,order:Se(o.dir)}),i.length===1&&n)return Gt(e,t,i[0]);let d=o&&i.some(u=>u.fieldPath===o.field)?Se(o.dir):"ASCENDING";return i.push({fieldPath:"__name__",order:d}),Lt(e,t,n,i)}function Lt(e,t,n,r,o="(default)"){let i=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...Ee(1,i),...pe(2,n?2:1)];for(let l of r)a.push(...Ge(3,Ve(l)));let d=o==="(default)"?"-default-":o,u=encodeURIComponent(Je(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${d}/indexes?create_composite=${u}`}function Wt(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Ce(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function ve(e,t){return e<<3|t}function Ee(e,t){let n=Array.from(new TextEncoder().encode(t));return [ve(e,2),...Ce(n.length),...n]}function pe(e,t){return [ve(e,0),...Ce(t)]}function Ge(e,t){return [ve(e,2),...Ce(t.length),...t]}function Ve(e){let t=[...Ee(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...pe(3,1)):t.push(...pe(2,e.order==="DESCENDING"?2:1)),t}function Je(e){let t=String.fromCharCode(...e),n;if(typeof Buffer<"u")n=Buffer.from(e).toString("base64");else if(typeof btoa<"u")n=btoa(t);else throw new Error("No base64 encoder available");return n.replace(/=+$/,"")}function Gt(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,i=[...Ee(1,o),...pe(2,2),...Ge(3,Ve(n))],a=r==="(default)"?"-default-":r,d=encodeURIComponent(Je(i));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${d}`}function Vt(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let o of n)if(typeof o=="string"&&o.length>0)return o;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function Jt(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Qe(e,t){let n=e??{},r=Jt(e),o;if(r&&(o=n.message?Wt(n.message):void 0,!o)){let i=Vt(t.ref);if(i){let a=Ut(t.path);o=Kt(i,a,t.isGroup,t.filters,t.sort);}}return {type:r?"index":"error",message:r?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}function fe(e,t,n=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof firestore.Timestamp&&t instanceof firestore.Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(n.get(e)===t)return true;n.set(e,t);for(let r=0;r<e.length;r++)if(!fe(e[r],t[r],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof firestore.Timestamp||t instanceof firestore.Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return false;for(let i of r)if(!Object.prototype.hasOwnProperty.call(t,i)||!fe(e[i],t[i],n))return false;return true}return false}function G(e,t){let n=e||{},r={},o={...n};for(let[i,a]of Object.entries(t||{})){let d=n[i];fe(d,a)||(r[i]=a,o[i]=a);}return {before:n,after:o,changes:r}}function Qt(e){return e}async function Xe(e,t,n){let r=e.changes||{};for(let o of Object.keys(r)){let i=t[o];if(i&&i.length>0){for(let a of i)if(await a.rule({diff:e,key:o,user:n,authenticatedUser:n})===false)return {allowed:false,reason:a.description}}}return {allowed:true}}function Xt(e){return async t=>Xe(t.diff,e,t.user)}var Oe=1e3;function Ye(e,t){if(e===void 0)return {success:true,value:Math.min(Math.max(1,t),Oe)};let n=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return !Number.isInteger(n)||n<=0||n>Oe?{success:false,error:`Invalid pageSize: must be an integer between 1 and ${Oe}`}:{success:true,value:n}}function De(e,t,n=200){let r=Be(t);return e.json(r,n)}function X(e,t,n,r=200){return De(e,{success:true,data:t,meta:n},r)}function A(e,t,n=400){return De(e,{success:false,error:t},n)}async function Pe(e,t,n,r,o,i){let a=Qe(t,n),d=a.type==="index",u=d?424:500,g={success:false,error:d?a.message:o&&t instanceof Error?t.message:r};if(d&&(g.errorType="index",a.indexUrl&&(g.indexUrl=a.indexUrl,i)))try{let y=i({indexUrl:a.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});y instanceof Promise&&await y;}catch(y){o&&console.error("[crudServer] Error in indexesError callback:",y);}return De(e,g,u)}function Y(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return zod.z.preprocess(r=>Me(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[i,a]of Object.entries(r))o[i]=Y(a);return zod.z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return zod.z.array(Y(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return Y(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return Y(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let i=Y(r);return typeof o=="function"?i.default(o()):i.default(o)}}return e}function Yt(e,t,n=[]){let r=e.shape,o={},i=t&&t.length>0?t:Object.keys(r);for(let a of i){if(n.includes(a))continue;let d=a.split(".")[0];d&&r[d]&&(o[d]=r[d]);}return zod.z.object(o)}function Ie(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function nt(e,t){let n=t.split("."),r=Ie(e);for(let o=0;o<n.length;o++){let i=n[o];if(!i)continue;let a=r?.shape;if(!a||!a[i])return;let d=a[i];if(o===n.length-1)return d;r=Ie(d);}return r}function ee(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type;if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[i,a]of Object.entries(r))o[i]=ee(a);return zod.z.object(o).partial()}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let o=ee(r);return o===r?e:o.optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let o=ee(r);return o===r?e:o.nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?ee(r).optional():e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let o=r.map(a=>ee(a));return o.some((a,d)=>a!==r[d])?zod.z.union(o):e}return e}function ye(e,t,n,r=false,o=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let i=t,a={},d={};for(let[u,l]of Object.entries(i))if(u.includes(".")){let g=u.split(".")[0];if(o.includes(u)||o.includes(g))continue;if(n&&n.length>0&&!n.includes(u)&&!n.includes(g))return {success:!1,error:`Field '${u}' is not allowed for this operation`};let y=nt(e,u);if(!y)return {success:!1,error:`Field '${u}' does not exist in schema`};let R=r?ee(y):y,M=(Ae()==="normalize"?Y(R):R).parse(l);a[u]=M;}else d[u]=l;if(Object.keys(d).length>0||Object.keys(a).length===0){let u=Yt(e,n,o),l=r?ee(u):u,y=(Ae()==="normalize"?Y(l):l).parse(d);Object.assign(a,y);}return {success:!0,data:a}}catch(i){return i instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${i.issues.map(d=>`${d.path.join(".")}: ${d.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var rt={eq:"==","==":"==",ne:"!=","!=":"!=",lt:"<","<":"<",lte:"<=","<=":"<=",gt:">",">":">",gte:">=",">=":">=",in:"in",nin:"not-in","not-in":"not-in",not_in:"not-in",contains:"array-contains","array-contains":"array-contains",array_contains:"array-contains",arrayContains:"array-contains",containsAny:"array-contains-any","array-contains-any":"array-contains-any",array_contains_any:"array-contains-any",arrayContainsAny:"array-contains-any"};function ie(e){return rt[e]??e}function en(e){return e in rt}function me(e,t,n,r){let o=nt(e,t);if(!o||typeof o.safeParse!="function")return {success:true,data:n};let i=r?ie(r):void 0,a=Ie(o),d=We(a);if(i==="array-contains"){let g=d??o;if(typeof g.safeParse=="function"){let y=g.safeParse(n);return y.success?{success:true,data:y.data}:{success:false,error:y.error.issues.map(_=>_.message).join(", ")}}return {success:true,data:n}}if(i==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let g=d??o,y=[];for(let R of n)if(typeof g.safeParse=="function"){let _=g.safeParse(R);if(_.success)y.push(_.data);else return {success:false,error:_.error.issues.map(q=>q.message).join(", ")}}else y.push(R);return {success:true,data:y}}let u=o.safeParse(n);if(u.success)return {success:true,data:u.data};if(Array.isArray(n)){let g=d??o,y=[];for(let R of n)if(typeof g.safeParse=="function"){let _=g.safeParse(R);if(_.success)y.push(_.data);else return {success:false,error:_.error.issues.map(q=>q.message).join(", ")}}else y.push(R);return {success:true,data:y}}return {success:false,error:u.error.issues.map(g=>g.message).join(", ")}}function tn(e,t){let n=[],r=t?new Set(t):null;for(let[o,i]of Object.entries(e)){if(i===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(o))continue;let a=Array.isArray(i)?i[0]:i;if(a===void 0||a==="")continue;let d=o.lastIndexOf("__"),u,l="==";if(d!==-1){let y=o.slice(0,d),R=o.slice(d+2);en(R)?(u=y,l=ie(R)):(u=o,l="==");}else u=o;if(r&&!r.has(u))continue;let g=a;l==="in"||l==="not-in"||l==="array-contains-any"?g=a.split(",").map(y=>et(y.trim())):g=et(a),n.push({field:u,op:l,value:g});}return n}function et(e){if(e==="true")return true;if(e==="false")return false;if(e==="null"||e==="__null__")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function he(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function tt(e,t){if(!t)return;let n;if(typeof t=="string")try{n=JSON.parse(t);}catch{n=t.includes("/")?{docPath:t}:{docId:t};}else typeof t=="object"&&(n=t);if(!n)return;let r=typeof n.docPath=="string"?n.docPath:void 0,o=typeof n.docId=="string"?n.docId:void 0;try{let i=e.repo.ref,a=i?.firestore;if(r&&a&&typeof a.doc=="function"){let d=await a.doc(r).get();if(d.exists)return d}if(o&&o.includes("/")&&a&&typeof a.doc=="function"){let d=await a.doc(o).get();if(d.exists)return d}if(o&&typeof i.doc=="function"){let d=await i.doc(o).get();if(d.exists)return d}return}catch{return}}function ge(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t={},n=0;for(let[r,o]of Object.entries(e))o!==void 0&&(t[r]=o,n++);return n>0?t:null}function ot(e,t,n,r,o){async function i(b,c,f,s){let w=false;if(b.hooks?.onAfterError){w=true;try{let h=b.hooks.onAfterError(s,f.hook);h instanceof Promise&&await h;}catch(h){console.error("[crudServer] Error in hooks.onAfterError callback:",h);}}if(o){w=true;try{let h=o({...f,error:s});h instanceof Promise&&await h;}catch(h){console.error("[crudServer] Error in onHookError callback:",h);}}if(!w){if(c&&typeof c.error=="function"){c.error(s,{hook:f.hook,repoName:f.repoName,path:f.path,...f.id!==void 0?{id:f.id}:{},...f.pathArgs!==void 0?{pathArgs:f.pathArgs}:{}});return}console.error(`[crudServer] Hook "${f.hook}" failed on repo "${f.repoName}":`,{hook:f.hook,repoName:f.repoName,path:f.path,...f.id!==void 0?{id:f.id}:{},...f.pathArgs!==void 0?{pathArgs:f.pathArgs}:{},error:s});}}async function a(b,c,f,s){if(!c.rules)return {allowed:true};let w=c.rules?.[f];if(!w)return {allowed:false,errorResponse:A(b,`Operation "${f}" is not allowed for this repository`,403)};try{let h=await w(s);return h===!1?{allowed:!1,errorResponse:A(b,"Forbidden",403)}:typeof h=="string"?{allowed:!1,errorResponse:A(b,h,403)}:typeof h=="object"&&h!==null&&!h.allowed?{allowed:!1,errorResponse:A(b,h.reason||"Forbidden",403)}:{allowed:!0}}catch(h){let S=n&&h instanceof Error?h.message:"Forbidden";return {allowed:false,errorResponse:A(b,S,403)}}}async function d(b,c,f,s){if(!b.rules)return s;let w=b.rules?.filter;if(!w)return s;let h=[];for(let S of s)try{await w({user:c,doc:S,params:f})&&h.push(S);}catch{}return h}function u(b){return b.get("user")??b.get("docsUser")??null}function l(b,c){if(!b){let f=c.req.path.split("/");for(let s of f)if(e[s]){b=s;break}}return !b||!e[b]?null:e[b]??null}function g(b,c){return Le(b,{pathKey:c.pathKey,documentKey:c.documentKey,parentKeys:c.parentKeys,documentPathTemplate:c.documentPathTemplate,isGroup:c.isGroup})}async function y(b,c){let f=`by${b.documentKey.charAt(0).toUpperCase()}${b.documentKey.slice(1)}`,s=b.repo.get[f];if(typeof s=="function")try{let h=await s(c);if(h)return h}catch{}return (await b.repo.query.by({where:[[b.documentKey,"==",c]],limit:1}))[0]??null}async function R(b){let c=b.c,f=c.req.param(),s=l(f.repoName,c);if(!s)return A(c,"Repository not found",404);let w=u(c),h=await a(c,s,"list",{user:w,query:c.req.query(),params:f});if(!h.allowed)return h.errorResponse;let S=[],E;try{let m=c.req.query(),H=Ye(m.pageSize,s.pageSize);if(!H.success)return A(c,H.error,400);let N=H.value,j=m.cursor,I=m.direction?.toLowerCase()==="prev"?"prev":"next",p=m.orderBy,x=m.orderDir?.toLowerCase()==="desc"?"desc":"asc",C=m.select,Z=C?C.split(",").map(L=>L.trim()):void 0,k=m.withTotal,v=k==="true"||k==="1"||k===!0,z;s.allowedIncludes&&m.includes&&(z=(typeof m.includes=="string"?m.includes.split(",").map(J=>J.trim()):Array.isArray(m.includes)?m.includes:[]).filter(J=>typeof J=="string"&&s.allowedIncludes.includes(J)),z?.length===0&&(z=void 0));let D=tn(m,s.filterableFields);S=D.map(L=>({field:L.field,op:L.op,value:String(L.value??"")})),p&&(E={field:p,dir:x});let B={pageSize:N,direction:I,...v?{withTotal:!0}:{}};if(j)try{let L=typeof j=="string"?JSON.parse(j):j;B.cursor=await tt(s,L);}catch{}if(p){if(s.orderableFields&&!s.orderableFields.includes(p))return A(c,`Field not orderable: ${p}`,400);B.orderBy=[{field:p,direction:x}];}if(D.length>0){B.where=[];for(let L of D){let J=me(s.schema,L.field,L.value,L.op);if(!J.success)return A(c,`Invalid filter value for '${L.field}': ${J.error}`,400);B.where.push([L.field,L.op,J.data]);}}Z&&(B.select=Z),z&&(B.include=z);let U=await s.repo.query.paginate(B),It={items:await d(s,u(c),f,U.data),hasNextPage:U.hasNextPage,hasPrevPage:U.hasPrevPage,nextCursor:he(U.nextCursor),prevCursor:he(U.prevCursor),...U.totalCount!==void 0?{totalCount:U.totalCount,totalCountIsExact:U.totalCountIsExact}:{}};return X(c,It,{pageSize:N,hasMore:U.hasNextPage,...U.totalCount!==void 0?{totalCount:U.totalCount,totalCountIsExact:U.totalCountIsExact}:{}})}catch(m){return await Pe(c,m,{repoName:f.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:S,sort:E},"Failed to fetch documents",n,r)}}async function _(b){let c=b.c,f=c.req.param(),s=l(f.repoName,c);if(!s)return A(c,"Repository not found",404);let w=u(c),h=await a(c,s,"list",{user:w,query:b.input||{},params:f});if(!h.allowed)return h.errorResponse;let S=[],E;try{let m=b.input||{},H=Ye(m.pageSize,s.pageSize);if(!H.success)return A(c,H.error,400);let N=H.value,j=m.direction==="prev"?"prev":"next";m.where&&(S=m.where.map(k=>({field:String(k[0]),op:k[1],value:String(k[2]??"")}))),m.orderBy&&m.orderBy[0]&&(E={field:m.orderBy[0].field,dir:m.orderBy[0].direction==="desc"?"desc":"asc"});let I=m.withTotal===!0||String(m.withTotal)==="true",p={pageSize:N,direction:j,...I?{withTotal:!0}:{}};if(m.cursor)try{let k=typeof m.cursor=="string"?JSON.parse(m.cursor):m.cursor;p.cursor=await tt(s,k);}catch{}if(s.allowedIncludes&&m.includes&&m.includes.length>0){let k=m.includes.filter(v=>typeof v=="string"?s.allowedIncludes.includes(v):typeof v=="object"&&v!==null&&"relation"in v&&typeof v.relation=="string"?s.allowedIncludes.includes(v.relation):!1);k.length>0&&(p.include=k);}if(m.where&&m.where.length>0){if(s.filterableFields){let v=new Set(s.filterableFields),z=m.where.filter(D=>!v.has(D[0]));if(z.length>0){A(c,`Fields not filterable: ${z.map(D=>D[0]).join(", ")}`,400);return}}let k=[];for(let v of m.where){let z=ie(v[1]),D=me(s.schema,v[0],v[2],z);if(!D.success){A(c,`Invalid filter value for '${v[0]}': ${D.error}`,400);return}k.push([v[0],z,D.data]);}p.where=k;}if(m.orWhere&&m.orWhere.length>0){if(s.filterableFields){let v=new Set(s.filterableFields),z=m.orWhere.filter(D=>!v.has(D[0]));if(z.length>0){A(c,`Fields not filterable: ${z.map(D=>D[0]).join(", ")}`,400);return}}let k=[];for(let v of m.orWhere){let z=ie(v[1]),D=me(s.schema,v[0],v[2],z);if(!D.success){A(c,`Invalid filter value for '${v[0]}': ${D.error}`,400);return}k.push([v[0],z,D.data]);}p.orWhere=k;}if(m.orWhereGroups&&m.orWhereGroups.length>0){if(s.filterableFields){let v=new Set(s.filterableFields);for(let z of m.orWhereGroups){let D=z.filter(B=>!v.has(B[0]));if(D.length>0){A(c,`Fields not filterable: ${D.map(B=>B[0]).join(", ")}`,400);return}}}let k=[];for(let v of m.orWhereGroups){let z=[];for(let D of v){let B=ie(D[1]),U=me(s.schema,D[0],D[2],B);if(!U.success){A(c,`Invalid filter value for '${D[0]}': ${U.error}`,400);return}z.push([D[0],B,U.data]);}k.push(z);}p.orWhereGroups=k;}if(m.orderBy&&m.orderBy.length>0){if(s.orderableFields){let k=new Set(s.orderableFields),v=m.orderBy.filter(z=>!k.has(z.field));if(v.length>0){A(c,`Fields not orderable: ${v.map(z=>z.field).join(", ")}`,400);return}}p.orderBy=m.orderBy;}m.select&&m.select.length>0&&(p.select=m.select);let x=await s.repo.query.paginate(p),Z={items:await d(s,u(c),f,x.data),hasNextPage:x.hasNextPage,hasPrevPage:x.hasPrevPage,nextCursor:he(x.nextCursor),prevCursor:he(x.prevCursor),...x.totalCount!==void 0?{totalCount:x.totalCount,totalCountIsExact:x.totalCountIsExact}:{}};return X(c,Z,{pageSize:N,hasMore:x.hasNextPage,...x.totalCount!==void 0?{totalCount:x.totalCount,totalCountIsExact:x.totalCountIsExact}:{}})}catch(m){return await Pe(c,m,{repoName:f.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:S,sort:E},"Failed to query documents",n,r)}}async function M(b){let c=b.c,f=c.req.param(),s=l(f.repoName,c);if(!s)return A(c,"Repository not found",404);let w=f.id;if(!w)return A(c,"Document ID required",400);try{let h=await y(s,w);if(!h)return A(c,"Document not found",404);let S=u(c),E=await a(c,s,"get",{user:S,doc:h,params:f});if(!E.allowed)return E.errorResponse;if(s.rules?.filter)try{if(!await s.rules.filter({user:S,doc:h,params:f}))return A(c,"Document not found",404)}catch{return A(c,"Document not found",404)}return X(c,h)}catch(h){return await Pe(c,h,{repoName:f.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:[{field:s.documentKey,op:"==",value:w}]},"Failed to fetch document",n,r)}}async function q(b){let c=b.c,f=c.req.param(),s=l(f.repoName,c);if(!s)return A(c,"Repository not found",404);try{let w=b.input||{},h=u(c),S=await a(c,s,"create",{user:h,body:w,params:f});if(!S.allowed)return S.errorResponse;let E=ye(s.schema,w,s.createFields,!1,s.systemKeys);if(!E.success)return A(c,E.error,400);if(s.validate){let j=await s.validate(E.data,"create");if(j)return A(c,j,400)}s.hooks?.beforeCreate&&await s.hooks.beforeCreate({user:h,body:E.data,params:f,c});let m,H;if(s.isGroup&&s.parentKeys&&s.parentKeys.length>0){let j={...E.data},I=s.parentKeys.filter(p=>j[p]===void 0||j[p]===null||typeof j[p]=="string"&&j[p].trim()==="");if(I.length>0)return A(c,`Missing parent key(s) for subcollection create: ${I.join(", ")}`,400);if(typeof s.repo.create=="function")m=await s.repo.create(j);else {let p=s.parentKeys.map(C=>String(j[C])),x=j[s.documentKey]||ke();H=[...p,x],m=await s.repo.set(...p,x,j);}}else m=await s.repo.create(E.data);let N=m;if(s.hooks?.afterCreate){let j=m?.[s.documentKey]??H?.[H.length-1]??"",I=String(j),p=H??g(m,s)??g({...E.data,...I?{[s.documentKey]:I}:{}},s)??(I?[I]:[]);try{let x=await s.hooks.afterCreate({user:h,doc:m,id:I,pathArgs:p,params:f,c}),C=ge(x);C&&p.length>0&&(N=await s.repo.update(...p,C));}catch(x){await i(s,b.logger,{hook:"afterCreate",repoName:s.name,path:s.path,id:I,pathArgs:p,user:h,c},x);}}return X(c,N,void 0,201)}catch(w){let h=n&&w instanceof Error?w.message:"Failed to create document";return A(c,h,500)}}async function T(b,c){let f=b.c,s=f.req.param(),w=l(s.repoName,f);if(!w)return A(f,"Repository not found",404);let h=s.id;if(!h)return A(f,"Document ID required",400);try{let S=b.input||{},E=await y(w,h);if(!E)return A(f,"Document not found",404);let m=ye(w.schema,S,w.mutableFields,c,w.systemKeys);if(!m.success)return A(f,m.error,400);if(w.validate){let k=await w.validate(m.data,"update");if(k)return A(f,k,400)}let H=G(E,m.data),N=u(f),j=await a(f,w,"update",{user:N,doc:E,body:m.data,diff:H,params:s});if(!j.allowed)return j.errorResponse;if(w.hooks?.beforeUpdate){let k=w.rules?.update?G(E,m.data):H;await w.hooks.beforeUpdate({user:N,doc:E,body:m.data,diff:k,params:s,c:f});}let I={...m.data},p=w.hooks?.afterUpdate?G(E,I):H,x=g(E,w)??[h],C=await w.repo.update(...x,m.data),Z=C;if(w.hooks?.afterUpdate)try{let k=await w.hooks.afterUpdate({user:N,before:E,after:C,body:I,diff:p,id:h,pathArgs:x,params:s,c:f}),v=ge(k);v&&(Z=await w.repo.update(...x,v));}catch(k){await i(w,b.logger,{hook:"afterUpdate",repoName:w.name,path:w.path,id:h,pathArgs:x,user:N,c:f},k);}return X(f,Z)}catch(S){let E=n&&S instanceof Error?S.message:"Failed to update document";return A(f,E,500)}}async function F(b){let c=b.c,f=c.req.param(),s=l(f.repoName,c);if(!s)return A(c,"Repository not found",404);if(!s.allowDelete)return A(c,"Delete not allowed for this repository",403);let w=f.id;if(!w)return A(c,"Document ID required",400);try{let h=await y(s,w);if(!h)return A(c,"Document not found",404);let S=u(c),E=await a(c,s,"delete",{user:S,doc:h,params:f});if(!E.allowed)return E.errorResponse;let m=g(h,s)??[w];if(await s.repo.delete(...m),s.hooks?.afterDelete)try{await s.hooks.afterDelete({user:S,doc:h,id:w,pathArgs:m,params:f,c});}catch(H){await i(s,b.logger,{hook:"afterDelete",repoName:s.name,path:s.path,id:w,pathArgs:m,user:S,c},H);}return X(c,{deleted:!0})}catch(h){let S=n&&h instanceof Error?h.message:"Failed to delete document";return A(c,S,500)}}function O(b){return b.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-History-Reason, X-History-Comment","Access-Control-Max-Age":"86400"})}async function P(b){let c=b.c,f=c.req.param(),s=l(f.repoName,c);if(!s)return A(c,"Repository not found",404);try{let w=b.input||{};if(!Array.isArray(w.operations))return A(c,"operations array is required",400);let h=u(c),S=s.repo.batch.create(),E=[],m=!!s.hooks,H=[],N=[],j=[];for(let p of w.operations){if(!p.type||!["create","update","delete"].includes(p.type))return A(c,"Invalid operation type",400);if(p.type==="create"){let x=await a(c,s,"create",{user:h,body:p.data,params:f});if(!x.allowed)return x.errorResponse;let C=ye(s.schema,p.data,s.createFields,!1,s.systemKeys);if(!C.success)return A(c,C.error,400);s.hooks?.beforeCreate&&await s.hooks.beforeCreate({user:h,body:C.data,params:f,c});let Z=p.data[s.documentKey]||C.data[s.documentKey]||ke(),k={...C.data};s.createdKey&&k[s.createdKey]===void 0&&(k[s.createdKey]=new Date);let v;if(s.isGroup&&s.parentKeys){let z=s.parentKeys.map(D=>String(k[D]));v=[...z,Z],S.set(...z,Z,k);}else v=[Z],S.set(Z,k);if(E.push({op:"create",id:Z}),m){let z={...k,[s.documentKey]:Z};if(s.pathKey&&typeof s.repo.documentRef=="function")try{let D=s.repo.documentRef(...v);D?.path&&(z[s.pathKey]=D.path);}catch{}H.push({id:Z,pathArgs:v,doc:z});}}else if(p.type==="update"){if(!p.id)return A(c,"id required for update",400);let x=await y(s,p.id);if(!x)return A(c,`Document ${p.id} not found`,404);let C=ye(s.schema,p.data,s.mutableFields,!0,s.systemKeys);if(!C.success)return A(c,C.error,400);if(s.validate){let B=await s.validate(C.data,"update");if(B)return A(c,B,400)}let Z=G(x,C.data),k=await a(c,s,"update",{user:h,doc:x,body:C.data,diff:Z,params:f});if(!k.allowed)return k.errorResponse;if(s.hooks?.beforeUpdate){let B=s.rules?.update?G(x,C.data):Z;await s.hooks.beforeUpdate({user:h,doc:x,body:C.data,diff:B,params:f,c});}let v={...C.data},z=m?G(x,v):Z,D=g(x,s)??[p.id];S.update(...D,C.data),E.push({op:"update",id:p.id}),m&&N.push({id:p.id,pathArgs:D,before:x,after:z.after,body:v,diff:z});}else if(p.type==="delete"){if(!s.allowDelete)return A(c,"Delete not allowed",403);if(!p.id)return A(c,"id required for delete",400);let x=await y(s,p.id);if(!x)return A(c,`Document ${p.id} not found`,404);let C=await a(c,s,"delete",{user:h,doc:x,params:f});if(!C.allowed)return C.errorResponse;let Z=g(x,s)??[p.id];S.delete(...Z),E.push({op:"delete",id:p.id}),m&&j.push({id:p.id,pathArgs:Z,doc:x});}}await S.commit();let I=H.length>0||N.length>0||j.length>0;if(s.hooks&&I)if(s.hooks.afterBatch)try{await s.hooks.afterBatch({user:h,created:H,updated:N,deleted:j,params:f,c});}catch(p){await i(s,b.logger,{hook:"afterBatch",repoName:s.name,path:s.path,user:h,c},p);}else {if(s.hooks.afterCreate)for(let p of H)try{let x=await s.hooks.afterCreate({user:h,doc:p.doc,id:p.id,pathArgs:p.pathArgs,params:f,c}),C=ge(x);C&&p.pathArgs.length>0&&await s.repo.update(...p.pathArgs,C);}catch(x){await i(s,b.logger,{hook:"afterCreate",repoName:s.name,path:s.path,id:p.id,pathArgs:p.pathArgs,user:h,c},x);}if(s.hooks.afterUpdate)for(let p of N)try{let x=await s.hooks.afterUpdate({user:h,before:p.before,after:p.after,body:p.body,diff:p.diff,id:p.id,pathArgs:p.pathArgs,params:f,c}),C=ge(x);C&&p.pathArgs.length>0&&await s.repo.update(...p.pathArgs,C);}catch(x){await i(s,b.logger,{hook:"afterUpdate",repoName:s.name,path:s.path,id:p.id,pathArgs:p.pathArgs,user:h,c},x);}if(s.hooks.afterDelete)for(let p of j)try{await s.hooks.afterDelete({user:h,doc:p.doc,id:p.id,pathArgs:p.pathArgs,params:f,c});}catch(x){await i(s,b.logger,{hook:"afterDelete",repoName:s.name,path:s.path,id:p.id,pathArgs:p.pathArgs,user:h,c},x);}}return X(c,{results:E})}catch(w){let h=n&&w instanceof Error?w.message:"Batch operation failed";return A(c,h,500)}}return {handleList:R,handleQuery:_,handleGet:M,handleCreate:q,handleUpdate:T,handleDelete:F,handleBatch:P,handleOptions:O}}function oe(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=zodToOpenapi.getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function K(e){return {$ref:`#/components/schemas/${e}`}}function $(e){return {description:e,content:{"application/json":{schema:K("ErrorResponse")}}}}function re(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function nn(e){return {description:"Paginated list of documents",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:{type:"object",properties:{items:{type:"array",items:e},nextCursor:{oneOf:[{type:"object"},{type:"null"}]},prevCursor:{oneOf:[{type:"object"},{type:"null"}]},hasNextPage:{type:"boolean"},hasPrevPage:{type:"boolean"},totalCount:{type:"integer",description:"Total count of matching documents (when requested with withTotal=true)"},totalCountIsExact:{type:"boolean",description:"Whether totalCount is exact (true) or estimated due to OR conditions (false)"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},totalCount:{type:"integer"},totalCountIsExact:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function ce(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function rn(e,t){let n=t.split("."),r=ce(e);for(let o=0;o<n.length;o++){let i=n[o];if(!i)continue;let a=r?.shape;if(!a||!a[i])return;let d=a[i];if(o===n.length-1)return d;r=ce(d);}return r}function ne(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,r=o=>{let i=zodToOpenapi.getOpenApiMetadata(e);return i&&typeof o.openapi=="function"?o.openapi(i):o};if(n==="ZodObject"||n==="object"){let o=e.shape,i={};for(let[a,d]of Object.entries(o))i[a]=ne(d);return r(zod.z.object(i).partial())}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let i=ne(o);return i===o?e:r(i.optional())}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let i=ne(o);return i===o?e:r(i.nullable())}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?r(ne(o).optional()):e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let i=o.map(d=>ne(d));return i.some((d,u)=>d!==o[u])?r(zod.z.union(i)):e}return e}function je(e,t="",n=0){if(n>5)return [];let o=ce(e)?.shape;if(!o)return [];let i=[];for(let[a,d]of Object.entries(o)){let u=t?`${t}.${a}`:a,l=ce(d);l?.shape&&typeof l.shape=="object"?(i.push({path:u,zodSchema:d}),i.push(...je(l,u,n+1))):i.push({path:u,zodSchema:d});}return i}function on(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:rn(e.schema,t)})):je(e.schema)}function st(e){if(!e)return {type:"string"};let t=oe(e);return delete t.$schema,delete t.title,t}function at(){return {type:"object",properties:{where:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3}},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string"},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string"},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function sn(e){let t=on(e),n=e.orderableFields??t.map(a=>a.path),r=t.map(a=>a.path);if(t.length===0)return at();let o=[];for(let{path:a,zodSchema:d}of t){let u=st(d),l=ce(d),y=l?._zod?.def?.type==="array"||l?._def?.typeName==="ZodArray"||l?._def?.type==="array"?st(l?._zod?.def?.element??l?._def?.type??l?._def?.element):u;o.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},u],minItems:3,maxItems:3}),o.push({type:"array",description:`List condition on '${a}' (in, not-in)`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:u}],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},y],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains-any condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:y}],minItems:3,maxItems:3});}let i={oneOf:o};return {type:"object",properties:{where:{type:"array",items:i,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:i,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:i},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string",enum:n},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string",enum:r},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:e.allowedIncludes&&e.allowedIncludes.length>0?{oneOf:[{type:"string",enum:e.allowedIncludes},{type:"object",properties:{relation:{type:"string",enum:e.allowedIncludes},select:{type:"array",items:{type:"string"}}},required:["relation"]}]}:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function an(e,t,n,r,o,i=null,a="QueryRequestBody"){let d={},u=e.name,l=`${t}/${e.name}`,g=`${l}/{${e.documentKey}}`,y={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};d[l]={post:{operationId:`create${Q(e.name)}`,summary:`Create a ${V(e.name)}`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:K(r??n)}}},responses:{201:re("Document created",K(n)),400:$("Validation error"),403:$("Forbidden"),500:$("Internal server error")}}},d[`${l}/query`]={post:{operationId:`query${Q(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:K(a)}}},responses:{200:nn(K(n)),400:$("Invalid query"),403:$("Forbidden"),424:$("Missing composite index (includes indexUrl in response)"),500:$("Internal server error")}}},d[`${l}/batch`]={post:{operationId:`batch${Q(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:K(`${n}BatchRequest`)}}},responses:{200:re("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:$("Validation error"),403:$("Forbidden"),404:$("Document not found"),500:$("Internal server error")}}};let R={};return R.get={operationId:`get${Q(V(e.name))}`,summary:`Get a single ${V(e.name)}`,tags:[u],parameters:[y],responses:{200:re("Document found",K(n)),400:$("Document ID required"),403:$("Forbidden"),404:$("Document not found"),424:$("Missing composite index (includes indexUrl in response)"),500:$("Internal server error")}},R.put={operationId:`update${Q(V(e.name))}`,summary:`Update a ${V(e.name)} (full replace)`,tags:[u],parameters:[y],requestBody:{required:true,content:{"application/json":{schema:K(o??n)}}},responses:{200:re("Document updated",K(n)),400:$("Validation error"),403:$("Forbidden"),404:$("Document not found"),500:$("Internal server error")}},R.patch={operationId:`patch${Q(V(e.name))}`,summary:`Partially update a ${V(e.name)}`,tags:[u],parameters:[y],requestBody:{required:true,content:{"application/json":{schema:K(i??o??n)}}},responses:{200:re("Document patched",K(n)),400:$("Validation error"),403:$("Forbidden"),404:$("Document not found"),500:$("Internal server error")}},e.allowDelete&&(R.delete={operationId:`delete${Q(V(e.name))}`,summary:`Delete a ${V(e.name)}`,tags:[u],parameters:[y],responses:{200:re("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:$("Document ID required"),403:$("Forbidden"),404:$("Document not found"),500:$("Internal server error")}}),d[g]=R,d}function ze(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:i,servers:a,auth:d=false}=n,u=t==="/"?"":t.replace(/\/$/,""),l={},g={},y=[];l.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string",description:"Human-readable error description"},errorType:{type:"string",enum:["index"],description:"Error category discriminator. Set to 'index' when a Firestore composite index is missing."},indexUrl:{type:"string",format:"uri",description:"Direct Firebase Console URL to create the required composite index (when errorType is 'index')."}},required:["success","error"]},l.QueryRequestBody=at();for(let[q,T]of Object.entries(e)){let F=Q(V(q)),O=`${F}Create`,P=`${F}Update`,b=`${F}Patch`,c=`${F}QueryRequestBody`;l[F]=oe(T.schema),l[c]=sn(T);let f=I=>{let p={},x=je(T.schema);for(let{path:C,zodSchema:Z}of x){let k=C.split(".")[0];T.systemKeys.includes(k)||T.systemKeys.includes(C)||I&&I.length>0&&!I.includes(C)&&!I.includes(k)||(C.includes(".")?p[C]=Z.optional():p[C]=Z);}return p},s=null,w=f(T.createFields);if(T.isGroup&&T.parentKeys&&T.parentKeys.length>0){let I=T.schema?.shape??{};for(let p of T.parentKeys)!w[p]&&I[p]&&(w[p]=I[p]);}if(Object.keys(w).length>0){let I=oe(zod.z.object(w));if(T.isGroup&&T.parentKeys&&T.parentKeys.length>0){let p=new Set(Array.isArray(I.required)?I.required:[]);for(let x of T.parentKeys)I.properties?.[x]&&p.add(x);p.size>0&&(I.required=Array.from(p));}l[O]=I,s=O;}let h=null,S=null,E=f(T.mutableFields);if(Object.keys(E).length>0){let I=zod.z.object(E);l[P]=oe(I),h=P,l[b]=oe(ne(I)),S=b;}else l[b]=oe(ne(T.schema)),S=b;let m=`${F}BatchCreateOperation`,H=`${F}BatchUpdateOperation`,N=`${F}BatchDeleteOperation`;l[m]={type:"object",title:`${F} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:K(s??F)},required:["type","data"]},l[H]={type:"object",title:`${F} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:K(S??h??F)},required:["type","id","data"]},T.allowDelete&&(l[N]={type:"object",title:`${F} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),l[`${F}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[K(m),K(H),...T.allowDelete?[K(N)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let j=an(T,u,F,s,h,S,c);Object.assign(g,j),y.push({name:q,description:`Operations on ${q} (collection: ${T.path})`});}let R={},_;return d==="basic"?(R.basicAuth={type:"http",scheme:"basic"},_=[{basicAuth:[]}]):d==="bearer"&&(R.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},_=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...i?{description:i}:{}},...a&&a.length>0?{servers:a}:{},paths:g,components:{schemas:l,...Object.keys(R).length>0?{securitySchemes:R}:{}},..._?{security:_}:{},tags:y}}function Q(e){return e.charAt(0).toUpperCase()+e.slice(1)}function V(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var se=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var de=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},ue=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function ct(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function dt(e,t){return t instanceof se?e.json({success:false,error:"Validation failed",issues:ct(t.zodError)},400):t instanceof de?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof ue?e.json({success:false,error:"Output validation failed",issues:ct(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var ut="Successful response",pt="Error response";function W(e,t=new Set){if(!e||typeof e!="object"||t.has(e))return;t.add(e);let n=e,r=n._zod?.def??n.def;if(!r)return;if(r.type==="custom"){let i=zodToOpenapi.getOpenApiMetadata(n);i?.type||zod.z.globalRegistry.add(n,{...i??{},type:"object"});return}if(r.innerType&&W(r.innerType,t),r.element&&W(r.element,t),r.valueType&&W(r.valueType,t),r.keyType&&W(r.keyType,t),r.left&&W(r.left,t),r.right&&W(r.right,t),r.in&&W(r.in,t),r.out&&W(r.out,t),typeof r.getter=="function")try{W(r.getter(),t);}catch{}if(Array.isArray(r.options))for(let i of r.options)W(i,t);if(Array.isArray(r.items))for(let i of r.items)W(i,t);let o=typeof r.shape=="function"?r.shape():r.shape;if(o&&typeof o=="object")for(let i of Object.values(o))W(i,t);}function _e(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)_e(n);return}let t=e;(Array.isArray(t.anyOf)||Array.isArray(t.oneOf))&&"type"in t&&delete t.type;for(let n of Object.values(t))_e(n);}function ln(e){return e==="get"?"query":"json"}function fn(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function yn(e){if(typeof e.safeParse=="function")return {description:pt,schema:e};let t=e;return {description:t.description??pt,schema:t.schema}}function yt(e,t,n,r){let o=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[d,u]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",d,u);for(let d of e){let u=d.method,l=d.source??ln(u),g=gn(t,d.path??"/"),y=d.status??200;d.input&&W(d.input);let R=mn(u,l,d.input),_=lt(l,d.input,"query"),M=lt(l,d.input,"param"),q=wn(u,g),T=fn(d.output,r);T&&W(T);let F={[y]:T?{description:ut,content:{"application/json":{schema:T}}}:{description:ut}};if(r?.errors)for(let[O,P]of Object.entries(r.errors)){let{description:b,schema:c}=yn(P);c&&W(c),F[O]=c?{description:b,content:{"application/json":{schema:c}}}:{description:b};}o.registerPath({method:u,path:hn(g),operationId:q,summary:d.summary,description:d.description,tags:d.tags,deprecated:d.deprecated,security:d.security,request:{..._?{query:_}:{},...M?{params:M}:{},...R?{body:R}:{}},responses:F});}let a=new zodToOpenapi.OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return _e(a),a}function mn(e,t,n){return !n||e==="get"?null:t==="json"?{content:{"application/json":{schema:n}}}:t==="form"?{content:{"application/x-www-form-urlencoded":{schema:n}}}:null}function lt(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function hn(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function gn(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function wn(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function mt(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
2
2
|
<html lang="en">
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8" />
|
|
@@ -9,5 +9,5 @@
|
|
|
9
9
|
<script id="api-reference" data-url="${n}"></script>
|
|
10
10
|
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
11
11
|
</body>
|
|
12
|
-
</html>`}function pt(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var je=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),ze=globalThis,fn=ze[je]??(ze[je]=new async_hooks.AsyncLocalStorage);function yn(e,t){if(!t.includes("."))return e[t];let n=e;for(let r of t.split(".")){if(!n||typeof n!="object")return;n=n[r];}return n}function ft(e,t){for(let n of t){let r=yn(e,n);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function yt(e,t){if(t===false)return;let n=e?.req?.header;if(typeof n!="function")return;let r=n.call(e.req,t);return typeof r=="string"&&r.length>0?r:void 0}function mt(e={}){let t=e.contextKeys??["user","docsUser"],n=e.userIdFields??["uid","id","sub"],r=e.userEmailFields??["email"],o=e.reasonHeader===void 0?"x-history-reason":e.reasonHeader,i=e.commentHeader===void 0?"x-history-comment":e.commentHeader,c=e.extras;return u=>{let d=null,p=u?.get;if(typeof p=="function")for(let O of t){let N=p.call(u,O);if(N&&typeof N=="object"){d=N;break}}let m=yt(u,o),y=yt(u,i),b=c?c(u,d):void 0;return d?{userId:ft(d,n),userEmail:ft(d,r),...m!==void 0?{reason:m}:{},...y!==void 0?{comment:y}:{},...b?{extras:b}:{}}:m===void 0&&y===void 0&&!b?null:{...m!==void 0?{reason:m}:{},...y!==void 0?{comment:y}:{},...b?{extras:b}:{}}}}mt();function mn(e){if(e)return typeof e=="function"?e:mt(e)}function gt(e){let t=mn(e);return async(n,r)=>{await fn.run({c:n,resolver:t},async()=>{await r();});}}var _e=new async_hooks.AsyncLocalStorage;function ht(){return async(e,t)=>{await _e.run({c:e},async()=>{await t();});}}var bn=Object.freeze({}),ge=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new hono.Hono,this.mountedRoutes=Sn(t.routes,t.api),this.app.use("*",gt(t.actorResolver)),t.services&&this.app.use("*",ht());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let r of n)this.app.use("*",r);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return nodeServer.getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let r=this.nodeHandler;return n?t(n,r):t(r)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=dt(this.mountedRoutes,this.options.basePath??"",this.options.openapi,Rn(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,r=this.options.verbose??false;for(let o of this.mountedRoutes){if(!o.path)throw new Error(`[HonoServer] route "${o.method.toUpperCase()} (no path)" \u2014 missing \`path\`. Run the codegen so the path is derived from the file location, or set it explicitly.`);let i=me(t,o.path),c=o.middlewares??[],u=o.source??(o.method==="get"?"query":"json"),d=vn(o,u,n,xn(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),p=o.method.toUpperCase();this.app.on(p,[i],...c,d),r&&console.log(`[HonoServer] ${o.method.toUpperCase().padEnd(6)} ${i}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",r=t.docsPath===void 0?"/docs":t.docsPath,o=me(this.options.basePath??"",n),i=r===false?null:me(this.options.basePath??"",r),c;if(pt(t.docsAuth)){let u=t.docsAuth;c=[u.middleware];let d=An(i??o);for(let p of u.routes)this.app.on(p.method,[me(d,p.name)],p.handler);}else c=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...c,u=>u.json(this.buildOpenApiSpec())),i){let u=Tn(i,o);this.app.on("GET",[i],...c,d=>d.html(lt(u,t.info.title)));}}};function wt(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function xn(e){if(e)return wt(e)?e.handler:e}function Rn(e){return wt(e)?e:void 0}function Sn(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function me(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function An(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Tn(e,t){let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean);n.pop();let o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let i=n.length-o;return [...Array(i).fill(".."),...r.slice(o)].join("/")||"./"}function vn(e,t,n,r,o,i,c){let u=e.input,d=e.output,p=e.status??200,m=o??bn;return async y=>{let b=async C=>{if(i){let S=await i.handle({error:C,c:y,route:e,services:m,logger:c});if(S)return S}return st(y,C)},O=async()=>{let C,S;try{S=await kn(y,t,e.method);}catch(f){throw new ie(f instanceof Error?f.message:String(f))}if(u){let f=u.safeParse(S);if(!f.success)throw new ne(f.error,t);C=f.data;}else C=S;let z=await e.handler({input:C,c:y,services:m,errorHandler:i,logger:c});if(n&&d&&!(z instanceof Response)){let f=d.safeParse(z);if(!f.success)throw new ae(f.error);return f.data}return z},N;if(r)try{N=await r({next:O,route:e,c:y,services:m,errorHandler:i,logger:c});}catch(C){let S=await b(C);if(S)return S;throw C}else try{N=await O();}catch(C){let S=await b(C);if(S)return S;throw C}return N instanceof Response?N:y.json(N,p)}}async function kn(e,t,n){switch(t){case "json":{if(n==="get")return e.req.query();let r=await e.req.text();if(!r)return {};try{return JSON.parse(r)}catch(o){throw new Error(`Invalid JSON body: ${o instanceof Error?o.message:String(o)}`)}}case "query":return e.req.query();case "form":return await e.req.parseBody();case "param":return e.req.param();default:return {}}}function Cr(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:i=false,httpsOptions:c}=e,u=t==="/"?"":t.replace(/\/$/,""),d={};for(let[f,s]of Object.entries(n)){if(!s.repo)throw new Error(`[createCrudServer] Repository "${f}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let g=s.schema??s.repo.schema??null;if(!g)throw new Error(`[createCrudServer] Repository "${f}" has no Zod schema.`);let a,w,h,R;if(s.fieldsConfig){let _=s.fieldsConfig;a=[],w=[],h=[],R=[];for(let[E,A]of Object.entries(_))for(let $ of A)$==="filterable"?a.push(E):$==="orderable"?w.push(E):$==="mutable"?h.push(E):$==="create"&&R.push(E);w.length===0&&(w=a),a.length===0&&(a=void 0),w&&w.length===0&&(w=void 0),h.length===0&&(h=void 0),R.length===0&&(R=void 0);}let v=(()=>{let _=s.repo._parentKeys;return _&&_.length>0?_:void 0})();if(v&&R)for(let _ of v)R.includes(_)||R.push(_);let l=s.repo._systemKeys??[s.documentKey??"docId"],T=s.repo._historyIdentityKeys??[],P=Array.from(new Set([...l,...T])),D={name:f,path:s.path,repo:s.repo,schema:g,systemKeys:P,documentKey:s.documentKey??"docId",pathKey:s.repo._pathKey??void 0,isGroup:!!s.repo._isGroup,parentKeys:v,documentPathTemplate:s.repo._documentPathTemplate??void 0,createdKey:s.repo._createdKey??void 0,pageSize:s.pageSize??25,filterableFields:a,orderableFields:w,mutableFields:h,createFields:R,allowDelete:s.allowDelete??false,allowedIncludes:s.allowedIncludes,validate:s.validate,rules:s.rules};d[f]=D;}let p=e.indexesError??e.onIndexError,m=et(d,u,i,p),y=e.openapi,b=y&&typeof y=="object"?y:{},O=null;function N(){return O||(O=Pe(d,u,{...b,auth:b.auth??false})),O}let C=[];for(let f of Object.keys(d))C.push({api:"crud",method:"post",path:`/${f}/query`,source:"json",handler:m.handleQuery}),C.push({api:"crud",method:"get",path:`/${f}/:id`,source:"query",handler:m.handleGet}),C.push({api:"crud",method:"post",path:`/${f}`,source:"json",handler:m.handleCreate}),C.push({api:"crud",method:"put",path:`/${f}/:id`,source:"json",handler:s=>m.handleUpdate(s,false)}),C.push({api:"crud",method:"patch",path:`/${f}/:id`,source:"json",handler:s=>m.handleUpdate(s,true)}),C.push({api:"crud",method:"delete",path:`/${f}/:id`,source:"query",handler:m.handleDelete}),C.push({api:"crud",method:"post",path:`/${f}/batch`,source:"json",handler:m.handleBatch});let S=new ge({...e,openapi:y!==false?{path:b.path??"/openapi.json",docsPath:b.docsPath??"/docs",info:{title:b.title??"CRUD API",version:b.version??"1.0.0"},docsAuth:b.docsAuth}:void 0,basePath:t,api:"crud",routes:C,middlewares:[async(f,s)=>{if(f.req.method==="OPTIONS")return f.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-History-Reason, X-History-Comment","Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});f.header("Access-Control-Allow-Origin","*"),f.header("Access-Control-Allow-Credentials","true"),await s();},...e.middlewares||[]]});if(y!==false&&(S.buildOpenApiSpec=N),o!==false){let{securityHeaders:f}=(At(),Pt(St)),s=o===void 0?{csp:false}:o;S.hono.use("*",async(g,a)=>{let w=f(s);await new Promise(h=>{let R=g.req.raw;w(R,{setHeader:(l,T)=>g.header(l,T),removeHeader:l=>g.res.headers.delete(l)},()=>h());}),await a();});}let z=S.nodeHandler;return z.spec=N,c&&(z.httpsOptions=c),z}exports.applyRules=We;exports.computeDeepDiff=le;exports.createBeforeRules=Kt;exports.createCrudServer=Cr;exports.createRules=Ut;exports.generateOpenAPISpec=Pe;//# sourceMappingURL=index.cjs.map
|
|
12
|
+
</html>`}function ht(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var qe=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),Ne=globalThis,xn=Ne[qe]??(Ne[qe]=new async_hooks.AsyncLocalStorage);function Rn(e,t){if(!t.includes("."))return e[t];let n=e;for(let r of t.split(".")){if(!n||typeof n!="object")return;n=n[r];}return n}function gt(e,t){for(let n of t){let r=Rn(e,n);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function wt(e,t){if(t===false)return;let n=e?.req?.header;if(typeof n!="function")return;let r=n.call(e.req,t);return typeof r=="string"&&r.length>0?r:void 0}function bt(e={}){let t=e.contextKeys??["user","docsUser"],n=e.userIdFields??["uid","id","sub"],r=e.userEmailFields??["email"],o=e.reasonHeader===void 0?"x-history-reason":e.reasonHeader,i=e.commentHeader===void 0?"x-history-comment":e.commentHeader,a=e.extras;return d=>{let u=null,l=d?.get;if(typeof l=="function")for(let _ of t){let M=l.call(d,_);if(M&&typeof M=="object"){u=M;break}}let g=wt(d,o),y=wt(d,i),R=a?a(d,u):void 0;return u?{userId:gt(u,n),userEmail:gt(u,r),...g!==void 0?{reason:g}:{},...y!==void 0?{comment:y}:{},...R?{extras:R}:{}}:g===void 0&&y===void 0&&!R?null:{...g!==void 0?{reason:g}:{},...y!==void 0?{comment:y}:{},...R?{extras:R}:{}}}}bt();function An(e){if(e)return typeof e=="function"?e:bt(e)}function xt(e){let t=An(e);return async(n,r)=>{await xn.run({c:n,resolver:t},async()=>{await r();});}}var Fe=new async_hooks.AsyncLocalStorage;function Rt(){return async(e,t)=>{await Fe.run({c:e},async()=>{await t();});}}var Cn=Object.freeze({}),be=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new hono.Hono,this.mountedRoutes=On(t.routes,t.api),this.app.use("*",xt(t.actorResolver)),t.services&&this.app.use("*",Rt());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let r of n)this.app.use("*",r);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return nodeServer.getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let r=this.nodeHandler;return n?t(n,r):t(r)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=yt(this.mountedRoutes,this.options.basePath??"",this.options.openapi,En(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,r=this.options.verbose??false;for(let o of this.mountedRoutes){if(!o.path)throw new Error(`[HonoServer] route "${o.method.toUpperCase()} (no path)" \u2014 missing \`path\`. Run the codegen so the path is derived from the file location, or set it explicitly.`);let i=we(t,o.path),a=o.middlewares??[],d=o.source??(o.method==="get"?"query":"json"),u=Dn(o,d,n,vn(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),l=o.method.toUpperCase();this.app.on(l,[i],...a,u),r&&console.log(`[HonoServer] ${o.method.toUpperCase().padEnd(6)} ${i}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",r=t.docsPath===void 0?"/docs":t.docsPath,o=we(this.options.basePath??"",n),i=r===false?null:we(this.options.basePath??"",r),a;if(ht(t.docsAuth)){let d=t.docsAuth;a=[d.middleware];let u=Pn(i??o);for(let l of d.routes)this.app.on(l.method,[we(u,l.name)],l.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...a,d=>d.json(this.buildOpenApiSpec())),i){let d=In(i,o);this.app.on("GET",[i],...a,u=>u.html(mt(d,t.info.title)));}}};function At(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function vn(e){if(e)return At(e)?e.handler:e}function En(e){return At(e)?e:void 0}function On(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function we(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function Pn(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function In(e,t){let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean);n.pop();let o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let i=n.length-o;return [...Array(i).fill(".."),...r.slice(o)].join("/")||"./"}function Dn(e,t,n,r,o,i,a){let d=e.input,u=e.output,l=e.status??200,g=o??Cn;return async y=>{let R=async q=>{if(i){let T=await i.handle({error:q,c:y,route:e,services:g,logger:a});if(T)return T}return dt(y,q)},_=async()=>{let q,T;try{T=await jn(y,t,e.method);}catch(O){throw new de(O instanceof Error?O.message:String(O))}if(d){let O=d.safeParse(T);if(!O.success)throw new se(O.error,t);q=O.data;}else q=T;let F=await e.handler({input:q,c:y,services:g,errorHandler:i,logger:a});if(n&&u&&!(F instanceof Response)){let O=u.safeParse(F);if(!O.success)throw new ue(O.error);return O.data}return F},M;if(r)try{M=await r({next:_,route:e,c:y,services:g,errorHandler:i,logger:a});}catch(q){let T=await R(q);if(T)return T;throw q}else try{M=await _();}catch(q){let T=await R(q);if(T)return T;throw q}return M instanceof Response?M:y.json(M,l)}}async function jn(e,t,n){switch(t){case "json":{if(n==="get")return e.req.query();let r=await e.req.text();if(!r)return {};try{return JSON.parse(r)}catch(o){throw new Error(`Invalid JSON body: ${o instanceof Error?o.message:String(o)}`)}}case "query":return e.req.query();case "form":return await e.req.parseBody();case "param":return e.req.param();default:return {}}}function zn(e){return e}async function Tt(e,t){if(e?.length){for(let n of e)if(typeof n=="function")await n(t);else if(n&&typeof n.mutation=="function"){if(n.operations&&!n.operations.includes(t.operation))continue;await n.mutation(t);}}}async function He(e,t,n,r,o,i=t?"update":"create"){for(let a of Object.keys(n.changes))await Tt(r[a],{body:e,doc:t,diff:n,key:a,operation:i,user:o});await Tt(r["*"],{body:e,doc:t,diff:n,key:"*",operation:i,user:o});}function _n(e){return async t=>{await He(t.body,t.doc,t.diff,e,t.user,"update");}}function qn(e){return async t=>{let n=G({},t.body);await He(t.body,null,n,e,t.user,"create");}}function Nn(e){return e}async function kt(e,t,n,r,o,i,a,d){if(!e?.length)return i;let u=i;for(let l of e){let g=null,y=false;try{if(y=!!await l.rule({diff:n,key:t,user:a,operation:d}),y){let R=await l.handler(r);R&&(u={...u,...R});}}catch(R){g=R;}o.push({key:String(t),description:l.description,isCalled:y,error:g});}return u}async function St(e,t,n,r,o="update"){let i=[],a={};for(let d of Object.keys(e.changes))a=await kt(t[d],d,e,n,i,a,r,o);return a=await kt(t["*"],"*",e,n,i,a,r,o),{results:i,changesNeeded:a,hasErrors:i.some(d=>d.error!==null)}}function Fn(e,t,n){return async r=>{let o=t(r),{results:i,changesNeeded:a}=await St(r.diff,e,o,r.user,"update");if(n?.onRuleError)for(let d of i)d.error&&await n.onRuleError(d,r);return Object.keys(a).length>0?a:void 0}}function Br(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:i=false,httpsOptions:a}=e,d=t==="/"?"":t.replace(/\/$/,""),u={};for(let[O,P]of Object.entries(n)){if(!P.repo)throw new Error(`[createCrudServer] Repository "${O}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let b=P.schema??P.repo.schema??null;if(!b)throw new Error(`[createCrudServer] Repository "${O}" has no Zod schema.`);let c,f,s,w;if(P.fieldsConfig){let N=P.fieldsConfig;c=[],f=[],s=[],w=[];for(let[j,I]of Object.entries(N))for(let p of I)p==="filterable"?c.push(j):p==="orderable"?f.push(j):p==="mutable"?s.push(j):p==="create"&&w.push(j);f.length===0&&(f=c),c.length===0&&(c=void 0),f&&f.length===0&&(f=void 0),s.length===0&&(s=void 0),w.length===0&&(w=void 0);}let h=(()=>{let N=P.repo._parentKeys;return N&&N.length>0?N:void 0})();if(h&&w)for(let N of h)w.includes(N)||w.push(N);let S=P.repo._systemKeys??[P.documentKey??"docId"],E=P.repo._historyIdentityKeys??[],m=Array.from(new Set([...S,...E])),H={name:O,path:P.path,repo:P.repo,schema:b,systemKeys:m,documentKey:P.documentKey??"docId",pathKey:P.repo._pathKey??void 0,isGroup:!!P.repo._isGroup,parentKeys:h,documentPathTemplate:P.repo._documentPathTemplate??void 0,createdKey:P.repo._createdKey??void 0,pageSize:P.pageSize??25,filterableFields:c,orderableFields:f,mutableFields:s,createFields:w,allowDelete:P.allowDelete??false,allowedIncludes:P.allowedIncludes,validate:P.validate,rules:P.rules,hooks:P.hooks};u[O]=H;}let l=e.indexesError??e.onIndexError,g=ot(u,d,i,l,e.onHookError),y=e.openapi,R=y&&typeof y=="object"?y:{},_=null;function M(){return _||(_=ze(u,d,{...R,auth:R.auth??false})),_}let q=[];for(let O of Object.keys(u))q.push({api:"crud",method:"post",path:`/${O}/query`,source:"json",handler:g.handleQuery}),q.push({api:"crud",method:"get",path:`/${O}/:id`,source:"query",handler:g.handleGet}),q.push({api:"crud",method:"post",path:`/${O}`,source:"json",handler:g.handleCreate}),q.push({api:"crud",method:"put",path:`/${O}/:id`,source:"json",handler:P=>g.handleUpdate(P,false)}),q.push({api:"crud",method:"patch",path:`/${O}/:id`,source:"json",handler:P=>g.handleUpdate(P,true)}),q.push({api:"crud",method:"delete",path:`/${O}/:id`,source:"query",handler:g.handleDelete}),q.push({api:"crud",method:"post",path:`/${O}/batch`,source:"json",handler:g.handleBatch});let T=new be({...e,openapi:y!==false?{path:R.path??"/openapi.json",docsPath:R.docsPath??"/docs",info:{title:R.title??"CRUD API",version:R.version??"1.0.0"},docsAuth:R.docsAuth}:void 0,basePath:t,api:"crud",routes:q,middlewares:[async(O,P)=>{if(O.req.method==="OPTIONS")return O.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-History-Reason, X-History-Comment","Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});O.header("Access-Control-Allow-Origin","*"),O.header("Access-Control-Allow-Credentials","true"),await P();},...e.middlewares||[]]});if(y!==false&&(T.buildOpenApiSpec=M),o!==false){let{securityHeaders:O}=(Pt(),Ft(Ot)),P=o===void 0?{csp:false}:o;T.hono.use("*",async(b,c)=>{let f=O(P);await new Promise(s=>{let w=b.req.raw;f(w,{setHeader:(S,E)=>b.header(S,E),removeHeader:S=>b.res.headers.delete(S)},()=>s());}),await c();});}let F=T.nodeHandler;return F.spec=M,a&&(F.httpsOptions=a),F}exports.applyEffects=St;exports.applyMutations=He;exports.applyRules=Xe;exports.computeDeepDiff=G;exports.createAfterUpdateEffects=Fn;exports.createBeforeCreateMutations=qn;exports.createBeforeRules=Xt;exports.createBeforeUpdateMutations=_n;exports.createCrudServer=Br;exports.createEffects=Nn;exports.createMutations=zn;exports.createRules=Qt;exports.generateOpenAPISpec=ze;//# sourceMappingURL=index.cjs.map
|
|
13
13
|
//# sourceMappingURL=index.cjs.map
|