@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,2623 @@
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
+ * Phantom type for inference - initialized to force type materialization
712
+ */
713
+ this._types = null;
714
+ }
715
+ unique() {
716
+ this.attr.unique = true;
717
+ return this;
718
+ }
719
+ minLength(value) {
720
+ this.attr.minLength = value;
721
+ return this;
722
+ }
723
+ maxLength(value) {
724
+ this.attr.maxLength = value;
725
+ return this;
726
+ }
727
+ pattern(value) {
728
+ this.attr.pattern = value;
729
+ return this;
730
+ }
731
+ required() {
732
+ this.setRequired(true);
733
+ return this;
734
+ }
735
+ optional() {
736
+ this.setRequired(false);
737
+ return this;
738
+ }
739
+ /**
740
+ * Set email validation pattern
741
+ */
742
+ email() {
743
+ this.attr.pattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
744
+ return this;
745
+ }
746
+ /**
747
+ * Set URL validation pattern
748
+ */
749
+ url() {
750
+ this.attr.pattern = "^https?:\\/\\/[\\w\\-]+(\\.[\\w\\-]+)+[/#?]?.*$";
751
+ return this;
752
+ }
753
+ /**
754
+ * Set slug validation pattern
755
+ */
756
+ slug() {
757
+ this.attr.pattern = "^[a-z0-9]+(?:-[a-z0-9]+)*$";
758
+ return this;
759
+ }
760
+ };
761
+ function text(config) {
762
+ return new TextAttributeBuilder(config.name, config.label);
763
+ }
764
+ var NumberAttributeBuilder = class extends BaseAttributeBuilder {
765
+ constructor(name, label) {
766
+ super("number", name, label);
767
+ this._types = null;
768
+ }
769
+ unique() {
770
+ this.attr.unique = true;
771
+ return this;
772
+ }
773
+ multiple() {
774
+ this.attr.multiple = true;
775
+ return this;
776
+ }
777
+ min(value) {
778
+ this.attr.min = value;
779
+ return this;
780
+ }
781
+ max(value) {
782
+ this.attr.max = value;
783
+ return this;
784
+ }
785
+ integer() {
786
+ this.attr.unit = "integer";
787
+ this.attr.decimals = 0;
788
+ return this;
789
+ }
790
+ decimal(decimals = 2) {
791
+ this.attr.unit = "decimal";
792
+ this.attr.decimals = decimals;
793
+ return this;
794
+ }
795
+ percentage() {
796
+ this.attr.unit = "percentage";
797
+ return this;
798
+ }
799
+ required() {
800
+ this.setRequired(true);
801
+ return this;
802
+ }
803
+ optional() {
804
+ this.setRequired(false);
805
+ return this;
806
+ }
807
+ };
808
+ function number(config) {
809
+ return new NumberAttributeBuilder(config.name, config.label);
810
+ }
811
+ var CheckboxAttributeBuilder = class extends BaseAttributeBuilder {
812
+ constructor(name, label) {
813
+ super("checkbox", name, label);
814
+ this._types = null;
815
+ }
816
+ unique() {
817
+ this.attr.unique = true;
818
+ return this;
819
+ }
820
+ required() {
821
+ this.setRequired(true);
822
+ return this;
823
+ }
824
+ optional() {
825
+ this.setRequired(false);
826
+ return this;
827
+ }
828
+ };
829
+ function checkbox(config) {
830
+ return new CheckboxAttributeBuilder(config.name, config.label);
831
+ }
832
+ var DateAttributeBuilder = class extends BaseAttributeBuilder {
833
+ constructor(name, label) {
834
+ super("date", name, label);
835
+ this._types = null;
836
+ }
837
+ unique() {
838
+ this.attr.unique = true;
839
+ return this;
840
+ }
841
+ multiple() {
842
+ this.attr.multiple = true;
843
+ return this;
844
+ }
845
+ format(value) {
846
+ this.attr.dateFormat = value;
847
+ return this;
848
+ }
849
+ minDate(value) {
850
+ this.attr.minDate = value;
851
+ return this;
852
+ }
853
+ maxDate(value) {
854
+ this.attr.maxDate = value;
855
+ return this;
856
+ }
857
+ required() {
858
+ this.setRequired(true);
859
+ return this;
860
+ }
861
+ optional() {
862
+ this.setRequired(false);
863
+ return this;
864
+ }
865
+ };
866
+ function date(config) {
867
+ return new DateAttributeBuilder(config.name, config.label);
868
+ }
869
+ var PhoneAttributeBuilder = class extends BaseAttributeBuilder {
870
+ constructor(name, label) {
871
+ super("phone", name, label);
872
+ this._types = null;
873
+ }
874
+ unique() {
875
+ this.attr.unique = true;
876
+ return this;
877
+ }
878
+ multiple() {
879
+ this.attr.multiple = true;
880
+ return this;
881
+ }
882
+ defaultCountry(value) {
883
+ this.attr.defaultCountryCode = 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 phone(config) {
896
+ return new PhoneAttributeBuilder(config.name, config.label);
897
+ }
898
+ var CurrencyAttributeBuilder = class extends BaseAttributeBuilder {
899
+ constructor(name, label) {
900
+ super("currency", name, label);
901
+ this._types = null;
902
+ }
903
+ unique() {
904
+ this.attr.unique = true;
905
+ return this;
906
+ }
907
+ multiple() {
908
+ this.attr.multiple = true;
909
+ return this;
910
+ }
911
+ defaultCurrency(value) {
912
+ this.attr.defaultCurrency = value;
913
+ return this;
914
+ }
915
+ allowedCurrencies(value) {
916
+ this.attr.allowedCurrencies = value;
917
+ return this;
918
+ }
919
+ required() {
920
+ this.setRequired(true);
921
+ return this;
922
+ }
923
+ optional() {
924
+ this.setRequired(false);
925
+ return this;
926
+ }
927
+ };
928
+ function currency(config) {
929
+ return new CurrencyAttributeBuilder(config.name, config.label);
930
+ }
931
+ var StatusAttributeBuilder = class extends BaseAttributeBuilder {
932
+ constructor(name, label) {
933
+ super("status", name, label);
934
+ this._types = null;
935
+ }
936
+ unique() {
937
+ this.attr.unique = true;
938
+ return this;
939
+ }
940
+ /**
941
+ * Set all options at once (preserves literal types for values)
942
+ */
943
+ options(value) {
944
+ this.attr.options = value;
945
+ return this;
946
+ }
947
+ option(config) {
948
+ if (!this.attr.options) {
949
+ this.attr.options = [];
950
+ }
951
+ this.attr.options.push(config);
952
+ return this;
953
+ }
954
+ required() {
955
+ this.setRequired(true);
956
+ return this;
957
+ }
958
+ optional() {
959
+ this.setRequired(false);
960
+ return this;
961
+ }
962
+ };
963
+ function status(config) {
964
+ return new StatusAttributeBuilder(config.name, config.label);
965
+ }
966
+ var SelectAttributeBuilder = class extends BaseAttributeBuilder {
967
+ constructor(name, label) {
968
+ super("select", name, label);
969
+ this._types = null;
970
+ }
971
+ unique() {
972
+ this.attr.unique = true;
973
+ return this;
974
+ }
975
+ /**
976
+ * Set all options at once (preserves literal types for values)
977
+ */
978
+ options(value) {
979
+ this.attr.options = value;
980
+ return this;
981
+ }
982
+ option(config) {
983
+ if (!this.attr.options) {
984
+ this.attr.options = [];
985
+ }
986
+ this.attr.options.push(config);
987
+ return this;
988
+ }
989
+ required() {
990
+ this.setRequired(true);
991
+ return this;
992
+ }
993
+ optional() {
994
+ this.setRequired(false);
995
+ return this;
996
+ }
997
+ };
998
+ function select(config) {
999
+ return new SelectAttributeBuilder(config.name, config.label);
1000
+ }
1001
+ var MultiselectAttributeBuilder = class extends BaseAttributeBuilder {
1002
+ constructor(name, label) {
1003
+ super("multiselect", name, label);
1004
+ this._types = null;
1005
+ }
1006
+ unique() {
1007
+ this.attr.unique = true;
1008
+ return this;
1009
+ }
1010
+ /**
1011
+ * Set all options at once (preserves literal types for values)
1012
+ */
1013
+ options(value) {
1014
+ this.attr.options = value;
1015
+ return this;
1016
+ }
1017
+ option(config) {
1018
+ if (!this.attr.options) {
1019
+ this.attr.options = [];
1020
+ }
1021
+ this.attr.options.push(config);
1022
+ return this;
1023
+ }
1024
+ required() {
1025
+ this.setRequired(true);
1026
+ return this;
1027
+ }
1028
+ optional() {
1029
+ this.setRequired(false);
1030
+ return this;
1031
+ }
1032
+ };
1033
+ function multiselect(config) {
1034
+ return new MultiselectAttributeBuilder(config.name, config.label);
1035
+ }
1036
+ var LocationAttributeBuilder = class extends BaseAttributeBuilder {
1037
+ constructor(name, label) {
1038
+ super("location", name, label);
1039
+ this._types = null;
1040
+ }
1041
+ unique() {
1042
+ this.attr.unique = true;
1043
+ return this;
1044
+ }
1045
+ multiple() {
1046
+ this.attr.multiple = true;
1047
+ return this;
1048
+ }
1049
+ granularity(value) {
1050
+ this.attr.granularity = value;
1051
+ return this;
1052
+ }
1053
+ enableAutocomplete() {
1054
+ this.attr.enableAutocomplete = true;
1055
+ return this;
1056
+ }
1057
+ enableMap() {
1058
+ this.attr.enableMap = true;
1059
+ return this;
1060
+ }
1061
+ defaultCountry(value) {
1062
+ this.attr.defaultCountry = value;
1063
+ return this;
1064
+ }
1065
+ allowedCountries(value) {
1066
+ this.attr.allowedCountries = value;
1067
+ return this;
1068
+ }
1069
+ displayFormat(value) {
1070
+ this.attr.displayFormat = value;
1071
+ return this;
1072
+ }
1073
+ required() {
1074
+ this.setRequired(true);
1075
+ return this;
1076
+ }
1077
+ optional() {
1078
+ this.setRequired(false);
1079
+ return this;
1080
+ }
1081
+ };
1082
+ function location(config) {
1083
+ return new LocationAttributeBuilder(config.name, config.label);
1084
+ }
1085
+ var TimestampAttributeBuilder = class extends BaseAttributeBuilder {
1086
+ constructor(name, label) {
1087
+ super("timestamp", name, label);
1088
+ this._types = null;
1089
+ }
1090
+ unique() {
1091
+ this.attr.unique = true;
1092
+ return this;
1093
+ }
1094
+ multiple() {
1095
+ this.attr.multiple = true;
1096
+ return this;
1097
+ }
1098
+ autoUpdate() {
1099
+ this.attr.autoUpdate = true;
1100
+ return this;
1101
+ }
1102
+ required() {
1103
+ this.setRequired(true);
1104
+ return this;
1105
+ }
1106
+ optional() {
1107
+ this.setRequired(false);
1108
+ return this;
1109
+ }
1110
+ };
1111
+ function timestamp(config) {
1112
+ return new TimestampAttributeBuilder(config.name, config.label);
1113
+ }
1114
+ var FileAttributeBuilder = class extends BaseAttributeBuilder {
1115
+ constructor(name, label) {
1116
+ super("file", name, label);
1117
+ this._types = null;
1118
+ }
1119
+ unique() {
1120
+ this.attr.unique = true;
1121
+ return this;
1122
+ }
1123
+ multiple(maxFiles) {
1124
+ this.attr.multiple = true;
1125
+ if (maxFiles !== void 0) {
1126
+ this.attr.maxFiles = maxFiles;
1127
+ }
1128
+ return this;
1129
+ }
1130
+ maxSize(bytes) {
1131
+ this.attr.maxSize = bytes;
1132
+ return this;
1133
+ }
1134
+ allowedTypes(types) {
1135
+ this.attr.allowedTypes = types;
1136
+ return this;
1137
+ }
1138
+ verification(config) {
1139
+ this.attr.verification = config;
1140
+ return this;
1141
+ }
1142
+ required() {
1143
+ this.setRequired(true);
1144
+ return this;
1145
+ }
1146
+ optional() {
1147
+ this.setRequired(false);
1148
+ return this;
1149
+ }
1150
+ };
1151
+ function file(config) {
1152
+ return new FileAttributeBuilder(config.name, config.label);
1153
+ }
1154
+ var UserAttributeBuilder = class extends BaseAttributeBuilder {
1155
+ constructor(name, label) {
1156
+ super("user", name, label);
1157
+ this._types = null;
1158
+ }
1159
+ unique() {
1160
+ this.attr.unique = true;
1161
+ return this;
1162
+ }
1163
+ multiple() {
1164
+ this.attr.multiple = true;
1165
+ return this;
1166
+ }
1167
+ allowedRoles(roles) {
1168
+ this.attr.allowedRoles = roles;
1169
+ return this;
1170
+ }
1171
+ required() {
1172
+ this.setRequired(true);
1173
+ return this;
1174
+ }
1175
+ optional() {
1176
+ this.setRequired(false);
1177
+ return this;
1178
+ }
1179
+ };
1180
+ function user(config) {
1181
+ return new UserAttributeBuilder(config.name, config.label);
1182
+ }
1183
+ var RelationAttributeBuilder = class extends BaseAttributeBuilder {
1184
+ constructor(name, label) {
1185
+ super("relation", name, label);
1186
+ this._types = null;
1187
+ }
1188
+ unique() {
1189
+ this.attr.unique = true;
1190
+ return this;
1191
+ }
1192
+ multiple(limit) {
1193
+ this.attr.multiple = true;
1194
+ if (limit !== void 0) {
1195
+ this.attr.limit = limit;
1196
+ }
1197
+ return this;
1198
+ }
1199
+ relation(objectIds) {
1200
+ this.attr.relation = objectIds;
1201
+ return this;
1202
+ }
1203
+ cascadeDelete() {
1204
+ this.attr.cascadeDelete = true;
1205
+ return this;
1206
+ }
1207
+ required() {
1208
+ this.setRequired(true);
1209
+ return this;
1210
+ }
1211
+ optional() {
1212
+ this.setRequired(false);
1213
+ return this;
1214
+ }
1215
+ };
1216
+ function relation(config) {
1217
+ return new RelationAttributeBuilder(config.name, config.label);
1218
+ }
1219
+ var RatingAttributeBuilder = class extends BaseAttributeBuilder {
1220
+ constructor(name, label) {
1221
+ super("rating", name, label);
1222
+ this._types = null;
1223
+ }
1224
+ unique() {
1225
+ this.attr.unique = true;
1226
+ return this;
1227
+ }
1228
+ max(value) {
1229
+ this.attr.max = value;
1230
+ return this;
1231
+ }
1232
+ iconType(value) {
1233
+ this.attr.iconType = value;
1234
+ return this;
1235
+ }
1236
+ required() {
1237
+ this.setRequired(true);
1238
+ return this;
1239
+ }
1240
+ optional() {
1241
+ this.setRequired(false);
1242
+ return this;
1243
+ }
1244
+ };
1245
+ function rating(config) {
1246
+ return new RatingAttributeBuilder(config.name, config.label);
1247
+ }
1248
+
1249
+ // src/builders/object-builder.ts
1250
+ import z2 from "zod";
1251
+ var ObjectBuilder = class {
1252
+ constructor(config) {
1253
+ this.validateName(config.name);
1254
+ this.obj = {
1255
+ name: config.name,
1256
+ label: config.label,
1257
+ attributes: [],
1258
+ system: false
1259
+ };
1260
+ }
1261
+ /**
1262
+ * Set object description
1263
+ */
1264
+ description(value) {
1265
+ this.obj.description = value;
1266
+ return this;
1267
+ }
1268
+ /**
1269
+ * Set object icon
1270
+ */
1271
+ icon(value) {
1272
+ this.obj.icon = value;
1273
+ return this;
1274
+ }
1275
+ /**
1276
+ * Mark as system/native object (defined in code, protected)
1277
+ * System objects cannot be deleted/modified by clients
1278
+ */
1279
+ system() {
1280
+ this.obj.system = true;
1281
+ return this;
1282
+ }
1283
+ /**
1284
+ * Add an attribute to the object with type accumulation
1285
+ *
1286
+ * The return type accumulates the attribute's name and value type
1287
+ * into the TRecord generic, enabling full inference.
1288
+ *
1289
+ * @param attr - Attribute definition or builder (auto-builds if builder)
1290
+ */
1291
+ attribute(attr) {
1292
+ if (!this.obj.attributes) {
1293
+ this.obj.attributes = [];
1294
+ }
1295
+ const finalAttr = "build" in attr && typeof attr.build === "function" ? attr.build() : attr;
1296
+ this.obj.attributes.push(finalAttr);
1297
+ return this;
1298
+ }
1299
+ /**
1300
+ * Add multiple attributes at once
1301
+ * Note: For full type inference, prefer chaining .attribute() calls
1302
+ */
1303
+ attributes(attrs) {
1304
+ if (!this.obj.attributes) {
1305
+ this.obj.attributes = [];
1306
+ }
1307
+ const finalAttrs = attrs.map((attr) => "build" in attr ? attr.build() : attr);
1308
+ this.obj.attributes.push(...finalAttrs);
1309
+ return this;
1310
+ }
1311
+ /**
1312
+ * Set metadata
1313
+ */
1314
+ metadata(value) {
1315
+ this.obj.metadata = value;
1316
+ return this;
1317
+ }
1318
+ /**
1319
+ * Build the final ObjectDefinition
1320
+ * @throws Error if required fields are missing or invalid
1321
+ */
1322
+ build() {
1323
+ if (!this.obj.name) {
1324
+ throw new Error("[ObjectBuilder] Missing required field: name");
1325
+ }
1326
+ if (!this.obj.label) {
1327
+ throw new Error("[ObjectBuilder] Missing required field: label");
1328
+ }
1329
+ return this.obj;
1330
+ }
1331
+ /**
1332
+ * Validate object name format
1333
+ * Must be kebab-case (slug format), max 63 characters
1334
+ * @internal
1335
+ */
1336
+ validateName(name) {
1337
+ if (name === void 0) {
1338
+ return;
1339
+ }
1340
+ 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-]*$/, {
1341
+ 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'"
1342
+ });
1343
+ try {
1344
+ objectNameSchema.parse(name);
1345
+ } catch (error) {
1346
+ if (error instanceof z2.ZodError) {
1347
+ throw new Error(`[ObjectBuilder] ${error.errors[0].message}`);
1348
+ }
1349
+ throw error;
1350
+ }
1351
+ }
1352
+ };
1353
+ function object(config) {
1354
+ return new ObjectBuilder(config);
1355
+ }
1356
+
1357
+ // src/runtime/services/object-schema.service.ts
1358
+ var ObjectSchemaService = class {
1359
+ constructor(adapter, nativeRegistry) {
1360
+ this.adapter = adapter;
1361
+ this.nativeRegistry = nativeRegistry;
1362
+ }
1363
+ /**
1364
+ * Create a new custom object
1365
+ * Validates name format and ensures system=false
1366
+ *
1367
+ * @param definition - Object definition (attributes can be raw definitions or builders)
1368
+ * @param tenantId - Tenant ID owning the object
1369
+ * @returns Created ObjectDefinition
1370
+ */
1371
+ async createCustomObject(definition, tenantId) {
1372
+ const builder = object({
1373
+ name: definition.name,
1374
+ label: definition.label
1375
+ });
1376
+ if (definition.description) builder.description(definition.description);
1377
+ if (definition.icon) builder.icon(definition.icon);
1378
+ if (definition.metadata) builder.metadata(definition.metadata);
1379
+ if (definition.attributes && definition.attributes.length > 0) {
1380
+ builder.attributes(definition.attributes);
1381
+ }
1382
+ const objectDef = builder.build();
1383
+ const existing = await this.adapter.objects.findByName(tenantId, objectDef.name);
1384
+ if (existing) {
1385
+ throw new Error(`Object with name "${objectDef.name}" already exists`);
1386
+ }
1387
+ const metadata = {
1388
+ ...objectDef.metadata,
1389
+ icon: objectDef.icon
1390
+ };
1391
+ const dbObject = await this.adapter.objects.create({
1392
+ tenantId,
1393
+ name: objectDef.name,
1394
+ label: objectDef.label,
1395
+ description: objectDef.description,
1396
+ system: false,
1397
+ // Always false for custom objects
1398
+ metadata
1399
+ });
1400
+ const createdAttributes = [];
1401
+ if (objectDef.attributes.length > 0) {
1402
+ for (const attr of objectDef.attributes) {
1403
+ const dbAttr = await this.adapter.attributes.create({
1404
+ objectId: dbObject.id,
1405
+ name: attr.name,
1406
+ label: attr.label,
1407
+ type: attr.type,
1408
+ required: attr.required ?? false,
1409
+ unique: attr.unique ?? false,
1410
+ system: false,
1411
+ // Always false for custom attributes
1412
+ config: {
1413
+ ...attr,
1414
+ // Remove common fields stored in columns
1415
+ id: void 0,
1416
+ name: void 0,
1417
+ label: void 0,
1418
+ type: void 0,
1419
+ required: void 0,
1420
+ unique: void 0,
1421
+ system: void 0
1422
+ }
1423
+ });
1424
+ createdAttributes.push(this.convertDBAttributeToAttribute(dbAttr));
1425
+ }
1426
+ }
1427
+ return {
1428
+ ...objectDef,
1429
+ id: dbObject.id,
1430
+ attributes: createdAttributes,
1431
+ system: false
1432
+ };
1433
+ }
1434
+ /**
1435
+ * Add a custom attribute to an existing object
1436
+ * Can be used on both custom and native objects
1437
+ * Attributes added via API are always custom (system=false)
1438
+ *
1439
+ * @param objectId - Object UUID from database
1440
+ * @param attribute - Attribute definition
1441
+ * @returns Created Attribute
1442
+ */
1443
+ async addAttributeToObject(objectId, attribute) {
1444
+ this.validateAttributeName(attribute.name);
1445
+ const dbObject = await this.adapter.objects.findById(objectId);
1446
+ if (!dbObject) {
1447
+ throw new Error(`Object with id "${objectId}" not found`);
1448
+ }
1449
+ const existingAttributes = await this.adapter.attributes.findByObjectId(objectId);
1450
+ const duplicate = existingAttributes.find((attr) => attr.name === attribute.name);
1451
+ if (duplicate) {
1452
+ throw new Error(
1453
+ `Attribute with name "${attribute.name}" already exists on object "${dbObject.name}"`
1454
+ );
1455
+ }
1456
+ const dbAttr = await this.adapter.attributes.create({
1457
+ objectId,
1458
+ name: attribute.name,
1459
+ label: attribute.label,
1460
+ type: attribute.type,
1461
+ required: attribute.required ?? false,
1462
+ unique: attribute.unique ?? false,
1463
+ system: false,
1464
+ // Always false for attributes added via API
1465
+ config: {
1466
+ // Store all extra properties in config
1467
+ ...attribute,
1468
+ // Remove common fields stored in columns
1469
+ name: void 0,
1470
+ label: void 0,
1471
+ type: void 0,
1472
+ required: void 0,
1473
+ unique: void 0,
1474
+ system: void 0
1475
+ }
1476
+ });
1477
+ return this.convertDBAttributeToAttribute(dbAttr);
1478
+ }
1479
+ /**
1480
+ * Update an attribute
1481
+ * Can only update custom attributes (system=false)
1482
+ *
1483
+ * @param attributeId - Attribute UUID
1484
+ * @param updates - Partial attribute updates
1485
+ * @returns Updated Attribute
1486
+ */
1487
+ async updateAttribute(attributeId, updates) {
1488
+ const dbAttr = await this.adapter.attributes.findById(attributeId);
1489
+ if (!dbAttr) {
1490
+ throw new Error(`Attribute with id "${attributeId}" not found`);
1491
+ }
1492
+ if (dbAttr.system) {
1493
+ throw new Error(
1494
+ `Cannot modify system attribute "${dbAttr.name}". System attributes are protected.`
1495
+ );
1496
+ }
1497
+ if (updates.name && updates.name !== dbAttr.name) {
1498
+ throw new Error(
1499
+ "Attribute name cannot be changed after creation. Create a new attribute instead."
1500
+ );
1501
+ }
1502
+ if (updates.type && updates.type !== dbAttr.type) {
1503
+ throw new Error(
1504
+ "Attribute type cannot be changed after creation. Create a new attribute instead."
1505
+ );
1506
+ }
1507
+ const updatedDbAttr = await this.adapter.attributes.update(attributeId, {
1508
+ label: updates.label,
1509
+ required: updates.required,
1510
+ config: updates ? {
1511
+ ...dbAttr.config,
1512
+ ...updates,
1513
+ // Remove common fields
1514
+ name: void 0,
1515
+ label: void 0,
1516
+ type: void 0,
1517
+ required: void 0,
1518
+ unique: void 0,
1519
+ system: void 0
1520
+ } : dbAttr.config
1521
+ });
1522
+ return this.convertDBAttributeToAttribute(updatedDbAttr);
1523
+ }
1524
+ /**
1525
+ * Delete an attribute
1526
+ * Can only delete custom attributes (system=false)
1527
+ *
1528
+ * @param attributeId - Attribute UUID
1529
+ */
1530
+ async deleteAttribute(attributeId) {
1531
+ const dbAttr = await this.adapter.attributes.findById(attributeId);
1532
+ if (!dbAttr) {
1533
+ throw new Error(`Attribute with id "${attributeId}" not found`);
1534
+ }
1535
+ if (dbAttr.system) {
1536
+ throw new Error(
1537
+ `Cannot delete system attribute "${dbAttr.name}". System attributes are protected.`
1538
+ );
1539
+ }
1540
+ await this.adapter.attributes.delete(attributeId);
1541
+ }
1542
+ /**
1543
+ * List attributes for an object
1544
+ *
1545
+ * @param objectId - Object UUID
1546
+ * @param options - Filter options
1547
+ * @returns List of attributes
1548
+ */
1549
+ async listAttributes(objectId, options) {
1550
+ const dbAttributes = await this.adapter.attributes.findByObjectId(objectId);
1551
+ let filtered = dbAttributes;
1552
+ if (options?.systemOnly) {
1553
+ filtered = dbAttributes.filter((attr) => attr.system);
1554
+ } else if (options?.customOnly) {
1555
+ filtered = dbAttributes.filter((attr) => !attr.system);
1556
+ }
1557
+ return filtered.map((attr) => this.convertDBAttributeToAttribute(attr));
1558
+ }
1559
+ /**
1560
+ * Validate attribute name format (variable identifier)
1561
+ * @internal
1562
+ */
1563
+ validateAttributeName(name) {
1564
+ const variableNameRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
1565
+ if (!name || name.length === 0) {
1566
+ throw new Error("Attribute name cannot be empty");
1567
+ }
1568
+ if (name.length > 63) {
1569
+ throw new Error("Attribute name is too long (max 63 characters)");
1570
+ }
1571
+ if (!variableNameRegex.test(name)) {
1572
+ throw new Error(
1573
+ "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'"
1574
+ );
1575
+ }
1576
+ }
1577
+ /**
1578
+ * Get complete object schema (system + custom attributes)
1579
+ * If object is native, merges registry definition with DB custom attributes
1580
+ * If object is custom, returns DB definition only
1581
+ *
1582
+ * @param objectId - Object UUID from database
1583
+ * @returns Complete ObjectDefinition with all attributes
1584
+ *
1585
+ * @example
1586
+ * ```typescript
1587
+ * const service = new ObjectSchemaService(adapter, registry);
1588
+ * const productSchema = await service.getObjectSchema("obj-123");
1589
+ *
1590
+ * console.log(productSchema.attributes); // System + custom attributes
1591
+ * ```
1592
+ */
1593
+ async getObjectSchema(objectId) {
1594
+ const dbObject = await this.adapter.objects.findById(objectId);
1595
+ if (!dbObject) {
1596
+ throw new Error(`Object with id "${objectId}" not found`);
1597
+ }
1598
+ const dbAttributes = await this.adapter.attributes.findByObjectId(objectId);
1599
+ if (dbObject.system) {
1600
+ return this.mergeNativeObject(dbObject, dbAttributes);
1601
+ }
1602
+ return this.convertDBObjectToDefinition(dbObject, dbAttributes);
1603
+ }
1604
+ /**
1605
+ * Get object schema by name (for system/native objects)
1606
+ */
1607
+ async getObjectSchemaByName(name) {
1608
+ const dbObject = await this.adapter.objects.findSystemByName(name);
1609
+ if (!dbObject) {
1610
+ throw new Error(`Native object "${name}" not found in database`);
1611
+ }
1612
+ const dbAttributes = await this.adapter.attributes.findByObjectId(dbObject.id);
1613
+ return this.mergeNativeObject(dbObject, dbAttributes);
1614
+ }
1615
+ /**
1616
+ * List all object schemas for a tenant
1617
+ */
1618
+ async listObjectSchemas(tenantId) {
1619
+ const dbObjects = await this.adapter.objects.list(tenantId);
1620
+ const schemas = await Promise.all(
1621
+ dbObjects.map(async (dbObject) => {
1622
+ const dbAttributes = await this.adapter.attributes.findByObjectId(dbObject.id);
1623
+ if (dbObject.system) {
1624
+ return this.mergeNativeObject(dbObject, dbAttributes);
1625
+ }
1626
+ return this.convertDBObjectToDefinition(dbObject, dbAttributes);
1627
+ })
1628
+ );
1629
+ return schemas;
1630
+ }
1631
+ /**
1632
+ * Merge native object from registry with custom attributes from DB
1633
+ * @internal
1634
+ */
1635
+ mergeNativeObject(dbObject, dbAttributes) {
1636
+ const nativeObject = this.nativeRegistry.getByName(dbObject.name);
1637
+ if (!nativeObject) {
1638
+ throw new Error(
1639
+ `Native object "${dbObject.name}" not found in registry. Make sure to register it before querying.`
1640
+ );
1641
+ }
1642
+ const customAttributes = dbAttributes.filter((attr) => !attr.system);
1643
+ const customAttrs = customAttributes.map(
1644
+ (dbAttr) => this.convertDBAttributeToAttribute(dbAttr)
1645
+ );
1646
+ return {
1647
+ ...nativeObject,
1648
+ id: dbObject.id,
1649
+ attributes: [
1650
+ ...nativeObject.attributes,
1651
+ // System attributes from code
1652
+ ...customAttrs
1653
+ // Custom attributes from DB
1654
+ ]
1655
+ };
1656
+ }
1657
+ /**
1658
+ * Convert DB object + attributes to ObjectDefinition
1659
+ * @internal
1660
+ */
1661
+ convertDBObjectToDefinition(dbObject, dbAttributes) {
1662
+ const attributes = dbAttributes.map(
1663
+ (dbAttr) => this.convertDBAttributeToAttribute(dbAttr)
1664
+ );
1665
+ return {
1666
+ id: dbObject.id,
1667
+ name: dbObject.name,
1668
+ label: dbObject.label,
1669
+ description: dbObject.description,
1670
+ icon: dbObject.metadata?.icon,
1671
+ attributes,
1672
+ system: dbObject.system,
1673
+ metadata: dbObject.metadata
1674
+ };
1675
+ }
1676
+ /**
1677
+ * Convert DB attribute to Attribute type
1678
+ * @internal
1679
+ */
1680
+ convertDBAttributeToAttribute(dbAttr) {
1681
+ const baseAttr = {
1682
+ ...dbAttr.config,
1683
+ id: dbAttr.id,
1684
+ name: dbAttr.name,
1685
+ label: dbAttr.label,
1686
+ type: dbAttr.type,
1687
+ required: dbAttr.required,
1688
+ system: dbAttr.system,
1689
+ unique: dbAttr.unique
1690
+ };
1691
+ return baseAttr;
1692
+ }
1693
+ };
1694
+
1695
+ // src/native/registry.ts
1696
+ var NativeObjectRegistryClass = class {
1697
+ constructor() {
1698
+ this.objects = /* @__PURE__ */ new Map();
1699
+ }
1700
+ /**
1701
+ * Register one or more native objects
1702
+ * Auto-builds if ObjectBuilder is passed instead of ObjectDefinition
1703
+ * @param objects - Single object/builder or array of objects/builders to register
1704
+ * @returns this (for chaining)
1705
+ * @throws Error if object is invalid or already registered
1706
+ *
1707
+ * @example
1708
+ * ```typescript
1709
+ * // No .build() needed - registry auto-builds!
1710
+ * const PRODUCT = object({ id: "obj-product", name: "products", label: "Product" })
1711
+ * .system()
1712
+ * .attribute(text({ id: "attr-name", name: "name", label: "Name" }));
1713
+ *
1714
+ * registry.register(PRODUCT); // ← Auto-builds here
1715
+ *
1716
+ * // Can still explicitly .build() if you want
1717
+ * registry.register(PRODUCT.build());
1718
+ *
1719
+ * // Register multiple
1720
+ * registry.register([PRODUCT, ORDER, CUSTOMER]);
1721
+ * ```
1722
+ */
1723
+ register(objects) {
1724
+ const objectsArray = Array.isArray(objects) ? objects : [objects];
1725
+ for (const obj of objectsArray) {
1726
+ const object2 = "build" in obj && typeof obj.build === "function" ? obj.build() : obj;
1727
+ this.validateAndRegister(object2);
1728
+ }
1729
+ return this;
1730
+ }
1731
+ /**
1732
+ * Validate and register a single object
1733
+ * @internal
1734
+ */
1735
+ validateAndRegister(object2) {
1736
+ if (!object2.system) {
1737
+ throw new Error(
1738
+ `[NativeObjectRegistry] Cannot register object "${object2.name}" (id: ${object2.id}): missing system flag.
1739
+ Native objects must have system=true. Did you forget to call .system() in your builder?`
1740
+ );
1741
+ }
1742
+ if (this.objects.has(object2.name)) {
1743
+ const existing = this.objects.get(object2.name);
1744
+ throw new Error(
1745
+ `[NativeObjectRegistry] Duplicate object name "${object2.name}":
1746
+ - Existing: "${existing?.label}" (id: ${existing?.id})
1747
+ - New: "${object2.label}" (id: ${object2.id})
1748
+ Please use unique names for each native object.`
1749
+ );
1750
+ }
1751
+ this.objects.set(object2.name, object2);
1752
+ }
1753
+ /**
1754
+ * Get a native object by its name
1755
+ * @param name - The object name
1756
+ * @returns The object definition or undefined if not found
1757
+ *
1758
+ * @example
1759
+ * ```typescript
1760
+ * const product = registry.getByName("products");
1761
+ * if (product) {
1762
+ * console.log(product.label); // "Product"
1763
+ * }
1764
+ * ```
1765
+ */
1766
+ getByName(name) {
1767
+ return this.objects.get(name);
1768
+ }
1769
+ /**
1770
+ * Get a native object or throw if not found
1771
+ * @param name - The object name
1772
+ * @returns The object definition
1773
+ * @throws Error if not found
1774
+ */
1775
+ getByNameOrThrow(name) {
1776
+ const object2 = this.objects.get(name);
1777
+ if (!object2) {
1778
+ throw new Error(
1779
+ `[NativeObjectRegistry] Native object "${name}" not found.
1780
+ Available objects: ${this.listNames().join(", ")}`
1781
+ );
1782
+ }
1783
+ return object2;
1784
+ }
1785
+ /**
1786
+ * Get all registered native objects
1787
+ * @returns Array of all registered object definitions
1788
+ */
1789
+ getAll() {
1790
+ return Array.from(this.objects.values());
1791
+ }
1792
+ /**
1793
+ * Get all registered native object names
1794
+ * @returns Array of object names
1795
+ */
1796
+ listNames() {
1797
+ return Array.from(this.objects.keys());
1798
+ }
1799
+ /**
1800
+ * Check if a native object is registered
1801
+ * @param name - The object name
1802
+ * @returns true if registered, false otherwise
1803
+ */
1804
+ has(name) {
1805
+ return this.objects.has(name);
1806
+ }
1807
+ /**
1808
+ * Get the number of registered objects
1809
+ */
1810
+ get size() {
1811
+ return this.objects.size;
1812
+ }
1813
+ /**
1814
+ * Clear all registered objects (useful for testing)
1815
+ * @internal
1816
+ */
1817
+ clear() {
1818
+ this.objects.clear();
1819
+ }
1820
+ /**
1821
+ * Get registry summary for debugging
1822
+ */
1823
+ summary() {
1824
+ const objects = this.getAll();
1825
+ return [
1826
+ `[NativeObjectRegistry] ${this.size} native object(s) registered:`,
1827
+ ...objects.map(
1828
+ (obj) => ` - ${obj.name}: "${obj.label}" (${obj.attributes.length} attributes)`
1829
+ )
1830
+ ].join("\n");
1831
+ }
1832
+ /**
1833
+ * Log registry summary to console
1834
+ */
1835
+ debug() {
1836
+ console.info(this.summary());
1837
+ }
1838
+ };
1839
+ var registry = new NativeObjectRegistryClass();
1840
+
1841
+ // src/validation/validators.ts
1842
+ import { z as z3 } from "zod";
1843
+ function createTextValidator(attr) {
1844
+ let schema = z3.string();
1845
+ if (attr.minLength !== void 0) {
1846
+ schema = schema.min(
1847
+ attr.minLength,
1848
+ `${attr.label} must be at least ${attr.minLength} characters`
1849
+ );
1850
+ }
1851
+ if (attr.maxLength !== void 0) {
1852
+ schema = schema.max(
1853
+ attr.maxLength,
1854
+ `${attr.label} must be at most ${attr.maxLength} characters`
1855
+ );
1856
+ }
1857
+ if (attr.pattern) {
1858
+ schema = schema.regex(new RegExp(attr.pattern), `${attr.label} format is invalid`);
1859
+ }
1860
+ return schema;
1861
+ }
1862
+ function createNumberValidator(attr) {
1863
+ let schema = z3.number();
1864
+ if (attr.min !== void 0) {
1865
+ schema = schema.min(attr.min, `${attr.label} must be at least ${attr.min}`);
1866
+ }
1867
+ if (attr.max !== void 0) {
1868
+ schema = schema.max(attr.max, `${attr.label} must be at most ${attr.max}`);
1869
+ }
1870
+ if (attr.unit === "integer") {
1871
+ schema = schema.int(`${attr.label} must be an integer`);
1872
+ }
1873
+ if (attr.multiple) {
1874
+ return z3.array(schema);
1875
+ }
1876
+ return schema;
1877
+ }
1878
+ function createCheckboxValidator(_attr) {
1879
+ return z3.boolean();
1880
+ }
1881
+ function createDateValidator(attr) {
1882
+ const schema = z3.string().datetime({ message: `${attr.label} must be a valid ISO date` });
1883
+ if (attr.multiple) {
1884
+ return z3.array(schema);
1885
+ }
1886
+ return schema;
1887
+ }
1888
+ function createPhoneValidator(attr) {
1889
+ const schema = z3.object({
1890
+ countryCode: z3.string().length(3),
1891
+ phoneNumber: z3.string().min(1)
1892
+ });
1893
+ if (attr.multiple) {
1894
+ return z3.array(schema);
1895
+ }
1896
+ return schema;
1897
+ }
1898
+ function createCurrencyValidator(attr) {
1899
+ const schema = z3.object({
1900
+ code: z3.string().length(3),
1901
+ value: z3.number().min(0)
1902
+ });
1903
+ if (attr.multiple) {
1904
+ return z3.array(schema);
1905
+ }
1906
+ return schema;
1907
+ }
1908
+ function createStatusValidator(attr) {
1909
+ const validValues = attr.options.map((opt) => opt.value);
1910
+ return z3.enum(validValues, {
1911
+ errorMap: () => ({
1912
+ message: `${attr.label} must be one of: ${validValues.join(", ")}`
1913
+ })
1914
+ });
1915
+ }
1916
+ function createSelectValidator(attr) {
1917
+ const validValues = attr.options.map((opt) => opt.value);
1918
+ return z3.enum(validValues, {
1919
+ errorMap: () => ({
1920
+ message: `${attr.label} must be one of: ${validValues.join(", ")}`
1921
+ })
1922
+ });
1923
+ }
1924
+ function createMultiselectValidator(attr) {
1925
+ const validValues = attr.options.map((opt) => opt.value);
1926
+ return z3.array(
1927
+ z3.enum(validValues, {
1928
+ errorMap: () => ({
1929
+ message: `Each value must be one of: ${validValues.join(", ")}`
1930
+ })
1931
+ })
1932
+ );
1933
+ }
1934
+ function createLocationValidator(attr) {
1935
+ const schema = z3.object({
1936
+ address: z3.string().optional(),
1937
+ address2: z3.string().optional(),
1938
+ city: z3.string().optional(),
1939
+ state: z3.string().optional(),
1940
+ postalCode: z3.string().optional(),
1941
+ country: z3.string().length(3).optional(),
1942
+ latitude: z3.number().optional(),
1943
+ longitude: z3.number().optional()
1944
+ });
1945
+ if (attr.multiple) {
1946
+ return z3.array(schema);
1947
+ }
1948
+ return schema;
1949
+ }
1950
+ function createTimestampValidator(attr) {
1951
+ const schema = z3.number().int().positive();
1952
+ if (attr.multiple) {
1953
+ return z3.array(schema);
1954
+ }
1955
+ return schema;
1956
+ }
1957
+ function createFileValidator(attr) {
1958
+ const schema = z3.string().uuid();
1959
+ if (attr.multiple) {
1960
+ const arraySchema = z3.array(schema);
1961
+ if (attr.maxFiles) {
1962
+ return arraySchema.max(attr.maxFiles, `Maximum ${attr.maxFiles} files allowed`);
1963
+ }
1964
+ return arraySchema;
1965
+ }
1966
+ return schema;
1967
+ }
1968
+ function createUserValidator(attr) {
1969
+ const schema = z3.string().uuid();
1970
+ if (attr.multiple) {
1971
+ return z3.array(schema);
1972
+ }
1973
+ return schema;
1974
+ }
1975
+ function createRelationValidator(attr) {
1976
+ const schema = z3.string().uuid();
1977
+ if (attr.multiple) {
1978
+ const arraySchema = z3.array(schema);
1979
+ if (attr.limit) {
1980
+ return arraySchema.max(attr.limit, `Maximum ${attr.limit} relations allowed`);
1981
+ }
1982
+ return arraySchema;
1983
+ }
1984
+ return schema;
1985
+ }
1986
+ function createRatingValidator(attr) {
1987
+ let schema = z3.number().int().min(0);
1988
+ if (attr.max !== void 0) {
1989
+ schema = schema.max(attr.max, `${attr.label} must be at most ${attr.max}`);
1990
+ }
1991
+ return schema;
1992
+ }
1993
+ function createAttributeValidator(attr) {
1994
+ switch (attr.type) {
1995
+ case "text":
1996
+ return createTextValidator(attr);
1997
+ case "number":
1998
+ return createNumberValidator(attr);
1999
+ case "checkbox":
2000
+ return createCheckboxValidator(attr);
2001
+ case "date":
2002
+ return createDateValidator(attr);
2003
+ case "phone":
2004
+ return createPhoneValidator(attr);
2005
+ case "currency":
2006
+ return createCurrencyValidator(attr);
2007
+ case "status":
2008
+ return createStatusValidator(attr);
2009
+ case "location":
2010
+ return createLocationValidator(attr);
2011
+ case "timestamp":
2012
+ return createTimestampValidator(attr);
2013
+ case "select":
2014
+ return createSelectValidator(attr);
2015
+ case "multiselect":
2016
+ return createMultiselectValidator(attr);
2017
+ case "file":
2018
+ return createFileValidator(attr);
2019
+ case "user":
2020
+ return createUserValidator(attr);
2021
+ case "relation":
2022
+ return createRelationValidator(attr);
2023
+ case "rating":
2024
+ return createRatingValidator(attr);
2025
+ default:
2026
+ return z3.unknown();
2027
+ }
2028
+ }
2029
+ function createObjectValidator(objectDef) {
2030
+ const shape = {};
2031
+ for (const attr of objectDef.attributes) {
2032
+ let validator = createAttributeValidator(attr);
2033
+ if (!attr.required) {
2034
+ validator = validator.optional();
2035
+ }
2036
+ shape[attr.name] = validator;
2037
+ }
2038
+ return z3.object(shape);
2039
+ }
2040
+ function validateAttribute(attr, value) {
2041
+ const validator = createAttributeValidator(attr);
2042
+ if (!attr.required && (value === void 0 || value === null)) {
2043
+ return { success: true, data: { [attr.name]: value } };
2044
+ }
2045
+ const result = validator.safeParse(value);
2046
+ if (result.success) {
2047
+ return {
2048
+ success: true,
2049
+ data: { [attr.name]: result.data }
2050
+ };
2051
+ }
2052
+ return {
2053
+ success: false,
2054
+ errors: result.error.errors.map((err) => ({
2055
+ path: [attr.name, ...err.path.map(String)],
2056
+ message: err.message
2057
+ }))
2058
+ };
2059
+ }
2060
+ function validateObject(objectDef, data) {
2061
+ const validator = createObjectValidator(objectDef);
2062
+ const result = validator.safeParse(data);
2063
+ if (result.success) {
2064
+ return {
2065
+ success: true,
2066
+ data: result.data
2067
+ };
2068
+ }
2069
+ return {
2070
+ success: false,
2071
+ errors: result.error.errors.map((err) => ({
2072
+ path: err.path.map(String),
2073
+ message: err.message
2074
+ }))
2075
+ };
2076
+ }
2077
+ function validateObjectOrThrow(objectDef, data) {
2078
+ const result = validateObject(objectDef, data);
2079
+ if (!result.success) {
2080
+ const errorMessages = result.errors?.map((err) => `${err.path.join(".")}: ${err.message}`).join("\n") || "Unknown validation error";
2081
+ throw new Error(`Validation failed for ${objectDef.label}:
2082
+ ${errorMessages}`);
2083
+ }
2084
+ return result.data;
2085
+ }
2086
+
2087
+ // src/runtime/services/record.service.ts
2088
+ var RecordService = class {
2089
+ constructor(adapter, tenantId) {
2090
+ this.adapter = adapter;
2091
+ this.tenantId = tenantId;
2092
+ this.schemaService = new ObjectSchemaService(adapter, registry);
2093
+ }
2094
+ /**
2095
+ * Create a new record with validation
2096
+ *
2097
+ * @param objectId - Object UUID
2098
+ * @param data - Record data (attribute values)
2099
+ * @param options - Creation options
2100
+ * @returns Created record
2101
+ *
2102
+ * @example
2103
+ * ```typescript
2104
+ * const service = new RecordService(adapter, "tenant-123");
2105
+ *
2106
+ * const product = await service.createRecord("obj-product", {
2107
+ * name: "Nike Air Max",
2108
+ * price: 129.99,
2109
+ * sku: "NIKE-AM-001"
2110
+ * });
2111
+ * ```
2112
+ */
2113
+ async createRecord(objectId, data, options) {
2114
+ const schema = await this.schemaService.getObjectSchema(objectId);
2115
+ if (options?.validate !== false) {
2116
+ validateObjectOrThrow(schema, data);
2117
+ }
2118
+ const record = await this.adapter.objectRecords.create({
2119
+ tenantId: this.tenantId,
2120
+ objectId,
2121
+ data
2122
+ });
2123
+ return record;
2124
+ }
2125
+ /**
2126
+ * Get a record by ID
2127
+ *
2128
+ * @param recordId - Record UUID
2129
+ * @param options - Query options
2130
+ * @returns Record or null if not found
2131
+ */
2132
+ async getRecord(recordId, options) {
2133
+ const record = await this.adapter.objectRecords.findById(recordId);
2134
+ if (!record) {
2135
+ return null;
2136
+ }
2137
+ if (options?.includeSchema) {
2138
+ const schema = await this.schemaService.getObjectSchema(record.objectId);
2139
+ const recordWithSchema = record;
2140
+ recordWithSchema.schema = schema;
2141
+ return recordWithSchema;
2142
+ }
2143
+ return record;
2144
+ }
2145
+ /**
2146
+ * Get a record by ID or throw if not found
2147
+ */
2148
+ async getRecordOrThrow(recordId) {
2149
+ const record = await this.getRecord(recordId);
2150
+ if (!record) {
2151
+ throw new Error(`Record with id "${recordId}" not found`);
2152
+ }
2153
+ return record;
2154
+ }
2155
+ /**
2156
+ * Update a record with validation
2157
+ *
2158
+ * @param recordId - Record UUID
2159
+ * @param data - Partial data to update
2160
+ * @param options - Update options
2161
+ * @returns Updated record
2162
+ */
2163
+ async updateRecord(recordId, data, options) {
2164
+ const existing = await this.getRecordOrThrow(recordId);
2165
+ const schema = await this.schemaService.getObjectSchema(existing.objectId);
2166
+ const mergedData = { ...existing.values, ...data };
2167
+ if (options?.validate !== false && !options?.partial) {
2168
+ validateObjectOrThrow(schema, mergedData);
2169
+ }
2170
+ const updated = await this.adapter.objectRecords.update(recordId, data);
2171
+ return updated;
2172
+ }
2173
+ /**
2174
+ * Delete a record
2175
+ *
2176
+ * @param recordId - Record UUID
2177
+ * @param options - Delete options
2178
+ */
2179
+ async deleteRecord(recordId, options) {
2180
+ if (options?.checkSystem) {
2181
+ const record = await this.getRecordOrThrow(recordId);
2182
+ const schema = await this.schemaService.getObjectSchema(record.objectId);
2183
+ if (schema.system) {
2184
+ throw new Error(`Cannot delete record of system object "${schema.label}"`);
2185
+ }
2186
+ }
2187
+ await this.adapter.objectRecords.delete(recordId);
2188
+ }
2189
+ /**
2190
+ * List records for an object with pagination
2191
+ *
2192
+ * @param objectId - Object UUID
2193
+ * @param options - List options
2194
+ * @returns Records and total count
2195
+ */
2196
+ async listRecords(objectId, options) {
2197
+ return await this.adapter.objectRecords.list(this.tenantId, objectId, options);
2198
+ }
2199
+ /**
2200
+ * Search records using full-text search
2201
+ *
2202
+ * @param objectId - Object UUID
2203
+ * @param query - Search query
2204
+ * @param options - Search options
2205
+ * @returns Matching records and total count
2206
+ */
2207
+ async searchRecords(objectId, query, options) {
2208
+ return await this.adapter.objectRecords.search(this.tenantId, objectId, query, options);
2209
+ }
2210
+ /**
2211
+ * Validate data against object schema without saving
2212
+ *
2213
+ * @param objectId - Object UUID
2214
+ * @param data - Data to validate
2215
+ * @returns Validation result
2216
+ */
2217
+ async validateData(objectId, data) {
2218
+ const schema = await this.schemaService.getObjectSchema(objectId);
2219
+ return validateObject(schema, data);
2220
+ }
2221
+ };
2222
+
2223
+ // src/runtime/services/user-profile.service.ts
2224
+ var UserProfileService = class {
2225
+ constructor(adapter, tenantId) {
2226
+ this.adapter = adapter;
2227
+ this.tenantId = tenantId;
2228
+ }
2229
+ /**
2230
+ * Create a new user profile (typically after first auth)
2231
+ *
2232
+ * @param data - User profile creation data
2233
+ * @returns Created user profile
2234
+ *
2235
+ * @example
2236
+ * ```typescript
2237
+ * const service = new UserProfileService(adapter, "tenant-123");
2238
+ *
2239
+ * // After Supabase auth
2240
+ * const profile = await service.createProfile({
2241
+ * tenantId: "tenant-123",
2242
+ * authId: authUser.id,
2243
+ * email: authUser.email,
2244
+ * firstName: authUser.user_metadata.first_name,
2245
+ * lastName: authUser.user_metadata.last_name,
2246
+ * role: "member",
2247
+ * status: "active"
2248
+ * });
2249
+ * ```
2250
+ */
2251
+ async createProfile(data) {
2252
+ if (data.tenantId !== this.tenantId) {
2253
+ throw new Error(
2254
+ `Tenant mismatch: service initialized with "${this.tenantId}" but data has "${data.tenantId}"`
2255
+ );
2256
+ }
2257
+ const existing = await this.adapter.userProfiles.findByAuthId(data.authId);
2258
+ if (existing) {
2259
+ throw new Error(`User profile with authId "${data.authId}" already exists`);
2260
+ }
2261
+ const existingEmail = await this.adapter.userProfiles.findByEmail(this.tenantId, data.email);
2262
+ if (existingEmail) {
2263
+ throw new Error(`User profile with email "${data.email}" already exists in this tenant`);
2264
+ }
2265
+ return await this.adapter.userProfiles.create(data);
2266
+ }
2267
+ /**
2268
+ * Get user profile by ID
2269
+ */
2270
+ async getProfile(profileId) {
2271
+ return await this.adapter.userProfiles.findById(profileId);
2272
+ }
2273
+ /**
2274
+ * Get user profile by ID or throw
2275
+ */
2276
+ async getProfileOrThrow(profileId) {
2277
+ const profile = await this.getProfile(profileId);
2278
+ if (!profile) {
2279
+ throw new Error(`User profile with id "${profileId}" not found`);
2280
+ }
2281
+ return profile;
2282
+ }
2283
+ /**
2284
+ * Get user profile by auth provider ID
2285
+ *
2286
+ * @param authId - Auth provider user ID (Supabase, Clerk, etc.)
2287
+ * @returns User profile or null
2288
+ */
2289
+ async getProfileByAuthId(authId) {
2290
+ return await this.adapter.userProfiles.findByAuthId(authId);
2291
+ }
2292
+ /**
2293
+ * Get or create user profile (idempotent operation)
2294
+ * Useful for auth callbacks - ensures profile exists
2295
+ *
2296
+ * @param authId - Auth provider user ID
2297
+ * @param data - Profile data to create if doesn't exist
2298
+ * @returns Existing or newly created profile
2299
+ *
2300
+ * @example
2301
+ * ```typescript
2302
+ * // In Supabase auth callback
2303
+ * const profile = await service.getOrCreateProfile(
2304
+ * authUser.id,
2305
+ * {
2306
+ * tenantId: "tenant-123",
2307
+ * authId: authUser.id,
2308
+ * email: authUser.email,
2309
+ * role: "member",
2310
+ * status: "active"
2311
+ * }
2312
+ * );
2313
+ * ```
2314
+ */
2315
+ async getOrCreateProfile(authId, data) {
2316
+ const existing = await this.getProfileByAuthId(authId);
2317
+ if (existing) {
2318
+ return existing;
2319
+ }
2320
+ return await this.createProfile(data);
2321
+ }
2322
+ /**
2323
+ * Update user profile
2324
+ */
2325
+ async updateProfile(profileId, data) {
2326
+ await this.getProfileOrThrow(profileId);
2327
+ return await this.adapter.userProfiles.update(profileId, data);
2328
+ }
2329
+ /**
2330
+ * Delete user profile
2331
+ *
2332
+ * @param profileId - Profile UUID
2333
+ * @param options - Delete options
2334
+ */
2335
+ async deleteProfile(profileId, options) {
2336
+ if (options?.checkAdmin) {
2337
+ const profile = await this.getProfileOrThrow(profileId);
2338
+ if (profile.role === "admin") {
2339
+ const allProfiles = await this.listProfiles();
2340
+ const adminCount = allProfiles.filter((p) => p.role === "admin").length;
2341
+ if (adminCount <= 1) {
2342
+ throw new Error("Cannot delete the last admin user");
2343
+ }
2344
+ }
2345
+ }
2346
+ await this.adapter.userProfiles.delete(profileId);
2347
+ }
2348
+ /**
2349
+ * List all user profiles for the tenant
2350
+ */
2351
+ async listProfiles(options) {
2352
+ return await this.adapter.userProfiles.list(this.tenantId, options);
2353
+ }
2354
+ /**
2355
+ * Update last login timestamp
2356
+ *
2357
+ * @param profileId - Profile UUID
2358
+ *
2359
+ * @example
2360
+ * ```typescript
2361
+ * // After successful auth
2362
+ * await service.updateLastLogin(profile.id);
2363
+ * ```
2364
+ */
2365
+ async updateLastLogin(profileId) {
2366
+ await this.adapter.userProfiles.updateLastLogin(profileId);
2367
+ }
2368
+ /**
2369
+ * Change user role
2370
+ *
2371
+ * @param profileId - Profile UUID
2372
+ * @param newRole - New role
2373
+ */
2374
+ async changeRole(profileId, newRole) {
2375
+ return await this.updateProfile(profileId, { role: newRole });
2376
+ }
2377
+ /**
2378
+ * Change user status
2379
+ *
2380
+ * @param profileId - Profile UUID
2381
+ * @param newStatus - New status
2382
+ */
2383
+ async changeStatus(profileId, newStatus) {
2384
+ return await this.updateProfile(profileId, { status: newStatus });
2385
+ }
2386
+ /**
2387
+ * Get user by email
2388
+ */
2389
+ async getProfileByEmail(email) {
2390
+ return await this.adapter.userProfiles.findByEmail(this.tenantId, email);
2391
+ }
2392
+ /**
2393
+ * Check if user has role
2394
+ */
2395
+ async hasRole(profileId, role) {
2396
+ const profile = await this.getProfile(profileId);
2397
+ return profile?.role === role;
2398
+ }
2399
+ /**
2400
+ * Check if user is admin
2401
+ */
2402
+ async isAdmin(profileId) {
2403
+ return await this.hasRole(profileId, "admin");
2404
+ }
2405
+ };
2406
+
2407
+ // src/runtime/sync.ts
2408
+ var BASE_ATTRIBUTE_KEYS = /* @__PURE__ */ new Set([
2409
+ "id",
2410
+ "name",
2411
+ "label",
2412
+ "type",
2413
+ "required",
2414
+ "system",
2415
+ "unique",
2416
+ "order"
2417
+ ]);
2418
+ function extractAttributeConfig(attr) {
2419
+ return Object.fromEntries(
2420
+ Object.entries(attr).filter(
2421
+ ([key, value]) => !BASE_ATTRIBUTE_KEYS.has(key) && value !== void 0
2422
+ )
2423
+ );
2424
+ }
2425
+ async function syncNativeObjects(adapter, nativeRegistry, options = {}) {
2426
+ const result = {
2427
+ success: true,
2428
+ objectsSynced: 0,
2429
+ attributesSynced: 0,
2430
+ objectsCreated: 0,
2431
+ objectsUpdated: 0,
2432
+ attributesCreated: 0,
2433
+ attributesUpdated: 0,
2434
+ attributesDeleted: 0,
2435
+ errors: []
2436
+ };
2437
+ const nativeObjects = nativeRegistry.getAll();
2438
+ if (options.verbose) {
2439
+ console.info(`[SyncService] Starting sync for ${nativeObjects.length} native objects...`);
2440
+ }
2441
+ try {
2442
+ await adapter.transaction(async (tx) => {
2443
+ for (const nativeObject of nativeObjects) {
2444
+ try {
2445
+ await syncSingleObject(tx, nativeObject, result, options);
2446
+ } catch (error) {
2447
+ result.success = false;
2448
+ result.errors.push({
2449
+ objectName: nativeObject.name,
2450
+ error: error instanceof Error ? error.message : String(error)
2451
+ });
2452
+ if (options.verbose) {
2453
+ console.error(`[SyncService] \u2717 Failed to sync ${nativeObject.name}:`, error);
2454
+ }
2455
+ }
2456
+ }
2457
+ });
2458
+ } catch (error) {
2459
+ result.success = false;
2460
+ result.errors.push({
2461
+ objectName: "transaction",
2462
+ error: error instanceof Error ? error.message : String(error)
2463
+ });
2464
+ }
2465
+ if (options.verbose) {
2466
+ console.info(
2467
+ `[SyncService] ${result.success ? "\u2713" : "\u2717"} Sync complete:
2468
+ Objects: ${result.objectsCreated} created, ${result.objectsUpdated} updated
2469
+ Attributes: ${result.attributesCreated} created, ${result.attributesUpdated} updated, ${result.attributesDeleted} deleted
2470
+ Errors: ${result.errors.length}`
2471
+ );
2472
+ }
2473
+ return result;
2474
+ }
2475
+ async function syncSingleObject(adapter, nativeObject, result, options) {
2476
+ if (!nativeObject.system) {
2477
+ throw new Error(`Object ${nativeObject.name} is not marked as system`);
2478
+ }
2479
+ const existingObject = await adapter.objects.findSystemByName(nativeObject.name);
2480
+ const isNew = !existingObject;
2481
+ updateObjectStats(result, isNew);
2482
+ if (options.dryRun) {
2483
+ await handleDryRun(adapter, nativeObject, existingObject, result, options, isNew);
2484
+ return;
2485
+ }
2486
+ const dbObject = await upsertObject(adapter, nativeObject, options);
2487
+ await syncAttributes(adapter, nativeObject, dbObject, existingObject, result);
2488
+ if (!isNew) {
2489
+ await cleanupAttributes(adapter, dbObject.id, nativeObject, result);
2490
+ }
2491
+ logSyncSuccess(nativeObject, options);
2492
+ }
2493
+ function updateObjectStats(result, isNew) {
2494
+ if (isNew) {
2495
+ result.objectsCreated++;
2496
+ } else {
2497
+ result.objectsUpdated++;
2498
+ }
2499
+ result.objectsSynced++;
2500
+ }
2501
+ async function handleDryRun(adapter, nativeObject, existingObject, result, options, isNew) {
2502
+ if (options.verbose) {
2503
+ console.info(`[SyncService] Would ${isNew ? "create" : "update"} object: ${nativeObject.name}`);
2504
+ }
2505
+ for (const attr of nativeObject.attributes) {
2506
+ const existingAttr = existingObject ? await adapter.attributes.findByObjectId(existingObject.id).then((attrs) => attrs.find((a) => a.name === attr.name)) : null;
2507
+ if (existingAttr) {
2508
+ result.attributesUpdated++;
2509
+ } else {
2510
+ result.attributesCreated++;
2511
+ }
2512
+ result.attributesSynced++;
2513
+ }
2514
+ }
2515
+ async function upsertObject(adapter, nativeObject, options) {
2516
+ return await adapter.objects.upsert({
2517
+ tenantId: options.tenantId || "default",
2518
+ system: true,
2519
+ name: nativeObject.name,
2520
+ label: nativeObject.label,
2521
+ description: nativeObject.description,
2522
+ metadata: nativeObject.metadata
2523
+ });
2524
+ }
2525
+ async function syncAttributes(adapter, nativeObject, dbObject, existingObject, result) {
2526
+ for (const [index, attr] of nativeObject.attributes.entries()) {
2527
+ const existingAttr = existingObject ? await adapter.attributes.findByObjectId(dbObject.id).then((attrs) => attrs.find((a) => a.name === attr.name)) : null;
2528
+ await adapter.attributes.upsert({
2529
+ objectId: dbObject.id,
2530
+ name: attr.name,
2531
+ label: attr.label,
2532
+ type: attr.type,
2533
+ system: attr.system ?? true,
2534
+ required: attr.required ?? false,
2535
+ unique: "unique" in attr ? attr.unique ?? false : false,
2536
+ orderIndex: attr.order ?? index,
2537
+ config: extractAttributeConfig(attr)
2538
+ });
2539
+ if (existingAttr) {
2540
+ result.attributesUpdated++;
2541
+ } else {
2542
+ result.attributesCreated++;
2543
+ }
2544
+ result.attributesSynced++;
2545
+ }
2546
+ }
2547
+ async function cleanupAttributes(adapter, objectId, nativeObject, result) {
2548
+ const attributeNames = nativeObject.attributes.map((attr) => attr.name);
2549
+ const deletedCount = await adapter.attributes.deleteByNames(objectId, attributeNames);
2550
+ result.attributesDeleted += deletedCount;
2551
+ }
2552
+ function logSyncSuccess(nativeObject, options) {
2553
+ if (options.verbose) {
2554
+ console.info(
2555
+ `[SyncService] \u2713 Synced ${nativeObject.name}: ${nativeObject.attributes.length} attributes`
2556
+ );
2557
+ }
2558
+ }
2559
+ async function verifyNativeObjectsSync(adapter, nativeRegistry) {
2560
+ const nativeObjects = nativeRegistry.getAll();
2561
+ for (const obj of nativeObjects) {
2562
+ if (!obj.system) continue;
2563
+ const existing = await adapter.objects.findSystemByName(obj.name);
2564
+ if (!existing) {
2565
+ return false;
2566
+ }
2567
+ }
2568
+ return true;
2569
+ }
2570
+ async function getSyncPreview(adapter, nativeRegistry) {
2571
+ return await syncNativeObjects(adapter, nativeRegistry, { dryRun: true });
2572
+ }
2573
+
2574
+ export {
2575
+ generateId,
2576
+ generatePrefixedId,
2577
+ text,
2578
+ number,
2579
+ checkbox,
2580
+ date,
2581
+ phone,
2582
+ currency,
2583
+ status,
2584
+ select,
2585
+ multiselect,
2586
+ location,
2587
+ timestamp,
2588
+ file,
2589
+ user,
2590
+ relation,
2591
+ rating,
2592
+ ObjectBuilder,
2593
+ object,
2594
+ registry,
2595
+ createTextValidator,
2596
+ createNumberValidator,
2597
+ createCheckboxValidator,
2598
+ createDateValidator,
2599
+ createPhoneValidator,
2600
+ createCurrencyValidator,
2601
+ createStatusValidator,
2602
+ createSelectValidator,
2603
+ createMultiselectValidator,
2604
+ createLocationValidator,
2605
+ createTimestampValidator,
2606
+ createFileValidator,
2607
+ createUserValidator,
2608
+ createRelationValidator,
2609
+ createRatingValidator,
2610
+ createAttributeValidator,
2611
+ createObjectValidator,
2612
+ validateAttribute,
2613
+ validateObject,
2614
+ validateObjectOrThrow,
2615
+ createMockAdapter,
2616
+ FileService,
2617
+ ObjectSchemaService,
2618
+ RecordService,
2619
+ UserProfileService,
2620
+ syncNativeObjects,
2621
+ verifyNativeObjectsSync,
2622
+ getSyncPreview
2623
+ };