@classytic/mongokit 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +221 -7
  2. package/dist/actions/index.cjs +479 -0
  3. package/dist/actions/index.cjs.map +1 -0
  4. package/dist/actions/index.d.cts +3 -0
  5. package/dist/actions/index.d.ts +3 -0
  6. package/dist/actions/index.js +473 -0
  7. package/dist/actions/index.js.map +1 -0
  8. package/dist/index-BfVJZF-3.d.cts +337 -0
  9. package/dist/index-CgOJ2pqz.d.ts +337 -0
  10. package/dist/index.cjs +2142 -0
  11. package/dist/index.cjs.map +1 -0
  12. package/dist/index.d.cts +239 -0
  13. package/dist/index.d.ts +239 -0
  14. package/dist/index.js +2108 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/memory-cache-DG2oSSbx.d.ts +142 -0
  17. package/dist/memory-cache-DqfFfKes.d.cts +142 -0
  18. package/dist/pagination/PaginationEngine.cjs +375 -0
  19. package/dist/pagination/PaginationEngine.cjs.map +1 -0
  20. package/dist/pagination/PaginationEngine.d.cts +117 -0
  21. package/dist/pagination/PaginationEngine.d.ts +117 -0
  22. package/dist/pagination/PaginationEngine.js +369 -0
  23. package/dist/pagination/PaginationEngine.js.map +1 -0
  24. package/dist/plugins/index.cjs +874 -0
  25. package/dist/plugins/index.cjs.map +1 -0
  26. package/dist/plugins/index.d.cts +275 -0
  27. package/dist/plugins/index.d.ts +275 -0
  28. package/dist/plugins/index.js +857 -0
  29. package/dist/plugins/index.js.map +1 -0
  30. package/dist/types-Nxhmi1aI.d.cts +510 -0
  31. package/dist/types-Nxhmi1aI.d.ts +510 -0
  32. package/dist/utils/index.cjs +667 -0
  33. package/dist/utils/index.cjs.map +1 -0
  34. package/dist/utils/index.d.cts +189 -0
  35. package/dist/utils/index.d.ts +189 -0
  36. package/dist/utils/index.js +643 -0
  37. package/dist/utils/index.js.map +1 -0
  38. package/package.json +44 -21
  39. package/src/Repository.js +0 -296
  40. package/src/actions/aggregate.js +0 -266
  41. package/src/actions/create.js +0 -59
  42. package/src/actions/delete.js +0 -88
  43. package/src/actions/index.js +0 -11
  44. package/src/actions/read.js +0 -188
  45. package/src/actions/update.js +0 -176
  46. package/src/hooks/lifecycle.js +0 -146
  47. package/src/index.js +0 -71
  48. package/src/pagination/PaginationEngine.js +0 -348
  49. package/src/pagination/utils/cursor.js +0 -119
  50. package/src/pagination/utils/filter.js +0 -42
  51. package/src/pagination/utils/limits.js +0 -82
  52. package/src/pagination/utils/sort.js +0 -101
  53. package/src/plugins/aggregate-helpers.plugin.js +0 -71
  54. package/src/plugins/audit-log.plugin.js +0 -60
  55. package/src/plugins/batch-operations.plugin.js +0 -66
  56. package/src/plugins/field-filter.plugin.js +0 -27
  57. package/src/plugins/index.js +0 -19
  58. package/src/plugins/method-registry.plugin.js +0 -140
  59. package/src/plugins/mongo-operations.plugin.js +0 -317
  60. package/src/plugins/soft-delete.plugin.js +0 -46
  61. package/src/plugins/subdocument.plugin.js +0 -66
  62. package/src/plugins/timestamp.plugin.js +0 -19
  63. package/src/plugins/validation-chain.plugin.js +0 -145
  64. package/src/types.d.ts +0 -87
  65. package/src/utils/error.js +0 -12
  66. package/src/utils/field-selection.js +0 -156
  67. package/src/utils/index.js +0 -12
  68. package/types/Repository.d.ts +0 -95
  69. package/types/Repository.d.ts.map +0 -1
  70. package/types/actions/aggregate.d.ts +0 -112
  71. package/types/actions/aggregate.d.ts.map +0 -1
  72. package/types/actions/create.d.ts +0 -21
  73. package/types/actions/create.d.ts.map +0 -1
  74. package/types/actions/delete.d.ts +0 -37
  75. package/types/actions/delete.d.ts.map +0 -1
  76. package/types/actions/index.d.ts +0 -6
  77. package/types/actions/index.d.ts.map +0 -1
  78. package/types/actions/read.d.ts +0 -135
  79. package/types/actions/read.d.ts.map +0 -1
  80. package/types/actions/update.d.ts +0 -58
  81. package/types/actions/update.d.ts.map +0 -1
  82. package/types/hooks/lifecycle.d.ts +0 -44
  83. package/types/hooks/lifecycle.d.ts.map +0 -1
  84. package/types/index.d.ts +0 -25
  85. package/types/index.d.ts.map +0 -1
  86. package/types/pagination/PaginationEngine.d.ts +0 -386
  87. package/types/pagination/PaginationEngine.d.ts.map +0 -1
  88. package/types/pagination/utils/cursor.d.ts +0 -40
  89. package/types/pagination/utils/cursor.d.ts.map +0 -1
  90. package/types/pagination/utils/filter.d.ts +0 -28
  91. package/types/pagination/utils/filter.d.ts.map +0 -1
  92. package/types/pagination/utils/limits.d.ts +0 -64
  93. package/types/pagination/utils/limits.d.ts.map +0 -1
  94. package/types/pagination/utils/sort.d.ts +0 -41
  95. package/types/pagination/utils/sort.d.ts.map +0 -1
  96. package/types/plugins/aggregate-helpers.plugin.d.ts +0 -6
  97. package/types/plugins/aggregate-helpers.plugin.d.ts.map +0 -1
  98. package/types/plugins/audit-log.plugin.d.ts +0 -6
  99. package/types/plugins/audit-log.plugin.d.ts.map +0 -1
  100. package/types/plugins/batch-operations.plugin.d.ts +0 -6
  101. package/types/plugins/batch-operations.plugin.d.ts.map +0 -1
  102. package/types/plugins/field-filter.plugin.d.ts +0 -6
  103. package/types/plugins/field-filter.plugin.d.ts.map +0 -1
  104. package/types/plugins/index.d.ts +0 -11
  105. package/types/plugins/index.d.ts.map +0 -1
  106. package/types/plugins/method-registry.plugin.d.ts +0 -3
  107. package/types/plugins/method-registry.plugin.d.ts.map +0 -1
  108. package/types/plugins/mongo-operations.plugin.d.ts +0 -4
  109. package/types/plugins/mongo-operations.plugin.d.ts.map +0 -1
  110. package/types/plugins/soft-delete.plugin.d.ts +0 -6
  111. package/types/plugins/soft-delete.plugin.d.ts.map +0 -1
  112. package/types/plugins/subdocument.plugin.d.ts +0 -6
  113. package/types/plugins/subdocument.plugin.d.ts.map +0 -1
  114. package/types/plugins/timestamp.plugin.d.ts +0 -6
  115. package/types/plugins/timestamp.plugin.d.ts.map +0 -1
  116. package/types/plugins/validation-chain.plugin.d.ts +0 -31
  117. package/types/plugins/validation-chain.plugin.d.ts.map +0 -1
  118. package/types/utils/error.d.ts +0 -11
  119. package/types/utils/error.d.ts.map +0 -1
  120. package/types/utils/field-selection.d.ts +0 -9
  121. package/types/utils/field-selection.d.ts.map +0 -1
  122. package/types/utils/index.d.ts +0 -2
  123. package/types/utils/index.d.ts.map +0 -1
@@ -0,0 +1,643 @@
1
+ import mongoose2 from 'mongoose';
2
+
3
+ // src/utils/field-selection.ts
4
+ function getFieldsForUser(user, preset) {
5
+ if (!preset) {
6
+ throw new Error("Field preset is required");
7
+ }
8
+ const fields = [...preset.public || []];
9
+ if (user) {
10
+ fields.push(...preset.authenticated || []);
11
+ const roles = Array.isArray(user.roles) ? user.roles : user.roles ? [user.roles] : [];
12
+ if (roles.includes("admin") || roles.includes("superadmin")) {
13
+ fields.push(...preset.admin || []);
14
+ }
15
+ }
16
+ return [...new Set(fields)];
17
+ }
18
+ function getMongooseProjection(user, preset) {
19
+ const fields = getFieldsForUser(user, preset);
20
+ return fields.join(" ");
21
+ }
22
+ function filterObject(obj, allowedFields) {
23
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
24
+ return obj;
25
+ }
26
+ const filtered = {};
27
+ for (const field of allowedFields) {
28
+ if (field in obj) {
29
+ filtered[field] = obj[field];
30
+ }
31
+ }
32
+ return filtered;
33
+ }
34
+ function filterResponseData(data, preset, user = null) {
35
+ const allowedFields = getFieldsForUser(user, preset);
36
+ if (Array.isArray(data)) {
37
+ return data.map((item) => filterObject(item, allowedFields));
38
+ }
39
+ return filterObject(data, allowedFields);
40
+ }
41
+ function createFieldPreset(config) {
42
+ return {
43
+ public: config.public || [],
44
+ authenticated: config.authenticated || [],
45
+ admin: config.admin || []
46
+ };
47
+ }
48
+ var QueryParser = class {
49
+ operators = {
50
+ eq: "$eq",
51
+ ne: "$ne",
52
+ gt: "$gt",
53
+ gte: "$gte",
54
+ lt: "$lt",
55
+ lte: "$lte",
56
+ in: "$in",
57
+ nin: "$nin",
58
+ like: "$regex",
59
+ contains: "$regex",
60
+ regex: "$regex",
61
+ exists: "$exists",
62
+ size: "$size",
63
+ type: "$type"
64
+ };
65
+ /**
66
+ * Dangerous MongoDB operators that should never be accepted from user input
67
+ * Security: Prevent NoSQL injection attacks
68
+ */
69
+ dangerousOperators = ["$where", "$function", "$accumulator", "$expr"];
70
+ /**
71
+ * Parse query parameters into MongoDB query format
72
+ */
73
+ parseQuery(query) {
74
+ const {
75
+ page,
76
+ limit = 20,
77
+ sort = "-createdAt",
78
+ populate,
79
+ search,
80
+ after,
81
+ cursor,
82
+ ...filters
83
+ } = query || {};
84
+ const parsed = {
85
+ filters: this._parseFilters(filters),
86
+ limit: parseInt(String(limit), 10),
87
+ sort: this._parseSort(sort),
88
+ populate,
89
+ search
90
+ };
91
+ if (after || cursor) {
92
+ parsed.after = after || cursor;
93
+ } else if (page !== void 0) {
94
+ parsed.page = parseInt(String(page), 10);
95
+ } else {
96
+ parsed.page = 1;
97
+ }
98
+ const orGroup = this._parseOr(query);
99
+ if (orGroup) {
100
+ parsed.filters = { ...parsed.filters, $or: orGroup };
101
+ }
102
+ parsed.filters = this._enhanceWithBetween(parsed.filters);
103
+ return parsed;
104
+ }
105
+ /**
106
+ * Parse sort parameter
107
+ * Converts string like '-createdAt' to { createdAt: -1 }
108
+ * Handles multiple sorts: '-createdAt,name' → { createdAt: -1, name: 1 }
109
+ */
110
+ _parseSort(sort) {
111
+ if (!sort) return void 0;
112
+ if (typeof sort === "object") return sort;
113
+ const sortObj = {};
114
+ const fields = sort.split(",").map((s) => s.trim());
115
+ for (const field of fields) {
116
+ if (field.startsWith("-")) {
117
+ sortObj[field.substring(1)] = -1;
118
+ } else {
119
+ sortObj[field] = 1;
120
+ }
121
+ }
122
+ return sortObj;
123
+ }
124
+ /**
125
+ * Parse standard filter parameter (filter[field]=value)
126
+ */
127
+ _parseFilters(filters) {
128
+ const parsedFilters = {};
129
+ for (const [key, value] of Object.entries(filters)) {
130
+ if (this.dangerousOperators.includes(key) || key.startsWith("$") && !["$or", "$and"].includes(key)) {
131
+ console.warn(`[mongokit] Blocked dangerous operator: ${key}`);
132
+ continue;
133
+ }
134
+ if (["page", "limit", "sort", "populate", "search", "select", "lean", "includeDeleted"].includes(key)) {
135
+ continue;
136
+ }
137
+ const operatorMatch = key.match(/^(.+)\[(.+)\]$/);
138
+ if (operatorMatch) {
139
+ const [, , operator] = operatorMatch;
140
+ if (this.dangerousOperators.includes("$" + operator)) {
141
+ console.warn(`[mongokit] Blocked dangerous operator: ${operator}`);
142
+ continue;
143
+ }
144
+ this._handleOperatorSyntax(parsedFilters, {}, operatorMatch, value);
145
+ continue;
146
+ }
147
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
148
+ this._handleBracketSyntax(key, value, parsedFilters);
149
+ } else {
150
+ parsedFilters[key] = this._convertValue(value);
151
+ }
152
+ }
153
+ return parsedFilters;
154
+ }
155
+ /**
156
+ * Handle operator syntax: field[operator]=value
157
+ */
158
+ _handleOperatorSyntax(filters, regexFields, operatorMatch, value) {
159
+ const [, field, operator] = operatorMatch;
160
+ if (operator.toLowerCase() === "options" && regexFields[field]) {
161
+ const fieldValue = filters[field];
162
+ if (typeof fieldValue === "object" && fieldValue !== null && "$regex" in fieldValue) {
163
+ fieldValue.$options = value;
164
+ }
165
+ return;
166
+ }
167
+ if (operator.toLowerCase() === "contains" || operator.toLowerCase() === "like") {
168
+ filters[field] = { $regex: new RegExp(String(value), "i") };
169
+ regexFields[field] = true;
170
+ return;
171
+ }
172
+ const mongoOperator = this._toMongoOperator(operator);
173
+ if (this.dangerousOperators.includes(mongoOperator)) {
174
+ console.warn(`[mongokit] Blocked dangerous operator in field[${operator}]: ${mongoOperator}`);
175
+ return;
176
+ }
177
+ if (mongoOperator === "$eq") {
178
+ filters[field] = value;
179
+ } else if (mongoOperator === "$regex") {
180
+ filters[field] = { $regex: value };
181
+ regexFields[field] = true;
182
+ } else {
183
+ if (typeof filters[field] !== "object" || filters[field] === null || Array.isArray(filters[field])) {
184
+ filters[field] = {};
185
+ }
186
+ let processedValue;
187
+ const op = operator.toLowerCase();
188
+ if (["gt", "gte", "lt", "lte", "size"].includes(op)) {
189
+ processedValue = parseFloat(String(value));
190
+ if (isNaN(processedValue)) return;
191
+ } else if (op === "in" || op === "nin") {
192
+ processedValue = Array.isArray(value) ? value : String(value).split(",").map((v) => v.trim());
193
+ } else {
194
+ processedValue = this._convertValue(value);
195
+ }
196
+ filters[field][mongoOperator] = processedValue;
197
+ }
198
+ }
199
+ /**
200
+ * Handle bracket syntax with object value
201
+ */
202
+ _handleBracketSyntax(field, operators, parsedFilters) {
203
+ if (!parsedFilters[field]) {
204
+ parsedFilters[field] = {};
205
+ }
206
+ for (const [operator, value] of Object.entries(operators)) {
207
+ if (operator === "between") {
208
+ parsedFilters[field].between = value;
209
+ continue;
210
+ }
211
+ if (this.operators[operator]) {
212
+ const mongoOperator = this.operators[operator];
213
+ let processedValue;
214
+ if (["gt", "gte", "lt", "lte", "size"].includes(operator)) {
215
+ processedValue = parseFloat(String(value));
216
+ if (isNaN(processedValue)) continue;
217
+ } else if (operator === "in" || operator === "nin") {
218
+ processedValue = Array.isArray(value) ? value : String(value).split(",").map((v) => v.trim());
219
+ } else if (operator === "like" || operator === "contains") {
220
+ processedValue = value !== void 0 && value !== null ? new RegExp(String(value), "i") : /.*/;
221
+ } else {
222
+ processedValue = this._convertValue(value);
223
+ }
224
+ parsedFilters[field][mongoOperator] = processedValue;
225
+ }
226
+ }
227
+ }
228
+ /**
229
+ * Convert operator to MongoDB format
230
+ */
231
+ _toMongoOperator(operator) {
232
+ const op = operator.toLowerCase();
233
+ return op.startsWith("$") ? op : "$" + op;
234
+ }
235
+ /**
236
+ * Convert values based on operator type
237
+ */
238
+ _convertValue(value) {
239
+ if (value === null || value === void 0) return value;
240
+ if (Array.isArray(value)) return value.map((v) => this._convertValue(v));
241
+ if (typeof value === "object") return value;
242
+ const stringValue = String(value);
243
+ if (stringValue === "true") return true;
244
+ if (stringValue === "false") return false;
245
+ if (mongoose2.Types.ObjectId.isValid(stringValue) && stringValue.length === 24) {
246
+ return stringValue;
247
+ }
248
+ return stringValue;
249
+ }
250
+ /**
251
+ * Parse $or conditions
252
+ */
253
+ _parseOr(query) {
254
+ const orArray = [];
255
+ const raw = query?.or || query?.OR || query?.$or;
256
+ if (!raw) return void 0;
257
+ const items = Array.isArray(raw) ? raw : typeof raw === "object" ? Object.values(raw) : [];
258
+ for (const item of items) {
259
+ if (typeof item === "object" && item) {
260
+ orArray.push(this._parseFilters(item));
261
+ }
262
+ }
263
+ return orArray.length ? orArray : void 0;
264
+ }
265
+ /**
266
+ * Enhance filters with between operator
267
+ */
268
+ _enhanceWithBetween(filters) {
269
+ const output = { ...filters };
270
+ for (const [key, value] of Object.entries(filters || {})) {
271
+ if (value && typeof value === "object" && "between" in value) {
272
+ const between = value.between;
273
+ const [from, to] = String(between).split(",").map((s) => s.trim());
274
+ const fromDate = from ? new Date(from) : void 0;
275
+ const toDate = to ? new Date(to) : void 0;
276
+ const range = {};
277
+ if (fromDate && !isNaN(fromDate.getTime())) range.$gte = fromDate;
278
+ if (toDate && !isNaN(toDate.getTime())) range.$lte = toDate;
279
+ output[key] = range;
280
+ }
281
+ }
282
+ return output;
283
+ }
284
+ };
285
+ var queryParser_default = new QueryParser();
286
+ function isMongooseSchema(value) {
287
+ return value instanceof mongoose2.Schema;
288
+ }
289
+ function isPlainObject(value) {
290
+ return Object.prototype.toString.call(value) === "[object Object]";
291
+ }
292
+ function isObjectIdType(t) {
293
+ return t === mongoose2.Schema.Types.ObjectId || t === mongoose2.Types.ObjectId;
294
+ }
295
+ function buildCrudSchemasFromMongooseSchema(mongooseSchema, options = {}) {
296
+ const tree = mongooseSchema?.obj || {};
297
+ const jsonCreate = buildJsonSchemaForCreate(tree, options);
298
+ const jsonUpdate = buildJsonSchemaForUpdate(jsonCreate, options);
299
+ const jsonParams = {
300
+ type: "object",
301
+ properties: { id: { type: "string", pattern: "^[0-9a-fA-F]{24}$" } },
302
+ required: ["id"]
303
+ };
304
+ const jsonQuery = buildJsonSchemaForQuery(tree, options);
305
+ const crudSchemas = {
306
+ create: { body: jsonCreate },
307
+ update: { body: jsonUpdate, params: jsonParams },
308
+ get: { params: jsonParams },
309
+ list: { query: jsonQuery },
310
+ remove: { params: jsonParams }
311
+ };
312
+ return { createBody: jsonCreate, updateBody: jsonUpdate, params: jsonParams, listQuery: jsonQuery, crudSchemas };
313
+ }
314
+ function buildCrudSchemasFromModel(mongooseModel, options = {}) {
315
+ if (!mongooseModel || !mongooseModel.schema) {
316
+ throw new Error("Invalid mongoose model");
317
+ }
318
+ return buildCrudSchemasFromMongooseSchema(mongooseModel.schema, options);
319
+ }
320
+ function getImmutableFields(options = {}) {
321
+ const immutable = [];
322
+ const fieldRules = options?.fieldRules || {};
323
+ Object.entries(fieldRules).forEach(([field, rules]) => {
324
+ if (rules.immutable || rules.immutableAfterCreate) {
325
+ immutable.push(field);
326
+ }
327
+ });
328
+ (options?.update?.omitFields || []).forEach((f) => {
329
+ if (!immutable.includes(f)) immutable.push(f);
330
+ });
331
+ return immutable;
332
+ }
333
+ function getSystemManagedFields(options = {}) {
334
+ const systemManaged = [];
335
+ const fieldRules = options?.fieldRules || {};
336
+ Object.entries(fieldRules).forEach(([field, rules]) => {
337
+ if (rules.systemManaged) {
338
+ systemManaged.push(field);
339
+ }
340
+ });
341
+ return systemManaged;
342
+ }
343
+ function isFieldUpdateAllowed(fieldName, options = {}) {
344
+ const immutableFields = getImmutableFields(options);
345
+ const systemManagedFields = getSystemManagedFields(options);
346
+ return !immutableFields.includes(fieldName) && !systemManagedFields.includes(fieldName);
347
+ }
348
+ function validateUpdateBody(body = {}, options = {}) {
349
+ const violations = [];
350
+ const immutableFields = getImmutableFields(options);
351
+ const systemManagedFields = getSystemManagedFields(options);
352
+ Object.keys(body).forEach((field) => {
353
+ if (immutableFields.includes(field)) {
354
+ violations.push({ field, reason: "Field is immutable" });
355
+ } else if (systemManagedFields.includes(field)) {
356
+ violations.push({ field, reason: "Field is system-managed" });
357
+ }
358
+ });
359
+ return {
360
+ valid: violations.length === 0,
361
+ violations
362
+ };
363
+ }
364
+ function jsonTypeFor(def, options, seen) {
365
+ if (Array.isArray(def)) {
366
+ if (def[0] === mongoose2.Schema.Types.Mixed) {
367
+ return { type: "array", items: { type: "object", additionalProperties: true } };
368
+ }
369
+ return { type: "array", items: jsonTypeFor(def[0] ?? String, options, seen) };
370
+ }
371
+ if (isPlainObject(def) && "type" in def) {
372
+ const typedDef = def;
373
+ if (typedDef.enum && Array.isArray(typedDef.enum) && typedDef.enum.length) {
374
+ return { type: "string", enum: typedDef.enum.map(String) };
375
+ }
376
+ if (Array.isArray(typedDef.type)) {
377
+ const inner = typedDef.type[0] !== void 0 ? typedDef.type[0] : String;
378
+ if (inner === mongoose2.Schema.Types.Mixed) {
379
+ return { type: "array", items: { type: "object", additionalProperties: true } };
380
+ }
381
+ return { type: "array", items: jsonTypeFor(inner, options, seen) };
382
+ }
383
+ if (typedDef.type === String) return { type: "string" };
384
+ if (typedDef.type === Number) return { type: "number" };
385
+ if (typedDef.type === Boolean) return { type: "boolean" };
386
+ if (typedDef.type === Date) {
387
+ const mode = options?.dateAs || "datetime";
388
+ return mode === "date" ? { type: "string", format: "date" } : { type: "string", format: "date-time" };
389
+ }
390
+ if (typedDef.type === Map || typedDef.type === mongoose2.Schema.Types.Map) {
391
+ const ofSchema = jsonTypeFor(typedDef.of || String, options, seen);
392
+ return { type: "object", additionalProperties: ofSchema };
393
+ }
394
+ if (typedDef.type === mongoose2.Schema.Types.Mixed) {
395
+ return { type: "object", additionalProperties: true };
396
+ }
397
+ if (isObjectIdType(typedDef.type)) {
398
+ return { type: "string", pattern: "^[0-9a-fA-F]{24}$" };
399
+ }
400
+ if (isMongooseSchema(typedDef.type)) {
401
+ const obj = typedDef.type.obj;
402
+ if (obj && typeof obj === "object") {
403
+ if (seen.has(obj)) return { type: "object", additionalProperties: true };
404
+ seen.add(obj);
405
+ return convertTreeToJsonSchema(obj, options, seen);
406
+ }
407
+ }
408
+ }
409
+ if (def === String) return { type: "string" };
410
+ if (def === Number) return { type: "number" };
411
+ if (def === Boolean) return { type: "boolean" };
412
+ if (def === Date) {
413
+ const mode = options?.dateAs || "datetime";
414
+ return mode === "date" ? { type: "string", format: "date" } : { type: "string", format: "date-time" };
415
+ }
416
+ if (isObjectIdType(def)) return { type: "string", pattern: "^[0-9a-fA-F]{24}$" };
417
+ if (isPlainObject(def)) {
418
+ if (seen.has(def)) return { type: "object", additionalProperties: true };
419
+ seen.add(def);
420
+ return convertTreeToJsonSchema(def, options, seen);
421
+ }
422
+ return {};
423
+ }
424
+ function convertTreeToJsonSchema(tree, options, seen = /* @__PURE__ */ new WeakSet()) {
425
+ if (!tree || typeof tree !== "object") {
426
+ return { type: "object", properties: {} };
427
+ }
428
+ if (seen.has(tree)) {
429
+ return { type: "object", additionalProperties: true };
430
+ }
431
+ seen.add(tree);
432
+ const properties = {};
433
+ const required = [];
434
+ for (const [key, val] of Object.entries(tree || {})) {
435
+ if (key === "__v" || key === "_id" || key === "id") continue;
436
+ const cfg = isPlainObject(val) && "type" in val ? val : { };
437
+ properties[key] = jsonTypeFor(val, options, seen);
438
+ if (cfg.required === true) required.push(key);
439
+ }
440
+ const schema = { type: "object", properties };
441
+ if (required.length) schema.required = required;
442
+ return schema;
443
+ }
444
+ function buildJsonSchemaForCreate(tree, options) {
445
+ const base = convertTreeToJsonSchema(tree, options, /* @__PURE__ */ new WeakSet());
446
+ const fieldsToOmit = /* @__PURE__ */ new Set(["createdAt", "updatedAt", "__v"]);
447
+ (options?.create?.omitFields || []).forEach((f) => fieldsToOmit.add(f));
448
+ const fieldRules = options?.fieldRules || {};
449
+ Object.entries(fieldRules).forEach(([field, rules]) => {
450
+ if (rules.systemManaged) {
451
+ fieldsToOmit.add(field);
452
+ }
453
+ });
454
+ fieldsToOmit.forEach((field) => {
455
+ if (base.properties?.[field]) {
456
+ delete base.properties[field];
457
+ }
458
+ if (base.required) {
459
+ base.required = base.required.filter((k) => k !== field);
460
+ }
461
+ });
462
+ const reqOv = options?.create?.requiredOverrides || {};
463
+ const optOv = options?.create?.optionalOverrides || {};
464
+ base.required = base.required || [];
465
+ for (const [k, v] of Object.entries(reqOv)) {
466
+ if (v && !base.required.includes(k)) base.required.push(k);
467
+ }
468
+ for (const [k, v] of Object.entries(optOv)) {
469
+ if (v && base.required) base.required = base.required.filter((x) => x !== k);
470
+ }
471
+ Object.entries(fieldRules).forEach(([field, rules]) => {
472
+ if (rules.optional && base.required) {
473
+ base.required = base.required.filter((x) => x !== field);
474
+ }
475
+ });
476
+ const schemaOverrides = options?.create?.schemaOverrides || {};
477
+ for (const [k, override] of Object.entries(schemaOverrides)) {
478
+ if (base.properties?.[k]) {
479
+ base.properties[k] = override;
480
+ }
481
+ }
482
+ if (options?.strictAdditionalProperties === true) {
483
+ base.additionalProperties = false;
484
+ }
485
+ return base;
486
+ }
487
+ function buildJsonSchemaForUpdate(createJson, options) {
488
+ const clone = JSON.parse(JSON.stringify(createJson));
489
+ delete clone.required;
490
+ const fieldsToOmit = /* @__PURE__ */ new Set();
491
+ (options?.update?.omitFields || []).forEach((f) => fieldsToOmit.add(f));
492
+ const fieldRules = options?.fieldRules || {};
493
+ Object.entries(fieldRules).forEach(([field, rules]) => {
494
+ if (rules.immutable || rules.immutableAfterCreate) {
495
+ fieldsToOmit.add(field);
496
+ }
497
+ });
498
+ fieldsToOmit.forEach((field) => {
499
+ if (clone.properties?.[field]) {
500
+ delete clone.properties[field];
501
+ }
502
+ });
503
+ if (options?.strictAdditionalProperties === true) {
504
+ clone.additionalProperties = false;
505
+ }
506
+ return clone;
507
+ }
508
+ function buildJsonSchemaForQuery(_tree, options) {
509
+ const basePagination = {
510
+ type: "object",
511
+ properties: {
512
+ page: { type: "string" },
513
+ limit: { type: "string" },
514
+ sort: { type: "string" },
515
+ populate: { type: "string" },
516
+ search: { type: "string" },
517
+ select: { type: "string" },
518
+ lean: { type: "string" },
519
+ includeDeleted: { type: "string" }
520
+ },
521
+ additionalProperties: true
522
+ };
523
+ const filterable = options?.query?.filterableFields || {};
524
+ for (const [k, v] of Object.entries(filterable)) {
525
+ if (basePagination.properties) {
526
+ basePagination.properties[k] = v && typeof v === "object" && "type" in v ? v : { type: "string" };
527
+ }
528
+ }
529
+ return basePagination;
530
+ }
531
+
532
+ // src/utils/error.ts
533
+ function createError(status, message) {
534
+ const error = new Error(message);
535
+ error.status = status;
536
+ return error;
537
+ }
538
+
539
+ // src/utils/memory-cache.ts
540
+ function createMemoryCache(maxEntries = 1e3) {
541
+ const cache = /* @__PURE__ */ new Map();
542
+ function cleanup() {
543
+ const now = Date.now();
544
+ for (const [key, entry] of cache) {
545
+ if (entry.expiresAt < now) {
546
+ cache.delete(key);
547
+ }
548
+ }
549
+ }
550
+ function evictOldest() {
551
+ if (cache.size >= maxEntries) {
552
+ const firstKey = cache.keys().next().value;
553
+ if (firstKey) cache.delete(firstKey);
554
+ }
555
+ }
556
+ return {
557
+ async get(key) {
558
+ cleanup();
559
+ const entry = cache.get(key);
560
+ if (!entry) return null;
561
+ if (entry.expiresAt < Date.now()) {
562
+ cache.delete(key);
563
+ return null;
564
+ }
565
+ return entry.value;
566
+ },
567
+ async set(key, value, ttl) {
568
+ cleanup();
569
+ evictOldest();
570
+ cache.set(key, {
571
+ value,
572
+ expiresAt: Date.now() + ttl * 1e3
573
+ });
574
+ },
575
+ async del(key) {
576
+ cache.delete(key);
577
+ },
578
+ async clear(pattern) {
579
+ if (!pattern) {
580
+ cache.clear();
581
+ return;
582
+ }
583
+ const regex = new RegExp(
584
+ "^" + pattern.replace(/\*/g, ".*").replace(/\?/g, ".") + "$"
585
+ );
586
+ for (const key of cache.keys()) {
587
+ if (regex.test(key)) {
588
+ cache.delete(key);
589
+ }
590
+ }
591
+ }
592
+ };
593
+ }
594
+
595
+ // src/utils/cache-keys.ts
596
+ function hashString(str) {
597
+ let hash = 5381;
598
+ for (let i = 0; i < str.length; i++) {
599
+ hash = (hash << 5) + hash ^ str.charCodeAt(i);
600
+ }
601
+ return (hash >>> 0).toString(16);
602
+ }
603
+ function stableStringify(obj) {
604
+ if (obj === null || obj === void 0) return "";
605
+ if (typeof obj !== "object") return String(obj);
606
+ if (Array.isArray(obj)) {
607
+ return "[" + obj.map(stableStringify).join(",") + "]";
608
+ }
609
+ const sorted = Object.keys(obj).sort().map((key) => `${key}:${stableStringify(obj[key])}`);
610
+ return "{" + sorted.join(",") + "}";
611
+ }
612
+ function byIdKey(prefix, model, id) {
613
+ return `${prefix}:id:${model}:${id}`;
614
+ }
615
+ function byQueryKey(prefix, model, query, options) {
616
+ const hashInput = stableStringify({ q: query, s: options?.select, p: options?.populate });
617
+ return `${prefix}:one:${model}:${hashString(hashInput)}`;
618
+ }
619
+ function listQueryKey(prefix, model, version, params) {
620
+ const hashInput = stableStringify({
621
+ f: params.filters,
622
+ s: params.sort,
623
+ pg: params.page,
624
+ lm: params.limit,
625
+ af: params.after,
626
+ sl: params.select,
627
+ pp: params.populate
628
+ });
629
+ return `${prefix}:list:${model}:${version}:${hashString(hashInput)}`;
630
+ }
631
+ function versionKey(prefix, model) {
632
+ return `${prefix}:ver:${model}`;
633
+ }
634
+ function modelPattern(prefix, model) {
635
+ return `${prefix}:*:${model}:*`;
636
+ }
637
+ function listPattern(prefix, model) {
638
+ return `${prefix}:list:${model}:*`;
639
+ }
640
+
641
+ export { buildCrudSchemasFromModel, buildCrudSchemasFromMongooseSchema, byIdKey, byQueryKey, createError, createFieldPreset, createMemoryCache, filterResponseData, getFieldsForUser, getImmutableFields, getMongooseProjection, getSystemManagedFields, isFieldUpdateAllowed, listPattern, listQueryKey, modelPattern, queryParser_default as queryParser, validateUpdateBody, versionKey };
642
+ //# sourceMappingURL=index.js.map
643
+ //# sourceMappingURL=index.js.map