@kyro-cms/core 0.9.7 → 0.9.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/dist/{WebhookService-BKszZlG0.d.cts → WebhookService-Dj8pJ3sp.d.cts} +1 -1
  2. package/dist/{WebhookService-Ccf1j-IN.d.ts → WebhookService-DpRB940h.d.ts} +1 -1
  3. package/dist/api-handler-graphql.cjs +18 -13
  4. package/dist/api-handler-graphql.cjs.map +1 -1
  5. package/dist/api-handler-graphql.js +14 -9
  6. package/dist/api-handler-graphql.js.map +1 -1
  7. package/dist/api-handler-trpc.cjs +9 -9
  8. package/dist/api-handler-trpc.js +7 -7
  9. package/dist/api-handler.cjs +10 -10
  10. package/dist/api-handler.js +7 -7
  11. package/dist/{base-CIuXkrH4.d.cts → base-BjyoF6da.d.cts} +2 -2
  12. package/dist/{base-fFo4lqER.d.ts → base-C2YR8lWt.d.ts} +2 -2
  13. package/dist/{chunk-NZEUU7QB.js → chunk-3AKCVYDB.js} +4 -109
  14. package/dist/chunk-3AKCVYDB.js.map +1 -0
  15. package/dist/{chunk-FKKQUMXR.cjs → chunk-4OCMVGEY.cjs} +4 -110
  16. package/dist/chunk-4OCMVGEY.cjs.map +1 -0
  17. package/dist/{chunk-VLK5SJRI.js → chunk-5RFGYEQ3.js} +133 -46
  18. package/dist/chunk-5RFGYEQ3.js.map +1 -0
  19. package/dist/chunk-5RPRLTTN.js +861 -0
  20. package/dist/chunk-5RPRLTTN.js.map +1 -0
  21. package/dist/{chunk-AX2TZRQJ.js → chunk-BVUDFKKS.js} +16 -3
  22. package/dist/chunk-BVUDFKKS.js.map +1 -0
  23. package/dist/{chunk-DRVOUQMT.cjs → chunk-E4JZ73FY.cjs} +54 -79
  24. package/dist/chunk-E4JZ73FY.cjs.map +1 -0
  25. package/dist/{chunk-E5UJBLQ7.js → chunk-FIAMXNTH.js} +2 -2
  26. package/dist/chunk-FIAMXNTH.js.map +1 -0
  27. package/dist/{chunk-QVJNSAQL.cjs → chunk-IEIHABVR.cjs} +152 -65
  28. package/dist/chunk-IEIHABVR.cjs.map +1 -0
  29. package/dist/{chunk-QFLB4EIJ.cjs → chunk-LNTFRAHF.cjs} +118 -9
  30. package/dist/chunk-LNTFRAHF.cjs.map +1 -0
  31. package/dist/chunk-N4GN6Q3V.cjs +869 -0
  32. package/dist/chunk-N4GN6Q3V.cjs.map +1 -0
  33. package/dist/{chunk-FSKONGCX.cjs → chunk-OJ2AM75W.cjs} +2 -2
  34. package/dist/chunk-OJ2AM75W.cjs.map +1 -0
  35. package/dist/{chunk-QX3WNQ7V.js → chunk-OX6GOIPH.js} +4 -4
  36. package/dist/{chunk-QX3WNQ7V.js.map → chunk-OX6GOIPH.js.map} +1 -1
  37. package/dist/{chunk-OZ3CCTTA.cjs → chunk-OXYSOU6Z.cjs} +18 -5
  38. package/dist/chunk-OXYSOU6Z.cjs.map +1 -0
  39. package/dist/{chunk-CMXVTUYV.js → chunk-OYCICW4B.js} +38 -63
  40. package/dist/chunk-OYCICW4B.js.map +1 -0
  41. package/dist/{chunk-HVCUIII2.cjs → chunk-TQG7G7YI.cjs} +13 -13
  42. package/dist/{chunk-HVCUIII2.cjs.map → chunk-TQG7G7YI.cjs.map} +1 -1
  43. package/dist/{chunk-3UK5XBVJ.js → chunk-WDTTHKDS.js} +117 -10
  44. package/dist/chunk-WDTTHKDS.js.map +1 -0
  45. package/dist/cli/index.cjs +148 -14
  46. package/dist/cli/index.cjs.map +1 -1
  47. package/dist/cli/index.js +148 -14
  48. package/dist/cli/index.js.map +1 -1
  49. package/dist/client.cjs +3 -3
  50. package/dist/client.d.cts +2 -2
  51. package/dist/client.d.ts +2 -2
  52. package/dist/client.js +1 -1
  53. package/dist/drizzle/index.d.cts +3 -3
  54. package/dist/drizzle/index.d.ts +3 -3
  55. package/dist/fields/index.cjs +21 -21
  56. package/dist/fields/index.d.cts +1 -1
  57. package/dist/fields/index.d.ts +1 -1
  58. package/dist/fields/index.js +1 -1
  59. package/dist/graphql/index.cjs +13 -5
  60. package/dist/graphql/index.d.cts +37 -7
  61. package/dist/graphql/index.d.ts +37 -7
  62. package/dist/graphql/index.js +2 -2
  63. package/dist/{index-BKta3cBH.d.cts → index-DHbywDs-.d.cts} +2 -2
  64. package/dist/{index-ClOqnkTO.d.ts → index-jLs0zlft.d.ts} +2 -2
  65. package/dist/index.cjs +90 -90
  66. package/dist/index.d.cts +15 -14
  67. package/dist/index.d.ts +15 -14
  68. package/dist/index.js +8 -8
  69. package/dist/mongodb/index.d.cts +3 -3
  70. package/dist/mongodb/index.d.ts +3 -3
  71. package/dist/rest/index.cjs +5 -5
  72. package/dist/rest/index.d.cts +4 -4
  73. package/dist/rest/index.d.ts +4 -4
  74. package/dist/rest/index.js +3 -3
  75. package/dist/templates/index.d.cts +2 -2
  76. package/dist/templates/index.d.ts +2 -2
  77. package/dist/trpc/index.cjs +12 -12
  78. package/dist/trpc/index.d.cts +3 -3
  79. package/dist/trpc/index.d.ts +3 -3
  80. package/dist/trpc/index.js +3 -3
  81. package/dist/{types-Dgzlftb7.d.ts → types-BzH3_rtP.d.ts} +7 -7
  82. package/dist/{types-Ds0tCA3L.d.cts → types-CY_iNunL.d.cts} +7 -7
  83. package/dist/{types-DeSApf9T.d.ts → types-C_rVxU2T.d.cts} +4 -4
  84. package/dist/{types-DeSApf9T.d.cts → types-C_rVxU2T.d.ts} +4 -4
  85. package/package.json +2 -1
  86. package/dist/chunk-3UK5XBVJ.js.map +0 -1
  87. package/dist/chunk-AX2TZRQJ.js.map +0 -1
  88. package/dist/chunk-CMXVTUYV.js.map +0 -1
  89. package/dist/chunk-DRVOUQMT.cjs.map +0 -1
  90. package/dist/chunk-E5UJBLQ7.js.map +0 -1
  91. package/dist/chunk-FKKQUMXR.cjs.map +0 -1
  92. package/dist/chunk-FSKONGCX.cjs.map +0 -1
  93. package/dist/chunk-NZEUU7QB.js.map +0 -1
  94. package/dist/chunk-OZ3CCTTA.cjs.map +0 -1
  95. package/dist/chunk-PONTBXR5.js +0 -842
  96. package/dist/chunk-PONTBXR5.js.map +0 -1
  97. package/dist/chunk-QFLB4EIJ.cjs.map +0 -1
  98. package/dist/chunk-QVJNSAQL.cjs.map +0 -1
  99. package/dist/chunk-RRKCIAPU.cjs +0 -848
  100. package/dist/chunk-RRKCIAPU.cjs.map +0 -1
  101. package/dist/chunk-VLK5SJRI.js.map +0 -1
@@ -0,0 +1,861 @@
1
+ import { hasApiKeyPermission, evaluateAccess } from './chunk-3AKCVYDB.js';
2
+ import { hasPermission } from './chunk-L4EZKIEX.js';
3
+ import { GraphQLScalarType, Kind, GraphQLObjectType, GraphQLString, GraphQLInputObjectType, GraphQLBoolean, GraphQLInt, GraphQLList, GraphQLNonNull, GraphQLSchema, GraphQLFloat } from 'graphql';
4
+ export { printSchema } from 'graphql';
5
+
6
+ var RelationLoader = class {
7
+ db;
8
+ tenantID;
9
+ user;
10
+ caches = /* @__PURE__ */ new Map();
11
+ pending = /* @__PURE__ */ new Map();
12
+ waiting = /* @__PURE__ */ new Map();
13
+ flushScheduled = false;
14
+ constructor(opts) {
15
+ this.db = opts.db;
16
+ this.tenantID = opts.tenantID;
17
+ this.user = opts.user;
18
+ }
19
+ getCacheKey(collection) {
20
+ return collection;
21
+ }
22
+ async load(collection, id) {
23
+ const key = this.getCacheKey(collection);
24
+ let cache = this.caches.get(key);
25
+ if (!cache) {
26
+ cache = /* @__PURE__ */ new Map();
27
+ this.caches.set(key, cache);
28
+ }
29
+ if (cache.has(id)) {
30
+ return cache.get(id);
31
+ }
32
+ let pendingSet = this.pending.get(key);
33
+ if (!pendingSet) {
34
+ pendingSet = /* @__PURE__ */ new Set();
35
+ this.pending.set(key, pendingSet);
36
+ }
37
+ pendingSet.add(id);
38
+ cache.set(id, void 0);
39
+ if (!this.flushScheduled) {
40
+ this.flushScheduled = true;
41
+ queueMicrotask(() => {
42
+ this.flushScheduled = false;
43
+ this.flushAll();
44
+ });
45
+ }
46
+ return new Promise((resolve) => {
47
+ this.waiting.set(`${key}:${id}`, resolve);
48
+ });
49
+ }
50
+ async flushAll() {
51
+ for (const [key, ids] of this.pending) {
52
+ if (ids.size === 0) continue;
53
+ const cache = this.caches.get(key);
54
+ const docs = await this.db.find({
55
+ collection: key,
56
+ where: { id: { in: Array.from(ids) } },
57
+ limit: ids.size,
58
+ tenantID: this.tenantID,
59
+ draft: !!this.user
60
+ });
61
+ for (const doc of docs.docs || []) {
62
+ if (doc && doc.id) {
63
+ cache.set(doc.id, doc);
64
+ const resolve = this.waiting.get(`${key}:${doc.id}`);
65
+ if (resolve) {
66
+ resolve(doc);
67
+ this.waiting.delete(`${key}:${doc.id}`);
68
+ }
69
+ }
70
+ }
71
+ }
72
+ for (const [keyId, resolve] of this.waiting) {
73
+ resolve(void 0);
74
+ }
75
+ this.waiting.clear();
76
+ this.pending.clear();
77
+ }
78
+ resolveOne(collection, id) {
79
+ return this.caches.get(this.getCacheKey(collection))?.get(id);
80
+ }
81
+ };
82
+ var GraphQLJSON = new GraphQLScalarType({
83
+ name: "JSON",
84
+ description: "Arbitrary JSON value",
85
+ serialize(value) {
86
+ return value;
87
+ },
88
+ parseValue(value) {
89
+ return value;
90
+ },
91
+ parseLiteral(ast) {
92
+ switch (ast.kind) {
93
+ case Kind.STRING:
94
+ return ast.value;
95
+ case Kind.INT:
96
+ case Kind.FLOAT:
97
+ return parseFloat(ast.value);
98
+ case Kind.BOOLEAN:
99
+ return ast.value;
100
+ case Kind.OBJECT: {
101
+ const obj = {};
102
+ for (const field of ast.fields) {
103
+ obj[field.name.value] = GraphQLJSON.parseLiteral(field.value);
104
+ }
105
+ return obj;
106
+ }
107
+ case Kind.LIST:
108
+ return ast.values.map((v) => GraphQLJSON.parseLiteral(v));
109
+ case Kind.NULL:
110
+ return null;
111
+ default:
112
+ return null;
113
+ }
114
+ }
115
+ });
116
+ function depthLimit(maxDepth) {
117
+ return (validationContext) => {
118
+ let depth = 0;
119
+ return {
120
+ Field() {
121
+ depth++;
122
+ if (depth > maxDepth) {
123
+ validationContext.reportError(
124
+ new Error(`Query exceeds max depth of ${maxDepth}`)
125
+ );
126
+ }
127
+ },
128
+ leaveField() {
129
+ depth--;
130
+ }
131
+ };
132
+ };
133
+ }
134
+ function toPascal(slug) {
135
+ return slug.split(/[-_]/).map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join("");
136
+ }
137
+ function toCamel(slug) {
138
+ const p = toPascal(slug);
139
+ return p.charAt(0).toLowerCase() + p.slice(1);
140
+ }
141
+ function toSingular(slug) {
142
+ return slug.endsWith("s") && slug.length > 1 ? slug.slice(0, -1) : slug;
143
+ }
144
+ async function checkGraphQLAccess(collection, operation, context) {
145
+ const accessRule = collection.access?.[operation];
146
+ if (context.apiKey) {
147
+ if (context.apiKey.permissions?.length > 0) {
148
+ const resource = collection.slug;
149
+ const action = operation === "read" ? "read" : operation === "create" ? "create" : "update";
150
+ const permission = `${resource}:${action}`;
151
+ if (!hasApiKeyPermission(context.apiKey.permissions, permission) && !hasApiKeyPermission(context.apiKey.permissions, `${resource}:admin`)) {
152
+ return { allowed: false };
153
+ }
154
+ return { allowed: true };
155
+ }
156
+ if (accessRule) {
157
+ const result2 = await evaluateAccess(accessRule, {
158
+ req: context.req,
159
+ user: context.user,
160
+ tenantID: context.tenantID
161
+ });
162
+ if (typeof result2 === "boolean") {
163
+ return { allowed: result2 };
164
+ }
165
+ return { allowed: true, extraWhere: result2 };
166
+ }
167
+ return { allowed: true };
168
+ }
169
+ if (context.user) {
170
+ const resource = collection.slug;
171
+ const action = operation === "read" ? "read" : operation === "create" ? "create" : operation === "update" ? "update" : "delete";
172
+ const permission = `${resource}:${action}`;
173
+ const userHasPermission = hasPermission(
174
+ { id: context.user.id, email: context.user.email, role: context.user.role },
175
+ permission
176
+ );
177
+ if (!userHasPermission && !hasPermission(
178
+ { id: context.user.id, email: context.user.email, role: context.user.role },
179
+ `${resource}:admin`
180
+ )) {
181
+ if (!accessRule) {
182
+ return { allowed: false };
183
+ }
184
+ }
185
+ }
186
+ if (!accessRule) {
187
+ if (!context.user) {
188
+ return { allowed: false };
189
+ }
190
+ return { allowed: true };
191
+ }
192
+ const result = await evaluateAccess(accessRule, {
193
+ req: context.req,
194
+ user: context.user,
195
+ tenantID: context.tenantID
196
+ });
197
+ if (typeof result === "boolean") {
198
+ return { allowed: result };
199
+ }
200
+ return { allowed: true, extraWhere: result };
201
+ }
202
+ async function checkGlobalAccess(global, operation, context) {
203
+ const accessRule = global.access?.[operation];
204
+ if (context.apiKey) {
205
+ if (context.apiKey.permissions?.length > 0) {
206
+ const resource = global.slug;
207
+ const permission = `${resource}:${operation}`;
208
+ if (!hasApiKeyPermission(context.apiKey.permissions, permission) && !hasApiKeyPermission(context.apiKey.permissions, `${resource}:admin`) && !hasApiKeyPermission(context.apiKey.permissions, `${resource}:*`)) {
209
+ return { allowed: false };
210
+ }
211
+ return { allowed: true };
212
+ }
213
+ if (accessRule) {
214
+ const result2 = await evaluateAccess(accessRule, {
215
+ req: context.req,
216
+ user: context.user,
217
+ tenantID: context.tenantID
218
+ });
219
+ return { allowed: typeof result2 === "boolean" ? result2 : true };
220
+ }
221
+ return { allowed: true };
222
+ }
223
+ if (!accessRule) {
224
+ if (!context.user) {
225
+ return { allowed: false };
226
+ }
227
+ const userRole = context.user.role;
228
+ if (userRole === "super_admin" || userRole === "admin") {
229
+ return { allowed: true };
230
+ }
231
+ return { allowed: false };
232
+ }
233
+ const result = await evaluateAccess(accessRule, {
234
+ req: context.req,
235
+ user: context.user,
236
+ tenantID: context.tenantID
237
+ });
238
+ if (typeof result === "boolean") {
239
+ return { allowed: result };
240
+ }
241
+ return { allowed: true };
242
+ }
243
+ function resolveMediaUrl(url, origin) {
244
+ if (!url) return null;
245
+ if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("blob:") || url.startsWith("data:")) return url;
246
+ const base = (process.env.KYRO_BASE_URL || origin || "http://localhost:4321").replace(/\/+$/, "");
247
+ return `${base}${url.startsWith("/") ? "" : "/"}${url}`;
248
+ }
249
+ function processMediaDoc(doc, origin) {
250
+ if (!doc) return doc;
251
+ if (doc.url) doc.url = resolveMediaUrl(doc.url, origin);
252
+ if (doc.thumbnailUrl) doc.thumbnailUrl = resolveMediaUrl(doc.thumbnailUrl, origin);
253
+ return doc;
254
+ }
255
+ function fieldToGraphQLType(field, registry, collectionTypes, isInputType = false) {
256
+ switch (field.type) {
257
+ case "text":
258
+ case "email":
259
+ case "password":
260
+ case "textarea":
261
+ case "color":
262
+ case "code":
263
+ case "markdown":
264
+ case "date":
265
+ case "select":
266
+ case "radio":
267
+ return GraphQLString;
268
+ case "upload": {
269
+ const uploadField = field;
270
+ if (isInputType) {
271
+ return uploadField.hasMany ? new GraphQLList(GraphQLString) : GraphQLString;
272
+ }
273
+ if (uploadField.relationTo && collectionTypes?.[uploadField.relationTo]) {
274
+ const refType = collectionTypes[uploadField.relationTo];
275
+ return uploadField.hasMany ? new GraphQLList(refType) : refType;
276
+ }
277
+ return GraphQLJSON;
278
+ }
279
+ case "image": {
280
+ if (isInputType) return GraphQLString;
281
+ const imageField = field;
282
+ if (imageField.relationTo && collectionTypes?.[imageField.relationTo]) {
283
+ return collectionTypes[imageField.relationTo];
284
+ }
285
+ return GraphQLJSON;
286
+ }
287
+ case "number":
288
+ return field.integer ? GraphQLInt : GraphQLFloat;
289
+ case "checkbox":
290
+ return GraphQLBoolean;
291
+ case "json":
292
+ case "richtext":
293
+ case "blocks":
294
+ case "tabs":
295
+ return isInputType ? GraphQLJSON : GraphQLJSON;
296
+ case "relationship":
297
+ if (typeof field.relationTo === "string") {
298
+ if (isInputType) {
299
+ return field.hasMany ? new GraphQLList(GraphQLString) : GraphQLString;
300
+ }
301
+ if (collectionTypes?.[field.relationTo]) {
302
+ return field.hasMany ? new GraphQLList(collectionTypes[field.relationTo]) : collectionTypes[field.relationTo];
303
+ }
304
+ const relatedCollection = registry.getCollection(field.relationTo);
305
+ if (relatedCollection) {
306
+ return new GraphQLObjectType({
307
+ name: `${toPascal(field.relationTo)}Ref`,
308
+ fields: () => ({
309
+ id: { type: GraphQLString },
310
+ ...buildFieldsFromCollection(relatedCollection, registry, collectionTypes)
311
+ })
312
+ });
313
+ }
314
+ }
315
+ return GraphQLString;
316
+ case "array":
317
+ return new GraphQLList(GraphQLString);
318
+ case "group":
319
+ return isInputType ? GraphQLJSON : GraphQLJSON;
320
+ default:
321
+ return GraphQLString;
322
+ }
323
+ }
324
+ function buildFieldsFromCollection(config, registry, collectionTypes) {
325
+ const fields = {};
326
+ for (const field of config.fields) {
327
+ if (field.name && field.admin?.hidden !== true) {
328
+ const fieldConfig = buildFieldConfig(field, registry, collectionTypes);
329
+ if (fieldConfig) {
330
+ fields[field.name] = fieldConfig;
331
+ }
332
+ }
333
+ }
334
+ return fields;
335
+ }
336
+ function buildFieldConfig(field, registry, collectionTypes) {
337
+ if (!field.name) return null;
338
+ const deprecationReason = field.deprecated || void 0;
339
+ if (field.type === "upload") {
340
+ const gqlType2 = fieldToGraphQLType(field, registry, collectionTypes, false);
341
+ const uploadField = field;
342
+ return {
343
+ type: field.required ? new GraphQLNonNull(gqlType2) : gqlType2,
344
+ description: field.admin?.description || field.label,
345
+ deprecationReason,
346
+ resolve: async (source, args, ctx) => {
347
+ const loader = ctx?.relationLoader;
348
+ const value = source?.[uploadField.name];
349
+ const origin = ctx?.req?.url ? new URL(ctx.req.url).origin : void 0;
350
+ if (!value) return null;
351
+ if (uploadField.hasMany) {
352
+ const items = Array.isArray(value) ? value : [];
353
+ return Promise.all(items.map(async (item) => {
354
+ const id2 = typeof item === "string" ? item : item?.id;
355
+ if (!id2) return processMediaDoc(item, origin);
356
+ if (typeof item === "object" && item?.url) return processMediaDoc(item, origin);
357
+ if (loader) {
358
+ const cached = loader.resolveOne(uploadField.relationTo, id2);
359
+ if (cached) return processMediaDoc(cached, origin);
360
+ const loaded = await loader.load(uploadField.relationTo, id2);
361
+ if (loaded) return processMediaDoc(loaded, origin);
362
+ }
363
+ return { id: id2 };
364
+ }));
365
+ }
366
+ const id = typeof value === "string" ? value : value?.id;
367
+ if (!id) return processMediaDoc(value, origin);
368
+ if (typeof value === "object" && value?.url) return processMediaDoc(value, origin);
369
+ if (loader) {
370
+ const cached = loader.resolveOne(uploadField.relationTo, id);
371
+ if (cached) return processMediaDoc(cached, origin);
372
+ const loaded = await loader.load(uploadField.relationTo, id);
373
+ if (loaded) return processMediaDoc(loaded, origin);
374
+ }
375
+ return { id };
376
+ }
377
+ };
378
+ }
379
+ if (field.type === "relationship" && !field.hasMany) {
380
+ const gqlType2 = fieldToGraphQLType(field, registry, collectionTypes, false);
381
+ return {
382
+ type: field.required ? new GraphQLNonNull(gqlType2) : gqlType2,
383
+ description: field.admin?.description || field.label,
384
+ deprecationReason,
385
+ resolve: async (source, args, ctx) => {
386
+ const loader = ctx?.relationLoader;
387
+ const relField = field;
388
+ const id = source?.[relField.name];
389
+ if (!id) return null;
390
+ if (loader && typeof id === "string") {
391
+ const cached = loader.resolveOne(relField.relationTo, id);
392
+ if (cached) return cached;
393
+ const loaded = await loader.load(relField.relationTo, id);
394
+ if (loaded) return loaded;
395
+ }
396
+ return { id };
397
+ }
398
+ };
399
+ }
400
+ if (field.type === "relationship" && field.hasMany) {
401
+ const gqlType2 = fieldToGraphQLType(field, registry, collectionTypes, false);
402
+ return {
403
+ type: gqlType2,
404
+ description: field.admin?.description || field.label,
405
+ deprecationReason,
406
+ resolve: async (source, args, ctx) => {
407
+ const loader = ctx?.relationLoader;
408
+ const relField = field;
409
+ const ids = source?.[relField.name] || [];
410
+ if (!ids.length) return [];
411
+ if (loader) {
412
+ const results = [];
413
+ for (const id of ids) {
414
+ const cached = loader.resolveOne(relField.relationTo, id);
415
+ if (cached) results.push(cached);
416
+ else {
417
+ const loaded = await loader.load(relField.relationTo, id);
418
+ results.push(loaded || { id });
419
+ }
420
+ }
421
+ return results;
422
+ }
423
+ return ids.map((id) => ({ id }));
424
+ }
425
+ };
426
+ }
427
+ const gqlType = fieldToGraphQLType(field, registry, collectionTypes, false);
428
+ return {
429
+ type: field.required ? new GraphQLNonNull(gqlType) : gqlType,
430
+ description: field.admin?.description || field.label,
431
+ deprecationReason
432
+ };
433
+ }
434
+ function buildGraphQLSchema(options) {
435
+ const { registry, db, user, req, tenantID, apiKey, settings } = options;
436
+ const apiAccess = settings?.access?.apiAccess;
437
+ if (apiAccess?.graphqlEnabled === false) {
438
+ throw new Error("GraphQL API is disabled");
439
+ }
440
+ const collections = registry.getCollections();
441
+ const globals = registry.getGlobals();
442
+ const collectionTypes = {};
443
+ const collectionInputTypes = {};
444
+ for (const collection of collections) {
445
+ collectionTypes[collection.slug] = new GraphQLObjectType({
446
+ name: toPascal(toSingular(collection.slug)),
447
+ fields: () => ({
448
+ id: { type: GraphQLString },
449
+ ...buildFieldsFromCollection(collection, registry, collectionTypes),
450
+ ...collection.timestamps ? {
451
+ createdAt: { type: GraphQLString },
452
+ updatedAt: { type: GraphQLString }
453
+ } : {},
454
+ ...collection.tenantScoped ? {
455
+ tenantID: { type: GraphQLString }
456
+ } : {}
457
+ })
458
+ });
459
+ const inputFields = {};
460
+ for (const field of collection.fields) {
461
+ if (field.name && field.name !== "id") {
462
+ inputFields[field.name] = {
463
+ type: fieldToGraphQLType(field, registry, collectionTypes, true)
464
+ };
465
+ }
466
+ }
467
+ collectionInputTypes[collection.slug] = new GraphQLInputObjectType({
468
+ name: `${toPascal(toSingular(collection.slug))}Input`,
469
+ fields: () => inputFields
470
+ });
471
+ }
472
+ const globalTypes = {};
473
+ const globalInputTypes = {};
474
+ for (const global of globals) {
475
+ globalTypes[global.slug] = new GraphQLObjectType({
476
+ name: `${toPascal(global.slug)}Global`,
477
+ fields: () => ({
478
+ id: { type: GraphQLString },
479
+ ...buildFieldsFromCollection(
480
+ { slug: global.slug, fields: global.fields },
481
+ registry,
482
+ collectionTypes
483
+ )
484
+ })
485
+ });
486
+ globalInputTypes[global.slug] = new GraphQLInputObjectType({
487
+ name: `${toPascal(global.slug)}GlobalInput`,
488
+ fields: () => {
489
+ const inputFields = {};
490
+ for (const field of global.fields) {
491
+ if (field.name && field.name !== "id") {
492
+ inputFields[field.name] = {
493
+ type: fieldToGraphQLType(field, registry, collectionTypes, true)
494
+ };
495
+ }
496
+ }
497
+ return inputFields;
498
+ }
499
+ });
500
+ }
501
+ const queryFields = {};
502
+ for (const collection of collections) {
503
+ const type = collectionTypes[collection.slug];
504
+ if (!type) continue;
505
+ queryFields[toCamel(collection.slug)] = {
506
+ type: new GraphQLObjectType({
507
+ name: `${toPascal(toSingular(collection.slug))}FindResult`,
508
+ fields: {
509
+ docs: { type: new GraphQLList(type) },
510
+ totalDocs: { type: GraphQLInt },
511
+ page: { type: GraphQLInt },
512
+ totalPages: { type: GraphQLInt },
513
+ hasNextPage: { type: GraphQLBoolean },
514
+ hasPrevPage: { type: GraphQLBoolean }
515
+ }
516
+ }),
517
+ args: {
518
+ where: { type: GraphQLString },
519
+ sort: { type: GraphQLString },
520
+ limit: { type: GraphQLInt },
521
+ page: { type: GraphQLInt },
522
+ draft: { type: GraphQLBoolean }
523
+ },
524
+ resolve: async (_, args, context) => {
525
+ const access = await checkGraphQLAccess(collection, "read", {
526
+ user: context.user,
527
+ req: context.req,
528
+ tenantID: context.tenantID,
529
+ apiKey: context.apiKey
530
+ });
531
+ if (!access.allowed) {
532
+ throw new Error("Access denied");
533
+ }
534
+ if (context.tenantID) {
535
+ db.setTenantContext({ tenantId: context.tenantID, userId: context.user?.id ?? "", role: context.user?.role, isSuperAdmin: context.user?.role === "super_admin" });
536
+ }
537
+ let where = {};
538
+ if (args.where) {
539
+ try {
540
+ where = JSON.parse(args.where);
541
+ } catch {
542
+ }
543
+ }
544
+ if (access.extraWhere) {
545
+ where = { ...where, ...access.extraWhere };
546
+ }
547
+ const isDraft = args.draft ?? !!context.user;
548
+ return db.find({
549
+ collection: collection.slug,
550
+ where,
551
+ sort: args.sort,
552
+ limit: args.limit || 10,
553
+ page: args.page || 1,
554
+ tenantID: context.tenantID,
555
+ draft: isDraft
556
+ });
557
+ }
558
+ };
559
+ queryFields[toCamel(toSingular(collection.slug))] = {
560
+ type,
561
+ args: {
562
+ id: { type: GraphQLString },
563
+ slug: { type: GraphQLString },
564
+ draft: { type: GraphQLBoolean }
565
+ },
566
+ resolve: async (_, args, context) => {
567
+ if (!args.id && !args.slug) {
568
+ throw new Error("Either id or slug is required");
569
+ }
570
+ const access = await checkGraphQLAccess(collection, "read", {
571
+ user: context.user,
572
+ req: context.req,
573
+ tenantID: context.tenantID,
574
+ apiKey: context.apiKey
575
+ });
576
+ if (!access.allowed) {
577
+ throw new Error("Access denied");
578
+ }
579
+ if (context.tenantID) {
580
+ db.setTenantContext({ tenantId: context.tenantID, userId: context.user?.id ?? "", role: context.user?.role, isSuperAdmin: context.user?.role === "super_admin" });
581
+ }
582
+ const isDraft = args.draft ?? !!context.user;
583
+ if (args.id) {
584
+ return db.findByID({
585
+ collection: collection.slug,
586
+ id: args.id,
587
+ tenantID: context.tenantID,
588
+ draft: isDraft
589
+ });
590
+ }
591
+ const result = await db.find({
592
+ collection: collection.slug,
593
+ where: { slug: { equals: args.slug } },
594
+ limit: 1,
595
+ page: 1,
596
+ tenantID: context.tenantID,
597
+ draft: isDraft
598
+ });
599
+ return result.docs?.[0] || null;
600
+ }
601
+ };
602
+ queryFields[`count${toPascal(collection.slug)}`] = {
603
+ type: new GraphQLObjectType({
604
+ name: `${toPascal(toSingular(collection.slug))}Count`,
605
+ fields: {
606
+ totalDocs: { type: GraphQLInt }
607
+ }
608
+ }),
609
+ args: {
610
+ where: { type: GraphQLString }
611
+ },
612
+ resolve: async (_, args, context) => {
613
+ const access = await checkGraphQLAccess(collection, "read", {
614
+ user: context.user,
615
+ req: context.req,
616
+ tenantID: context.tenantID,
617
+ apiKey: context.apiKey
618
+ });
619
+ if (!access.allowed) {
620
+ return { totalDocs: 0 };
621
+ }
622
+ let where = {};
623
+ if (args.where) {
624
+ try {
625
+ where = JSON.parse(args.where);
626
+ } catch {
627
+ }
628
+ }
629
+ const count = await db.count({
630
+ collection: collection.slug,
631
+ where,
632
+ tenantID: context.tenantID
633
+ });
634
+ return { totalDocs: count };
635
+ }
636
+ };
637
+ }
638
+ for (const global of globals) {
639
+ const type = globalTypes[global.slug];
640
+ if (!type) continue;
641
+ queryFields[toCamel(toSingular(global.slug))] = {
642
+ type,
643
+ resolve: async (_, args, context) => {
644
+ const access = await checkGlobalAccess(global, "read", {
645
+ user: context.user,
646
+ req: context.req,
647
+ tenantID: context.tenantID,
648
+ apiKey: context.apiKey
649
+ });
650
+ if (!access.allowed) {
651
+ throw new Error("Access denied: cannot read global");
652
+ }
653
+ if (context.tenantID) {
654
+ db.setTenantContext({ tenantId: context.tenantID, userId: context.user?.id ?? "", role: context.user?.role, isSuperAdmin: context.user?.role === "super_admin" });
655
+ }
656
+ return db.findOne({
657
+ collection: `_globals_${global.slug}`,
658
+ where: {},
659
+ tenantID: context.tenantID
660
+ });
661
+ }
662
+ };
663
+ }
664
+ const Query = new GraphQLObjectType({
665
+ name: "Query",
666
+ fields: queryFields
667
+ });
668
+ const mutationFields = {};
669
+ for (const collection of collections) {
670
+ const type = collectionTypes[collection.slug];
671
+ const inputType = collectionInputTypes[collection.slug];
672
+ if (!type || !inputType) continue;
673
+ mutationFields[`create${toPascal(toSingular(collection.slug))}`] = {
674
+ type: new GraphQLObjectType({
675
+ name: `${toPascal(toSingular(collection.slug))}CreateResult`,
676
+ fields: {
677
+ doc: { type },
678
+ message: { type: GraphQLString }
679
+ }
680
+ }),
681
+ args: {
682
+ data: { type: new GraphQLNonNull(inputType) }
683
+ },
684
+ resolve: async (_, args, context) => {
685
+ const access = await checkGraphQLAccess(collection, "create", {
686
+ user: context.user,
687
+ req: context.req,
688
+ tenantID: context.tenantID,
689
+ apiKey: context.apiKey
690
+ });
691
+ if (!access.allowed) {
692
+ throw new Error("Access denied: cannot create");
693
+ }
694
+ if (context.tenantID) {
695
+ db.setTenantContext({ tenantId: context.tenantID, userId: context.user?.id ?? "", role: context.user?.role, isSuperAdmin: context.user?.role === "super_admin" });
696
+ }
697
+ const schema = registry.getCreateZodSchema(collection.slug);
698
+ const validated = schema.parse(args.data);
699
+ const doc = await db.create({
700
+ collection: collection.slug,
701
+ data: validated,
702
+ tenantID: context.tenantID
703
+ });
704
+ return { doc, message: "Created successfully" };
705
+ }
706
+ };
707
+ mutationFields[`update${toPascal(toSingular(collection.slug))}`] = {
708
+ type: new GraphQLObjectType({
709
+ name: `${toPascal(toSingular(collection.slug))}UpdateResult`,
710
+ fields: {
711
+ doc: { type },
712
+ message: { type: GraphQLString }
713
+ }
714
+ }),
715
+ args: {
716
+ id: { type: new GraphQLNonNull(GraphQLString) },
717
+ data: { type: new GraphQLNonNull(inputType) },
718
+ baseUpdatedAt: { type: GraphQLString }
719
+ },
720
+ resolve: async (_, args, context) => {
721
+ const access = await checkGraphQLAccess(collection, "update", {
722
+ user: context.user,
723
+ req: context.req,
724
+ tenantID: context.tenantID,
725
+ apiKey: context.apiKey
726
+ });
727
+ if (!access.allowed) {
728
+ throw new Error("Access denied: cannot update");
729
+ }
730
+ if (context.tenantID) {
731
+ db.setTenantContext({ tenantId: context.tenantID, userId: context.user?.id ?? "", role: context.user?.role, isSuperAdmin: context.user?.role === "super_admin" });
732
+ }
733
+ if (args.baseUpdatedAt) {
734
+ const originalDoc = await db.findByID({
735
+ collection: collection.slug,
736
+ id: args.id,
737
+ tenantID: context.tenantID,
738
+ draft: true
739
+ });
740
+ if (originalDoc && originalDoc.updatedAt && args.baseUpdatedAt !== originalDoc.updatedAt) {
741
+ throw new Error(`Revision conflict: document has changed since ${args.baseUpdatedAt}. Current updatedAt: ${originalDoc.updatedAt}`);
742
+ }
743
+ }
744
+ const schema = registry.getUpdateZodSchema(collection.slug);
745
+ const validated = schema.parse(args.data);
746
+ const doc = await db.update({
747
+ collection: collection.slug,
748
+ id: args.id,
749
+ data: validated,
750
+ tenantID: context.tenantID
751
+ });
752
+ return { doc, message: "Updated successfully" };
753
+ }
754
+ };
755
+ mutationFields[`delete${toPascal(toSingular(collection.slug))}`] = {
756
+ type: new GraphQLObjectType({
757
+ name: `${toPascal(toSingular(collection.slug))}DeleteResult`,
758
+ fields: {
759
+ doc: { type },
760
+ message: { type: GraphQLString }
761
+ }
762
+ }),
763
+ args: {
764
+ id: { type: new GraphQLNonNull(GraphQLString) }
765
+ },
766
+ resolve: async (_, args, context) => {
767
+ const access = await checkGraphQLAccess(collection, "delete", {
768
+ user: context.user,
769
+ req: context.req,
770
+ tenantID: context.tenantID,
771
+ apiKey: context.apiKey
772
+ });
773
+ if (!access.allowed) {
774
+ throw new Error("Access denied: cannot delete");
775
+ }
776
+ if (context.tenantID) {
777
+ db.setTenantContext({ tenantId: context.tenantID, userId: context.user?.id ?? "", role: context.user?.role, isSuperAdmin: context.user?.role === "super_admin" });
778
+ }
779
+ const doc = await db.delete({
780
+ collection: collection.slug,
781
+ id: args.id,
782
+ tenantID: context.tenantID
783
+ });
784
+ return { doc, message: "Deleted successfully" };
785
+ }
786
+ };
787
+ }
788
+ for (const global of globals) {
789
+ const inputType = globalInputTypes[global.slug];
790
+ if (!inputType) continue;
791
+ mutationFields[`update${toPascal(global.slug)}`] = {
792
+ type: new GraphQLObjectType({
793
+ name: `${toPascal(global.slug)}UpdateResult`,
794
+ fields: {
795
+ doc: { type: globalTypes[global.slug] || GraphQLString },
796
+ message: { type: GraphQLString }
797
+ }
798
+ }),
799
+ args: {
800
+ data: { type: new GraphQLNonNull(inputType) }
801
+ },
802
+ resolve: async (_, args, context) => {
803
+ const access = await checkGlobalAccess(global, "update", {
804
+ user: context.user,
805
+ req: context.req,
806
+ tenantID: context.tenantID,
807
+ apiKey: context.apiKey
808
+ });
809
+ if (!access.allowed) {
810
+ throw new Error("Access denied: cannot update global");
811
+ }
812
+ if (context.tenantID) {
813
+ db.setTenantContext({ tenantId: context.tenantID, userId: context.user?.id ?? "", role: context.user?.role, isSuperAdmin: context.user?.role === "super_admin" });
814
+ }
815
+ const doc = await db.findOne({
816
+ collection: `_globals_${global.slug}`,
817
+ where: {},
818
+ tenantID: context.tenantID
819
+ });
820
+ let result;
821
+ if (doc) {
822
+ result = await db.update({
823
+ collection: `_globals_${global.slug}`,
824
+ id: doc.id,
825
+ data: args.data,
826
+ tenantID: context.tenantID
827
+ });
828
+ } else {
829
+ result = await db.create({
830
+ collection: `_globals_${global.slug}`,
831
+ data: args.data,
832
+ tenantID: context.tenantID
833
+ });
834
+ }
835
+ return { doc: result, message: "Updated successfully" };
836
+ }
837
+ };
838
+ }
839
+ const Mutation = new GraphQLObjectType({
840
+ name: "Mutation",
841
+ fields: mutationFields
842
+ });
843
+ return new GraphQLSchema({
844
+ query: Query,
845
+ mutation: Mutation
846
+ });
847
+ }
848
+ function createGraphQLSchema(registry, db, options) {
849
+ return buildGraphQLSchema({
850
+ registry,
851
+ db,
852
+ user: options?.user,
853
+ req: options?.req,
854
+ tenantID: options?.tenantID,
855
+ apiKey: options?.apiKey
856
+ });
857
+ }
858
+
859
+ export { RelationLoader, buildGraphQLSchema, createGraphQLSchema, depthLimit };
860
+ //# sourceMappingURL=chunk-5RPRLTTN.js.map
861
+ //# sourceMappingURL=chunk-5RPRLTTN.js.map