@stndrds/schema 0.1.0-alpha.14

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 (128) hide show
  1. package/dist/chunk-3ABIOLKO.mjs +4624 -0
  2. package/dist/chunk-3IRX2BDY.mjs +3970 -0
  3. package/dist/chunk-4OTLPWSP.mjs +4448 -0
  4. package/dist/chunk-54ODQBUN.mjs +3867 -0
  5. package/dist/chunk-6HIA3FR2.mjs +4230 -0
  6. package/dist/chunk-6P3XHNLD.mjs +4171 -0
  7. package/dist/chunk-7LJECNAS.mjs +4167 -0
  8. package/dist/chunk-A2WNLUKV.mjs +4475 -0
  9. package/dist/chunk-AA3234RM.mjs +4475 -0
  10. package/dist/chunk-ADNXDLLD.mjs +3136 -0
  11. package/dist/chunk-B4DCDQUI.mjs +4695 -0
  12. package/dist/chunk-B4PSXY6I.mjs +4527 -0
  13. package/dist/chunk-BJHJBZCM.mjs +4228 -0
  14. package/dist/chunk-C3ZWTO6G.mjs +4474 -0
  15. package/dist/chunk-CLOGNKDD.mjs +4040 -0
  16. package/dist/chunk-EW4V63PA.mjs +3053 -0
  17. package/dist/chunk-FR2LCO6R.mjs +2485 -0
  18. package/dist/chunk-GJSF2RKL.mjs +2786 -0
  19. package/dist/chunk-GO5NPP2X.mjs +4726 -0
  20. package/dist/chunk-H3ZYJUDS.mjs +3050 -0
  21. package/dist/chunk-IDDLSFSK.mjs +4230 -0
  22. package/dist/chunk-JRADUJQ7.mjs +4726 -0
  23. package/dist/chunk-NEDR6N7R.mjs +3118 -0
  24. package/dist/chunk-NESPRMDF.mjs +2482 -0
  25. package/dist/chunk-NWFGRJBW.mjs +4612 -0
  26. package/dist/chunk-NXJ57GSN.mjs +2918 -0
  27. package/dist/chunk-O4C5FCTS.mjs +3961 -0
  28. package/dist/chunk-O4PRB27Q.mjs +2513 -0
  29. package/dist/chunk-OJDFNUCR.mjs +4463 -0
  30. package/dist/chunk-OSEKVBHC.mjs +4627 -0
  31. package/dist/chunk-QX4U6U6K.mjs +2484 -0
  32. package/dist/chunk-RMDQ6LKV.mjs +3046 -0
  33. package/dist/chunk-SBXKDATH.mjs +2673 -0
  34. package/dist/chunk-SKMP3AP3.mjs +2918 -0
  35. package/dist/chunk-STMS7WZD.mjs +2623 -0
  36. package/dist/chunk-T3T6PTFG.mjs +3057 -0
  37. package/dist/chunk-TPW72RAH.mjs +4624 -0
  38. package/dist/chunk-TUQEGNGV.mjs +2534 -0
  39. package/dist/chunk-TVKFS3YN.mjs +2449 -0
  40. package/dist/chunk-TZTH3BHG.mjs +3110 -0
  41. package/dist/chunk-W6MU3XPG.mjs +4612 -0
  42. package/dist/chunk-WL7Z3YFR.mjs +4603 -0
  43. package/dist/chunk-XNVVYHH3.mjs +4602 -0
  44. package/dist/chunk-XTA3WY64.mjs +2918 -0
  45. package/dist/chunk-YV7DEZFZ.mjs +2528 -0
  46. package/dist/chunk-ZLJPJND6.mjs +4474 -0
  47. package/dist/chunk-ZNZXTCEX.mjs +4234 -0
  48. package/dist/index.d.mts +1222 -0
  49. package/dist/index.d.ts +1222 -0
  50. package/dist/index.js +5320 -0
  51. package/dist/index.mjs +635 -0
  52. package/dist/runtime-2iKarXtl.d.mts +1924 -0
  53. package/dist/runtime-2iKarXtl.d.ts +1924 -0
  54. package/dist/runtime-4l2ddHZ7.d.mts +2242 -0
  55. package/dist/runtime-4l2ddHZ7.d.ts +2243 -0
  56. package/dist/runtime-8hKS6zAv.d.mts +2226 -0
  57. package/dist/runtime-8hKS6zAv.d.ts +2226 -0
  58. package/dist/runtime-B6yjtoR3.d.mts +4142 -0
  59. package/dist/runtime-B6yjtoR3.d.ts +4142 -0
  60. package/dist/runtime-BGCShrZB.d.mts +2001 -0
  61. package/dist/runtime-BGCShrZB.d.ts +2001 -0
  62. package/dist/runtime-BRW4NGAk.d.mts +1668 -0
  63. package/dist/runtime-BRW4NGAk.d.ts +1668 -0
  64. package/dist/runtime-BnfBr314.d.mts +1683 -0
  65. package/dist/runtime-BnfBr314.d.ts +1683 -0
  66. package/dist/runtime-BrqhiJUF.d.mts +4151 -0
  67. package/dist/runtime-BrqhiJUF.d.ts +4151 -0
  68. package/dist/runtime-Bvj8c-BE.d.mts +4277 -0
  69. package/dist/runtime-Bvj8c-BE.d.ts +4277 -0
  70. package/dist/runtime-C03qT4qU.d.mts +4267 -0
  71. package/dist/runtime-C03qT4qU.d.ts +4267 -0
  72. package/dist/runtime-CaCZ7mSf.d.mts +2974 -0
  73. package/dist/runtime-CaCZ7mSf.d.ts +2974 -0
  74. package/dist/runtime-CaIzNX0Z.d.mts +4091 -0
  75. package/dist/runtime-CaIzNX0Z.d.ts +4091 -0
  76. package/dist/runtime-ChPTgmLP.d.mts +4320 -0
  77. package/dist/runtime-ChPTgmLP.d.ts +4320 -0
  78. package/dist/runtime-CnImZ1Vv.d.mts +4267 -0
  79. package/dist/runtime-CnImZ1Vv.d.ts +4267 -0
  80. package/dist/runtime-Cp-B26Nj.d.mts +2890 -0
  81. package/dist/runtime-Cp-B26Nj.d.ts +2890 -0
  82. package/dist/runtime-Cq8jfk3c.d.mts +4277 -0
  83. package/dist/runtime-Cq8jfk3c.d.ts +4277 -0
  84. package/dist/runtime-CqDFXhhP.d.mts +1685 -0
  85. package/dist/runtime-CqDFXhhP.d.ts +1685 -0
  86. package/dist/runtime-CqtpZLdL.d.mts +4280 -0
  87. package/dist/runtime-CqtpZLdL.d.ts +4280 -0
  88. package/dist/runtime-D-4DblaZ.d.mts +4147 -0
  89. package/dist/runtime-D-4DblaZ.d.ts +4147 -0
  90. package/dist/runtime-D59sSqNl.d.mts +4146 -0
  91. package/dist/runtime-D59sSqNl.d.ts +4146 -0
  92. package/dist/runtime-DEfPk3wT.d.mts +1840 -0
  93. package/dist/runtime-DEfPk3wT.d.ts +1840 -0
  94. package/dist/runtime-DGV-7vES.d.mts +1685 -0
  95. package/dist/runtime-DGV-7vES.d.ts +1685 -0
  96. package/dist/runtime-DNacghqc.d.mts +3971 -0
  97. package/dist/runtime-DNacghqc.d.ts +3971 -0
  98. package/dist/runtime-DPLsUHYK.d.mts +3977 -0
  99. package/dist/runtime-DPLsUHYK.d.ts +3977 -0
  100. package/dist/runtime-DTxCw60F.d.mts +2973 -0
  101. package/dist/runtime-DTxCw60F.d.ts +2973 -0
  102. package/dist/runtime-DUXJ-zNS.d.mts +2788 -0
  103. package/dist/runtime-DUXJ-zNS.d.ts +2788 -0
  104. package/dist/runtime-DbljInhV.d.mts +2237 -0
  105. package/dist/runtime-DbljInhV.d.ts +2237 -0
  106. package/dist/runtime-DcH3y6Yu.d.mts +4272 -0
  107. package/dist/runtime-DcH3y6Yu.d.ts +4272 -0
  108. package/dist/runtime-DdBFz85g.d.mts +4229 -0
  109. package/dist/runtime-DdBFz85g.d.ts +4229 -0
  110. package/dist/runtime-DjMWhjkm.d.mts +4321 -0
  111. package/dist/runtime-DjMWhjkm.d.ts +4321 -0
  112. package/dist/runtime-Djz3fOBE.d.mts +2078 -0
  113. package/dist/runtime-Djz3fOBE.d.ts +2078 -0
  114. package/dist/runtime-Dli8g3Aq.d.mts +2082 -0
  115. package/dist/runtime-Dli8g3Aq.d.ts +2082 -0
  116. package/dist/runtime-a8J378im.d.mts +4123 -0
  117. package/dist/runtime-a8J378im.d.ts +4123 -0
  118. package/dist/runtime-dp3rb3Lf.d.mts +2968 -0
  119. package/dist/runtime-dp3rb3Lf.d.ts +2968 -0
  120. package/dist/runtime-iWXlSN_H.d.mts +1683 -0
  121. package/dist/runtime-iWXlSN_H.d.ts +1683 -0
  122. package/dist/runtime-yMql0npY.d.mts +4321 -0
  123. package/dist/runtime-yMql0npY.d.ts +4321 -0
  124. package/dist/runtime.d.mts +3 -0
  125. package/dist/runtime.d.ts +3 -0
  126. package/dist/runtime.js +3626 -0
  127. package/dist/runtime.mjs +48 -0
  128. package/package.json +58 -0
@@ -0,0 +1,2484 @@
1
+ // src/utils.ts
2
+ function generateId() {
3
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
4
+ return crypto.randomUUID();
5
+ }
6
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
7
+ const r = Math.random() * 16 | 0;
8
+ const v = c === "x" ? r : r & 3 | 8;
9
+ return v.toString(16);
10
+ });
11
+ }
12
+ function generatePrefixedId(prefix) {
13
+ return `${prefix}_${generateId()}`;
14
+ }
15
+
16
+ // src/runtime/mock-adapter.ts
17
+ function createMockObjectsRepository(stores) {
18
+ return {
19
+ findById(id) {
20
+ return Promise.resolve(stores.objects.get(id) ?? null);
21
+ },
22
+ findByName(tenantId, name) {
23
+ for (const obj of stores.objects.values()) {
24
+ if (obj.tenantId === tenantId && obj.name === name) {
25
+ return Promise.resolve(obj);
26
+ }
27
+ }
28
+ return Promise.resolve(null);
29
+ },
30
+ findSystemByName(name) {
31
+ for (const obj of stores.objects.values()) {
32
+ if (obj.system && obj.name === name) {
33
+ return Promise.resolve(obj);
34
+ }
35
+ }
36
+ return Promise.resolve(null);
37
+ },
38
+ create(data) {
39
+ const obj = {
40
+ id: generateId(),
41
+ tenantId: data.tenantId,
42
+ name: data.name,
43
+ label: data.label,
44
+ description: data.description,
45
+ system: data.system ?? false,
46
+ metadata: data.metadata,
47
+ createdAt: /* @__PURE__ */ new Date(),
48
+ updatedAt: /* @__PURE__ */ new Date()
49
+ };
50
+ stores.objects.set(obj.id, obj);
51
+ return Promise.resolve(obj);
52
+ },
53
+ update(id, data) {
54
+ const existing = stores.objects.get(id);
55
+ if (!existing) {
56
+ return Promise.reject(new Error(`Object ${id} not found`));
57
+ }
58
+ const updated = {
59
+ ...existing,
60
+ ...data,
61
+ updatedAt: /* @__PURE__ */ new Date()
62
+ };
63
+ stores.objects.set(id, updated);
64
+ return Promise.resolve(updated);
65
+ },
66
+ delete(id) {
67
+ stores.objects.delete(id);
68
+ return Promise.resolve();
69
+ },
70
+ list(tenantId) {
71
+ const results = Array.from(stores.objects.values()).filter(
72
+ (obj) => obj.tenantId === tenantId
73
+ );
74
+ return Promise.resolve(results);
75
+ },
76
+ upsert(data) {
77
+ for (const obj of stores.objects.values()) {
78
+ if (obj.system && obj.name === data.name) {
79
+ const updated = {
80
+ ...obj,
81
+ label: data.label,
82
+ description: data.description,
83
+ metadata: data.metadata,
84
+ updatedAt: /* @__PURE__ */ new Date()
85
+ };
86
+ stores.objects.set(obj.id, updated);
87
+ return Promise.resolve(updated);
88
+ }
89
+ }
90
+ const newObj = {
91
+ id: generateId(),
92
+ tenantId: data.tenantId,
93
+ name: data.name,
94
+ label: data.label,
95
+ description: data.description,
96
+ system: data.system,
97
+ metadata: data.metadata,
98
+ createdAt: /* @__PURE__ */ new Date(),
99
+ updatedAt: /* @__PURE__ */ new Date()
100
+ };
101
+ stores.objects.set(newObj.id, newObj);
102
+ return Promise.resolve(newObj);
103
+ }
104
+ };
105
+ }
106
+ function createMockAttributesRepository(stores) {
107
+ return {
108
+ findById(id) {
109
+ return Promise.resolve(stores.attributes.get(id) ?? null);
110
+ },
111
+ findByObjectId(objectId) {
112
+ const results = Array.from(stores.attributes.values()).filter(
113
+ (attr) => attr.objectId === objectId
114
+ );
115
+ return Promise.resolve(results);
116
+ },
117
+ create(data) {
118
+ const attr = {
119
+ id: generateId(),
120
+ objectId: data.objectId,
121
+ name: data.name,
122
+ label: data.label,
123
+ type: data.type,
124
+ system: data.system ?? false,
125
+ required: data.required ?? false,
126
+ unique: data.unique ?? false,
127
+ orderIndex: data.orderIndex ?? 0,
128
+ config: data.config ?? {},
129
+ createdAt: /* @__PURE__ */ new Date(),
130
+ updatedAt: /* @__PURE__ */ new Date()
131
+ };
132
+ stores.attributes.set(attr.id, attr);
133
+ return Promise.resolve(attr);
134
+ },
135
+ update(id, data) {
136
+ const existing = stores.attributes.get(id);
137
+ if (!existing) {
138
+ return Promise.reject(new Error(`Attribute ${id} not found`));
139
+ }
140
+ const updated = {
141
+ ...existing,
142
+ ...data,
143
+ updatedAt: /* @__PURE__ */ new Date()
144
+ };
145
+ stores.attributes.set(id, updated);
146
+ return Promise.resolve(updated);
147
+ },
148
+ delete(id) {
149
+ stores.attributes.delete(id);
150
+ return Promise.resolve();
151
+ },
152
+ deleteByNames(objectId, excludeNames) {
153
+ let count = 0;
154
+ for (const [id, attr] of stores.attributes.entries()) {
155
+ if (attr.objectId === objectId && !excludeNames.includes(attr.name)) {
156
+ stores.attributes.delete(id);
157
+ count++;
158
+ }
159
+ }
160
+ return Promise.resolve(count);
161
+ },
162
+ upsert(data) {
163
+ for (const attr of stores.attributes.values()) {
164
+ if (attr.objectId === data.objectId && attr.name === data.name) {
165
+ const updated = {
166
+ ...attr,
167
+ label: data.label ?? attr.label,
168
+ type: data.type ?? attr.type,
169
+ system: data.system ?? attr.system,
170
+ required: data.required ?? attr.required,
171
+ unique: data.unique ?? attr.unique,
172
+ orderIndex: data.orderIndex ?? attr.orderIndex,
173
+ config: data.config ?? attr.config,
174
+ updatedAt: /* @__PURE__ */ new Date()
175
+ };
176
+ stores.attributes.set(attr.id, updated);
177
+ return Promise.resolve(updated);
178
+ }
179
+ }
180
+ return this.create(data);
181
+ }
182
+ };
183
+ }
184
+ function createMockUserProfilesRepository(stores) {
185
+ return {
186
+ findById(id) {
187
+ return Promise.resolve(stores.userProfiles.get(id) ?? null);
188
+ },
189
+ findByAuthId(authId) {
190
+ for (const profile of stores.userProfiles.values()) {
191
+ if (profile.authId === authId) {
192
+ return Promise.resolve(profile);
193
+ }
194
+ }
195
+ return Promise.resolve(null);
196
+ },
197
+ findByEmail(tenantId, email) {
198
+ for (const profile of stores.userProfiles.values()) {
199
+ if (profile.tenantId === tenantId && profile.email === email) {
200
+ return Promise.resolve(profile);
201
+ }
202
+ }
203
+ return Promise.resolve(null);
204
+ },
205
+ create(data) {
206
+ const profile = {
207
+ id: generateId(),
208
+ tenantId: data.tenantId,
209
+ authId: data.authId,
210
+ email: data.email,
211
+ firstName: data.firstName,
212
+ lastName: data.lastName,
213
+ avatarUrl: data.avatarUrl,
214
+ role: data.role ?? "member",
215
+ status: data.status ?? "active",
216
+ createdAt: /* @__PURE__ */ new Date(),
217
+ updatedAt: /* @__PURE__ */ new Date()
218
+ };
219
+ stores.userProfiles.set(profile.id, profile);
220
+ return Promise.resolve(profile);
221
+ },
222
+ update(id, data) {
223
+ const existing = stores.userProfiles.get(id);
224
+ if (!existing) {
225
+ return Promise.reject(new Error(`UserProfile ${id} not found`));
226
+ }
227
+ const updated = {
228
+ ...existing,
229
+ ...data,
230
+ updatedAt: /* @__PURE__ */ new Date()
231
+ };
232
+ stores.userProfiles.set(id, updated);
233
+ return Promise.resolve(updated);
234
+ },
235
+ delete(id) {
236
+ stores.userProfiles.delete(id);
237
+ return Promise.resolve();
238
+ },
239
+ list(tenantId, options) {
240
+ let results = Array.from(stores.userProfiles.values()).filter((p) => p.tenantId === tenantId);
241
+ if (options?.limit) {
242
+ results = results.slice(options.offset ?? 0, (options.offset ?? 0) + options.limit);
243
+ }
244
+ return Promise.resolve(results);
245
+ },
246
+ updateLastLogin(id) {
247
+ const profile = stores.userProfiles.get(id);
248
+ if (profile) {
249
+ profile.lastLoginAt = /* @__PURE__ */ new Date();
250
+ stores.userProfiles.set(id, profile);
251
+ }
252
+ return Promise.resolve();
253
+ }
254
+ };
255
+ }
256
+ function createMockFilesRepository(stores) {
257
+ return {
258
+ findById(id) {
259
+ const file2 = stores.files.get(id);
260
+ if (file2?.deletedAt) return Promise.resolve(null);
261
+ return Promise.resolve(file2 ?? null);
262
+ },
263
+ create(data) {
264
+ const file2 = {
265
+ id: generateId(),
266
+ tenantId: data.tenantId,
267
+ name: data.name,
268
+ originalName: data.originalName,
269
+ mimeType: data.mimeType,
270
+ size: data.size,
271
+ storageProvider: data.storageProvider,
272
+ storagePath: data.storagePath,
273
+ storageBucket: data.storageBucket,
274
+ url: data.url,
275
+ uploadedBy: data.uploadedBy,
276
+ folderPath: data.folderPath,
277
+ tags: data.tags,
278
+ visibility: data.visibility ?? "private",
279
+ allowedUsers: data.allowedUsers,
280
+ createdAt: /* @__PURE__ */ new Date(),
281
+ updatedAt: /* @__PURE__ */ new Date()
282
+ };
283
+ stores.files.set(file2.id, file2);
284
+ return Promise.resolve(file2);
285
+ },
286
+ update(id, data) {
287
+ const existing = stores.files.get(id);
288
+ if (!existing) {
289
+ return Promise.reject(new Error(`File ${id} not found`));
290
+ }
291
+ const updated = {
292
+ ...existing,
293
+ ...data,
294
+ updatedAt: /* @__PURE__ */ new Date()
295
+ };
296
+ stores.files.set(id, updated);
297
+ return Promise.resolve(updated);
298
+ },
299
+ delete(id) {
300
+ const file2 = stores.files.get(id);
301
+ if (file2) {
302
+ file2.deletedAt = /* @__PURE__ */ new Date();
303
+ stores.files.set(id, file2);
304
+ }
305
+ return Promise.resolve();
306
+ },
307
+ hardDelete(id) {
308
+ stores.files.delete(id);
309
+ return Promise.resolve();
310
+ },
311
+ list(tenantId, options) {
312
+ let results = Array.from(stores.files.values()).filter(
313
+ (f) => f.tenantId === tenantId && !f.deletedAt
314
+ );
315
+ if (options?.mimeType) {
316
+ results = results.filter((f) => f.mimeType === options.mimeType);
317
+ }
318
+ if (options?.limit) {
319
+ results = results.slice(options.offset ?? 0, (options.offset ?? 0) + options.limit);
320
+ }
321
+ return Promise.resolve(results);
322
+ },
323
+ findByFolder(tenantId, folderPath) {
324
+ const results = Array.from(stores.files.values()).filter(
325
+ (f) => f.tenantId === tenantId && f.folderPath === folderPath && !f.deletedAt
326
+ );
327
+ return Promise.resolve(results);
328
+ },
329
+ findByUploader(uploadedBy) {
330
+ const results = Array.from(stores.files.values()).filter(
331
+ (f) => f.uploadedBy === uploadedBy && !f.deletedAt
332
+ );
333
+ return Promise.resolve(results);
334
+ }
335
+ };
336
+ }
337
+ function createMockObjectRecordsRepository(stores) {
338
+ return {
339
+ findById(id) {
340
+ const internal = stores.objectRecords.get(id);
341
+ if (!internal) return Promise.resolve(null);
342
+ const { tenantId: _, ...record } = internal;
343
+ return Promise.resolve(record);
344
+ },
345
+ create(data) {
346
+ const internal = {
347
+ id: generateId(),
348
+ tenantId: data.tenantId,
349
+ objectId: data.objectId,
350
+ values: data.data,
351
+ createdAt: /* @__PURE__ */ new Date(),
352
+ updatedAt: /* @__PURE__ */ new Date()
353
+ };
354
+ stores.objectRecords.set(internal.id, internal);
355
+ const { tenantId: _, ...record } = internal;
356
+ return Promise.resolve(record);
357
+ },
358
+ update(id, data) {
359
+ const existing = stores.objectRecords.get(id);
360
+ if (!existing) {
361
+ return Promise.reject(new Error(`ObjectRecord ${id} not found`));
362
+ }
363
+ const updated = {
364
+ ...existing,
365
+ values: { ...existing.values, ...data },
366
+ updatedAt: /* @__PURE__ */ new Date()
367
+ };
368
+ stores.objectRecords.set(id, updated);
369
+ const { tenantId: _, ...record } = updated;
370
+ return Promise.resolve(record);
371
+ },
372
+ delete(id) {
373
+ stores.objectRecords.delete(id);
374
+ return Promise.resolve();
375
+ },
376
+ list(tenantId, objectId, options) {
377
+ let results = Array.from(stores.objectRecords.values()).filter(
378
+ (r) => r.tenantId === tenantId && r.objectId === objectId
379
+ );
380
+ const total = results.length;
381
+ if (options?.limit) {
382
+ results = results.slice(options.offset ?? 0, (options.offset ?? 0) + options.limit);
383
+ }
384
+ const records = results.map(({ tenantId: _, ...r }) => r);
385
+ return Promise.resolve({ records, total });
386
+ },
387
+ search(tenantId, objectId, query, options) {
388
+ const lowerQuery = query.toLowerCase();
389
+ let results = Array.from(stores.objectRecords.values()).filter((r) => {
390
+ if (r.tenantId !== tenantId || r.objectId !== objectId) return false;
391
+ return Object.values(r.values).some(
392
+ (val) => String(val).toLowerCase().includes(lowerQuery)
393
+ );
394
+ });
395
+ const total = results.length;
396
+ if (options?.limit) {
397
+ results = results.slice(options.offset ?? 0, (options.offset ?? 0) + options.limit);
398
+ }
399
+ const records = results.map(({ tenantId: _, ...r }) => r);
400
+ return Promise.resolve({ records, total });
401
+ }
402
+ };
403
+ }
404
+ function createMockAdapter() {
405
+ const stores = {
406
+ objects: /* @__PURE__ */ new Map(),
407
+ attributes: /* @__PURE__ */ new Map(),
408
+ userProfiles: /* @__PURE__ */ new Map(),
409
+ files: /* @__PURE__ */ new Map(),
410
+ objectRecords: /* @__PURE__ */ new Map()
411
+ };
412
+ const adapter = {
413
+ objects: createMockObjectsRepository(stores),
414
+ attributes: createMockAttributesRepository(stores),
415
+ userProfiles: createMockUserProfilesRepository(stores),
416
+ files: createMockFilesRepository(stores),
417
+ objectRecords: createMockObjectRecordsRepository(stores),
418
+ async transaction(callback) {
419
+ return await callback(adapter);
420
+ },
421
+ // Expose stores for testing inspection
422
+ _stores: stores,
423
+ // Reset all stores (useful between tests)
424
+ reset() {
425
+ stores.objects.clear();
426
+ stores.attributes.clear();
427
+ stores.userProfiles.clear();
428
+ stores.files.clear();
429
+ stores.objectRecords.clear();
430
+ }
431
+ };
432
+ return adapter;
433
+ }
434
+
435
+ // src/runtime/services/file.service.ts
436
+ var FileService = class {
437
+ constructor(adapter, tenantId) {
438
+ this.adapter = adapter;
439
+ this.tenantId = tenantId;
440
+ }
441
+ /**
442
+ * Create a new file record (after upload to storage)
443
+ *
444
+ * @param data - File metadata
445
+ * @returns Created file record
446
+ *
447
+ * @example
448
+ * ```typescript
449
+ * const service = new FileService(adapter, "tenant-123");
450
+ *
451
+ * // After uploading to S3
452
+ * const file = await service.createFile({
453
+ * tenantId: "tenant-123",
454
+ * name: "contract-2025.pdf",
455
+ * originalName: "Contract Acme Corp 2025.pdf",
456
+ * mimeType: "application/pdf",
457
+ * size: 2458624,
458
+ * storageProvider: "s3",
459
+ * storagePath: "tenants/123/files/2025/contract.pdf",
460
+ * storageBucket: "my-app-files",
461
+ * url: "https://cdn.example.com/files/file-123",
462
+ * uploadedBy: "profile-456",
463
+ * visibility: "private"
464
+ * });
465
+ * ```
466
+ */
467
+ async createFile(data) {
468
+ if (data.tenantId !== this.tenantId) {
469
+ throw new Error(
470
+ `Tenant mismatch: service initialized with "${this.tenantId}" but data has "${data.tenantId}"`
471
+ );
472
+ }
473
+ return await this.adapter.files.create(data);
474
+ }
475
+ /**
476
+ * Get file by ID
477
+ */
478
+ async getFile(fileId) {
479
+ const file2 = await this.adapter.files.findById(fileId);
480
+ if (file2?.deletedAt) {
481
+ return null;
482
+ }
483
+ return file2;
484
+ }
485
+ /**
486
+ * Get file by ID or throw
487
+ */
488
+ async getFileOrThrow(fileId) {
489
+ const file2 = await this.getFile(fileId);
490
+ if (!file2) {
491
+ throw new Error(`File with id "${fileId}" not found`);
492
+ }
493
+ return file2;
494
+ }
495
+ /**
496
+ * Update file metadata
497
+ *
498
+ * @param fileId - File UUID
499
+ * @param data - Data to update
500
+ * @returns Updated file
501
+ */
502
+ async updateFile(fileId, data) {
503
+ await this.getFileOrThrow(fileId);
504
+ return await this.adapter.files.update(fileId, data);
505
+ }
506
+ /**
507
+ * Delete file (soft delete)
508
+ *
509
+ * @param fileId - File UUID
510
+ * @param options - Delete options
511
+ */
512
+ async deleteFile(fileId, options) {
513
+ if (options?.checkOwnership && options.userId) {
514
+ const file2 = await this.getFileOrThrow(fileId);
515
+ if (file2.uploadedBy !== options.userId) {
516
+ throw new Error("You can only delete files you uploaded");
517
+ }
518
+ }
519
+ if (options?.hard) {
520
+ await this.adapter.files.hardDelete(fileId);
521
+ } else {
522
+ await this.adapter.files.delete(fileId);
523
+ }
524
+ }
525
+ /**
526
+ * List files for the tenant
527
+ */
528
+ async listFiles(options) {
529
+ return await this.adapter.files.list(this.tenantId, options);
530
+ }
531
+ /**
532
+ * List files by folder
533
+ */
534
+ async listFilesByFolder(folderPath) {
535
+ return await this.adapter.files.findByFolder(this.tenantId, folderPath);
536
+ }
537
+ /**
538
+ * List files uploaded by a specific user
539
+ */
540
+ async listFilesByUploader(uploadedBy) {
541
+ return await this.adapter.files.findByUploader(uploadedBy);
542
+ }
543
+ /**
544
+ * Change file visibility
545
+ *
546
+ * @param fileId - File UUID
547
+ * @param visibility - New visibility level
548
+ * @param allowedUsers - Users allowed to access (if restricted)
549
+ */
550
+ async changeVisibility(fileId, visibility, allowedUsers) {
551
+ const updateData = { visibility };
552
+ if (visibility === "restricted" && allowedUsers) {
553
+ updateData.allowedUsers = allowedUsers;
554
+ }
555
+ return await this.updateFile(fileId, updateData);
556
+ }
557
+ /**
558
+ * Grant access to a file for specific users
559
+ *
560
+ * @param fileId - File UUID
561
+ * @param userIds - User IDs to grant access
562
+ */
563
+ async grantAccess(fileId, userIds) {
564
+ const file2 = await this.getFileOrThrow(fileId);
565
+ const currentAllowed = file2.allowedUsers || [];
566
+ const newAllowed = [.../* @__PURE__ */ new Set([...currentAllowed, ...userIds])];
567
+ return await this.updateFile(fileId, {
568
+ visibility: "restricted",
569
+ allowedUsers: newAllowed
570
+ });
571
+ }
572
+ /**
573
+ * Revoke access to a file for specific users
574
+ *
575
+ * @param fileId - File UUID
576
+ * @param userIds - User IDs to revoke access
577
+ */
578
+ async revokeAccess(fileId, userIds) {
579
+ const file2 = await this.getFileOrThrow(fileId);
580
+ const currentAllowed = file2.allowedUsers || [];
581
+ const newAllowed = currentAllowed.filter((id) => !userIds.includes(id));
582
+ return await this.updateFile(fileId, {
583
+ allowedUsers: newAllowed
584
+ });
585
+ }
586
+ /**
587
+ * Check if user has access to a file
588
+ *
589
+ * @param fileId - File UUID
590
+ * @param userId - User ID to check
591
+ * @returns true if user can access the file
592
+ */
593
+ async canAccess(fileId, userId) {
594
+ const file2 = await this.getFile(fileId);
595
+ if (!file2) {
596
+ return false;
597
+ }
598
+ if (file2.visibility === "public") {
599
+ return true;
600
+ }
601
+ if (file2.uploadedBy === userId) {
602
+ return true;
603
+ }
604
+ if (file2.visibility === "restricted") {
605
+ return file2.allowedUsers?.includes(userId) ?? false;
606
+ }
607
+ return false;
608
+ }
609
+ /**
610
+ * Move file to different folder
611
+ */
612
+ async moveToFolder(fileId, newFolderPath) {
613
+ return await this.updateFile(fileId, { folderPath: newFolderPath });
614
+ }
615
+ /**
616
+ * Add tags to file
617
+ */
618
+ async addTags(fileId, tags) {
619
+ const file2 = await this.getFileOrThrow(fileId);
620
+ const currentTags = file2.tags || [];
621
+ const newTags = [.../* @__PURE__ */ new Set([...currentTags, ...tags])];
622
+ return await this.updateFile(fileId, { tags: newTags });
623
+ }
624
+ /**
625
+ * Remove tags from file
626
+ */
627
+ async removeTags(fileId, tags) {
628
+ const file2 = await this.getFileOrThrow(fileId);
629
+ const currentTags = file2.tags || [];
630
+ const newTags = currentTags.filter((tag) => !tags.includes(tag));
631
+ return await this.updateFile(fileId, { tags: newTags });
632
+ }
633
+ };
634
+
635
+ // src/builders/attribute-builders.ts
636
+ import { z } from "zod";
637
+ var BaseAttributeBuilder = class {
638
+ constructor(type, name, label) {
639
+ this.validateVariableName(name);
640
+ this.attr = {
641
+ name,
642
+ label,
643
+ type,
644
+ required: false
645
+ };
646
+ }
647
+ /**
648
+ * Validate attribute name as valid variable identifier
649
+ * Accepts: camelCase, snake_case, PascalCase, UPPER_CASE
650
+ */
651
+ validateVariableName(name) {
652
+ const variableNameSchema = z.string().min(1, "Attribute name cannot be empty").max(63, "Attribute name is too long (max 63 characters)").regex(/^[a-zA-Z_][a-zA-Z0-9_]*$/, {
653
+ message: "Invalid attribute name format.\nName must be a valid variable identifier:\n \u2705 Valid: 'firstName', 'first_name', 'FirstName', 'FIRST_NAME'\n \u274C Invalid: 'first-name', 'first name', '123name', 'first.name'"
654
+ });
655
+ try {
656
+ variableNameSchema.parse(name);
657
+ } catch (error) {
658
+ if (error instanceof z.ZodError) {
659
+ throw new Error(`[AttributeBuilder] ${error.errors[0].message}`);
660
+ }
661
+ throw error;
662
+ }
663
+ }
664
+ setRequired(value) {
665
+ this.attr.required = value;
666
+ }
667
+ system() {
668
+ this.attr.system = true;
669
+ return this;
670
+ }
671
+ disabled() {
672
+ this.attr.disabled = true;
673
+ return this;
674
+ }
675
+ hidden() {
676
+ this.attr.hidden = true;
677
+ return this;
678
+ }
679
+ placeholder(value) {
680
+ this.attr.placeholder = value;
681
+ return this;
682
+ }
683
+ description(value) {
684
+ this.attr.description = value;
685
+ return this;
686
+ }
687
+ icon(value) {
688
+ this.attr.icon = value;
689
+ return this;
690
+ }
691
+ order(value) {
692
+ this.attr.order = value;
693
+ return this;
694
+ }
695
+ defaultValue(value) {
696
+ this.attr.defaultValue = value;
697
+ return this;
698
+ }
699
+ metadata(value) {
700
+ this.attr.metadata = value;
701
+ return this;
702
+ }
703
+ build() {
704
+ return this.attr;
705
+ }
706
+ };
707
+ var TextAttributeBuilder = class extends BaseAttributeBuilder {
708
+ constructor(name, label) {
709
+ super("text", name, label);
710
+ }
711
+ minLength(value) {
712
+ this.attr.minLength = value;
713
+ return this;
714
+ }
715
+ maxLength(value) {
716
+ this.attr.maxLength = value;
717
+ return this;
718
+ }
719
+ pattern(value) {
720
+ this.attr.pattern = value;
721
+ return this;
722
+ }
723
+ required() {
724
+ this.setRequired(true);
725
+ return this;
726
+ }
727
+ optional() {
728
+ this.setRequired(false);
729
+ return this;
730
+ }
731
+ /**
732
+ * Set email validation pattern
733
+ */
734
+ email() {
735
+ this.attr.pattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
736
+ return this;
737
+ }
738
+ /**
739
+ * Set URL validation pattern
740
+ */
741
+ url() {
742
+ this.attr.pattern = "^https?:\\/\\/[\\w\\-]+(\\.[\\w\\-]+)+[/#?]?.*$";
743
+ return this;
744
+ }
745
+ /**
746
+ * Set slug validation pattern
747
+ */
748
+ slug() {
749
+ this.attr.pattern = "^[a-z0-9]+(?:-[a-z0-9]+)*$";
750
+ return this;
751
+ }
752
+ };
753
+ function text(config) {
754
+ return new TextAttributeBuilder(config.name, config.label);
755
+ }
756
+ var TextAreaAttributeBuilder = class extends BaseAttributeBuilder {
757
+ constructor(name, label) {
758
+ super("textarea", name, label);
759
+ }
760
+ required() {
761
+ this.setRequired(true);
762
+ return this;
763
+ }
764
+ optional() {
765
+ this.setRequired(false);
766
+ return this;
767
+ }
768
+ };
769
+ function textarea(config) {
770
+ return new TextAreaAttributeBuilder(config.name, config.label);
771
+ }
772
+ var NumberAttributeBuilder = class extends BaseAttributeBuilder {
773
+ constructor(name, label) {
774
+ super("number", name, label);
775
+ }
776
+ min(value) {
777
+ this.attr.min = value;
778
+ return this;
779
+ }
780
+ max(value) {
781
+ this.attr.max = value;
782
+ return this;
783
+ }
784
+ integer() {
785
+ this.attr.unit = "integer";
786
+ this.attr.decimals = 0;
787
+ return this;
788
+ }
789
+ decimal(decimals = 2) {
790
+ this.attr.unit = "decimal";
791
+ this.attr.decimals = decimals;
792
+ return this;
793
+ }
794
+ percentage() {
795
+ this.attr.unit = "percentage";
796
+ return this;
797
+ }
798
+ required() {
799
+ this.setRequired(true);
800
+ return this;
801
+ }
802
+ optional() {
803
+ this.setRequired(false);
804
+ return this;
805
+ }
806
+ };
807
+ function number(config) {
808
+ return new NumberAttributeBuilder(config.name, config.label);
809
+ }
810
+ var CheckboxAttributeBuilder = class extends BaseAttributeBuilder {
811
+ constructor(name, label) {
812
+ super("checkbox", name, label);
813
+ }
814
+ required() {
815
+ this.setRequired(true);
816
+ return this;
817
+ }
818
+ optional() {
819
+ this.setRequired(false);
820
+ return this;
821
+ }
822
+ };
823
+ function checkbox(config) {
824
+ return new CheckboxAttributeBuilder(config.name, config.label);
825
+ }
826
+ var DateAttributeBuilder = class extends BaseAttributeBuilder {
827
+ constructor(name, label) {
828
+ super("date", name, label);
829
+ }
830
+ format(value) {
831
+ this.attr.dateFormat = value;
832
+ return this;
833
+ }
834
+ minDate(value) {
835
+ this.attr.minDate = value;
836
+ return this;
837
+ }
838
+ maxDate(value) {
839
+ this.attr.maxDate = value;
840
+ return this;
841
+ }
842
+ required() {
843
+ this.setRequired(true);
844
+ return this;
845
+ }
846
+ optional() {
847
+ this.setRequired(false);
848
+ return this;
849
+ }
850
+ };
851
+ function date(config) {
852
+ return new DateAttributeBuilder(config.name, config.label);
853
+ }
854
+ var PhoneAttributeBuilder = class extends BaseAttributeBuilder {
855
+ constructor(name, label) {
856
+ super("phone", name, label);
857
+ }
858
+ defaultCountry(value) {
859
+ this.attr.defaultCountryCode = value;
860
+ return this;
861
+ }
862
+ required() {
863
+ this.setRequired(true);
864
+ return this;
865
+ }
866
+ optional() {
867
+ this.setRequired(false);
868
+ return this;
869
+ }
870
+ };
871
+ function phone(config) {
872
+ return new PhoneAttributeBuilder(config.name, config.label);
873
+ }
874
+ var CurrencyAttributeBuilder = class extends BaseAttributeBuilder {
875
+ constructor(name, label) {
876
+ super("currency", name, label);
877
+ }
878
+ defaultCurrency(value) {
879
+ this.attr.defaultCurrency = value;
880
+ return this;
881
+ }
882
+ allowedCurrencies(value) {
883
+ this.attr.allowedCurrencies = value;
884
+ return this;
885
+ }
886
+ required() {
887
+ this.setRequired(true);
888
+ return this;
889
+ }
890
+ optional() {
891
+ this.setRequired(false);
892
+ return this;
893
+ }
894
+ };
895
+ function currency(config) {
896
+ return new CurrencyAttributeBuilder(config.name, config.label);
897
+ }
898
+ var StatusAttributeBuilder = class extends BaseAttributeBuilder {
899
+ constructor(name, label) {
900
+ super("status", name, label);
901
+ }
902
+ /**
903
+ * Set all options at once (preserves literal types for values)
904
+ */
905
+ options(value) {
906
+ this.attr.options = value;
907
+ return this;
908
+ }
909
+ option(config) {
910
+ if (!this.attr.options) {
911
+ this.attr.options = [];
912
+ }
913
+ this.attr.options.push(config);
914
+ return this;
915
+ }
916
+ required() {
917
+ this.setRequired(true);
918
+ return this;
919
+ }
920
+ optional() {
921
+ this.setRequired(false);
922
+ return this;
923
+ }
924
+ };
925
+ function status(config) {
926
+ return new StatusAttributeBuilder(config.name, config.label);
927
+ }
928
+ var SelectAttributeBuilder = class extends BaseAttributeBuilder {
929
+ constructor(name, label) {
930
+ super("select", name, label);
931
+ }
932
+ /**
933
+ * Set all options at once (preserves literal types for values)
934
+ */
935
+ options(value) {
936
+ this.attr.options = value;
937
+ return this;
938
+ }
939
+ option(config) {
940
+ if (!this.attr.options) {
941
+ this.attr.options = [];
942
+ }
943
+ this.attr.options.push(config);
944
+ return this;
945
+ }
946
+ required() {
947
+ this.setRequired(true);
948
+ return this;
949
+ }
950
+ optional() {
951
+ this.setRequired(false);
952
+ return this;
953
+ }
954
+ };
955
+ function select(config) {
956
+ return new SelectAttributeBuilder(config.name, config.label);
957
+ }
958
+ var MultiselectAttributeBuilder = class extends BaseAttributeBuilder {
959
+ constructor(name, label) {
960
+ super("multiselect", name, label);
961
+ }
962
+ /**
963
+ * Set all options at once (preserves literal types for values)
964
+ */
965
+ options(value) {
966
+ this.attr.options = value;
967
+ return this;
968
+ }
969
+ option(config) {
970
+ if (!this.attr.options) {
971
+ this.attr.options = [];
972
+ }
973
+ this.attr.options.push(config);
974
+ return this;
975
+ }
976
+ required() {
977
+ this.setRequired(true);
978
+ return this;
979
+ }
980
+ optional() {
981
+ this.setRequired(false);
982
+ return this;
983
+ }
984
+ };
985
+ function multiselect(config) {
986
+ return new MultiselectAttributeBuilder(config.name, config.label);
987
+ }
988
+ var LocationAttributeBuilder = class extends BaseAttributeBuilder {
989
+ constructor(name, label) {
990
+ super("location", name, label);
991
+ }
992
+ granularity(value) {
993
+ this.attr.granularity = value;
994
+ return this;
995
+ }
996
+ enableAutocomplete() {
997
+ this.attr.enableAutocomplete = true;
998
+ return this;
999
+ }
1000
+ enableMap() {
1001
+ this.attr.enableMap = true;
1002
+ return this;
1003
+ }
1004
+ defaultCountry(value) {
1005
+ this.attr.defaultCountry = value;
1006
+ return this;
1007
+ }
1008
+ allowedCountries(value) {
1009
+ this.attr.allowedCountries = value;
1010
+ return this;
1011
+ }
1012
+ displayFormat(value) {
1013
+ this.attr.displayFormat = value;
1014
+ return this;
1015
+ }
1016
+ required() {
1017
+ this.setRequired(true);
1018
+ return this;
1019
+ }
1020
+ optional() {
1021
+ this.setRequired(false);
1022
+ return this;
1023
+ }
1024
+ };
1025
+ function location(config) {
1026
+ return new LocationAttributeBuilder(config.name, config.label);
1027
+ }
1028
+ var TimestampAttributeBuilder = class extends BaseAttributeBuilder {
1029
+ constructor(name, label) {
1030
+ super("timestamp", name, label);
1031
+ }
1032
+ autoUpdate() {
1033
+ this.attr.autoUpdate = true;
1034
+ return this;
1035
+ }
1036
+ required() {
1037
+ this.setRequired(true);
1038
+ return this;
1039
+ }
1040
+ optional() {
1041
+ this.setRequired(false);
1042
+ return this;
1043
+ }
1044
+ };
1045
+ function timestamp(config) {
1046
+ return new TimestampAttributeBuilder(config.name, config.label);
1047
+ }
1048
+ var FileAttributeBuilder = class extends BaseAttributeBuilder {
1049
+ constructor(name, label) {
1050
+ super("file", name, label);
1051
+ }
1052
+ maxFiles(value) {
1053
+ this.attr.maxFiles = value;
1054
+ return this;
1055
+ }
1056
+ maxSize(bytes) {
1057
+ this.attr.maxSize = bytes;
1058
+ return this;
1059
+ }
1060
+ allowedTypes(types) {
1061
+ this.attr.allowedTypes = types;
1062
+ return this;
1063
+ }
1064
+ verification(config) {
1065
+ this.attr.verification = config;
1066
+ return this;
1067
+ }
1068
+ required() {
1069
+ this.setRequired(true);
1070
+ return this;
1071
+ }
1072
+ optional() {
1073
+ this.setRequired(false);
1074
+ return this;
1075
+ }
1076
+ };
1077
+ function file(config) {
1078
+ return new FileAttributeBuilder(config.name, config.label);
1079
+ }
1080
+ var UserAttributeBuilder = class extends BaseAttributeBuilder {
1081
+ constructor(name, label) {
1082
+ super("user", name, label);
1083
+ }
1084
+ allowedRoles(roles) {
1085
+ this.attr.allowedRoles = roles;
1086
+ return this;
1087
+ }
1088
+ required() {
1089
+ this.setRequired(true);
1090
+ return this;
1091
+ }
1092
+ optional() {
1093
+ this.setRequired(false);
1094
+ return this;
1095
+ }
1096
+ };
1097
+ function user(config) {
1098
+ return new UserAttributeBuilder(config.name, config.label);
1099
+ }
1100
+ var RelationAttributeBuilder = class extends BaseAttributeBuilder {
1101
+ constructor(name, label) {
1102
+ super("relation", name, label);
1103
+ }
1104
+ relation(objectIds) {
1105
+ this.attr.relation = objectIds;
1106
+ return this;
1107
+ }
1108
+ limit(value) {
1109
+ this.attr.limit = value;
1110
+ return this;
1111
+ }
1112
+ cascadeDelete() {
1113
+ this.attr.cascadeDelete = true;
1114
+ return this;
1115
+ }
1116
+ required() {
1117
+ this.setRequired(true);
1118
+ return this;
1119
+ }
1120
+ optional() {
1121
+ this.setRequired(false);
1122
+ return this;
1123
+ }
1124
+ };
1125
+ function relation(config) {
1126
+ return new RelationAttributeBuilder(config.name, config.label);
1127
+ }
1128
+ var RatingAttributeBuilder = class extends BaseAttributeBuilder {
1129
+ constructor(name, label) {
1130
+ super("rating", name, label);
1131
+ }
1132
+ max(value) {
1133
+ this.attr.max = value;
1134
+ return this;
1135
+ }
1136
+ iconType(value) {
1137
+ this.attr.iconType = value;
1138
+ return this;
1139
+ }
1140
+ required() {
1141
+ this.setRequired(true);
1142
+ return this;
1143
+ }
1144
+ optional() {
1145
+ this.setRequired(false);
1146
+ return this;
1147
+ }
1148
+ };
1149
+ function rating(config) {
1150
+ return new RatingAttributeBuilder(config.name, config.label);
1151
+ }
1152
+
1153
+ // src/builders/object-builder.ts
1154
+ import z2 from "zod";
1155
+ var ObjectBuilder = class {
1156
+ constructor(config) {
1157
+ this.validateName(config.name);
1158
+ this.obj = {
1159
+ name: config.name,
1160
+ label: config.label,
1161
+ attributes: [],
1162
+ system: false
1163
+ };
1164
+ }
1165
+ /**
1166
+ * Set object description
1167
+ */
1168
+ description(value) {
1169
+ this.obj.description = value;
1170
+ return this;
1171
+ }
1172
+ /**
1173
+ * Set object icon
1174
+ */
1175
+ icon(value) {
1176
+ this.obj.icon = value;
1177
+ return this;
1178
+ }
1179
+ /**
1180
+ * Mark as system/native object (defined in code, protected)
1181
+ * System objects cannot be deleted/modified by clients
1182
+ */
1183
+ system() {
1184
+ this.obj.system = true;
1185
+ return this;
1186
+ }
1187
+ /**
1188
+ * Add an attribute to the object with type accumulation
1189
+ *
1190
+ * The return type accumulates the attribute's name and value type
1191
+ * into the TRecord generic, enabling full inference.
1192
+ *
1193
+ * @param attr - Attribute definition or builder (auto-builds if builder)
1194
+ */
1195
+ attribute(attr) {
1196
+ if (!this.obj.attributes) {
1197
+ this.obj.attributes = [];
1198
+ }
1199
+ const finalAttr = "build" in attr && typeof attr.build === "function" ? attr.build() : attr;
1200
+ this.obj.attributes.push(finalAttr);
1201
+ return this;
1202
+ }
1203
+ /**
1204
+ * Add multiple attributes at once
1205
+ * Note: For full type inference, prefer chaining .attribute() calls
1206
+ */
1207
+ attributes(attrs) {
1208
+ if (!this.obj.attributes) {
1209
+ this.obj.attributes = [];
1210
+ }
1211
+ const finalAttrs = attrs.map((attr) => "build" in attr ? attr.build() : attr);
1212
+ this.obj.attributes.push(...finalAttrs);
1213
+ return this;
1214
+ }
1215
+ /**
1216
+ * Set metadata
1217
+ */
1218
+ metadata(value) {
1219
+ this.obj.metadata = value;
1220
+ return this;
1221
+ }
1222
+ /**
1223
+ * Build the final ObjectDefinition
1224
+ * @throws Error if required fields are missing or invalid
1225
+ */
1226
+ build() {
1227
+ if (!this.obj.name) {
1228
+ throw new Error("[ObjectBuilder] Missing required field: name");
1229
+ }
1230
+ if (!this.obj.label) {
1231
+ throw new Error("[ObjectBuilder] Missing required field: label");
1232
+ }
1233
+ return this.obj;
1234
+ }
1235
+ /**
1236
+ * Validate object name format
1237
+ * Must be kebab-case (slug format), max 63 characters
1238
+ * @internal
1239
+ */
1240
+ validateName(name) {
1241
+ if (name === void 0) {
1242
+ return;
1243
+ }
1244
+ const objectNameSchema = z2.string().min(1, "Object name cannot be empty").max(63, "Object name is too long (max 63 characters)").regex(/^[a-z][a-z0-9-]*$/, {
1245
+ message: "Invalid object name format.\nName must be in kebab-case (slug format):\n \u2705 Valid: 'products', 'user-profiles', 'order-items'\n \u274C Invalid: 'Products', 'userProfiles', 'user_profiles'"
1246
+ });
1247
+ try {
1248
+ objectNameSchema.parse(name);
1249
+ } catch (error) {
1250
+ if (error instanceof z2.ZodError) {
1251
+ throw new Error(`[ObjectBuilder] ${error.errors[0].message}`);
1252
+ }
1253
+ throw error;
1254
+ }
1255
+ }
1256
+ };
1257
+ function object(config) {
1258
+ return new ObjectBuilder(config);
1259
+ }
1260
+
1261
+ // src/runtime/services/object-schema.service.ts
1262
+ var ObjectSchemaService = class {
1263
+ constructor(adapter, nativeRegistry) {
1264
+ this.adapter = adapter;
1265
+ this.nativeRegistry = nativeRegistry;
1266
+ }
1267
+ /**
1268
+ * Create a new custom object
1269
+ * Validates name format and ensures system=false
1270
+ *
1271
+ * @param definition - Object definition (attributes can be raw definitions or builders)
1272
+ * @param tenantId - Tenant ID owning the object
1273
+ * @returns Created ObjectDefinition
1274
+ */
1275
+ async createCustomObject(definition, tenantId) {
1276
+ const builder = object({
1277
+ name: definition.name,
1278
+ label: definition.label
1279
+ });
1280
+ if (definition.description) builder.description(definition.description);
1281
+ if (definition.icon) builder.icon(definition.icon);
1282
+ if (definition.metadata) builder.metadata(definition.metadata);
1283
+ if (definition.attributes && definition.attributes.length > 0) {
1284
+ builder.attributes(definition.attributes);
1285
+ }
1286
+ const objectDef = builder.build();
1287
+ const existing = await this.adapter.objects.findByName(tenantId, objectDef.name);
1288
+ if (existing) {
1289
+ throw new Error(`Object with name "${objectDef.name}" already exists`);
1290
+ }
1291
+ const metadata = {
1292
+ ...objectDef.metadata,
1293
+ icon: objectDef.icon
1294
+ };
1295
+ const dbObject = await this.adapter.objects.create({
1296
+ tenantId,
1297
+ name: objectDef.name,
1298
+ label: objectDef.label,
1299
+ description: objectDef.description,
1300
+ system: false,
1301
+ // Always false for custom objects
1302
+ metadata
1303
+ });
1304
+ const createdAttributes = [];
1305
+ if (objectDef.attributes.length > 0) {
1306
+ for (const attr of objectDef.attributes) {
1307
+ const dbAttr = await this.adapter.attributes.create({
1308
+ objectId: dbObject.id,
1309
+ name: attr.name,
1310
+ label: attr.label,
1311
+ type: attr.type,
1312
+ required: attr.required ?? false,
1313
+ unique: attr.unique ?? false,
1314
+ system: false,
1315
+ // Always false for custom attributes
1316
+ config: {
1317
+ ...attr,
1318
+ // Remove common fields stored in columns
1319
+ id: void 0,
1320
+ name: void 0,
1321
+ label: void 0,
1322
+ type: void 0,
1323
+ required: void 0,
1324
+ unique: void 0,
1325
+ system: void 0
1326
+ }
1327
+ });
1328
+ createdAttributes.push(this.convertDBAttributeToAttribute(dbAttr));
1329
+ }
1330
+ }
1331
+ return {
1332
+ ...objectDef,
1333
+ id: dbObject.id,
1334
+ attributes: createdAttributes,
1335
+ system: false
1336
+ };
1337
+ }
1338
+ /**
1339
+ * Add a custom attribute to an existing object
1340
+ * Can be used on both custom and native objects
1341
+ * Attributes added via API are always custom (system=false)
1342
+ *
1343
+ * @param objectId - Object UUID from database
1344
+ * @param attribute - Attribute definition
1345
+ * @returns Created Attribute
1346
+ */
1347
+ async addAttributeToObject(objectId, attribute) {
1348
+ this.validateAttributeName(attribute.name);
1349
+ const dbObject = await this.adapter.objects.findById(objectId);
1350
+ if (!dbObject) {
1351
+ throw new Error(`Object with id "${objectId}" not found`);
1352
+ }
1353
+ const existingAttributes = await this.adapter.attributes.findByObjectId(objectId);
1354
+ const duplicate = existingAttributes.find((attr) => attr.name === attribute.name);
1355
+ if (duplicate) {
1356
+ throw new Error(
1357
+ `Attribute with name "${attribute.name}" already exists on object "${dbObject.name}"`
1358
+ );
1359
+ }
1360
+ const dbAttr = await this.adapter.attributes.create({
1361
+ objectId,
1362
+ name: attribute.name,
1363
+ label: attribute.label,
1364
+ type: attribute.type,
1365
+ required: attribute.required ?? false,
1366
+ unique: attribute.unique ?? false,
1367
+ system: false,
1368
+ // Always false for attributes added via API
1369
+ config: {
1370
+ // Store all extra properties in config
1371
+ ...attribute,
1372
+ // Remove common fields stored in columns
1373
+ name: void 0,
1374
+ label: void 0,
1375
+ type: void 0,
1376
+ required: void 0,
1377
+ unique: void 0,
1378
+ system: void 0
1379
+ }
1380
+ });
1381
+ return this.convertDBAttributeToAttribute(dbAttr);
1382
+ }
1383
+ /**
1384
+ * Update an attribute
1385
+ * Can only update custom attributes (system=false)
1386
+ *
1387
+ * @param attributeId - Attribute UUID
1388
+ * @param updates - Partial attribute updates
1389
+ * @returns Updated Attribute
1390
+ */
1391
+ async updateAttribute(attributeId, updates) {
1392
+ const dbAttr = await this.adapter.attributes.findById(attributeId);
1393
+ if (!dbAttr) {
1394
+ throw new Error(`Attribute with id "${attributeId}" not found`);
1395
+ }
1396
+ if (dbAttr.system) {
1397
+ throw new Error(
1398
+ `Cannot modify system attribute "${dbAttr.name}". System attributes are protected.`
1399
+ );
1400
+ }
1401
+ if (updates.name && updates.name !== dbAttr.name) {
1402
+ throw new Error(
1403
+ "Attribute name cannot be changed after creation. Create a new attribute instead."
1404
+ );
1405
+ }
1406
+ if (updates.type && updates.type !== dbAttr.type) {
1407
+ throw new Error(
1408
+ "Attribute type cannot be changed after creation. Create a new attribute instead."
1409
+ );
1410
+ }
1411
+ const updatedDbAttr = await this.adapter.attributes.update(attributeId, {
1412
+ label: updates.label,
1413
+ required: updates.required,
1414
+ config: updates ? {
1415
+ ...dbAttr.config,
1416
+ ...updates,
1417
+ // Remove common fields
1418
+ name: void 0,
1419
+ label: void 0,
1420
+ type: void 0,
1421
+ required: void 0,
1422
+ unique: void 0,
1423
+ system: void 0
1424
+ } : dbAttr.config
1425
+ });
1426
+ return this.convertDBAttributeToAttribute(updatedDbAttr);
1427
+ }
1428
+ /**
1429
+ * Delete an attribute
1430
+ * Can only delete custom attributes (system=false)
1431
+ *
1432
+ * @param attributeId - Attribute UUID
1433
+ */
1434
+ async deleteAttribute(attributeId) {
1435
+ const dbAttr = await this.adapter.attributes.findById(attributeId);
1436
+ if (!dbAttr) {
1437
+ throw new Error(`Attribute with id "${attributeId}" not found`);
1438
+ }
1439
+ if (dbAttr.system) {
1440
+ throw new Error(
1441
+ `Cannot delete system attribute "${dbAttr.name}". System attributes are protected.`
1442
+ );
1443
+ }
1444
+ await this.adapter.attributes.delete(attributeId);
1445
+ }
1446
+ /**
1447
+ * List attributes for an object
1448
+ *
1449
+ * @param objectId - Object UUID
1450
+ * @param options - Filter options
1451
+ * @returns List of attributes
1452
+ */
1453
+ async listAttributes(objectId, options) {
1454
+ const dbAttributes = await this.adapter.attributes.findByObjectId(objectId);
1455
+ let filtered = dbAttributes;
1456
+ if (options?.systemOnly) {
1457
+ filtered = dbAttributes.filter((attr) => attr.system);
1458
+ } else if (options?.customOnly) {
1459
+ filtered = dbAttributes.filter((attr) => !attr.system);
1460
+ }
1461
+ return filtered.map((attr) => this.convertDBAttributeToAttribute(attr));
1462
+ }
1463
+ /**
1464
+ * Validate attribute name format (variable identifier)
1465
+ * @internal
1466
+ */
1467
+ validateAttributeName(name) {
1468
+ const variableNameRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
1469
+ if (!name || name.length === 0) {
1470
+ throw new Error("Attribute name cannot be empty");
1471
+ }
1472
+ if (name.length > 63) {
1473
+ throw new Error("Attribute name is too long (max 63 characters)");
1474
+ }
1475
+ if (!variableNameRegex.test(name)) {
1476
+ throw new Error(
1477
+ "Invalid attribute name format.\nName must be a valid variable identifier:\n \u2705 Valid: 'firstName', 'first_name', 'FirstName', 'FIRST_NAME'\n \u274C Invalid: 'first-name', 'first name', '123name', 'first.name'"
1478
+ );
1479
+ }
1480
+ }
1481
+ /**
1482
+ * Get complete object schema (system + custom attributes)
1483
+ * If object is native, merges registry definition with DB custom attributes
1484
+ * If object is custom, returns DB definition only
1485
+ *
1486
+ * @param objectId - Object UUID from database
1487
+ * @returns Complete ObjectDefinition with all attributes
1488
+ *
1489
+ * @example
1490
+ * ```typescript
1491
+ * const service = new ObjectSchemaService(adapter, registry);
1492
+ * const productSchema = await service.getObjectSchema("obj-123");
1493
+ *
1494
+ * console.log(productSchema.attributes); // System + custom attributes
1495
+ * ```
1496
+ */
1497
+ async getObjectSchema(objectId) {
1498
+ const dbObject = await this.adapter.objects.findById(objectId);
1499
+ if (!dbObject) {
1500
+ throw new Error(`Object with id "${objectId}" not found`);
1501
+ }
1502
+ const dbAttributes = await this.adapter.attributes.findByObjectId(objectId);
1503
+ if (dbObject.system) {
1504
+ return this.mergeNativeObject(dbObject, dbAttributes);
1505
+ }
1506
+ return this.convertDBObjectToDefinition(dbObject, dbAttributes);
1507
+ }
1508
+ /**
1509
+ * Get object schema by name (for system/native objects)
1510
+ */
1511
+ async getObjectSchemaByName(name) {
1512
+ const dbObject = await this.adapter.objects.findSystemByName(name);
1513
+ if (!dbObject) {
1514
+ throw new Error(`Native object "${name}" not found in database`);
1515
+ }
1516
+ const dbAttributes = await this.adapter.attributes.findByObjectId(dbObject.id);
1517
+ return this.mergeNativeObject(dbObject, dbAttributes);
1518
+ }
1519
+ /**
1520
+ * List all object schemas for a tenant
1521
+ */
1522
+ async listObjectSchemas(tenantId) {
1523
+ const dbObjects = await this.adapter.objects.list(tenantId);
1524
+ const schemas = await Promise.all(
1525
+ dbObjects.map(async (dbObject) => {
1526
+ const dbAttributes = await this.adapter.attributes.findByObjectId(dbObject.id);
1527
+ if (dbObject.system) {
1528
+ return this.mergeNativeObject(dbObject, dbAttributes);
1529
+ }
1530
+ return this.convertDBObjectToDefinition(dbObject, dbAttributes);
1531
+ })
1532
+ );
1533
+ return schemas;
1534
+ }
1535
+ /**
1536
+ * Merge native object from registry with custom attributes from DB
1537
+ * @internal
1538
+ */
1539
+ mergeNativeObject(dbObject, dbAttributes) {
1540
+ const nativeObject = this.nativeRegistry.getByName(dbObject.name);
1541
+ if (!nativeObject) {
1542
+ throw new Error(
1543
+ `Native object "${dbObject.name}" not found in registry. Make sure to register it before querying.`
1544
+ );
1545
+ }
1546
+ const customAttributes = dbAttributes.filter((attr) => !attr.system);
1547
+ const customAttrs = customAttributes.map(
1548
+ (dbAttr) => this.convertDBAttributeToAttribute(dbAttr)
1549
+ );
1550
+ return {
1551
+ ...nativeObject,
1552
+ id: dbObject.id,
1553
+ attributes: [
1554
+ ...nativeObject.attributes,
1555
+ // System attributes from code
1556
+ ...customAttrs
1557
+ // Custom attributes from DB
1558
+ ]
1559
+ };
1560
+ }
1561
+ /**
1562
+ * Convert DB object + attributes to ObjectDefinition
1563
+ * @internal
1564
+ */
1565
+ convertDBObjectToDefinition(dbObject, dbAttributes) {
1566
+ const attributes = dbAttributes.map(
1567
+ (dbAttr) => this.convertDBAttributeToAttribute(dbAttr)
1568
+ );
1569
+ return {
1570
+ id: dbObject.id,
1571
+ name: dbObject.name,
1572
+ label: dbObject.label,
1573
+ description: dbObject.description,
1574
+ icon: dbObject.metadata?.icon,
1575
+ attributes,
1576
+ system: dbObject.system,
1577
+ metadata: dbObject.metadata
1578
+ };
1579
+ }
1580
+ /**
1581
+ * Convert DB attribute to Attribute type
1582
+ * @internal
1583
+ */
1584
+ convertDBAttributeToAttribute(dbAttr) {
1585
+ const baseAttr = {
1586
+ ...dbAttr.config,
1587
+ id: dbAttr.id,
1588
+ name: dbAttr.name,
1589
+ label: dbAttr.label,
1590
+ type: dbAttr.type,
1591
+ required: dbAttr.required,
1592
+ system: dbAttr.system,
1593
+ unique: dbAttr.unique
1594
+ };
1595
+ return baseAttr;
1596
+ }
1597
+ };
1598
+
1599
+ // src/native/registry.ts
1600
+ var NativeObjectRegistryClass = class {
1601
+ constructor() {
1602
+ this.objects = /* @__PURE__ */ new Map();
1603
+ }
1604
+ /**
1605
+ * Register one or more native objects
1606
+ * Auto-builds if ObjectBuilder is passed instead of ObjectDefinition
1607
+ * @param objects - Single object/builder or array of objects/builders to register
1608
+ * @returns this (for chaining)
1609
+ * @throws Error if object is invalid or already registered
1610
+ *
1611
+ * @example
1612
+ * ```typescript
1613
+ * // No .build() needed - registry auto-builds!
1614
+ * const PRODUCT = object({ id: "obj-product", name: "products", label: "Product" })
1615
+ * .system()
1616
+ * .attribute(text({ id: "attr-name", name: "name", label: "Name" }));
1617
+ *
1618
+ * registry.register(PRODUCT); // ← Auto-builds here
1619
+ *
1620
+ * // Can still explicitly .build() if you want
1621
+ * registry.register(PRODUCT.build());
1622
+ *
1623
+ * // Register multiple
1624
+ * registry.register([PRODUCT, ORDER, CUSTOMER]);
1625
+ * ```
1626
+ */
1627
+ register(objects) {
1628
+ const objectsArray = Array.isArray(objects) ? objects : [objects];
1629
+ for (const obj of objectsArray) {
1630
+ const object2 = "build" in obj && typeof obj.build === "function" ? obj.build() : obj;
1631
+ this.validateAndRegister(object2);
1632
+ }
1633
+ return this;
1634
+ }
1635
+ /**
1636
+ * Validate and register a single object
1637
+ * @internal
1638
+ */
1639
+ validateAndRegister(object2) {
1640
+ if (!object2.system) {
1641
+ throw new Error(
1642
+ `[NativeObjectRegistry] Cannot register object "${object2.name}" (id: ${object2.id}): missing system flag.
1643
+ Native objects must have system=true. Did you forget to call .system() in your builder?`
1644
+ );
1645
+ }
1646
+ if (this.objects.has(object2.name)) {
1647
+ const existing = this.objects.get(object2.name);
1648
+ throw new Error(
1649
+ `[NativeObjectRegistry] Duplicate object name "${object2.name}":
1650
+ - Existing: "${existing?.label}" (id: ${existing?.id})
1651
+ - New: "${object2.label}" (id: ${object2.id})
1652
+ Please use unique names for each native object.`
1653
+ );
1654
+ }
1655
+ this.objects.set(object2.name, object2);
1656
+ }
1657
+ /**
1658
+ * Get a native object by its name
1659
+ * @param name - The object name
1660
+ * @returns The object definition or undefined if not found
1661
+ *
1662
+ * @example
1663
+ * ```typescript
1664
+ * const product = registry.getByName("products");
1665
+ * if (product) {
1666
+ * console.log(product.label); // "Product"
1667
+ * }
1668
+ * ```
1669
+ */
1670
+ getByName(name) {
1671
+ return this.objects.get(name);
1672
+ }
1673
+ /**
1674
+ * Get a native object or throw if not found
1675
+ * @param name - The object name
1676
+ * @returns The object definition
1677
+ * @throws Error if not found
1678
+ */
1679
+ getByNameOrThrow(name) {
1680
+ const object2 = this.objects.get(name);
1681
+ if (!object2) {
1682
+ throw new Error(
1683
+ `[NativeObjectRegistry] Native object "${name}" not found.
1684
+ Available objects: ${this.listNames().join(", ")}`
1685
+ );
1686
+ }
1687
+ return object2;
1688
+ }
1689
+ /**
1690
+ * Get all registered native objects
1691
+ * @returns Array of all registered object definitions
1692
+ */
1693
+ getAll() {
1694
+ return Array.from(this.objects.values());
1695
+ }
1696
+ /**
1697
+ * Get all registered native object names
1698
+ * @returns Array of object names
1699
+ */
1700
+ listNames() {
1701
+ return Array.from(this.objects.keys());
1702
+ }
1703
+ /**
1704
+ * Check if a native object is registered
1705
+ * @param name - The object name
1706
+ * @returns true if registered, false otherwise
1707
+ */
1708
+ has(name) {
1709
+ return this.objects.has(name);
1710
+ }
1711
+ /**
1712
+ * Get the number of registered objects
1713
+ */
1714
+ get size() {
1715
+ return this.objects.size;
1716
+ }
1717
+ /**
1718
+ * Clear all registered objects (useful for testing)
1719
+ * @internal
1720
+ */
1721
+ clear() {
1722
+ this.objects.clear();
1723
+ }
1724
+ /**
1725
+ * Get registry summary for debugging
1726
+ */
1727
+ summary() {
1728
+ const objects = this.getAll();
1729
+ return [
1730
+ `[NativeObjectRegistry] ${this.size} native object(s) registered:`,
1731
+ ...objects.map(
1732
+ (obj) => ` - ${obj.name}: "${obj.label}" (${obj.attributes.length} attributes)`
1733
+ )
1734
+ ].join("\n");
1735
+ }
1736
+ /**
1737
+ * Log registry summary to console
1738
+ */
1739
+ debug() {
1740
+ console.info(this.summary());
1741
+ }
1742
+ };
1743
+ var registry = new NativeObjectRegistryClass();
1744
+
1745
+ // src/validation/validators.ts
1746
+ import { z as z3 } from "zod";
1747
+ function createTextValidator(attr) {
1748
+ let schema = z3.string();
1749
+ if (attr.minLength !== void 0) {
1750
+ schema = schema.min(
1751
+ attr.minLength,
1752
+ `${attr.label} must be at least ${attr.minLength} characters`
1753
+ );
1754
+ }
1755
+ if (attr.maxLength !== void 0) {
1756
+ schema = schema.max(
1757
+ attr.maxLength,
1758
+ `${attr.label} must be at most ${attr.maxLength} characters`
1759
+ );
1760
+ }
1761
+ if (attr.pattern) {
1762
+ schema = schema.regex(new RegExp(attr.pattern), `${attr.label} format is invalid`);
1763
+ }
1764
+ return schema;
1765
+ }
1766
+ function createNumberValidator(attr) {
1767
+ let schema = z3.number();
1768
+ if (attr.min !== void 0) {
1769
+ schema = schema.min(attr.min, `${attr.label} must be at least ${attr.min}`);
1770
+ }
1771
+ if (attr.max !== void 0) {
1772
+ schema = schema.max(attr.max, `${attr.label} must be at most ${attr.max}`);
1773
+ }
1774
+ if (attr.unit === "integer") {
1775
+ schema = schema.int(`${attr.label} must be an integer`);
1776
+ }
1777
+ return schema;
1778
+ }
1779
+ function createCheckboxValidator(_attr) {
1780
+ return z3.boolean();
1781
+ }
1782
+ function createDateValidator(attr) {
1783
+ return z3.string().datetime({ message: `${attr.label} must be a valid ISO date` });
1784
+ }
1785
+ function createPhoneValidator(_attr) {
1786
+ return z3.object({
1787
+ countryCode: z3.string().length(3),
1788
+ phoneNumber: z3.string().min(1)
1789
+ });
1790
+ }
1791
+ function createCurrencyValidator(_attr) {
1792
+ return z3.object({
1793
+ code: z3.string().length(3),
1794
+ value: z3.number().min(0)
1795
+ });
1796
+ }
1797
+ function createStatusValidator(attr) {
1798
+ const validValues = attr.options.map((opt) => opt.value);
1799
+ return z3.enum(validValues, {
1800
+ errorMap: () => ({
1801
+ message: `${attr.label} must be one of: ${validValues.join(", ")}`
1802
+ })
1803
+ });
1804
+ }
1805
+ function createSelectValidator(attr) {
1806
+ const validValues = attr.options.map((opt) => opt.value);
1807
+ return z3.enum(validValues, {
1808
+ errorMap: () => ({
1809
+ message: `${attr.label} must be one of: ${validValues.join(", ")}`
1810
+ })
1811
+ });
1812
+ }
1813
+ function createMultiselectValidator(attr) {
1814
+ const validValues = attr.options.map((opt) => opt.value);
1815
+ return z3.array(
1816
+ z3.enum(validValues, {
1817
+ errorMap: () => ({
1818
+ message: `Each value must be one of: ${validValues.join(", ")}`
1819
+ })
1820
+ })
1821
+ );
1822
+ }
1823
+ function createLocationValidator(_attr) {
1824
+ return z3.object({
1825
+ address: z3.string().optional(),
1826
+ address2: z3.string().optional(),
1827
+ city: z3.string().optional(),
1828
+ state: z3.string().optional(),
1829
+ postalCode: z3.string().optional(),
1830
+ country: z3.string().length(3).optional(),
1831
+ latitude: z3.number().optional(),
1832
+ longitude: z3.number().optional()
1833
+ });
1834
+ }
1835
+ function createTimestampValidator(_attr) {
1836
+ return z3.number().int().positive();
1837
+ }
1838
+ function createFileValidator(_attr) {
1839
+ return z3.string().uuid();
1840
+ }
1841
+ function createUserValidator(_attr) {
1842
+ return z3.string().uuid();
1843
+ }
1844
+ function createRelationValidator(_attr) {
1845
+ return z3.string().uuid();
1846
+ }
1847
+ function createRatingValidator(attr) {
1848
+ let schema = z3.number().int().min(0);
1849
+ if (attr.max !== void 0) {
1850
+ schema = schema.max(attr.max, `${attr.label} must be at most ${attr.max}`);
1851
+ }
1852
+ return schema;
1853
+ }
1854
+ function createAttributeValidator(attr) {
1855
+ switch (attr.type) {
1856
+ case "text":
1857
+ return createTextValidator(attr);
1858
+ case "number":
1859
+ return createNumberValidator(attr);
1860
+ case "checkbox":
1861
+ return createCheckboxValidator(attr);
1862
+ case "date":
1863
+ return createDateValidator(attr);
1864
+ case "phone":
1865
+ return createPhoneValidator(attr);
1866
+ case "currency":
1867
+ return createCurrencyValidator(attr);
1868
+ case "status":
1869
+ return createStatusValidator(attr);
1870
+ case "location":
1871
+ return createLocationValidator(attr);
1872
+ case "timestamp":
1873
+ return createTimestampValidator(attr);
1874
+ case "select":
1875
+ return createSelectValidator(attr);
1876
+ case "multiselect":
1877
+ return createMultiselectValidator(attr);
1878
+ case "file":
1879
+ return createFileValidator(attr);
1880
+ case "user":
1881
+ return createUserValidator(attr);
1882
+ case "relation":
1883
+ return createRelationValidator(attr);
1884
+ case "rating":
1885
+ return createRatingValidator(attr);
1886
+ default:
1887
+ return z3.unknown();
1888
+ }
1889
+ }
1890
+ function createObjectValidator(objectDef) {
1891
+ const shape = {};
1892
+ for (const attr of objectDef.attributes) {
1893
+ let validator = createAttributeValidator(attr);
1894
+ if (!attr.required) {
1895
+ validator = validator.optional();
1896
+ }
1897
+ shape[attr.name] = validator;
1898
+ }
1899
+ return z3.object(shape);
1900
+ }
1901
+ function validateAttribute(attr, value) {
1902
+ const validator = createAttributeValidator(attr);
1903
+ if (!attr.required && (value === void 0 || value === null)) {
1904
+ return { success: true, data: { [attr.name]: value } };
1905
+ }
1906
+ const result = validator.safeParse(value);
1907
+ if (result.success) {
1908
+ return {
1909
+ success: true,
1910
+ data: { [attr.name]: result.data }
1911
+ };
1912
+ }
1913
+ return {
1914
+ success: false,
1915
+ errors: result.error.errors.map((err) => ({
1916
+ path: [attr.name, ...err.path.map(String)],
1917
+ message: err.message
1918
+ }))
1919
+ };
1920
+ }
1921
+ function validateObject(objectDef, data) {
1922
+ const validator = createObjectValidator(objectDef);
1923
+ const result = validator.safeParse(data);
1924
+ if (result.success) {
1925
+ return {
1926
+ success: true,
1927
+ data: result.data
1928
+ };
1929
+ }
1930
+ return {
1931
+ success: false,
1932
+ errors: result.error.errors.map((err) => ({
1933
+ path: err.path.map(String),
1934
+ message: err.message
1935
+ }))
1936
+ };
1937
+ }
1938
+ function validateObjectOrThrow(objectDef, data) {
1939
+ const result = validateObject(objectDef, data);
1940
+ if (!result.success) {
1941
+ const errorMessages = result.errors?.map((err) => `${err.path.join(".")}: ${err.message}`).join("\n") || "Unknown validation error";
1942
+ throw new Error(`Validation failed for ${objectDef.label}:
1943
+ ${errorMessages}`);
1944
+ }
1945
+ return result.data;
1946
+ }
1947
+
1948
+ // src/runtime/services/record.service.ts
1949
+ var RecordService = class {
1950
+ constructor(adapter, tenantId) {
1951
+ this.adapter = adapter;
1952
+ this.tenantId = tenantId;
1953
+ this.schemaService = new ObjectSchemaService(adapter, registry);
1954
+ }
1955
+ /**
1956
+ * Create a new record with validation
1957
+ *
1958
+ * @param objectId - Object UUID
1959
+ * @param data - Record data (attribute values)
1960
+ * @param options - Creation options
1961
+ * @returns Created record
1962
+ *
1963
+ * @example
1964
+ * ```typescript
1965
+ * const service = new RecordService(adapter, "tenant-123");
1966
+ *
1967
+ * const product = await service.createRecord("obj-product", {
1968
+ * name: "Nike Air Max",
1969
+ * price: 129.99,
1970
+ * sku: "NIKE-AM-001"
1971
+ * });
1972
+ * ```
1973
+ */
1974
+ async createRecord(objectId, data, options) {
1975
+ const schema = await this.schemaService.getObjectSchema(objectId);
1976
+ if (options?.validate !== false) {
1977
+ validateObjectOrThrow(schema, data);
1978
+ }
1979
+ const record = await this.adapter.objectRecords.create({
1980
+ tenantId: this.tenantId,
1981
+ objectId,
1982
+ data
1983
+ });
1984
+ return record;
1985
+ }
1986
+ /**
1987
+ * Get a record by ID
1988
+ *
1989
+ * @param recordId - Record UUID
1990
+ * @param options - Query options
1991
+ * @returns Record or null if not found
1992
+ */
1993
+ async getRecord(recordId, options) {
1994
+ const record = await this.adapter.objectRecords.findById(recordId);
1995
+ if (!record) {
1996
+ return null;
1997
+ }
1998
+ if (options?.includeSchema) {
1999
+ const schema = await this.schemaService.getObjectSchema(record.objectId);
2000
+ const recordWithSchema = record;
2001
+ recordWithSchema.schema = schema;
2002
+ return recordWithSchema;
2003
+ }
2004
+ return record;
2005
+ }
2006
+ /**
2007
+ * Get a record by ID or throw if not found
2008
+ */
2009
+ async getRecordOrThrow(recordId) {
2010
+ const record = await this.getRecord(recordId);
2011
+ if (!record) {
2012
+ throw new Error(`Record with id "${recordId}" not found`);
2013
+ }
2014
+ return record;
2015
+ }
2016
+ /**
2017
+ * Update a record with validation
2018
+ *
2019
+ * @param recordId - Record UUID
2020
+ * @param data - Partial data to update
2021
+ * @param options - Update options
2022
+ * @returns Updated record
2023
+ */
2024
+ async updateRecord(recordId, data, options) {
2025
+ const existing = await this.getRecordOrThrow(recordId);
2026
+ const schema = await this.schemaService.getObjectSchema(existing.objectId);
2027
+ const mergedData = { ...existing.values, ...data };
2028
+ if (options?.validate !== false && !options?.partial) {
2029
+ validateObjectOrThrow(schema, mergedData);
2030
+ }
2031
+ const updated = await this.adapter.objectRecords.update(recordId, data);
2032
+ return updated;
2033
+ }
2034
+ /**
2035
+ * Delete a record
2036
+ *
2037
+ * @param recordId - Record UUID
2038
+ * @param options - Delete options
2039
+ */
2040
+ async deleteRecord(recordId, options) {
2041
+ if (options?.checkSystem) {
2042
+ const record = await this.getRecordOrThrow(recordId);
2043
+ const schema = await this.schemaService.getObjectSchema(record.objectId);
2044
+ if (schema.system) {
2045
+ throw new Error(`Cannot delete record of system object "${schema.label}"`);
2046
+ }
2047
+ }
2048
+ await this.adapter.objectRecords.delete(recordId);
2049
+ }
2050
+ /**
2051
+ * List records for an object with pagination
2052
+ *
2053
+ * @param objectId - Object UUID
2054
+ * @param options - List options
2055
+ * @returns Records and total count
2056
+ */
2057
+ async listRecords(objectId, options) {
2058
+ return await this.adapter.objectRecords.list(this.tenantId, objectId, options);
2059
+ }
2060
+ /**
2061
+ * Search records using full-text search
2062
+ *
2063
+ * @param objectId - Object UUID
2064
+ * @param query - Search query
2065
+ * @param options - Search options
2066
+ * @returns Matching records and total count
2067
+ */
2068
+ async searchRecords(objectId, query, options) {
2069
+ return await this.adapter.objectRecords.search(this.tenantId, objectId, query, options);
2070
+ }
2071
+ /**
2072
+ * Validate data against object schema without saving
2073
+ *
2074
+ * @param objectId - Object UUID
2075
+ * @param data - Data to validate
2076
+ * @returns Validation result
2077
+ */
2078
+ async validateData(objectId, data) {
2079
+ const schema = await this.schemaService.getObjectSchema(objectId);
2080
+ return validateObject(schema, data);
2081
+ }
2082
+ };
2083
+
2084
+ // src/runtime/services/user-profile.service.ts
2085
+ var UserProfileService = class {
2086
+ constructor(adapter, tenantId) {
2087
+ this.adapter = adapter;
2088
+ this.tenantId = tenantId;
2089
+ }
2090
+ /**
2091
+ * Create a new user profile (typically after first auth)
2092
+ *
2093
+ * @param data - User profile creation data
2094
+ * @returns Created user profile
2095
+ *
2096
+ * @example
2097
+ * ```typescript
2098
+ * const service = new UserProfileService(adapter, "tenant-123");
2099
+ *
2100
+ * // After Supabase auth
2101
+ * const profile = await service.createProfile({
2102
+ * tenantId: "tenant-123",
2103
+ * authId: authUser.id,
2104
+ * email: authUser.email,
2105
+ * firstName: authUser.user_metadata.first_name,
2106
+ * lastName: authUser.user_metadata.last_name,
2107
+ * role: "member",
2108
+ * status: "active"
2109
+ * });
2110
+ * ```
2111
+ */
2112
+ async createProfile(data) {
2113
+ if (data.tenantId !== this.tenantId) {
2114
+ throw new Error(
2115
+ `Tenant mismatch: service initialized with "${this.tenantId}" but data has "${data.tenantId}"`
2116
+ );
2117
+ }
2118
+ const existing = await this.adapter.userProfiles.findByAuthId(data.authId);
2119
+ if (existing) {
2120
+ throw new Error(`User profile with authId "${data.authId}" already exists`);
2121
+ }
2122
+ const existingEmail = await this.adapter.userProfiles.findByEmail(this.tenantId, data.email);
2123
+ if (existingEmail) {
2124
+ throw new Error(`User profile with email "${data.email}" already exists in this tenant`);
2125
+ }
2126
+ return await this.adapter.userProfiles.create(data);
2127
+ }
2128
+ /**
2129
+ * Get user profile by ID
2130
+ */
2131
+ async getProfile(profileId) {
2132
+ return await this.adapter.userProfiles.findById(profileId);
2133
+ }
2134
+ /**
2135
+ * Get user profile by ID or throw
2136
+ */
2137
+ async getProfileOrThrow(profileId) {
2138
+ const profile = await this.getProfile(profileId);
2139
+ if (!profile) {
2140
+ throw new Error(`User profile with id "${profileId}" not found`);
2141
+ }
2142
+ return profile;
2143
+ }
2144
+ /**
2145
+ * Get user profile by auth provider ID
2146
+ *
2147
+ * @param authId - Auth provider user ID (Supabase, Clerk, etc.)
2148
+ * @returns User profile or null
2149
+ */
2150
+ async getProfileByAuthId(authId) {
2151
+ return await this.adapter.userProfiles.findByAuthId(authId);
2152
+ }
2153
+ /**
2154
+ * Get or create user profile (idempotent operation)
2155
+ * Useful for auth callbacks - ensures profile exists
2156
+ *
2157
+ * @param authId - Auth provider user ID
2158
+ * @param data - Profile data to create if doesn't exist
2159
+ * @returns Existing or newly created profile
2160
+ *
2161
+ * @example
2162
+ * ```typescript
2163
+ * // In Supabase auth callback
2164
+ * const profile = await service.getOrCreateProfile(
2165
+ * authUser.id,
2166
+ * {
2167
+ * tenantId: "tenant-123",
2168
+ * authId: authUser.id,
2169
+ * email: authUser.email,
2170
+ * role: "member",
2171
+ * status: "active"
2172
+ * }
2173
+ * );
2174
+ * ```
2175
+ */
2176
+ async getOrCreateProfile(authId, data) {
2177
+ const existing = await this.getProfileByAuthId(authId);
2178
+ if (existing) {
2179
+ return existing;
2180
+ }
2181
+ return await this.createProfile(data);
2182
+ }
2183
+ /**
2184
+ * Update user profile
2185
+ */
2186
+ async updateProfile(profileId, data) {
2187
+ await this.getProfileOrThrow(profileId);
2188
+ return await this.adapter.userProfiles.update(profileId, data);
2189
+ }
2190
+ /**
2191
+ * Delete user profile
2192
+ *
2193
+ * @param profileId - Profile UUID
2194
+ * @param options - Delete options
2195
+ */
2196
+ async deleteProfile(profileId, options) {
2197
+ if (options?.checkAdmin) {
2198
+ const profile = await this.getProfileOrThrow(profileId);
2199
+ if (profile.role === "admin") {
2200
+ const allProfiles = await this.listProfiles();
2201
+ const adminCount = allProfiles.filter((p) => p.role === "admin").length;
2202
+ if (adminCount <= 1) {
2203
+ throw new Error("Cannot delete the last admin user");
2204
+ }
2205
+ }
2206
+ }
2207
+ await this.adapter.userProfiles.delete(profileId);
2208
+ }
2209
+ /**
2210
+ * List all user profiles for the tenant
2211
+ */
2212
+ async listProfiles(options) {
2213
+ return await this.adapter.userProfiles.list(this.tenantId, options);
2214
+ }
2215
+ /**
2216
+ * Update last login timestamp
2217
+ *
2218
+ * @param profileId - Profile UUID
2219
+ *
2220
+ * @example
2221
+ * ```typescript
2222
+ * // After successful auth
2223
+ * await service.updateLastLogin(profile.id);
2224
+ * ```
2225
+ */
2226
+ async updateLastLogin(profileId) {
2227
+ await this.adapter.userProfiles.updateLastLogin(profileId);
2228
+ }
2229
+ /**
2230
+ * Change user role
2231
+ *
2232
+ * @param profileId - Profile UUID
2233
+ * @param newRole - New role
2234
+ */
2235
+ async changeRole(profileId, newRole) {
2236
+ return await this.updateProfile(profileId, { role: newRole });
2237
+ }
2238
+ /**
2239
+ * Change user status
2240
+ *
2241
+ * @param profileId - Profile UUID
2242
+ * @param newStatus - New status
2243
+ */
2244
+ async changeStatus(profileId, newStatus) {
2245
+ return await this.updateProfile(profileId, { status: newStatus });
2246
+ }
2247
+ /**
2248
+ * Get user by email
2249
+ */
2250
+ async getProfileByEmail(email) {
2251
+ return await this.adapter.userProfiles.findByEmail(this.tenantId, email);
2252
+ }
2253
+ /**
2254
+ * Check if user has role
2255
+ */
2256
+ async hasRole(profileId, role) {
2257
+ const profile = await this.getProfile(profileId);
2258
+ return profile?.role === role;
2259
+ }
2260
+ /**
2261
+ * Check if user is admin
2262
+ */
2263
+ async isAdmin(profileId) {
2264
+ return await this.hasRole(profileId, "admin");
2265
+ }
2266
+ };
2267
+
2268
+ // src/runtime/sync.ts
2269
+ var BASE_ATTRIBUTE_KEYS = /* @__PURE__ */ new Set([
2270
+ "id",
2271
+ "name",
2272
+ "label",
2273
+ "type",
2274
+ "required",
2275
+ "system",
2276
+ "unique",
2277
+ "order"
2278
+ ]);
2279
+ function extractAttributeConfig(attr) {
2280
+ return Object.fromEntries(
2281
+ Object.entries(attr).filter(
2282
+ ([key, value]) => !BASE_ATTRIBUTE_KEYS.has(key) && value !== void 0
2283
+ )
2284
+ );
2285
+ }
2286
+ async function syncNativeObjects(adapter, nativeRegistry, options = {}) {
2287
+ const result = {
2288
+ success: true,
2289
+ objectsSynced: 0,
2290
+ attributesSynced: 0,
2291
+ objectsCreated: 0,
2292
+ objectsUpdated: 0,
2293
+ attributesCreated: 0,
2294
+ attributesUpdated: 0,
2295
+ attributesDeleted: 0,
2296
+ errors: []
2297
+ };
2298
+ const nativeObjects = nativeRegistry.getAll();
2299
+ if (options.verbose) {
2300
+ console.info(`[SyncService] Starting sync for ${nativeObjects.length} native objects...`);
2301
+ }
2302
+ try {
2303
+ await adapter.transaction(async (tx) => {
2304
+ for (const nativeObject of nativeObjects) {
2305
+ try {
2306
+ await syncSingleObject(tx, nativeObject, result, options);
2307
+ } catch (error) {
2308
+ result.success = false;
2309
+ result.errors.push({
2310
+ objectName: nativeObject.name,
2311
+ error: error instanceof Error ? error.message : String(error)
2312
+ });
2313
+ if (options.verbose) {
2314
+ console.error(`[SyncService] \u2717 Failed to sync ${nativeObject.name}:`, error);
2315
+ }
2316
+ }
2317
+ }
2318
+ });
2319
+ } catch (error) {
2320
+ result.success = false;
2321
+ result.errors.push({
2322
+ objectName: "transaction",
2323
+ error: error instanceof Error ? error.message : String(error)
2324
+ });
2325
+ }
2326
+ if (options.verbose) {
2327
+ console.info(
2328
+ `[SyncService] ${result.success ? "\u2713" : "\u2717"} Sync complete:
2329
+ Objects: ${result.objectsCreated} created, ${result.objectsUpdated} updated
2330
+ Attributes: ${result.attributesCreated} created, ${result.attributesUpdated} updated, ${result.attributesDeleted} deleted
2331
+ Errors: ${result.errors.length}`
2332
+ );
2333
+ }
2334
+ return result;
2335
+ }
2336
+ async function syncSingleObject(adapter, nativeObject, result, options) {
2337
+ if (!nativeObject.system) {
2338
+ throw new Error(`Object ${nativeObject.name} is not marked as system`);
2339
+ }
2340
+ const existingObject = await adapter.objects.findSystemByName(nativeObject.name);
2341
+ const isNew = !existingObject;
2342
+ updateObjectStats(result, isNew);
2343
+ if (options.dryRun) {
2344
+ await handleDryRun(adapter, nativeObject, existingObject, result, options, isNew);
2345
+ return;
2346
+ }
2347
+ const dbObject = await upsertObject(adapter, nativeObject, options);
2348
+ await syncAttributes(adapter, nativeObject, dbObject, existingObject, result);
2349
+ if (!isNew) {
2350
+ await cleanupAttributes(adapter, dbObject.id, nativeObject, result);
2351
+ }
2352
+ logSyncSuccess(nativeObject, options);
2353
+ }
2354
+ function updateObjectStats(result, isNew) {
2355
+ if (isNew) {
2356
+ result.objectsCreated++;
2357
+ } else {
2358
+ result.objectsUpdated++;
2359
+ }
2360
+ result.objectsSynced++;
2361
+ }
2362
+ async function handleDryRun(adapter, nativeObject, existingObject, result, options, isNew) {
2363
+ if (options.verbose) {
2364
+ console.info(`[SyncService] Would ${isNew ? "create" : "update"} object: ${nativeObject.name}`);
2365
+ }
2366
+ for (const attr of nativeObject.attributes) {
2367
+ const existingAttr = existingObject ? await adapter.attributes.findByObjectId(existingObject.id).then((attrs) => attrs.find((a) => a.name === attr.name)) : null;
2368
+ if (existingAttr) {
2369
+ result.attributesUpdated++;
2370
+ } else {
2371
+ result.attributesCreated++;
2372
+ }
2373
+ result.attributesSynced++;
2374
+ }
2375
+ }
2376
+ async function upsertObject(adapter, nativeObject, options) {
2377
+ return await adapter.objects.upsert({
2378
+ tenantId: options.tenantId || "default",
2379
+ system: true,
2380
+ name: nativeObject.name,
2381
+ label: nativeObject.label,
2382
+ description: nativeObject.description,
2383
+ metadata: nativeObject.metadata
2384
+ });
2385
+ }
2386
+ async function syncAttributes(adapter, nativeObject, dbObject, existingObject, result) {
2387
+ for (const [index, attr] of nativeObject.attributes.entries()) {
2388
+ const existingAttr = existingObject ? await adapter.attributes.findByObjectId(dbObject.id).then((attrs) => attrs.find((a) => a.name === attr.name)) : null;
2389
+ await adapter.attributes.upsert({
2390
+ objectId: dbObject.id,
2391
+ name: attr.name,
2392
+ label: attr.label,
2393
+ type: attr.type,
2394
+ system: attr.system ?? true,
2395
+ required: attr.required ?? false,
2396
+ orderIndex: attr.order ?? index,
2397
+ config: extractAttributeConfig(attr)
2398
+ });
2399
+ if (existingAttr) {
2400
+ result.attributesUpdated++;
2401
+ } else {
2402
+ result.attributesCreated++;
2403
+ }
2404
+ result.attributesSynced++;
2405
+ }
2406
+ }
2407
+ async function cleanupAttributes(adapter, objectId, nativeObject, result) {
2408
+ const attributeNames = nativeObject.attributes.map((attr) => attr.name);
2409
+ const deletedCount = await adapter.attributes.deleteByNames(objectId, attributeNames);
2410
+ result.attributesDeleted += deletedCount;
2411
+ }
2412
+ function logSyncSuccess(nativeObject, options) {
2413
+ if (options.verbose) {
2414
+ console.info(
2415
+ `[SyncService] \u2713 Synced ${nativeObject.name}: ${nativeObject.attributes.length} attributes`
2416
+ );
2417
+ }
2418
+ }
2419
+ async function verifyNativeObjectsSync(adapter, nativeRegistry) {
2420
+ const nativeObjects = nativeRegistry.getAll();
2421
+ for (const obj of nativeObjects) {
2422
+ if (!obj.system) continue;
2423
+ const existing = await adapter.objects.findSystemByName(obj.name);
2424
+ if (!existing) {
2425
+ return false;
2426
+ }
2427
+ }
2428
+ return true;
2429
+ }
2430
+ async function getSyncPreview(adapter, nativeRegistry) {
2431
+ return await syncNativeObjects(adapter, nativeRegistry, { dryRun: true });
2432
+ }
2433
+
2434
+ export {
2435
+ generateId,
2436
+ generatePrefixedId,
2437
+ text,
2438
+ textarea,
2439
+ number,
2440
+ checkbox,
2441
+ date,
2442
+ phone,
2443
+ currency,
2444
+ status,
2445
+ select,
2446
+ multiselect,
2447
+ location,
2448
+ timestamp,
2449
+ file,
2450
+ user,
2451
+ relation,
2452
+ rating,
2453
+ ObjectBuilder,
2454
+ object,
2455
+ registry,
2456
+ createTextValidator,
2457
+ createNumberValidator,
2458
+ createCheckboxValidator,
2459
+ createDateValidator,
2460
+ createPhoneValidator,
2461
+ createCurrencyValidator,
2462
+ createStatusValidator,
2463
+ createSelectValidator,
2464
+ createMultiselectValidator,
2465
+ createLocationValidator,
2466
+ createTimestampValidator,
2467
+ createFileValidator,
2468
+ createUserValidator,
2469
+ createRelationValidator,
2470
+ createRatingValidator,
2471
+ createAttributeValidator,
2472
+ createObjectValidator,
2473
+ validateAttribute,
2474
+ validateObject,
2475
+ validateObjectOrThrow,
2476
+ createMockAdapter,
2477
+ FileService,
2478
+ ObjectSchemaService,
2479
+ RecordService,
2480
+ UserProfileService,
2481
+ syncNativeObjects,
2482
+ verifyNativeObjectsSync,
2483
+ getSyncPreview
2484
+ };