@lpdjs/firestore-repo-service 2.6.48 → 2.6.51
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/README.md +4 -1
- package/dist/{create-servers-BjhepKI6.d.ts → create-servers-CwNxQQQ1.d.ts} +3 -3
- package/dist/{create-servers-DSLJF9cm.d.cts → create-servers-rVXsgSQE.d.cts} +3 -3
- package/dist/{index-BwN1OK3P.d.cts → index-CsuESJ5D.d.cts} +1 -1
- package/dist/{index-Df6FAq2n.d.ts → index-D0clYX8B.d.ts} +1 -1
- package/dist/index.cjs +76 -76
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -6
- package/dist/index.d.ts +16 -6
- package/dist/index.js +76 -76
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +178 -9
- package/dist/llms.txt +2 -1
- package/dist/{openapi-CC8PXZ3R.d.cts → openapi-BEBoB0y3.d.cts} +1 -1
- package/dist/{openapi-DuBKOatd.d.ts → openapi-ltqn60oy.d.ts} +1 -1
- package/dist/servers/admin/index.d.cts +2 -2
- package/dist/servers/admin/index.d.ts +2 -2
- 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 -4
- package/dist/servers/crud/index.d.ts +4 -4
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/index.cjs +60 -60
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +5 -5
- package/dist/servers/index.d.ts +5 -5
- package/dist/servers/index.js +60 -60
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/index.cjs +3 -3
- package/dist/sync/index.js +3 -3
- package/dist/{types-BEel_BJZ.d.ts → types-DG5Ys5AM.d.ts} +16 -0
- package/dist/{types-BQKFWe40.d.cts → types-DQwhnE4-.d.cts} +16 -0
- package/package.json +1 -1
package/dist/llms-full.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# @lpdjs/firestore-repo-service (v2.6.
|
|
1
|
+
# @lpdjs/firestore-repo-service (v2.6.51) — 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
|
|
|
@@ -526,17 +526,20 @@ interface QueryOptions<T> {
|
|
|
526
526
|
Cursor-based pagination — efficient for large collections.
|
|
527
527
|
|
|
528
528
|
```typescript
|
|
529
|
-
// First page
|
|
529
|
+
// First page with total count
|
|
530
530
|
const page1 = await repos.posts.query.paginate({
|
|
531
|
-
pageSize:
|
|
532
|
-
orderBy:
|
|
531
|
+
pageSize: 10,
|
|
532
|
+
orderBy: [{ field: "createdAt", direction: "desc" }],
|
|
533
|
+
withTotal: true,
|
|
533
534
|
});
|
|
534
535
|
|
|
535
|
-
// page1.data
|
|
536
|
-
// page1.hasNextPage
|
|
537
|
-
// page1.hasPrevPage
|
|
538
|
-
// page1.nextCursor
|
|
539
|
-
// page1.prevCursor
|
|
536
|
+
// page1.data → PostModel[]
|
|
537
|
+
// page1.hasNextPage → boolean
|
|
538
|
+
// page1.hasPrevPage → boolean
|
|
539
|
+
// page1.nextCursor → DocumentSnapshot | undefined
|
|
540
|
+
// page1.prevCursor → DocumentSnapshot | undefined
|
|
541
|
+
// page1.totalCount → number (e.g. 142)
|
|
542
|
+
// page1.totalCountIsExact → boolean (true for AND queries, false for OR queries)
|
|
540
543
|
|
|
541
544
|
// Next page
|
|
542
545
|
const page2 = await repos.posts.query.paginate({
|
|
@@ -553,6 +556,9 @@ const prev = await repos.posts.query.paginate({
|
|
|
553
556
|
});
|
|
554
557
|
```
|
|
555
558
|
|
|
559
|
+
**Server-side count performance (`withTotal`)**
|
|
560
|
+
When `withTotal: true` is passed, total document count is computed via Firestore's native `.count()` server-side aggregation (**1 index read per 1,000 documents**). For `orWhere` and `orWhereGroups`, counts across branches are aggregated in parallel (fast estimation without fetching document payloads).
|
|
561
|
+
|
|
556
562
|
### Paginate with filters and OR
|
|
557
563
|
|
|
558
564
|
```typescript
|
|
@@ -1153,6 +1159,169 @@ Each rule receives a typed context (`user`, plus `doc` / `body` / `query` / `par
|
|
|
1153
1159
|
|
|
1154
1160
|
---
|
|
1155
1161
|
|
|
1162
|
+
# CRUD Server
|
|
1163
|
+
|
|
1164
|
+
The CRUD REST API server is built via `createServers(repos).crud(...)` — a unified factory that exposes standard RESTful endpoints and advanced query APIs for all registered repositories.
|
|
1165
|
+
|
|
1166
|
+
**Features:**
|
|
1167
|
+
- Auto-generated REST endpoints (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`)
|
|
1168
|
+
- Advanced query endpoint (`POST /:repoName/query`) with `where`, `orWhere`, `orWhereGroups`, and `includes`
|
|
1169
|
+
- Atomic batch endpoint (`POST /:repoName/batch`)
|
|
1170
|
+
- Server-side total counting (`withTotal`) powered by Firestore `.count()` aggregation
|
|
1171
|
+
- Automatic OpenAPI 3.1 spec (`/openapi.json`) and Scalar documentation UI (`/docs`)
|
|
1172
|
+
- Zod schema validation for input payloads
|
|
1173
|
+
- Hono middleware support (Auth, logging, CORS, rate-limiting)
|
|
1174
|
+
|
|
1175
|
+
---
|
|
1176
|
+
|
|
1177
|
+
## Basic setup
|
|
1178
|
+
|
|
1179
|
+
```typescript
|
|
1180
|
+
import { onRequest } from "firebase-functions/v2/https";
|
|
1181
|
+
import { createServers } from "@lpdjs/firestore-repo-service";
|
|
1182
|
+
|
|
1183
|
+
const servers = createServers(repos, {
|
|
1184
|
+
onRequest,
|
|
1185
|
+
httpsOptions: { invoker: "public" },
|
|
1186
|
+
});
|
|
1187
|
+
|
|
1188
|
+
export const api = servers.crud({
|
|
1189
|
+
basePath: "/api",
|
|
1190
|
+
middlewares: [
|
|
1191
|
+
async (c, next) => {
|
|
1192
|
+
// Custom auth / middleware logic
|
|
1193
|
+
await next();
|
|
1194
|
+
},
|
|
1195
|
+
],
|
|
1196
|
+
repos: {
|
|
1197
|
+
users: {
|
|
1198
|
+
path: "users",
|
|
1199
|
+
filterableFields: ["email", "status", "role"],
|
|
1200
|
+
orderableFields: ["createdAt", "name"],
|
|
1201
|
+
allowDelete: true,
|
|
1202
|
+
},
|
|
1203
|
+
posts: {
|
|
1204
|
+
path: "posts",
|
|
1205
|
+
allowedIncludes: ["userId"],
|
|
1206
|
+
allowDelete: false,
|
|
1207
|
+
},
|
|
1208
|
+
},
|
|
1209
|
+
openapi: {
|
|
1210
|
+
title: "My CRUD API",
|
|
1211
|
+
version: "1.0.0",
|
|
1212
|
+
description: "RESTful API powered by Firestore Repo Service",
|
|
1213
|
+
},
|
|
1214
|
+
});
|
|
1215
|
+
```
|
|
1216
|
+
|
|
1217
|
+
---
|
|
1218
|
+
|
|
1219
|
+
## Endpoints overview
|
|
1220
|
+
|
|
1221
|
+
| Method | Endpoint | Description |
|
|
1222
|
+
|---|---|---|
|
|
1223
|
+
| `GET` | `/:repoName` | List documents (paginated, with query filters and `withTotal`) |
|
|
1224
|
+
| `GET` | `/:repoName/:id` | Get single document by ID |
|
|
1225
|
+
| `POST` | `/:repoName` | Create a new document (Zod validated) |
|
|
1226
|
+
| `PUT` | `/:repoName/:id` | Replace document |
|
|
1227
|
+
| `PATCH` | `/:repoName/:id` | Partial update document |
|
|
1228
|
+
| `DELETE` | `/:repoName/:id` | Delete document |
|
|
1229
|
+
| `POST` | `/:repoName/query` | Advanced query (AND, OR groups, includes, total count) |
|
|
1230
|
+
| `POST` | `/:repoName/batch` | Execute atomic batch write operations |
|
|
1231
|
+
| `GET` | `/openapi.json` | OpenAPI 3.1 JSON specification |
|
|
1232
|
+
| `GET` | `/docs` | Interactive Scalar API documentation |
|
|
1233
|
+
|
|
1234
|
+
---
|
|
1235
|
+
|
|
1236
|
+
## Listing documents (`GET /:repoName`)
|
|
1237
|
+
|
|
1238
|
+
Query parameters:
|
|
1239
|
+
- `pageSize`: Number of items per page (default: 25, max: 100)
|
|
1240
|
+
- `cursor`: Base64 cursor token for pagination
|
|
1241
|
+
- `direction`: Pagination direction (`next` | `prev`)
|
|
1242
|
+
- `orderBy`: Field to sort by
|
|
1243
|
+
- `orderDir`: Sort direction (`asc` | `desc`)
|
|
1244
|
+
- `select`: Comma-separated list of fields to project
|
|
1245
|
+
- `includes`: Comma-separated list of relations to populate
|
|
1246
|
+
- `withTotal`: Set to `true` to request total matching document count
|
|
1247
|
+
- Filter params: `?field=value`, `?field__gt=10`, `?field__in=a,b`, `?field__containsAny=x,y`
|
|
1248
|
+
|
|
1249
|
+
**Example:**
|
|
1250
|
+
`GET /api/users?status=active&pageSize=10&withTotal=true`
|
|
1251
|
+
|
|
1252
|
+
**Response:**
|
|
1253
|
+
```json
|
|
1254
|
+
{
|
|
1255
|
+
"success": true,
|
|
1256
|
+
"data": {
|
|
1257
|
+
"items": [ ... ],
|
|
1258
|
+
"nextCursor": "eyJ...",
|
|
1259
|
+
"prevCursor": null,
|
|
1260
|
+
"hasNextPage": true,
|
|
1261
|
+
"hasPrevPage": false,
|
|
1262
|
+
"totalCount": 142,
|
|
1263
|
+
"totalCountIsExact": true
|
|
1264
|
+
},
|
|
1265
|
+
"meta": {
|
|
1266
|
+
"pageSize": 10,
|
|
1267
|
+
"hasMore": true,
|
|
1268
|
+
"totalCount": 142,
|
|
1269
|
+
"totalCountIsExact": true
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
```
|
|
1273
|
+
|
|
1274
|
+
---
|
|
1275
|
+
|
|
1276
|
+
## Advanced query (`POST /:repoName/query`)
|
|
1277
|
+
|
|
1278
|
+
Send complex filter conditions including `where` (AND), `orWhere` (simple OR), and `orWhereGroups` (compound OR).
|
|
1279
|
+
|
|
1280
|
+
**Request Body:**
|
|
1281
|
+
```json
|
|
1282
|
+
{
|
|
1283
|
+
"where": [["status", "==", "active"]],
|
|
1284
|
+
"orWhereGroups": [
|
|
1285
|
+
[["role", "==", "admin"], ["age", ">=", 18]],
|
|
1286
|
+
[["role", "==", "moderator"]]
|
|
1287
|
+
],
|
|
1288
|
+
"orderBy": [{ "field": "createdAt", "direction": "desc" }],
|
|
1289
|
+
"pageSize": 10,
|
|
1290
|
+
"withTotal": true
|
|
1291
|
+
}
|
|
1292
|
+
```
|
|
1293
|
+
|
|
1294
|
+
**Total Count Behavior (`withTotal`):**
|
|
1295
|
+
- **Pure AND queries & split `in` clauses**: Uses server-side `.count()` aggregation. `totalCountIsExact` is `true`.
|
|
1296
|
+
- **OR queries (`orWhere`, `orWhereGroups`)**: Executes parallel server-side `.count()` queries across OR branches. Fast and lightweight (`1000 docs = 1 index read`). `totalCountIsExact` is `false` (estimated due to potential branch overlap).
|
|
1297
|
+
|
|
1298
|
+
---
|
|
1299
|
+
|
|
1300
|
+
## Configuration options (`CrudServerOptions`)
|
|
1301
|
+
|
|
1302
|
+
| Option | Type | Description |
|
|
1303
|
+
|---|---|---|
|
|
1304
|
+
| `basePath` | `string` | Base path prefix (e.g., `"/api/v1"`) |
|
|
1305
|
+
| `middlewares` | `MiddlewareHandler[]` | Custom Hono middleware array |
|
|
1306
|
+
| `repos` | `Record<string, CrudRepoConfig>` | Per-repository configuration mapping |
|
|
1307
|
+
| `openapi` | `OpenAPISpecOptions` | OpenAPI 3.1 documentation settings |
|
|
1308
|
+
| `verbose` | `boolean` | Include detailed error messages in HTTP 500 responses |
|
|
1309
|
+
|
|
1310
|
+
---
|
|
1311
|
+
|
|
1312
|
+
## Per-Repository Configuration (`CrudRepoConfig`)
|
|
1313
|
+
|
|
1314
|
+
| Option | Type | Description |
|
|
1315
|
+
|---|---|---|
|
|
1316
|
+
| `path` | `string` | Collection path |
|
|
1317
|
+
| `filterableFields` | `string[]` | List of allowed fields for filtering |
|
|
1318
|
+
| `orderableFields` | `string[]` | List of allowed fields for ordering |
|
|
1319
|
+
| `allowedIncludes` | `string[]` | List of relation keys allowed in `includes` |
|
|
1320
|
+
| `allowDelete` | `boolean` | Whether `DELETE /:id` is enabled |
|
|
1321
|
+
| `pageSize` | `number` | Default page size for list requests |
|
|
1322
|
+
|
|
1323
|
+
---
|
|
1324
|
+
|
|
1156
1325
|
# Change History
|
|
1157
1326
|
|
|
1158
1327
|
Opt-in, per-repo change-history capture using Firestore triggers, with a typed read API on the configured repository.
|
package/dist/llms.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# @lpdjs/firestore-repo-service (v2.6.
|
|
1
|
+
# @lpdjs/firestore-repo-service (v2.6.51)
|
|
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
|
|
|
@@ -11,6 +11,7 @@ Type-safe Firestore ORM + servers (admin UI, CRUD REST, Hono file-based API, Fir
|
|
|
11
11
|
- [Querying](https://frs.lpdjs.fr/guide/querying): Retrieve a single document by a foreign key.
|
|
12
12
|
- [Advanced Usage](https://frs.lpdjs.fr/guide/advanced): Creates or replaces a document with a specific ID.
|
|
13
13
|
- [Admin Server](https://frs.lpdjs.fr/guide/admin): The admin UI is built via createServers(repos).admin(...) — a unified factory that auto-binds the repository registry so each entry's repo field is inferred from its key (and so are model field paths in fieldsConfig).
|
|
14
|
+
- [CRUD Server](https://frs.lpdjs.fr/guide/crud): The CRUD REST API server is built via createServers(repos).crud(...) — a unified factory that exposes standard RESTful endpoints and advanced query APIs for all registered repositories.
|
|
14
15
|
- [Change History](https://frs.lpdjs.fr/guide/history): Opt-in, per-repo change-history capture using Firestore triggers, with a typed read API on the configured repository.
|
|
15
16
|
- [Firestore → SQL Sync](https://frs.lpdjs.fr/guide/sync): Automatically replicate Firestore collections to a SQL database (BigQuery, etc.) via Cloud Pub/Sub.
|
|
16
17
|
- [Hono API Server](https://frs.lpdjs.fr/guide/hono): A typed, file-based HTTP server built on Hono, designed
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import 'zod';
|
|
2
2
|
import 'firebase-functions/v2/https';
|
|
3
|
-
import '../../types-
|
|
3
|
+
import '../../types-DQwhnE4-.cjs';
|
|
4
4
|
export { h as Middleware, M as MiniRouter, R as RouteHandler } from '../../firebase-auth-DZ8lb2Ec.cjs';
|
|
5
|
-
export { a as AdminRepoConfig, b as AdminRepoEntry, A as AdminServerOptions, B as BasicAuthConfig, c as RepoRegistry, d as createAdminServer } from '../../index-
|
|
5
|
+
export { a as AdminRepoConfig, b as AdminRepoEntry, A as AdminServerOptions, B as BasicAuthConfig, c as RepoRegistry, d as createAdminServer } from '../../index-CsuESJ5D.cjs';
|
|
6
6
|
import '../../types-B4dMmfet.cjs';
|
|
7
7
|
import 'hono';
|
|
8
8
|
import '../../read-CTWZjxyh.cjs';
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import 'zod';
|
|
2
2
|
import 'firebase-functions/v2/https';
|
|
3
|
-
import '../../types-
|
|
3
|
+
import '../../types-DG5Ys5AM.js';
|
|
4
4
|
export { h as Middleware, M as MiniRouter, R as RouteHandler } from '../../firebase-auth-DZ8lb2Ec.js';
|
|
5
|
-
export { a as AdminRepoConfig, b as AdminRepoEntry, A as AdminServerOptions, B as BasicAuthConfig, c as RepoRegistry, d as createAdminServer } from '../../index-
|
|
5
|
+
export { a as AdminRepoConfig, b as AdminRepoEntry, A as AdminServerOptions, B as BasicAuthConfig, c as RepoRegistry, d as createAdminServer } from '../../index-D0clYX8B.js';
|
|
6
6
|
import '../../types-DyKJJ9UQ.js';
|
|
7
7
|
import 'hono';
|
|
8
8
|
import '../../read-CTWZjxyh.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var crypto=require('crypto'),zod=require('zod'),firestore=require('firebase-admin/firestore'),zodToOpenapi=require('@asteasolutions/zod-to-openapi'),hono=require('hono'),nodeServer=require('@hono/node-server'),async_hooks=require('async_hooks');var oe=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ve=Object.getOwnPropertyNames;var Xe=Object.prototype.hasOwnProperty;var Ye=(e,t)=>()=>(e&&(t=e(e=0)),t);var et=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:true});},tt=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ve(t))!Xe.call(e,i)&&i!==n&&oe(e,i,{get:()=>t[i],enumerable:!(s=Qe(t,i))||s.enumerable});return e};var nt=e=>tt(oe({},"__esModule",{value:true}),e);var Ge={};et(Ge,{DEFAULT_HTML_CSP:()=>Ze,securityHeaders:()=>Kt});function Kt(e={}){let t=e.csp===void 0?Ze:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,s=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,i=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(d,a,c)=>{typeof a?.setHeader=="function"&&(a.setHeader("X-Content-Type-Options","nosniff"),n&&a.setHeader("X-Frame-Options",n),s&&a.setHeader("Referrer-Policy",s),i&&a.setHeader("Cache-Control",i),t&&a.setHeader("Content-Security-Policy",t)),await c();}}var Ue,Ke,Ze,We=Ye(()=>{Ue="https://cdn.jsdelivr.net",Ke="https://www.gstatic.com",Ze=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Ue} ${Ke}`,`style-src 'self' 'unsafe-inline' ${Ue}`,`connect-src 'self' ${Ke} 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 be="preserve";function Se(){return be}function rt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function xe(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(rt(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 Re(e){return e}var st=new Set(["<","<=",">",">=","!="]),it=new Set(["array-contains","array-contains-any"]);function ie(e){return e==="desc"?"DESCENDING":"ASCENDING"}function at(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function ct(e,t,n,s,i){let d=[],a=new Set;for(let u of s)if(u.op==="=="||u.op==="in"||u.op==="not-in"){if(a.has(u.field))continue;a.add(u.field),d.push({fieldPath:u.field,order:"ASCENDING"});}for(let u of s)if(it.has(u.op)){if(a.has(u.field))continue;a.add(u.field),d.push({fieldPath:u.field,arrayConfig:"CONTAINS"});}for(let u of s)if(st.has(u.op)){if(a.has(u.field))continue;a.add(u.field);let m=i?.field===u.field?ie(i.dir):"ASCENDING";d.push({fieldPath:u.field,order:m});}if(i&&!a.has(i.field)&&d.push({fieldPath:i.field,order:ie(i.dir)}),d.length===1&&n)return pt(e,t,d[0]);let c=i&&d.some(u=>u.fieldPath===i.field)?ie(i.dir):"ASCENDING";return d.push({fieldPath:"__name__",order:c}),dt(e,t,n,d)}function dt(e,t,n,s,i="(default)"){let d=`projects/${e}/databases/${i}/collectionGroups/${t}/indexes/_`,a=[...de(1,d),...V(2,n?2:1)];for(let m of s)a.push(...ve(3,Ae(m)));let c=i==="(default)"?"-default-":i,u=encodeURIComponent(Oe(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes?create_composite=${u}`}function ut(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 ce(e,t){return e<<3|t}function de(e,t){let n=Array.from(new TextEncoder().encode(t));return [ce(e,2),...ae(n.length),...n]}function V(e,t){return [ce(e,0),...ae(t)]}function ve(e,t){return [ce(e,2),...ae(t.length),...t]}function Ae(e){let t=[...de(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...V(3,1)):t.push(...V(2,e.order==="DESCENDING"?2:1)),t}function Oe(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 pt(e,t,n,s="(default)"){let i=`projects/${e}/databases/${s}/collectionGroups/${t}/fields/${n.fieldPath}`,d=[...de(1,i),...V(2,2),...ve(3,Ae(n))],a=s==="(default)"?"-default-":s,c=encodeURIComponent(Oe(d));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${c}`}function lt(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 i of n)if(typeof i=="string"&&i.length>0)return i;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function ft(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function ke(e,t){let n=e??{},s=ft(e),i;if(s&&(i=n.message?ut(n.message):void 0,!i)){let d=lt(t.ref);if(d){let a=at(t.path);i=ct(d,a,t.isGroup,t.filters,t.sort);}}return {type:s?"index":"error",message:s?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:i}}function le(e,t,n=200){let s=Re(t);return e.json(s,n)}function L(e,t,n,s=200){return le(e,{success:true,data:t,meta:n},s)}function b(e,t,n=400){return le(e,{success:false,error:t},n)}function ue(e,t,n,s,i){let d=ke(t,n),a=d.type==="index",c=a?424:500,m={success:false,error:a?d.message:i&&t instanceof Error?t.message:s};return a&&(m.errorType="index",d.indexUrl&&(m.indexUrl=d.indexUrl)),le(e,m,c)}var pe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Te(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let s=t[n];s>=pe.length*4||(e+=pe.charAt(s%pe.length));}}return e}function U(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(s=>xe(s)??s,e);if(n==="ZodObject"||n==="object"){let s=e.shape,i={};for(let[d,a]of Object.entries(s))i[d]=U(a);return zod.z.object(i)}if(n==="ZodArray"||n==="array"){let s=t.element??t.type;if(s)return zod.z.array(U(s))}if(n==="ZodOptional"||n==="optional"){let s=t.innerType;if(s)return U(s).optional()}if(n==="ZodNullable"||n==="nullable"){let s=t.innerType;if(s)return U(s).nullable()}if(n==="ZodDefault"||n==="default"){let s=t.innerType,i=t.defaultValue;if(s){let d=U(s);return typeof i=="function"?d.default(i()):d.default(i)}}return e}function mt(e,t,n=[]){let s=e.shape,i={},d=t&&t.length>0?t:Object.keys(s);for(let a of d){if(n.includes(a))continue;let c=a.split(".")[0];c&&s[c]&&(i[c]=s[c]);}return zod.z.object(i)}function X(e,t,n,s=false,i=[]){try{let d=mt(e,n,i),a=s?d.partial():d;return {success:!0,data:(Se()==="normalize"?U(a):a).parse(t)}}catch(d){return d instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${d.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function Y(e,t,n){let s=e?.shape?.[t];if(!s||typeof s.safeParse!="function")return {success:true,data:n};let i=s.safeParse(n);if(i.success)return {success:true,data:i.data};if(Array.isArray(n)){let a=[];for(let c of n){let u=s.safeParse(c);if(u.success)a.push(u.data);else return {success:false,error:u.error.issues.map(v=>v.message).join(", ")}}return {success:true,data:a}}return {success:false,error:i.error.issues.map(a=>a.message).join(", ")}}function ht(e,t){let n=[],s=t?new Set(t):null,i={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[d,a]of Object.entries(e)){if(a===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(d))continue;let c=Array.isArray(a)?a[0]:a;if(c===void 0||c==="")continue;let u=d.match(/^(\w+)__(\w+)$/),m,v="==";if(u&&u[1]&&u[2]){m=u[1];let I=u[2];if(i[I])v=i[I];else continue}else if(!u)m=d;else continue;if(s&&!s.has(m))continue;let R=c;v==="in"||v==="not-in"||v==="array-contains-any"?R=c.split(",").map(I=>Ee(I.trim())):R=Ee(c),n.push({field:m,op:v,value:R});}return n}function Ee(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 ee(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Ce(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 s=typeof n.docPath=="string"?n.docPath:void 0,i=typeof n.docId=="string"?n.docId:void 0;try{let d=e.repo.ref,a=d?.firestore;if(s&&a&&typeof a.doc=="function"){let c=await a.doc(s).get();if(c.exists)return c}if(i&&i.includes("/")&&a&&typeof a.doc=="function"){let c=await a.doc(i).get();if(c.exists)return c}if(i&&typeof d.doc=="function"){let c=await d.doc(i).get();if(c.exists)return c}return}catch{return}}function Pe(e,t,n){async function s(p,r,y,o){if(!r.rules)return true;let f=r.rules?.[y];if(!f)return b(p,`Operation "${y}" is not allowed for this repository`,403),false;try{return await f(o)?!0:b(p,"Forbidden",403)}catch(h){let g=n&&h instanceof Error?h.message:"Forbidden";return b(p,g,403)}}async function i(p,r,y,o){if(!p.rules)return o;let f=p.rules?.filter;if(!f)return o;let h=[];for(let g of o)try{await f({user:r,doc:g,params:y})&&h.push(g);}catch{}return h}function d(p){return p.get("user")??p.get("docsUser")??null}function a(p,r){if(!p){let y=r.req.path.split("/");for(let o of y)if(e[o]){p=o;break}}return !p||!e[p]?null:e[p]??null}function c(p,r){if(!r)return;let y=p[r];if(typeof y!="string"||!y)return;let o=y.split("/").filter(Boolean),f=[];for(let h=1;h<o.length;h+=2)f.push(o[h]);return f.length>0?f:void 0}async function u(p,r){let y=`by${p.documentKey.charAt(0).toUpperCase()}${p.documentKey.slice(1)}`,o=p.repo.get[y];if(typeof o=="function")try{let h=await o(r);if(h)return h}catch{}return (await p.repo.query.by({where:[[p.documentKey,"==",r]],limit:1}))[0]??null}async function m(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);let f=d(r);if(!await s(r,o,"list",{user:f,query:r.req.query(),params:y}))return;let h=[],g;try{let l=r.req.query(),w=Math.min(Number(l.pageSize)||o.pageSize,100),S=l.cursor,O=l.direction?.toLowerCase()==="prev"?"prev":"next",k=l.orderBy,j=l.orderDir?.toLowerCase()==="desc"?"desc":"asc",B=l.select,T=B?B.split(",").map(z=>z.trim()):void 0,x;o.allowedIncludes&&l.includes&&(x=(typeof l.includes=="string"?l.includes.split(",").map(M=>M.trim()):Array.isArray(l.includes)?l.includes:[]).filter(M=>typeof M=="string"&&o.allowedIncludes.includes(M)),x?.length===0&&(x=void 0));let E=ht(l,o.filterableFields);h=E.map(z=>({field:z.field,op:z.op,value:String(z.value??"")})),k&&(g={field:k,dir:j});let P={pageSize:w,direction:O};if(S)try{let z=typeof S=="string"?JSON.parse(S):S;P.cursor=await Ce(o,z);}catch{}if(k){if(o.orderableFields&&!o.orderableFields.includes(k))return b(r,`Field not orderable: ${k}`,400);P.orderBy=[{field:k,direction:j}];}if(E.length>0){P.where=[];for(let z of E){let M=Y(o.schema,z.field,z.value);if(!M.success)return b(r,`Invalid filter value for '${z.field}': ${M.error}`,400);P.where.push([z.field,z.op,M.data]);}}T&&(P.select=T),x&&(P.include=x);let F=await o.repo.query.paginate(P),Je={items:await i(o,d(r),y,F.data),hasNextPage:F.hasNextPage,hasPrevPage:F.hasPrevPage,nextCursor:ee(F.nextCursor),prevCursor:ee(F.prevCursor)};return L(r,Je,{pageSize:w,hasMore:F.hasNextPage})}catch(l){ue(r,l,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:h,sort:g},"Failed to fetch documents",n);}}async function v(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);let f=d(r);if(!await s(r,o,"list",{user:f,query:p.input||{},params:y}))return;let h=[],g;try{let l=p.input||{},w=Math.min(l.pageSize||o.pageSize,100),S=l.direction==="prev"?"prev":"next";l.where&&(h=l.where.map(T=>({field:String(T[0]),op:T[1],value:String(T[2]??"")}))),l.orderBy&&l.orderBy[0]&&(g={field:l.orderBy[0].field,dir:l.orderBy[0].direction==="desc"?"desc":"asc"});let O={pageSize:w,direction:S};if(l.cursor)try{let T=typeof l.cursor=="string"?JSON.parse(l.cursor):l.cursor;O.cursor=await Ce(o,T);}catch{}if(o.allowedIncludes&&l.includes&&l.includes.length>0){let T=l.includes.filter(x=>typeof x=="string"?o.allowedIncludes.includes(x):typeof x=="object"&&x!==null&&"relation"in x&&typeof x.relation=="string"?o.allowedIncludes.includes(x.relation):!1);T.length>0&&(O.include=T);}if(l.where&&l.where.length>0){if(o.filterableFields){let x=new Set(o.filterableFields),E=l.where.filter(P=>!x.has(P[0]));if(E.length>0){b(r,`Fields not filterable: ${E.map(P=>P[0]).join(", ")}`,400);return}}let T=[];for(let x of l.where){let E=Y(o.schema,x[0],x[2]);if(!E.success){b(r,`Invalid filter value for '${x[0]}': ${E.error}`,400);return}T.push([x[0],x[1],E.data]);}O.where=T;}if(l.orWhere&&l.orWhere.length>0){if(o.filterableFields){let x=new Set(o.filterableFields),E=l.orWhere.filter(P=>!x.has(P[0]));if(E.length>0){b(r,`Fields not filterable: ${E.map(P=>P[0]).join(", ")}`,400);return}}let T=[];for(let x of l.orWhere){let E=Y(o.schema,x[0],x[2]);if(!E.success){b(r,`Invalid filter value for '${x[0]}': ${E.error}`,400);return}T.push([x[0],x[1],E.data]);}O.orWhere=T;}if(l.orWhereGroups&&l.orWhereGroups.length>0){if(o.filterableFields){let x=new Set(o.filterableFields);for(let E of l.orWhereGroups){let P=E.filter(F=>!x.has(F[0]));if(P.length>0){b(r,`Fields not filterable: ${P.map(F=>F[0]).join(", ")}`,400);return}}}let T=[];for(let x of l.orWhereGroups){let E=[];for(let P of x){let F=Y(o.schema,P[0],P[2]);if(!F.success){b(r,`Invalid filter value for '${P[0]}': ${F.error}`,400);return}E.push([P[0],P[1],F.data]);}T.push(E);}O.orWhereGroups=T;}if(l.orderBy&&l.orderBy.length>0){if(o.orderableFields){let T=new Set(o.orderableFields),x=l.orderBy.filter(E=>!T.has(E.field));if(x.length>0){b(r,`Fields not orderable: ${x.map(E=>E.field).join(", ")}`,400);return}}O.orderBy=l.orderBy;}l.select&&l.select.length>0&&(O.select=l.select);let k=await o.repo.query.paginate(O),B={items:await i(o,d(r),y,k.data),hasNextPage:k.hasNextPage,hasPrevPage:k.hasPrevPage,nextCursor:ee(k.nextCursor),prevCursor:ee(k.prevCursor)};return L(r,B,{pageSize:w,hasMore:k.hasNextPage})}catch(l){ue(r,l,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:h,sort:g},"Failed to query documents",n);}}async function R(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);let f=y.id;if(!f)return b(r,"Document ID required",400);try{let h=await u(o,f);if(!h)return b(r,"Document not found",404);let g=d(r);if(!await s(r,o,"get",{user:g,doc:h,params:y}))return;if(o.rules?.filter)try{if(!await o.rules.filter({user:g,doc:h,params:y}))return b(r,"Document not found",404)}catch{return b(r,"Document not found",404)}return L(r,h)}catch(h){ue(r,h,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:[{field:o.documentKey,op:"==",value:f}]},"Failed to fetch document",n);}}async function I(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);try{let f=p.input||{},h=d(r);if(!await s(r,o,"create",{user:h,body:f,params:y}))return;let g=X(o.schema,f,o.createFields,!1,o.systemKeys);if(!g.success)return b(r,g.error,400);if(o.validate){let w=await o.validate(g.data,"create");if(w)return b(r,w,400)}let l;if(o.isGroup&&o.parentKeys&&o.parentKeys.length>0){let w={...g.data};o.createdKey&&(w[o.createdKey]=new Date);let S=o.parentKeys.filter(j=>!w[j]);if(S.length>0){b(r,`Missing parent key(s) for subcollection create: ${S.join(", ")}`,400);return}let O=o.parentKeys.map(j=>w[j]),k=w[o.documentKey]||Te();l=await o.repo.set(...O,k,w);}else l=await o.repo.create(g.data);return L(r,l,void 0,201)}catch(f){let h=n&&f instanceof Error?f.message:"Failed to create document";return b(r,h,500)}}async function $(p,r){let y=p.c,o=y.req.param(),f=a(o.repoName,y);if(!f)return b(y,"Repository not found",404);let h=o.id;if(!h)return b(y,"Document ID required",400);try{let g=p.input||{},l=await u(f,h);if(!l)return b(y,"Document not found",404);let w=d(y);if(!await s(y,f,"update",{user:w,doc:l,body:g,params:o}))return;let S=X(f.schema,g,f.mutableFields,r,f.systemKeys);if(!S.success)return b(y,S.error,400);if(f.validate){let j=await f.validate(S.data,"update");if(j)return b(y,j,400)}let O=c(l,f.pathKey)??[h],k=await f.repo.update(...O,S.data);return L(y,k)}catch(g){let l=n&&g instanceof Error?g.message:"Failed to update document";return b(y,l,500)}}async function D(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);if(!o.allowDelete)return b(r,"Delete not allowed for this repository",403);let f=y.id;if(!f)return b(r,"Document ID required",400);try{let h=await u(o,f);if(!h)return b(r,"Document not found",404);let g=d(r);if(!await s(r,o,"delete",{user:g,doc:h,params:y}))return;let l=c(h,o.pathKey)??[f];return await o.repo.delete(...l),L(r,{deleted:!0})}catch(h){let g=n&&h instanceof Error?h.message:"Failed to delete document";return b(r,g,500)}}function C(p){return p.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400"})}async function A(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);try{let f=p.input||{};if(!Array.isArray(f.operations))return b(r,"operations array is required",400);let h=d(r),g=o.repo.batch.create(),l=[];for(let w of f.operations){if(!w.type||!["create","update","delete"].includes(w.type))return b(r,"Invalid operation type",400);if(w.type==="create"){if(!await s(r,o,"create",{user:h,body:w.data,params:y}))return;let S=X(o.schema,w.data,o.createFields,!1,o.systemKeys);if(!S.success)return b(r,S.error,400);let O=w.data[o.documentKey]||Te(),k={...S.data};if(o.createdKey&&(k[o.createdKey]=new Date),o.isGroup&&o.parentKeys){let j=o.parentKeys.map(B=>k[B]);g.set(...j,O,k);}else g.set(O,k);l.push({op:"create",id:O});}else if(w.type==="update"){if(!w.id)return b(r,"id required for update",400);let S=await u(o,w.id);if(!S)return b(r,`Document ${w.id} not found`,404);if(!await s(r,o,"update",{user:h,doc:S,body:w.data,params:y}))return;let O=X(o.schema,w.data,o.mutableFields,!0,o.systemKeys);if(!O.success)return b(r,O.error,400);let k=c(S,o.pathKey)??[w.id];g.update(...k,O.data),l.push({op:"update",id:w.id});}else if(w.type==="delete"){if(!o.allowDelete)return b(r,"Delete not allowed",403);if(!w.id)return b(r,"id required for delete",400);let S=await u(o,w.id);if(!S)return b(r,`Document ${w.id} not found`,404);if(!await s(r,o,"delete",{user:h,doc:S,params:y}))return;let O=c(S,o.pathKey)??[w.id];g.delete(...O),l.push({op:"delete",id:w.id});}}return await g.commit(),L(r,{results:l})}catch(f){let h=n&&f instanceof Error?f.message:"Batch operation failed";return b(r,h,500)}}return {handleList:m,handleQuery:v,handleGet:R,handleCreate:I,handleUpdate:$,handleDelete:D,handleBatch:A,handleOptions:C}}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 s=t.zodSchema?._zod?.def;s&&(s.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):s.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 _(e){return {$ref:`#/components/schemas/${e}`}}function q(e){return {description:e,content:{"application/json":{schema:_("ErrorResponse")}}}}function K(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Ie(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"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function W(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 wt(e,t){let n=t.split("."),s=W(e);for(let i=0;i<n.length;i++){let d=n[i];if(!d)continue;let a=s?.shape;if(!a||!a[d])return;let c=a[d];if(i===n.length-1)return c;s=W(c);}return s}function De(e,t="",n=0){if(n>5)return [];let i=W(e)?.shape;if(!i)return [];let d=[];for(let[a,c]of Object.entries(i)){let u=t?`${t}.${a}`:a,m=W(c);m?.shape&&typeof m.shape=="object"?(d.push({path:u,zodSchema:c}),d.push(...De(m,u,n+1))):d.push({path:u,zodSchema:c});}return d}function me(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:wt(e.schema,t)})):De(e.schema)}function ye(e){if(!e)return {type:"string"};let t=te(e);return delete t.$schema,delete t.title,t}function bt(e){let t=me(e),n=e.orderableFields??t.map(s=>s.path);return [{name:"pageSize",in:"query",schema:{type:"integer",default:e.pageSize,maximum:100},description:"Number of items per page"},{name:"cursor",in:"query",schema:{type:"string"},description:"Base64 pagination cursor"},{name:"orderBy",in:"query",schema:{type:"string",...n.length>0?{enum:n}:{}},description:"Field name to order by"},{name:"orderDir",in:"query",schema:{type:"string",enum:["asc","desc"]},description:"Order direction"},{name:"select",in:"query",schema:{type:"string"},description:`Comma-separated list of fields to return${t.length>0?` (${t.map(s=>s.path).join(", ")})`:""}`}]}function St(e){let t=me(e),n=["eq","ne","lt","lte","gt","gte","in","nin","contains","containsAny"],s={eq:"equals. Use 'null' or '__null__' to match null values",ne:"not equals. Use 'null' or '__null__' to match non-null values",lt:"less than",lte:"less than or equal",gt:"greater than",gte:"greater than or equal",in:"in list (comma-separated values). Supports 'null' and '__null__' (e.g. val1,val2,__null__)",nin:"not in list (comma-separated values). Supports 'null' and '__null__'",contains:"array-contains",containsAny:"array-contains-any (comma-separated values). Supports 'null' and '__null__'"},i=[];for(let{path:d,zodSchema:a}of t){let c=ye(a);i.push({name:d,in:"query",schema:c,description:`Filter by ${d} (equality). Use 'null' or '__null__' for null values`});for(let u of n){let m=s[u]?` (${s[u]})`:"",v=u==="in"||u==="nin"||u==="containsAny";i.push({name:`${d}__${u}`,in:"query",schema:v?{type:"string",description:"Comma-separated list of values"}:c,description:`Filter ${d} with operator ${u}${m}`});}}return i}function je(){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",maximum:100,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)"}}}}function xt(e){let t=me(e),n=e.orderableFields??t.map(a=>a.path),s=t.map(a=>a.path);if(t.length===0)return je();let i=[];for(let{path:a,zodSchema:c}of t){let u=ye(c),m=W(c),R=m?._zod?.def?.type==="array"||m?._def?.typeName==="ZodArray"||m?._def?.type==="array"?ye(m?._zod?.def?.element??m?._def?.type??m?._def?.element):u;i.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}),i.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}),i.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},R],minItems:3,maxItems:3}),i.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:R}],minItems:3,maxItems:3});}let d={oneOf:i};return {type:"object",properties:{where:{type:"array",items:d,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:d,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:d},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:s},description:"Fields to select (projection)"},pageSize:{type:"integer",maximum:100,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)"}}}}function Rt(e,t,n,s,i,d="QueryRequestBody"){let a={},c=e.name,u=`${t}/${e.name}`,m=`${u}/{${e.documentKey}}`,v={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[u]={get:{operationId:`list${N(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[c],parameters:[...bt(e),...St(e)],responses:{200:Ie(_(n)),500:q("Internal server error")}},post:{operationId:`create${N(e.name)}`,summary:`Create a ${H(e.name)}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(s??n)}}},responses:{201:K("Document created",_(n)),400:q("Validation error"),500:q("Internal server error")}}},a[`${u}/query`]={post:{operationId:`query${N(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(d)}}},responses:{200:Ie(_(n)),400:q("Invalid query"),500:q("Internal server error")}}},a[`${u}/batch`]={post:{operationId:`batch${N(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(`${n}BatchRequest`)}}},responses:{200:K("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:q("Validation error"),403:q("Forbidden"),404:q("Document not found"),500:q("Internal server error")}}};let R={};return R.get={operationId:`get${N(H(e.name))}`,summary:`Get a single ${H(e.name)}`,tags:[c],parameters:[v],responses:{200:K("Document found",_(n)),404:q("Document not found"),500:q("Internal server error")}},R.put={operationId:`update${N(H(e.name))}`,summary:`Update a ${H(e.name)} (full replace)`,tags:[c],parameters:[v],requestBody:{required:true,content:{"application/json":{schema:_(i??n)}}},responses:{200:K("Document updated",_(n)),400:q("Validation error"),404:q("Document not found"),500:q("Internal server error")}},R.patch={operationId:`patch${N(H(e.name))}`,summary:`Partially update a ${H(e.name)}`,tags:[c],parameters:[v],requestBody:{required:true,content:{"application/json":{schema:{allOf:[_(i??n)],description:"All fields are optional for partial updates"}}}},responses:{200:K("Document patched",_(n)),400:q("Validation error"),404:q("Document not found"),500:q("Internal server error")}},e.allowDelete&&(R.delete={operationId:`delete${N(H(e.name))}`,summary:`Delete a ${H(e.name)}`,tags:[c],parameters:[v],responses:{200:K("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:q("Document not found"),500:q("Internal server error")}}),a[m]=R,a}function he(e,t,n={}){let{title:s="CRUD API",version:i="1.0.0",description:d,servers:a,auth:c=false}=n,u=t==="/"?"":t.replace(/\/$/,""),m={},v={},R=[];m.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},m.QueryRequestBody=je();for(let[C,A]of Object.entries(e)){let p=N(H(C)),r=`${p}Create`,y=`${p}Update`,o=`${p}QueryRequestBody`;m[p]=te(A.schema),m[o]=xt(A);let f=O=>{let k=O&&O.length>0?O:Object.keys(A.schema.shape),j={};for(let B of k){let T=B.split(".")[0];T&&A.schema.shape[T]&&!A.systemKeys.includes(T)&&(j[T]=A.schema.shape[T]);}return j},h=null,g=f(A.createFields);Object.keys(g).length>0&&(m[r]=te(zod.z.object(g)),h=r);let l=null,w=f(A.mutableFields);Object.keys(w).length>0&&(m[y]=te(zod.z.object(w)),l=y),m[`${p}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:_(h??p)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[_(l??p)],description:"Partial updates allowed"}},required:["type","id","data"]},...A.allowDelete?[{type:"object",properties:{type:{type:"string",enum:["delete"]},id:{type:"string"}},required:["type","id"]}]:[]]}}},required:["operations"]};let S=Rt(A,u,p,h,l,o);Object.assign(v,S),R.push({name:C,description:`Operations on ${C} (collection: ${A.path})`});}let I={},$;return c==="basic"?(I.basicAuth={type:"http",scheme:"basic"},$=[{basicAuth:[]}]):c==="bearer"&&(I.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},$=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:s,version:i,...d?{description:d}:{}},...a&&a.length>0?{servers:a}:{},paths:v,components:{schemas:m,...Object.keys(I).length>0?{securitySchemes:I}:{}},...$?{security:$}:{},tags:R}}function N(e){return e.charAt(0).toUpperCase()+e.slice(1)}function H(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 Z=class extends Error{constructor(n,s){super("Request validation failed");this.zodError=n;this.source=s;this.statusCode=400;this.name="ValidationError";}};var J=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},Q=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function qe(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function $e(e,t){return t instanceof Z?e.json({success:false,error:"Validation failed",issues:qe(t.zodError)},400):t instanceof J?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof Q?e.json({success:false,error:"Output validation failed",issues:qe(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var Fe="Successful response",ze="Error response";function Tt(e){return e==="get"?"query":"json"}function Et(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function Ct(e){if(typeof e.safeParse=="function")return {description:ze,schema:e};let t=e;return {description:t.description??ze,schema:t.schema}}function He(e,t,n,s){let i=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[c,u]of Object.entries(n.securitySchemes))i.registerComponent("securitySchemes",c,u);for(let c of e){let u=c.method,m=c.source??Tt(u),v=Dt(t,c.path??"/"),R=c.status??200,I=Pt(u,m,c.input),$=_e(m,c.input,"query"),D=_e(m,c.input,"param"),C=jt(u,v),A=Et(c.output,s),p={[R]:A?{description:Fe,content:{"application/json":{schema:A}}}:{description:Fe}};if(s?.errors)for(let[r,y]of Object.entries(s.errors)){let{description:o,schema:f}=Ct(y);p[r]=f?{description:o,content:{"application/json":{schema:f}}}:{description:o};}i.registerPath({method:u,path:It(v),operationId:C,summary:c.summary,description:c.description,tags:c.tags,deprecated:c.deprecated,security:c.security,request:{...$?{query:$}:{},...D?{params:D}:{},...I?{body:I}:{}},responses:p});}return new zodToOpenapi.OpenApiGeneratorV31(i.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function Pt(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 _e(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function It(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Dt(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`,i=`${n}${s}`;return i===""?"/":i}function jt(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Ne(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
1
|
+
'use strict';var crypto=require('crypto'),zod=require('zod'),firestore=require('firebase-admin/firestore'),zodToOpenapi=require('@asteasolutions/zod-to-openapi'),hono=require('hono'),nodeServer=require('@hono/node-server'),async_hooks=require('async_hooks');var ie=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames;var nt=Object.prototype.hasOwnProperty;var rt=(e,t)=>()=>(e&&(t=e(e=0)),t);var ot=(e,t)=>{for(var n in t)ie(e,n,{get:t[n],enumerable:true});},st=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of tt(t))!nt.call(e,o)&&o!==n&&ie(e,o,{get:()=>t[o],enumerable:!(s=et(t,o))||s.enumerable});return e};var it=e=>st(ie({},"__esModule",{value:true}),e);var Ve={};ot(Ve,{DEFAULT_HTML_CSP:()=>Qe,securityHeaders:()=>Qt});function Qt(e={}){let t=e.csp===void 0?Qe:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,s=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,o=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(d,a,c)=>{typeof a?.setHeader=="function"&&(a.setHeader("X-Content-Type-Options","nosniff"),n&&a.setHeader("X-Frame-Options",n),s&&a.setHeader("Referrer-Policy",s),o&&a.setHeader("Cache-Control",o),t&&a.setHeader("Content-Security-Policy",t)),await c();}}var We,Je,Qe,Xe=rt(()=>{We="https://cdn.jsdelivr.net",Je="https://www.gstatic.com",Qe=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${We} ${Je}`,`style-src 'self' 'unsafe-inline' ${We}`,`connect-src 'self' ${Je} 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 Ae="preserve";function ce(){return Ae}function at(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Te(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(at(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 Oe(e){return e}var dt=new Set(["<","<=",">",">=","!="]),ut=new Set(["array-contains","array-contains-any"]);function de(e){return e==="desc"?"DESCENDING":"ASCENDING"}function pt(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function lt(e,t,n,s,o){let d=[],a=new Set;for(let u of s)if(u.op==="=="||u.op==="in"||u.op==="not-in"){if(a.has(u.field))continue;a.add(u.field),d.push({fieldPath:u.field,order:"ASCENDING"});}for(let u of s)if(ut.has(u.op)){if(a.has(u.field))continue;a.add(u.field),d.push({fieldPath:u.field,arrayConfig:"CONTAINS"});}for(let u of s)if(dt.has(u.op)){if(a.has(u.field))continue;a.add(u.field);let f=o?.field===u.field?de(o.dir):"ASCENDING";d.push({fieldPath:u.field,order:f});}if(o&&!a.has(o.field)&&d.push({fieldPath:o.field,order:de(o.dir)}),d.length===1&&n)return mt(e,t,d[0]);let c=o&&d.some(u=>u.fieldPath===o.field)?de(o.dir):"ASCENDING";return d.push({fieldPath:"__name__",order:c}),ft(e,t,n,d)}function ft(e,t,n,s,o="(default)"){let d=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...le(1,d),...Y(2,n?2:1)];for(let f of s)a.push(...ke(3,Ce(f)));let c=o==="(default)"?"-default-":o,u=encodeURIComponent(Ee(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes?create_composite=${u}`}function yt(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function ue(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function pe(e,t){return e<<3|t}function le(e,t){let n=Array.from(new TextEncoder().encode(t));return [pe(e,2),...ue(n.length),...n]}function Y(e,t){return [pe(e,0),...ue(t)]}function ke(e,t){return [pe(e,2),...ue(t.length),...t]}function Ce(e){let t=[...le(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...Y(3,1)):t.push(...Y(2,e.order==="DESCENDING"?2:1)),t}function Ee(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 mt(e,t,n,s="(default)"){let o=`projects/${e}/databases/${s}/collectionGroups/${t}/fields/${n.fieldPath}`,d=[...le(1,o),...Y(2,2),...ke(3,Ce(n))],a=s==="(default)"?"-default-":s,c=encodeURIComponent(Ee(d));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${c}`}function ht(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 gt(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Ie(e,t){let n=e??{},s=gt(e),o;if(s&&(o=n.message?yt(n.message):void 0,!o)){let d=ht(t.ref);if(d){let a=pt(t.path);o=lt(d,a,t.isGroup,t.filters,t.sort);}}return {type:s?"index":"error",message:s?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}function he(e,t,n=200){let s=Oe(t);return e.json(s,n)}function Z(e,t,n,s=200){return he(e,{success:true,data:t,meta:n},s)}function b(e,t,n=400){return he(e,{success:false,error:t},n)}function fe(e,t,n,s,o){let d=Ie(t,n),a=d.type==="index",c=a?424:500,f={success:false,error:a?d.message:o&&t instanceof Error?t.message:s};return a&&(f.errorType="index",d.indexUrl&&(f.indexUrl=d.indexUrl)),he(e,f,c)}var ye="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Pe(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let s=t[n];s>=ye.length*4||(e+=ye.charAt(s%ye.length));}}return e}function K(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(s=>Te(s)??s,e);if(n==="ZodObject"||n==="object"){let s=e.shape,o={};for(let[d,a]of Object.entries(s))o[d]=K(a);return zod.z.object(o)}if(n==="ZodArray"||n==="array"){let s=t.element??t.type;if(s)return zod.z.array(K(s))}if(n==="ZodOptional"||n==="optional"){let s=t.innerType;if(s)return K(s).optional()}if(n==="ZodNullable"||n==="nullable"){let s=t.innerType;if(s)return K(s).nullable()}if(n==="ZodDefault"||n==="default"){let s=t.innerType,o=t.defaultValue;if(s){let d=K(s);return typeof o=="function"?d.default(o()):d.default(o)}}return e}function bt(e,t,n=[]){let s=e.shape,o={},d=t&&t.length>0?t:Object.keys(s);for(let a of d){if(n.includes(a))continue;let c=a.split(".")[0];c&&s[c]&&(o[c]=s[c]);}return zod.z.object(o)}function me(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 St(e,t){let n=t.split("."),s=me(e);for(let o=0;o<n.length;o++){let d=n[o];if(!d)continue;let a=s?.shape;if(!a||!a[d])return;let c=a[d];if(o===n.length-1)return c;s=me(c);}return s}function qe(e){let t=me(e),n=t?._zod?.def??t?._def,s=n?.typeName??n?.type;if(s==="ZodObject"||s==="object"){let o=t.shape,d={};for(let[a,c]of Object.entries(o))d[a]=qe(c);return zod.z.object(d).partial()}return e}function ee(e,t,n,s=false,o=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let d=t,a={},c={};for(let[u,f]of Object.entries(d))if(u.includes(".")){let R=u.split(".")[0];if(o.includes(u)||o.includes(R))continue;if(n&&n.length>0&&!n.includes(u)&&!n.includes(R))return {success:!1,error:`Field '${u}' is not allowed for this operation`};let S=St(e,u);if(!S)return {success:!1,error:`Field '${u}' does not exist in schema`};let $=(ce()==="normalize"?K(S):S).parse(f);a[u]=$;}else c[u]=f;if(Object.keys(c).length>0||Object.keys(a).length===0){let u=bt(e,n,o),f=s?qe(u):u,S=(ce()==="normalize"?K(f):f).parse(c);Object.assign(a,S);}return {success:!0,data:a}}catch(d){return d instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${d.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function te(e,t,n){let s=e?.shape?.[t];if(!s||typeof s.safeParse!="function")return {success:true,data:n};let o=s.safeParse(n);if(o.success)return {success:true,data:o.data};if(Array.isArray(n)){let a=[];for(let c of n){let u=s.safeParse(c);if(u.success)a.push(u.data);else return {success:false,error:u.error.issues.map(R=>R.message).join(", ")}}return {success:true,data:a}}return {success:false,error:o.error.issues.map(a=>a.message).join(", ")}}function xt(e,t){let n=[],s=t?new Set(t):null,o={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[d,a]of Object.entries(e)){if(a===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(d))continue;let c=Array.isArray(a)?a[0]:a;if(c===void 0||c==="")continue;let u=d.match(/^(\w+)__(\w+)$/),f,R="==";if(u&&u[1]&&u[2]){f=u[1];let P=u[2];if(o[P])R=o[P];else continue}else if(!u)f=d;else continue;if(s&&!s.has(f))continue;let S=c;R==="in"||R==="not-in"||R==="array-contains-any"?S=c.split(",").map(P=>je(P.trim())):S=je(c),n.push({field:f,op:R,value:S});}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 ne(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function De(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 s=typeof n.docPath=="string"?n.docPath:void 0,o=typeof n.docId=="string"?n.docId:void 0;try{let d=e.repo.ref,a=d?.firestore;if(s&&a&&typeof a.doc=="function"){let c=await a.doc(s).get();if(c.exists)return c}if(o&&o.includes("/")&&a&&typeof a.doc=="function"){let c=await a.doc(o).get();if(c.exists)return c}if(o&&typeof d.doc=="function"){let c=await d.doc(o).get();if(c.exists)return c}return}catch{return}}function $e(e,t,n){async function s(p,r,m,i){if(!r.rules)return true;let y=r.rules?.[m];if(!y)return b(p,`Operation "${m}" is not allowed for this repository`,403),false;try{return await y(i)?!0:b(p,"Forbidden",403)}catch(h){let g=n&&h instanceof Error?h.message:"Forbidden";return b(p,g,403)}}async function o(p,r,m,i){if(!p.rules)return i;let y=p.rules?.filter;if(!y)return i;let h=[];for(let g of i)try{await y({user:r,doc:g,params:m})&&h.push(g);}catch{}return h}function d(p){return p.get("user")??p.get("docsUser")??null}function a(p,r){if(!p){let m=r.req.path.split("/");for(let i of m)if(e[i]){p=i;break}}return !p||!e[p]?null:e[p]??null}function c(p,r){if(!r)return;let m=p[r];if(typeof m!="string"||!m)return;let i=m.split("/").filter(Boolean),y=[];for(let h=1;h<i.length;h+=2)y.push(i[h]);return y.length>0?y:void 0}async function u(p,r){let m=`by${p.documentKey.charAt(0).toUpperCase()}${p.documentKey.slice(1)}`,i=p.repo.get[m];if(typeof i=="function")try{let h=await i(r);if(h)return h}catch{}return (await p.repo.query.by({where:[[p.documentKey,"==",r]],limit:1}))[0]??null}async function f(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);let y=d(r);if(!await s(r,i,"list",{user:y,query:r.req.query(),params:m}))return;let h=[],g;try{let l=r.req.query(),w=Math.min(Number(l.pageSize)||i.pageSize,100),x=l.cursor,C=l.direction?.toLowerCase()==="prev"?"prev":"next",A=l.orderBy,O=l.orderDir?.toLowerCase()==="desc"?"desc":"asc",H=l.select,U=H?H.split(",").map(F=>F.trim()):void 0,E=l.withTotal,T=E==="true"||E==="1"||E===!0,k;i.allowedIncludes&&l.includes&&(k=(typeof l.includes=="string"?l.includes.split(",").map(L=>L.trim()):Array.isArray(l.includes)?l.includes:[]).filter(L=>typeof L=="string"&&i.allowedIncludes.includes(L)),k?.length===0&&(k=void 0));let D=xt(l,i.filterableFields);h=D.map(F=>({field:F.field,op:F.op,value:String(F.value??"")})),A&&(g={field:A,dir:O});let z={pageSize:w,direction:C,...T?{withTotal:!0}:{}};if(x)try{let F=typeof x=="string"?JSON.parse(x):x;z.cursor=await De(i,F);}catch{}if(A){if(i.orderableFields&&!i.orderableFields.includes(A))return b(r,`Field not orderable: ${A}`,400);z.orderBy=[{field:A,direction:O}];}if(D.length>0){z.where=[];for(let F of D){let L=te(i.schema,F.field,F.value);if(!L.success)return b(r,`Invalid filter value for '${F.field}': ${L.error}`,400);z.where.push([F.field,F.op,L.data]);}}U&&(z.select=U),k&&(z.include=k);let N=await i.repo.query.paginate(z),Ye={items:await o(i,d(r),m,N.data),hasNextPage:N.hasNextPage,hasPrevPage:N.hasPrevPage,nextCursor:ne(N.nextCursor),prevCursor:ne(N.prevCursor),...N.totalCount!==void 0?{totalCount:N.totalCount,totalCountIsExact:N.totalCountIsExact}:{}};return Z(r,Ye,{pageSize:w,hasMore:N.hasNextPage,...N.totalCount!==void 0?{totalCount:N.totalCount,totalCountIsExact:N.totalCountIsExact}:{}})}catch(l){fe(r,l,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:h,sort:g},"Failed to fetch documents",n);}}async function R(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);let y=d(r);if(!await s(r,i,"list",{user:y,query:p.input||{},params:m}))return;let h=[],g;try{let l=p.input||{},w=Math.min(l.pageSize||i.pageSize,100),x=l.direction==="prev"?"prev":"next";l.where&&(h=l.where.map(E=>({field:String(E[0]),op:E[1],value:String(E[2]??"")}))),l.orderBy&&l.orderBy[0]&&(g={field:l.orderBy[0].field,dir:l.orderBy[0].direction==="desc"?"desc":"asc"});let C=l.withTotal===!0||String(l.withTotal)==="true",A={pageSize:w,direction:x,...C?{withTotal:!0}:{}};if(l.cursor)try{let E=typeof l.cursor=="string"?JSON.parse(l.cursor):l.cursor;A.cursor=await De(i,E);}catch{}if(i.allowedIncludes&&l.includes&&l.includes.length>0){let E=l.includes.filter(T=>typeof T=="string"?i.allowedIncludes.includes(T):typeof T=="object"&&T!==null&&"relation"in T&&typeof T.relation=="string"?i.allowedIncludes.includes(T.relation):!1);E.length>0&&(A.include=E);}if(l.where&&l.where.length>0){if(i.filterableFields){let T=new Set(i.filterableFields),k=l.where.filter(D=>!T.has(D[0]));if(k.length>0){b(r,`Fields not filterable: ${k.map(D=>D[0]).join(", ")}`,400);return}}let E=[];for(let T of l.where){let k=te(i.schema,T[0],T[2]);if(!k.success){b(r,`Invalid filter value for '${T[0]}': ${k.error}`,400);return}E.push([T[0],T[1],k.data]);}A.where=E;}if(l.orWhere&&l.orWhere.length>0){if(i.filterableFields){let T=new Set(i.filterableFields),k=l.orWhere.filter(D=>!T.has(D[0]));if(k.length>0){b(r,`Fields not filterable: ${k.map(D=>D[0]).join(", ")}`,400);return}}let E=[];for(let T of l.orWhere){let k=te(i.schema,T[0],T[2]);if(!k.success){b(r,`Invalid filter value for '${T[0]}': ${k.error}`,400);return}E.push([T[0],T[1],k.data]);}A.orWhere=E;}if(l.orWhereGroups&&l.orWhereGroups.length>0){if(i.filterableFields){let T=new Set(i.filterableFields);for(let k of l.orWhereGroups){let D=k.filter(z=>!T.has(z[0]));if(D.length>0){b(r,`Fields not filterable: ${D.map(z=>z[0]).join(", ")}`,400);return}}}let E=[];for(let T of l.orWhereGroups){let k=[];for(let D of T){let z=te(i.schema,D[0],D[2]);if(!z.success){b(r,`Invalid filter value for '${D[0]}': ${z.error}`,400);return}k.push([D[0],D[1],z.data]);}E.push(k);}A.orWhereGroups=E;}if(l.orderBy&&l.orderBy.length>0){if(i.orderableFields){let E=new Set(i.orderableFields),T=l.orderBy.filter(k=>!E.has(k.field));if(T.length>0){b(r,`Fields not orderable: ${T.map(k=>k.field).join(", ")}`,400);return}}A.orderBy=l.orderBy;}l.select&&l.select.length>0&&(A.select=l.select);let O=await i.repo.query.paginate(A),U={items:await o(i,d(r),m,O.data),hasNextPage:O.hasNextPage,hasPrevPage:O.hasPrevPage,nextCursor:ne(O.nextCursor),prevCursor:ne(O.prevCursor),...O.totalCount!==void 0?{totalCount:O.totalCount,totalCountIsExact:O.totalCountIsExact}:{}};return Z(r,U,{pageSize:w,hasMore:O.hasNextPage,...O.totalCount!==void 0?{totalCount:O.totalCount,totalCountIsExact:O.totalCountIsExact}:{}})}catch(l){fe(r,l,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:h,sort:g},"Failed to query documents",n);}}async function S(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);let y=m.id;if(!y)return b(r,"Document ID required",400);try{let h=await u(i,y);if(!h)return b(r,"Document not found",404);let g=d(r);if(!await s(r,i,"get",{user:g,doc:h,params:m}))return;if(i.rules?.filter)try{if(!await i.rules.filter({user:g,doc:h,params:m}))return b(r,"Document not found",404)}catch{return b(r,"Document not found",404)}return Z(r,h)}catch(h){fe(r,h,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:[{field:i.documentKey,op:"==",value:y}]},"Failed to fetch document",n);}}async function P(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);try{let y=p.input||{},h=d(r);if(!await s(r,i,"create",{user:h,body:y,params:m}))return;let g=ee(i.schema,y,i.createFields,!1,i.systemKeys);if(!g.success)return b(r,g.error,400);if(i.validate){let w=await i.validate(g.data,"create");if(w)return b(r,w,400)}let l;if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let w={...g.data};i.createdKey&&(w[i.createdKey]=new Date);let x=i.parentKeys.filter(O=>!w[O]);if(x.length>0){b(r,`Missing parent key(s) for subcollection create: ${x.join(", ")}`,400);return}let C=i.parentKeys.map(O=>w[O]),A=w[i.documentKey]||Pe();l=await i.repo.set(...C,A,w);}else l=await i.repo.create(g.data);return Z(r,l,void 0,201)}catch(y){let h=n&&y instanceof Error?y.message:"Failed to create document";return b(r,h,500)}}async function $(p,r){let m=p.c,i=m.req.param(),y=a(i.repoName,m);if(!y)return b(m,"Repository not found",404);let h=i.id;if(!h)return b(m,"Document ID required",400);try{let g=p.input||{},l=await u(y,h);if(!l)return b(m,"Document not found",404);let w=d(m);if(!await s(m,y,"update",{user:w,doc:l,body:g,params:i}))return;let x=ee(y.schema,g,y.mutableFields,r,y.systemKeys);if(!x.success)return b(m,x.error,400);if(y.validate){let O=await y.validate(x.data,"update");if(O)return b(m,O,400)}let C=c(l,y.pathKey)??[h],A=await y.repo.update(...C,x.data);return Z(m,A)}catch(g){let l=n&&g instanceof Error?g.message:"Failed to update document";return b(m,l,500)}}async function j(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);if(!i.allowDelete)return b(r,"Delete not allowed for this repository",403);let y=m.id;if(!y)return b(r,"Document ID required",400);try{let h=await u(i,y);if(!h)return b(r,"Document not found",404);let g=d(r);if(!await s(r,i,"delete",{user:g,doc:h,params:m}))return;let l=c(h,i.pathKey)??[y];return await i.repo.delete(...l),Z(r,{deleted:!0})}catch(h){let g=n&&h instanceof Error?h.message:"Failed to delete document";return b(r,g,500)}}function I(p){return p.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400"})}async function v(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);try{let y=p.input||{};if(!Array.isArray(y.operations))return b(r,"operations array is required",400);let h=d(r),g=i.repo.batch.create(),l=[];for(let w of y.operations){if(!w.type||!["create","update","delete"].includes(w.type))return b(r,"Invalid operation type",400);if(w.type==="create"){if(!await s(r,i,"create",{user:h,body:w.data,params:m}))return;let x=ee(i.schema,w.data,i.createFields,!1,i.systemKeys);if(!x.success)return b(r,x.error,400);let C=w.data[i.documentKey]||Pe(),A={...x.data};if(i.createdKey&&(A[i.createdKey]=new Date),i.isGroup&&i.parentKeys){let O=i.parentKeys.map(H=>A[H]);g.set(...O,C,A);}else g.set(C,A);l.push({op:"create",id:C});}else if(w.type==="update"){if(!w.id)return b(r,"id required for update",400);let x=await u(i,w.id);if(!x)return b(r,`Document ${w.id} not found`,404);if(!await s(r,i,"update",{user:h,doc:x,body:w.data,params:m}))return;let C=ee(i.schema,w.data,i.mutableFields,!0,i.systemKeys);if(!C.success)return b(r,C.error,400);let A=c(x,i.pathKey)??[w.id];g.update(...A,C.data),l.push({op:"update",id:w.id});}else if(w.type==="delete"){if(!i.allowDelete)return b(r,"Delete not allowed",403);if(!w.id)return b(r,"id required for delete",400);let x=await u(i,w.id);if(!x)return b(r,`Document ${w.id} not found`,404);if(!await s(r,i,"delete",{user:h,doc:x,params:m}))return;let C=c(x,i.pathKey)??[w.id];g.delete(...C),l.push({op:"delete",id:w.id});}}return await g.commit(),Z(r,{results:l})}catch(y){let h=n&&y instanceof Error?y.message:"Batch operation failed";return b(r,h,500)}}return {handleList:f,handleQuery:R,handleGet:S,handleCreate:P,handleUpdate:$,handleDelete:j,handleBatch:v,handleOptions:I}}function re(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 s=t.zodSchema?._zod?.def;s&&(s.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):s.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 _(e){return {$ref:`#/components/schemas/${e}`}}function q(e){return {description:e,content:{"application/json":{schema:_("ErrorResponse")}}}}function W(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function ze(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 Q(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 vt(e,t){let n=t.split("."),s=Q(e);for(let o=0;o<n.length;o++){let d=n[o];if(!d)continue;let a=s?.shape;if(!a||!a[d])return;let c=a[d];if(o===n.length-1)return c;s=Q(c);}return s}function be(e,t="",n=0){if(n>5)return [];let o=Q(e)?.shape;if(!o)return [];let d=[];for(let[a,c]of Object.entries(o)){let u=t?`${t}.${a}`:a,f=Q(c);f?.shape&&typeof f.shape=="object"?(d.push({path:u,zodSchema:c}),d.push(...be(f,u,n+1))):d.push({path:u,zodSchema:c});}return d}function Se(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:vt(e.schema,t)})):be(e.schema)}function we(e){if(!e)return {type:"string"};let t=re(e);return delete t.$schema,delete t.title,t}function At(e){let t=Se(e),n=e.orderableFields??t.map(s=>s.path);return [{name:"pageSize",in:"query",schema:{type:"integer",default:e.pageSize,maximum:100},description:"Number of items per page"},{name:"cursor",in:"query",schema:{type:"string"},description:"Base64 pagination cursor"},{name:"orderBy",in:"query",schema:{type:"string",...n.length>0?{enum:n}:{}},description:"Field name to order by"},{name:"orderDir",in:"query",schema:{type:"string",enum:["asc","desc"]},description:"Order direction"},{name:"select",in:"query",schema:{type:"string"},description:`Comma-separated list of fields to return${t.length>0?` (${t.map(s=>s.path).join(", ")})`:""}`},{name:"withTotal",in:"query",schema:{type:"boolean"},description:"Include total document count (totalCount and totalCountIsExact) in response"}]}function Tt(e){let t=Se(e),n=["eq","ne","lt","lte","gt","gte","in","nin","contains","containsAny"],s={eq:"equals. Use 'null' or '__null__' to match null values",ne:"not equals. Use 'null' or '__null__' to match non-null values",lt:"less than",lte:"less than or equal",gt:"greater than",gte:"greater than or equal",in:"in list (comma-separated values). Supports 'null' and '__null__' (e.g. val1,val2,__null__)",nin:"not in list (comma-separated values). Supports 'null' and '__null__'",contains:"array-contains",containsAny:"array-contains-any (comma-separated values). Supports 'null' and '__null__'"},o=[];for(let{path:d,zodSchema:a}of t){let c=we(a);o.push({name:d,in:"query",schema:c,description:`Filter by ${d} (equality). Use 'null' or '__null__' for null values`});for(let u of n){let f=s[u]?` (${s[u]})`:"",R=u==="in"||u==="nin"||u==="containsAny";o.push({name:`${d}__${u}`,in:"query",schema:R?{type:"string",description:"Comma-separated list of values"}:c,description:`Filter ${d} with operator ${u}${f}`});}}return o}function Fe(){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",maximum:100,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 Ot(e){let t=Se(e),n=e.orderableFields??t.map(a=>a.path),s=t.map(a=>a.path);if(t.length===0)return Fe();let o=[];for(let{path:a,zodSchema:c}of t){let u=we(c),f=Q(c),S=f?._zod?.def?.type==="array"||f?._def?.typeName==="ZodArray"||f?._def?.type==="array"?we(f?._zod?.def?.element??f?._def?.type??f?._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"]},S],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:S}],minItems:3,maxItems:3});}let d={oneOf:o};return {type:"object",properties:{where:{type:"array",items:d,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:d,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:d},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:s},description:"Fields to select (projection)"},pageSize:{type:"integer",maximum:100,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 kt(e,t,n,s,o,d="QueryRequestBody"){let a={},c=e.name,u=`${t}/${e.name}`,f=`${u}/{${e.documentKey}}`,R={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[u]={get:{operationId:`list${M(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[c],parameters:[...At(e),...Tt(e)],responses:{200:ze(_(n)),500:q("Internal server error")}},post:{operationId:`create${M(e.name)}`,summary:`Create a ${B(e.name)}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(s??n)}}},responses:{201:W("Document created",_(n)),400:q("Validation error"),500:q("Internal server error")}}},a[`${u}/query`]={post:{operationId:`query${M(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(d)}}},responses:{200:ze(_(n)),400:q("Invalid query"),500:q("Internal server error")}}},a[`${u}/batch`]={post:{operationId:`batch${M(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(`${n}BatchRequest`)}}},responses:{200:W("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:q("Validation error"),403:q("Forbidden"),404:q("Document not found"),500:q("Internal server error")}}};let S={};return S.get={operationId:`get${M(B(e.name))}`,summary:`Get a single ${B(e.name)}`,tags:[c],parameters:[R],responses:{200:W("Document found",_(n)),404:q("Document not found"),500:q("Internal server error")}},S.put={operationId:`update${M(B(e.name))}`,summary:`Update a ${B(e.name)} (full replace)`,tags:[c],parameters:[R],requestBody:{required:true,content:{"application/json":{schema:_(o??n)}}},responses:{200:W("Document updated",_(n)),400:q("Validation error"),404:q("Document not found"),500:q("Internal server error")}},S.patch={operationId:`patch${M(B(e.name))}`,summary:`Partially update a ${B(e.name)}`,tags:[c],parameters:[R],requestBody:{required:true,content:{"application/json":{schema:{allOf:[_(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:W("Document patched",_(n)),400:q("Validation error"),404:q("Document not found"),500:q("Internal server error")}},e.allowDelete&&(S.delete={operationId:`delete${M(B(e.name))}`,summary:`Delete a ${B(e.name)}`,tags:[c],parameters:[R],responses:{200:W("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:q("Document not found"),500:q("Internal server error")}}),a[f]=S,a}function xe(e,t,n={}){let{title:s="CRUD API",version:o="1.0.0",description:d,servers:a,auth:c=false}=n,u=t==="/"?"":t.replace(/\/$/,""),f={},R={},S=[];f.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},f.QueryRequestBody=Fe();for(let[I,v]of Object.entries(e)){let p=M(B(I)),r=`${p}Create`,m=`${p}Update`,i=`${p}QueryRequestBody`;f[p]=re(v.schema),f[i]=Ot(v);let y=C=>{let A={},O=be(v.schema);for(let{path:H,zodSchema:U}of O){let E=H.split(".")[0];v.systemKeys.includes(E)||v.systemKeys.includes(H)||C&&C.length>0&&!C.includes(H)&&!C.includes(E)||(H.includes(".")?A[H]=U.optional():A[H]=U);}return A},h=null,g=y(v.createFields);Object.keys(g).length>0&&(f[r]=re(zod.z.object(g)),h=r);let l=null,w=y(v.mutableFields);Object.keys(w).length>0&&(f[m]=re(zod.z.object(w)),l=m),f[`${p}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:_(h??p)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[_(l??p)],description:"Partial updates allowed"}},required:["type","id","data"]},...v.allowDelete?[{type:"object",properties:{type:{type:"string",enum:["delete"]},id:{type:"string"}},required:["type","id"]}]:[]]}}},required:["operations"]};let x=kt(v,u,p,h,l,i);Object.assign(R,x),S.push({name:I,description:`Operations on ${I} (collection: ${v.path})`});}let P={},$;return c==="basic"?(P.basicAuth={type:"http",scheme:"basic"},$=[{basicAuth:[]}]):c==="bearer"&&(P.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},$=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:s,version:o,...d?{description:d}:{}},...a&&a.length>0?{servers:a}:{},paths:R,components:{schemas:f,...Object.keys(P).length>0?{securitySchemes:P}:{}},...$?{security:$}:{},tags:S}}function M(e){return e.charAt(0).toUpperCase()+e.slice(1)}function B(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 J=class extends Error{constructor(n,s){super("Request validation failed");this.zodError=n;this.source=s;this.statusCode=400;this.name="ValidationError";}};var V=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},X=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function _e(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function He(e,t){return t instanceof J?e.json({success:false,error:"Validation failed",issues:_e(t.zodError)},400):t instanceof V?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof X?e.json({success:false,error:"Output validation failed",issues:_e(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var Ne="Successful response",Be="Error response";function jt(e){return e==="get"?"query":"json"}function Dt(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function qt(e){if(typeof e.safeParse=="function")return {description:Be,schema:e};let t=e;return {description:t.description??Be,schema:t.schema}}function Le(e,t,n,s){let o=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[c,u]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",c,u);for(let c of e){let u=c.method,f=c.source??jt(u),R=Ft(t,c.path??"/"),S=c.status??200,P=$t(u,f,c.input),$=Me(f,c.input,"query"),j=Me(f,c.input,"param"),I=_t(u,R),v=Dt(c.output,s),p={[S]:v?{description:Ne,content:{"application/json":{schema:v}}}:{description:Ne}};if(s?.errors)for(let[r,m]of Object.entries(s.errors)){let{description:i,schema:y}=qt(m);p[r]=y?{description:i,content:{"application/json":{schema:y}}}:{description:i};}o.registerPath({method:u,path:zt(R),operationId:I,summary:c.summary,description:c.description,tags:c.tags,deprecated:c.deprecated,security:c.security,request:{...$?{query:$}:{},...j?{params:j}:{},...P?{body:P}:{}},responses:p});}return new zodToOpenapi.OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function $t(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 Me(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function zt(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Ft(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`,o=`${n}${s}`;return o===""?"/":o}function _t(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Ue(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
|
|
12
|
+
</html>`}function Ze(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var Re=new async_hooks.AsyncLocalStorage;function Ke(){return async(e,t)=>{await Re.run({c:e},async()=>{await t();});}}var Mt=Object.freeze({}),se=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new hono.Hono,this.mountedRoutes=Zt(t.routes,t.api),t.services&&this.app.use("*",Ke());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let s of n)this.app.use("*",s);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 s=this.nodeHandler;return n?t(n,s):t(s)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=Le(this.mountedRoutes,this.options.basePath??"",this.options.openapi,Ut(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,s=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 d=oe(t,o.path),a=o.middlewares??[],c=o.source??(o.method==="get"?"query":"json"),u=Wt(o,c,n,Lt(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),f=o.method.toUpperCase();this.app.on(f,[d],...a,u),s&&console.log(`[HonoServer] ${o.method.toUpperCase().padEnd(6)} ${d}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",s=t.docsPath===void 0?"/docs":t.docsPath,o=oe(this.options.basePath??"",n),d=s===false?null:oe(this.options.basePath??"",s),a;if(Ze(t.docsAuth)){let c=t.docsAuth;a=[c.middleware];let u=Kt(d??o);for(let f of c.routes)this.app.on(f.method,[oe(u,f.name)],f.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...a,c=>c.json(this.buildOpenApiSpec())),d){let c=Gt(d,o);this.app.on("GET",[d],...a,u=>u.html(Ue(c,t.info.title)));}}};function Ge(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function Lt(e){if(e)return Ge(e)?e.handler:e}function Ut(e){return Ge(e)?e:void 0}function Zt(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function oe(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`,o=`${n}${s}`;return o===""?"/":o}function Kt(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Gt(e,t){let n=e.split("/").filter(Boolean),s=t.split("/").filter(Boolean);n.pop();let o=0;for(;o<n.length&&o<s.length&&n[o]===s[o];)o++;let d=n.length-o;return [...Array(d).fill(".."),...s.slice(o)].join("/")||"./"}function Wt(e,t,n,s,o,d,a){let c=e.input,u=e.output,f=e.status??200,R=o??Mt;return async S=>{let P=async I=>{if(d){let v=await d.handle({error:I,c:S,route:e,services:R,logger:a});if(v)return v}return He(S,I)},$=async()=>{let I,v;try{v=await Jt(S,t,e.method);}catch(r){throw new V(r instanceof Error?r.message:String(r))}if(c){let r=c.safeParse(v);if(!r.success)throw new J(r.error,t);I=r.data;}else I=v;let p=await e.handler({input:I,c:S,services:R,errorHandler:d,logger:a});if(n&&u&&!(p instanceof Response)){let r=u.safeParse(p);if(!r.success)throw new X(r.error);return r.data}return p},j;if(s)try{j=await s({next:$,route:e,c:S,services:R,errorHandler:d,logger:a});}catch(I){let v=await P(I);if(v)return v;throw I}else try{j=await $();}catch(I){let v=await P(I);if(v)return v;throw I}return j instanceof Response?j:S.json(j,f)}}async function Jt(e,t,n){switch(t){case "json":{if(n==="get")return e.req.query();let s=await e.req.text();if(!s)return {};try{return JSON.parse(s)}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 _n(e){let{basePath:t="/",repos:n,parseBody:s=true,securityHeaders:o,verbose:d=false,httpsOptions:a}=e,c=t==="/"?"":t.replace(/\/$/,""),u={};for(let[p,r]of Object.entries(n)){if(!r.repo)throw new Error(`[createCrudServer] Repository "${p}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let m=r.schema??r.repo.schema??null;if(!m)throw new Error(`[createCrudServer] Repository "${p}" has no Zod schema.`);let i,y,h,g;if(r.fieldsConfig){let x=r.fieldsConfig;i=[],y=[],h=[],g=[];for(let[C,A]of Object.entries(x))for(let O of A)O==="filterable"?i.push(C):O==="orderable"?y.push(C):O==="mutable"?h.push(C):O==="create"&&g.push(C);y.length===0&&(y=i),i.length===0&&(i=void 0),y&&y.length===0&&(y=void 0),h.length===0&&(h=void 0),g.length===0&&(g=void 0);}let l=(()=>{let x=r.repo._parentKeys;return x&&x.length>0?x:void 0})();if(l&&g)for(let x of l)g.includes(x)||g.push(x);let w={name:p,path:r.path,repo:r.repo,schema:m,systemKeys:r.repo._systemKeys??[r.documentKey??"docId"],documentKey:r.documentKey??"docId",pathKey:r.repo._pathKey??void 0,isGroup:!!r.repo._isGroup,parentKeys:l,createdKey:r.repo._createdKey??void 0,pageSize:r.pageSize??25,filterableFields:i,orderableFields:y,mutableFields:h,createFields:g,allowDelete:r.allowDelete??false,allowedIncludes:r.allowedIncludes,validate:r.validate,rules:r.rules};u[p]=w;}let f=$e(u,c,d),R=e.openapi,S=R&&typeof R=="object"?R:{},P=null;function $(){return P||(P=xe(u,c,{...S,auth:S.auth??false})),P}let j=[];for(let p of Object.keys(u))j.push({api:"crud",method:"get",path:`/${p}`,source:"query",handler:f.handleList}),j.push({api:"crud",method:"post",path:`/${p}/query`,source:"json",handler:f.handleQuery}),j.push({api:"crud",method:"get",path:`/${p}/:id`,source:"query",handler:f.handleGet}),j.push({api:"crud",method:"post",path:`/${p}`,source:"json",handler:f.handleCreate}),j.push({api:"crud",method:"put",path:`/${p}/:id`,source:"json",handler:r=>f.handleUpdate(r,false)}),j.push({api:"crud",method:"patch",path:`/${p}/:id`,source:"json",handler:r=>f.handleUpdate(r,true)}),j.push({api:"crud",method:"delete",path:`/${p}/:id`,source:"query",handler:f.handleDelete}),j.push({api:"crud",method:"post",path:`/${p}/batch`,source:"json",handler:f.handleBatch});let I=new se({...e,openapi:R!==false?{path:S.path??"/openapi.json",docsPath:S.docsPath??"/docs",info:{title:S.title??"CRUD API",version:S.version??"1.0.0"},docsAuth:S.docsAuth}:void 0,basePath:t,api:"crud",routes:j,middlewares:[async(p,r)=>{if(p.req.method==="OPTIONS")return p.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});p.header("Access-Control-Allow-Origin","*"),p.header("Access-Control-Allow-Credentials","true"),await r();},...e.middlewares||[]]});if(R!==false&&(I.buildOpenApiSpec=$),o!==false){let{securityHeaders:p}=(Xe(),it(Ve)),r=o===void 0?{csp:false}:o;I.hono.use("*",async(m,i)=>{let y=p(r);await new Promise(h=>{let g=m.req.raw;y(g,{setHeader:(w,x)=>m.header(w,x),removeHeader:w=>m.res.headers.delete(w)},()=>h());}),await i();});}let v=I.nodeHandler;return v.spec=$,a&&(v.httpsOptions=a),v}exports.createCrudServer=_n;exports.generateOpenAPISpec=xe;//# sourceMappingURL=index.cjs.map
|
|
13
13
|
//# sourceMappingURL=index.cjs.map
|