@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,4040 @@
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
+ icon: data.icon,
46
+ system: data.system ?? false,
47
+ metadata: data.metadata,
48
+ createdAt: /* @__PURE__ */ new Date(),
49
+ updatedAt: /* @__PURE__ */ new Date()
50
+ };
51
+ stores.objects.set(obj.id, obj);
52
+ return Promise.resolve(obj);
53
+ },
54
+ update(id, data) {
55
+ const existing = stores.objects.get(id);
56
+ if (!existing) {
57
+ return Promise.reject(new Error(`Object ${id} not found`));
58
+ }
59
+ const updated = {
60
+ ...existing,
61
+ ...data,
62
+ updatedAt: /* @__PURE__ */ new Date()
63
+ };
64
+ stores.objects.set(id, updated);
65
+ return Promise.resolve(updated);
66
+ },
67
+ delete(id) {
68
+ stores.objects.delete(id);
69
+ return Promise.resolve();
70
+ },
71
+ list(tenantId) {
72
+ const results = Array.from(stores.objects.values()).filter(
73
+ (obj) => obj.tenantId === tenantId
74
+ );
75
+ return Promise.resolve(results);
76
+ },
77
+ upsert(data) {
78
+ for (const obj of stores.objects.values()) {
79
+ if (obj.system && obj.name === data.name) {
80
+ const updated = {
81
+ ...obj,
82
+ label: data.label,
83
+ description: data.description,
84
+ icon: data.icon,
85
+ metadata: data.metadata,
86
+ updatedAt: /* @__PURE__ */ new Date()
87
+ };
88
+ stores.objects.set(obj.id, updated);
89
+ return Promise.resolve(updated);
90
+ }
91
+ }
92
+ const newObj = {
93
+ id: generateId(),
94
+ tenantId: data.tenantId,
95
+ name: data.name,
96
+ label: data.label,
97
+ description: data.description,
98
+ icon: data.icon,
99
+ system: data.system,
100
+ metadata: data.metadata,
101
+ createdAt: /* @__PURE__ */ new Date(),
102
+ updatedAt: /* @__PURE__ */ new Date()
103
+ };
104
+ stores.objects.set(newObj.id, newObj);
105
+ return Promise.resolve(newObj);
106
+ }
107
+ };
108
+ }
109
+ function createMockAttributesRepository(stores) {
110
+ return {
111
+ findById(id) {
112
+ return Promise.resolve(stores.attributes.get(id) ?? null);
113
+ },
114
+ findByObjectId(objectId) {
115
+ const results = Array.from(stores.attributes.values()).filter(
116
+ (attr) => attr.objectId === objectId
117
+ );
118
+ return Promise.resolve(results);
119
+ },
120
+ create(data) {
121
+ const attr = {
122
+ id: generateId(),
123
+ objectId: data.objectId,
124
+ name: data.name,
125
+ label: data.label,
126
+ type: data.type,
127
+ description: data.description,
128
+ icon: data.icon,
129
+ system: data.system ?? false,
130
+ required: data.required ?? false,
131
+ unique: data.unique ?? false,
132
+ order: data.order ?? 0,
133
+ hidden: data.hidden,
134
+ archived: data.archived,
135
+ deprecated: data.deprecated,
136
+ defaultValue: data.defaultValue,
137
+ config: data.config ?? {},
138
+ createdAt: /* @__PURE__ */ new Date(),
139
+ updatedAt: /* @__PURE__ */ new Date()
140
+ };
141
+ stores.attributes.set(attr.id, attr);
142
+ return Promise.resolve(attr);
143
+ },
144
+ update(id, data) {
145
+ const existing = stores.attributes.get(id);
146
+ if (!existing) {
147
+ return Promise.reject(new Error(`Attribute ${id} not found`));
148
+ }
149
+ const updated = {
150
+ ...existing,
151
+ ...data,
152
+ updatedAt: /* @__PURE__ */ new Date()
153
+ };
154
+ stores.attributes.set(id, updated);
155
+ return Promise.resolve(updated);
156
+ },
157
+ delete(id) {
158
+ stores.attributes.delete(id);
159
+ return Promise.resolve();
160
+ },
161
+ deleteByNames(objectId, excludeNames) {
162
+ let count = 0;
163
+ for (const [id, attr] of stores.attributes.entries()) {
164
+ if (attr.objectId === objectId && !excludeNames.includes(attr.name)) {
165
+ stores.attributes.delete(id);
166
+ count++;
167
+ }
168
+ }
169
+ return Promise.resolve(count);
170
+ },
171
+ upsert(data) {
172
+ for (const attr of stores.attributes.values()) {
173
+ if (attr.objectId === data.objectId && attr.name === data.name) {
174
+ const updated = {
175
+ ...attr,
176
+ label: data.label ?? attr.label,
177
+ type: data.type ?? attr.type,
178
+ description: data.description ?? attr.description,
179
+ icon: data.icon ?? attr.icon,
180
+ system: data.system ?? attr.system,
181
+ required: data.required ?? attr.required,
182
+ unique: data.unique ?? attr.unique,
183
+ order: data.order ?? attr.order,
184
+ hidden: data.hidden ?? attr.hidden,
185
+ archived: data.archived ?? attr.archived,
186
+ deprecated: data.deprecated ?? attr.deprecated,
187
+ defaultValue: data.defaultValue ?? attr.defaultValue,
188
+ config: data.config ?? attr.config,
189
+ updatedAt: /* @__PURE__ */ new Date()
190
+ };
191
+ stores.attributes.set(attr.id, updated);
192
+ return Promise.resolve(updated);
193
+ }
194
+ }
195
+ return this.create(data);
196
+ }
197
+ };
198
+ }
199
+ function createMockUserProfilesRepository(stores) {
200
+ return {
201
+ findById(id) {
202
+ return Promise.resolve(stores.userProfiles.get(id) ?? null);
203
+ },
204
+ findByAuthId(authId) {
205
+ for (const profile of stores.userProfiles.values()) {
206
+ if (profile.authId === authId) {
207
+ return Promise.resolve(profile);
208
+ }
209
+ }
210
+ return Promise.resolve(null);
211
+ },
212
+ findByEmail(tenantId, email) {
213
+ for (const profile of stores.userProfiles.values()) {
214
+ if (profile.tenantId === tenantId && profile.email === email) {
215
+ return Promise.resolve(profile);
216
+ }
217
+ }
218
+ return Promise.resolve(null);
219
+ },
220
+ create(data) {
221
+ const profile = {
222
+ id: generateId(),
223
+ tenantId: data.tenantId,
224
+ authId: data.authId,
225
+ email: data.email,
226
+ firstName: data.firstName,
227
+ lastName: data.lastName,
228
+ avatarUrl: data.avatarUrl,
229
+ role: data.role ?? "member",
230
+ status: data.status ?? "active",
231
+ createdAt: /* @__PURE__ */ new Date(),
232
+ updatedAt: /* @__PURE__ */ new Date()
233
+ };
234
+ stores.userProfiles.set(profile.id, profile);
235
+ return Promise.resolve(profile);
236
+ },
237
+ update(id, data) {
238
+ const existing = stores.userProfiles.get(id);
239
+ if (!existing) {
240
+ return Promise.reject(new Error(`UserProfile ${id} not found`));
241
+ }
242
+ const updated = {
243
+ ...existing,
244
+ ...data,
245
+ updatedAt: /* @__PURE__ */ new Date()
246
+ };
247
+ stores.userProfiles.set(id, updated);
248
+ return Promise.resolve(updated);
249
+ },
250
+ delete(id) {
251
+ stores.userProfiles.delete(id);
252
+ return Promise.resolve();
253
+ },
254
+ list(tenantId, options) {
255
+ let results = Array.from(stores.userProfiles.values()).filter((p) => p.tenantId === tenantId);
256
+ if (options?.limit) {
257
+ results = results.slice(options.offset ?? 0, (options.offset ?? 0) + options.limit);
258
+ }
259
+ return Promise.resolve(results);
260
+ },
261
+ updateLastLogin(id) {
262
+ const profile = stores.userProfiles.get(id);
263
+ if (profile) {
264
+ profile.lastLoginAt = /* @__PURE__ */ new Date();
265
+ stores.userProfiles.set(id, profile);
266
+ }
267
+ return Promise.resolve();
268
+ }
269
+ };
270
+ }
271
+ function createMockFilesRepository(stores) {
272
+ return {
273
+ findById(id) {
274
+ const file2 = stores.files.get(id);
275
+ if (file2?.deletedAt) return Promise.resolve(null);
276
+ return Promise.resolve(file2 ?? null);
277
+ },
278
+ create(data) {
279
+ const file2 = {
280
+ id: generateId(),
281
+ tenantId: data.tenantId,
282
+ name: data.name,
283
+ originalName: data.originalName,
284
+ mimeType: data.mimeType,
285
+ size: data.size,
286
+ storageProvider: data.storageProvider,
287
+ storagePath: data.storagePath,
288
+ storageBucket: data.storageBucket,
289
+ url: data.url,
290
+ uploadedBy: data.uploadedBy,
291
+ folderPath: data.folderPath,
292
+ tags: data.tags,
293
+ visibility: data.visibility ?? "private",
294
+ allowedUsers: data.allowedUsers,
295
+ createdAt: /* @__PURE__ */ new Date(),
296
+ updatedAt: /* @__PURE__ */ new Date()
297
+ };
298
+ stores.files.set(file2.id, file2);
299
+ return Promise.resolve(file2);
300
+ },
301
+ update(id, data) {
302
+ const existing = stores.files.get(id);
303
+ if (!existing) {
304
+ return Promise.reject(new Error(`File ${id} not found`));
305
+ }
306
+ const updated = {
307
+ ...existing,
308
+ ...data,
309
+ updatedAt: /* @__PURE__ */ new Date()
310
+ };
311
+ stores.files.set(id, updated);
312
+ return Promise.resolve(updated);
313
+ },
314
+ delete(id) {
315
+ const file2 = stores.files.get(id);
316
+ if (file2) {
317
+ file2.deletedAt = /* @__PURE__ */ new Date();
318
+ stores.files.set(id, file2);
319
+ }
320
+ return Promise.resolve();
321
+ },
322
+ hardDelete(id) {
323
+ stores.files.delete(id);
324
+ return Promise.resolve();
325
+ },
326
+ list(tenantId, options) {
327
+ let results = Array.from(stores.files.values()).filter(
328
+ (f) => f.tenantId === tenantId && !f.deletedAt
329
+ );
330
+ if (options?.mimeType) {
331
+ results = results.filter((f) => f.mimeType === options.mimeType);
332
+ }
333
+ if (options?.limit) {
334
+ results = results.slice(options.offset ?? 0, (options.offset ?? 0) + options.limit);
335
+ }
336
+ return Promise.resolve(results);
337
+ },
338
+ findByFolder(tenantId, folderPath) {
339
+ const results = Array.from(stores.files.values()).filter(
340
+ (f) => f.tenantId === tenantId && f.folderPath === folderPath && !f.deletedAt
341
+ );
342
+ return Promise.resolve(results);
343
+ },
344
+ findByUploader(uploadedBy) {
345
+ const results = Array.from(stores.files.values()).filter(
346
+ (f) => f.uploadedBy === uploadedBy && !f.deletedAt
347
+ );
348
+ return Promise.resolve(results);
349
+ }
350
+ };
351
+ }
352
+ function createMockObjectRecordsRepository(stores) {
353
+ return {
354
+ findById(id) {
355
+ const internal = stores.objectRecords.get(id);
356
+ if (!internal) return Promise.resolve(null);
357
+ const { tenantId: _, ...record } = internal;
358
+ return Promise.resolve(record);
359
+ },
360
+ create(data) {
361
+ const internal = {
362
+ id: generateId(),
363
+ tenantId: data.tenantId,
364
+ objectId: data.objectId,
365
+ completionStatus: data.completionStatus,
366
+ values: data.data,
367
+ createdAt: /* @__PURE__ */ new Date(),
368
+ updatedAt: /* @__PURE__ */ new Date()
369
+ };
370
+ stores.objectRecords.set(internal.id, internal);
371
+ const { tenantId: _, ...record } = internal;
372
+ return Promise.resolve(record);
373
+ },
374
+ update(id, data) {
375
+ const existing = stores.objectRecords.get(id);
376
+ if (!existing) {
377
+ return Promise.reject(new Error(`ObjectRecord ${id} not found`));
378
+ }
379
+ const { __completionStatus, ...valueData } = data;
380
+ const updated = {
381
+ ...existing,
382
+ completionStatus: __completionStatus ?? existing.completionStatus,
383
+ values: { ...existing.values, ...valueData },
384
+ updatedAt: /* @__PURE__ */ new Date()
385
+ };
386
+ stores.objectRecords.set(id, updated);
387
+ const { tenantId: _, ...record } = updated;
388
+ return Promise.resolve(record);
389
+ },
390
+ delete(id) {
391
+ stores.objectRecords.delete(id);
392
+ return Promise.resolve();
393
+ },
394
+ list(tenantId, objectId, options) {
395
+ let results = Array.from(stores.objectRecords.values()).filter(
396
+ (r) => r.tenantId === tenantId && r.objectId === objectId
397
+ );
398
+ const total = results.length;
399
+ if (options?.limit) {
400
+ results = results.slice(options.offset ?? 0, (options.offset ?? 0) + options.limit);
401
+ }
402
+ const records = results.map(({ tenantId: _, ...r }) => r);
403
+ return Promise.resolve({ records, total });
404
+ },
405
+ search(tenantId, objectId, query, options) {
406
+ const lowerQuery = query.toLowerCase();
407
+ let results = Array.from(stores.objectRecords.values()).filter((r) => {
408
+ if (r.tenantId !== tenantId || r.objectId !== objectId) return false;
409
+ return Object.values(r.values).some(
410
+ (val) => String(val).toLowerCase().includes(lowerQuery)
411
+ );
412
+ });
413
+ const total = results.length;
414
+ if (options?.limit) {
415
+ results = results.slice(options.offset ?? 0, (options.offset ?? 0) + options.limit);
416
+ }
417
+ const records = results.map(({ tenantId: _, ...r }) => r);
418
+ return Promise.resolve({ records, total });
419
+ }
420
+ };
421
+ }
422
+ function createMockViewsRepository(stores) {
423
+ return {
424
+ findById(id) {
425
+ return Promise.resolve(stores.views.get(id) ?? null);
426
+ },
427
+ findByName(tenantId, objectName, viewName) {
428
+ return Promise.resolve(
429
+ Array.from(stores.views.values()).find(
430
+ (v) => v.tenantId === tenantId && v.objectName === objectName && v.name === viewName
431
+ ) ?? null
432
+ );
433
+ },
434
+ findByObjectName(tenantId, objectName) {
435
+ return Promise.resolve(
436
+ Array.from(stores.views.values()).filter(
437
+ (v) => v.tenantId === tenantId && v.objectName === objectName
438
+ )
439
+ );
440
+ },
441
+ findAllForTenant(tenantId) {
442
+ return Promise.resolve(
443
+ Array.from(stores.views.values()).filter((v) => v.tenantId === tenantId)
444
+ );
445
+ },
446
+ findSystemByName(objectName, viewName) {
447
+ return Promise.resolve(
448
+ Array.from(stores.views.values()).find(
449
+ (v) => v.objectName === objectName && v.name === viewName && v.system
450
+ ) ?? null
451
+ );
452
+ },
453
+ findSystemByObjectName(objectName) {
454
+ return Promise.resolve(
455
+ Array.from(stores.views.values()).filter((v) => v.objectName === objectName && v.system)
456
+ );
457
+ },
458
+ create(data) {
459
+ const id = generateId();
460
+ const now = /* @__PURE__ */ new Date();
461
+ const dbView = {
462
+ id,
463
+ tenantId: data.tenantId,
464
+ objectName: data.objectName,
465
+ name: data.name,
466
+ label: data.label,
467
+ description: data.description,
468
+ icon: data.icon,
469
+ tabs: data.tabs,
470
+ default: data.default ?? false,
471
+ system: data.system ?? false,
472
+ metadata: data.metadata,
473
+ createdAt: now,
474
+ updatedAt: now
475
+ };
476
+ stores.views.set(id, dbView);
477
+ return Promise.resolve(dbView);
478
+ },
479
+ update(id, data) {
480
+ const view2 = stores.views.get(id);
481
+ if (!view2) {
482
+ return Promise.reject(new Error(`View not found: ${id}`));
483
+ }
484
+ const updated = {
485
+ ...view2,
486
+ ...data,
487
+ updatedAt: /* @__PURE__ */ new Date()
488
+ };
489
+ stores.views.set(id, updated);
490
+ return Promise.resolve(updated);
491
+ },
492
+ delete(id) {
493
+ stores.views.delete(id);
494
+ return Promise.resolve();
495
+ },
496
+ deleteNotIn(objectName, keepViewNames) {
497
+ let deleted = 0;
498
+ for (const [id, view2] of stores.views.entries()) {
499
+ if (view2.objectName === objectName && view2.system && !keepViewNames.includes(view2.name)) {
500
+ stores.views.delete(id);
501
+ deleted++;
502
+ }
503
+ }
504
+ return Promise.resolve(deleted);
505
+ },
506
+ async upsert(data) {
507
+ const existing = data.system ? await this.findSystemByName(data.objectName, data.name) : await this.findByName(data.tenantId, data.objectName, data.name);
508
+ if (existing) {
509
+ return this.update(existing.id, {
510
+ label: data.label,
511
+ description: data.description,
512
+ icon: data.icon,
513
+ tabs: data.tabs,
514
+ default: data.default,
515
+ metadata: data.metadata
516
+ });
517
+ }
518
+ return this.create(data);
519
+ }
520
+ };
521
+ }
522
+ function createMockAdapter() {
523
+ const stores = {
524
+ objects: /* @__PURE__ */ new Map(),
525
+ attributes: /* @__PURE__ */ new Map(),
526
+ userProfiles: /* @__PURE__ */ new Map(),
527
+ files: /* @__PURE__ */ new Map(),
528
+ objectRecords: /* @__PURE__ */ new Map(),
529
+ views: /* @__PURE__ */ new Map()
530
+ };
531
+ const adapter = {
532
+ objects: createMockObjectsRepository(stores),
533
+ attributes: createMockAttributesRepository(stores),
534
+ userProfiles: createMockUserProfilesRepository(stores),
535
+ files: createMockFilesRepository(stores),
536
+ objectRecords: createMockObjectRecordsRepository(stores),
537
+ views: createMockViewsRepository(stores),
538
+ async transaction(callback) {
539
+ return await callback(adapter);
540
+ },
541
+ // Expose stores for testing inspection
542
+ _stores: stores,
543
+ // Reset all stores (useful between tests)
544
+ reset() {
545
+ stores.objects.clear();
546
+ stores.attributes.clear();
547
+ stores.userProfiles.clear();
548
+ stores.files.clear();
549
+ stores.objectRecords.clear();
550
+ stores.views.clear();
551
+ }
552
+ };
553
+ return adapter;
554
+ }
555
+
556
+ // src/runtime/services/file.service.ts
557
+ var FileService = class {
558
+ constructor(adapter, tenantId) {
559
+ this.adapter = adapter;
560
+ this.tenantId = tenantId;
561
+ }
562
+ /**
563
+ * Create a new file record (after upload to storage)
564
+ *
565
+ * @param data - File metadata
566
+ * @returns Created file record
567
+ *
568
+ * @example
569
+ * ```typescript
570
+ * const service = new FileService(adapter, "tenant-123");
571
+ *
572
+ * // After uploading to S3
573
+ * const file = await service.createFile({
574
+ * tenantId: "tenant-123",
575
+ * name: "contract-2025.pdf",
576
+ * originalName: "Contract Acme Corp 2025.pdf",
577
+ * mimeType: "application/pdf",
578
+ * size: 2458624,
579
+ * storageProvider: "s3",
580
+ * storagePath: "tenants/123/files/2025/contract.pdf",
581
+ * storageBucket: "my-app-files",
582
+ * url: "https://cdn.example.com/files/file-123",
583
+ * uploadedBy: "profile-456",
584
+ * visibility: "private"
585
+ * });
586
+ * ```
587
+ */
588
+ async createFile(data) {
589
+ if (data.tenantId !== this.tenantId) {
590
+ throw new Error(
591
+ `Tenant mismatch: service initialized with "${this.tenantId}" but data has "${data.tenantId}"`
592
+ );
593
+ }
594
+ return await this.adapter.files.create(data);
595
+ }
596
+ /**
597
+ * Get file by ID
598
+ */
599
+ async getFile(fileId) {
600
+ const file2 = await this.adapter.files.findById(fileId);
601
+ if (file2?.deletedAt) {
602
+ return null;
603
+ }
604
+ return file2;
605
+ }
606
+ /**
607
+ * Get file by ID or throw
608
+ */
609
+ async getFileOrThrow(fileId) {
610
+ const file2 = await this.getFile(fileId);
611
+ if (!file2) {
612
+ throw new Error(`File with id "${fileId}" not found`);
613
+ }
614
+ return file2;
615
+ }
616
+ /**
617
+ * Update file metadata
618
+ *
619
+ * @param fileId - File UUID
620
+ * @param data - Data to update
621
+ * @returns Updated file
622
+ */
623
+ async updateFile(fileId, data) {
624
+ await this.getFileOrThrow(fileId);
625
+ return await this.adapter.files.update(fileId, data);
626
+ }
627
+ /**
628
+ * Delete file (soft delete)
629
+ *
630
+ * @param fileId - File UUID
631
+ * @param options - Delete options
632
+ */
633
+ async deleteFile(fileId, options) {
634
+ if (options?.checkOwnership && options.userId) {
635
+ const file2 = await this.getFileOrThrow(fileId);
636
+ if (file2.uploadedBy !== options.userId) {
637
+ throw new Error("You can only delete files you uploaded");
638
+ }
639
+ }
640
+ if (options?.hard) {
641
+ await this.adapter.files.hardDelete(fileId);
642
+ } else {
643
+ await this.adapter.files.delete(fileId);
644
+ }
645
+ }
646
+ /**
647
+ * List files for the tenant
648
+ */
649
+ async listFiles(options) {
650
+ return await this.adapter.files.list(this.tenantId, options);
651
+ }
652
+ /**
653
+ * List files by folder
654
+ */
655
+ async listFilesByFolder(folderPath) {
656
+ return await this.adapter.files.findByFolder(this.tenantId, folderPath);
657
+ }
658
+ /**
659
+ * List files uploaded by a specific user
660
+ */
661
+ async listFilesByUploader(uploadedBy) {
662
+ return await this.adapter.files.findByUploader(uploadedBy);
663
+ }
664
+ /**
665
+ * Change file visibility
666
+ *
667
+ * @param fileId - File UUID
668
+ * @param visibility - New visibility level
669
+ * @param allowedUsers - Users allowed to access (if restricted)
670
+ */
671
+ async changeVisibility(fileId, visibility, allowedUsers) {
672
+ const updateData = { visibility };
673
+ if (visibility === "restricted" && allowedUsers) {
674
+ updateData.allowedUsers = allowedUsers;
675
+ }
676
+ return await this.updateFile(fileId, updateData);
677
+ }
678
+ /**
679
+ * Grant access to a file for specific users
680
+ *
681
+ * @param fileId - File UUID
682
+ * @param userIds - User IDs to grant access
683
+ */
684
+ async grantAccess(fileId, userIds) {
685
+ const file2 = await this.getFileOrThrow(fileId);
686
+ const currentAllowed = file2.allowedUsers || [];
687
+ const newAllowed = [.../* @__PURE__ */ new Set([...currentAllowed, ...userIds])];
688
+ return await this.updateFile(fileId, {
689
+ visibility: "restricted",
690
+ allowedUsers: newAllowed
691
+ });
692
+ }
693
+ /**
694
+ * Revoke access to a file for specific users
695
+ *
696
+ * @param fileId - File UUID
697
+ * @param userIds - User IDs to revoke access
698
+ */
699
+ async revokeAccess(fileId, userIds) {
700
+ const file2 = await this.getFileOrThrow(fileId);
701
+ const currentAllowed = file2.allowedUsers || [];
702
+ const newAllowed = currentAllowed.filter((id) => !userIds.includes(id));
703
+ return await this.updateFile(fileId, {
704
+ allowedUsers: newAllowed
705
+ });
706
+ }
707
+ /**
708
+ * Check if user has access to a file
709
+ *
710
+ * @param fileId - File UUID
711
+ * @param userId - User ID to check
712
+ * @returns true if user can access the file
713
+ */
714
+ async canAccess(fileId, userId) {
715
+ const file2 = await this.getFile(fileId);
716
+ if (!file2) {
717
+ return false;
718
+ }
719
+ if (file2.visibility === "public") {
720
+ return true;
721
+ }
722
+ if (file2.uploadedBy === userId) {
723
+ return true;
724
+ }
725
+ if (file2.visibility === "restricted") {
726
+ return file2.allowedUsers?.includes(userId) ?? false;
727
+ }
728
+ return false;
729
+ }
730
+ /**
731
+ * Move file to different folder
732
+ */
733
+ async moveToFolder(fileId, newFolderPath) {
734
+ return await this.updateFile(fileId, { folderPath: newFolderPath });
735
+ }
736
+ /**
737
+ * Add tags to file
738
+ */
739
+ async addTags(fileId, tags) {
740
+ const file2 = await this.getFileOrThrow(fileId);
741
+ const currentTags = file2.tags || [];
742
+ const newTags = [.../* @__PURE__ */ new Set([...currentTags, ...tags])];
743
+ return await this.updateFile(fileId, { tags: newTags });
744
+ }
745
+ /**
746
+ * Remove tags from file
747
+ */
748
+ async removeTags(fileId, tags) {
749
+ const file2 = await this.getFileOrThrow(fileId);
750
+ const currentTags = file2.tags || [];
751
+ const newTags = currentTags.filter((tag) => !tags.includes(tag));
752
+ return await this.updateFile(fileId, { tags: newTags });
753
+ }
754
+ };
755
+
756
+ // src/runtime/services/geocoding.service.ts
757
+ var GeocodingService = class {
758
+ constructor(adapter) {
759
+ this.adapter = adapter;
760
+ }
761
+ /**
762
+ * Search for address suggestions as the user types
763
+ */
764
+ async autocomplete(params) {
765
+ if (!params.query || params.query.trim().length < 2) {
766
+ return [];
767
+ }
768
+ return await this.adapter.autocomplete({
769
+ ...params,
770
+ query: params.query.trim(),
771
+ limit: params.limit ?? 5
772
+ });
773
+ }
774
+ /**
775
+ * Reverse geocode coordinates to an address
776
+ */
777
+ async reverse(params) {
778
+ if (!this.adapter.reverse) {
779
+ throw new Error("Reverse geocoding is not supported by the configured adapter");
780
+ }
781
+ return await this.adapter.reverse(params);
782
+ }
783
+ /**
784
+ * Geocode a structured address to coordinates
785
+ */
786
+ async geocode(params) {
787
+ if (!this.adapter.geocode) {
788
+ throw new Error("Geocoding is not supported by the configured adapter");
789
+ }
790
+ return await this.adapter.geocode(params);
791
+ }
792
+ };
793
+
794
+ // src/builders/attribute-validators.ts
795
+ import { ICONS } from "@andyoucreate/constants";
796
+ var VALID_ICONS = new Set(ICONS);
797
+ var ATTRIBUTE_NAME_REGEX = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
798
+ var MAX_NAME_LENGTH = 63;
799
+ var MAX_LABEL_LENGTH = 128;
800
+ function validateAttributeName(name) {
801
+ if (!name || name.length === 0) {
802
+ throw new Error("[AttributeBuilder] Attribute name cannot be empty");
803
+ }
804
+ if (name.length > MAX_NAME_LENGTH) {
805
+ throw new Error(
806
+ `[AttributeBuilder] Attribute name is too long (max ${MAX_NAME_LENGTH} characters)`
807
+ );
808
+ }
809
+ if (!ATTRIBUTE_NAME_REGEX.test(name)) {
810
+ throw new Error(
811
+ "[AttributeBuilder] 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'"
812
+ );
813
+ }
814
+ }
815
+ function validateLabel(label) {
816
+ if (!label || label.length === 0) {
817
+ throw new Error("[AttributeBuilder] Attribute label cannot be empty");
818
+ }
819
+ if (label.length > MAX_LABEL_LENGTH) {
820
+ throw new Error(
821
+ `[AttributeBuilder] Attribute label is too long (max ${MAX_LABEL_LENGTH} characters)`
822
+ );
823
+ }
824
+ }
825
+ function validateIconName(icon, context) {
826
+ if (!VALID_ICONS.has(icon)) {
827
+ throw new Error(
828
+ `[AttributeBuilder] Invalid icon "${icon}" in ${context}.
829
+ Icon must be one of the predefined icons from @andyoucreate/constants.`
830
+ );
831
+ }
832
+ }
833
+ function validateOptions(options, attributeName) {
834
+ if (options.length === 0) return;
835
+ const ids = /* @__PURE__ */ new Set();
836
+ const values = /* @__PURE__ */ new Set();
837
+ for (const option of options) {
838
+ if (!option.id?.trim()) {
839
+ throw new Error(
840
+ `[AttributeBuilder] Option in "${attributeName}" has an empty or missing id.`
841
+ );
842
+ }
843
+ if (!option.value?.trim()) {
844
+ throw new Error(
845
+ `[AttributeBuilder] Option "${option.id}" in "${attributeName}" has an empty or missing value.`
846
+ );
847
+ }
848
+ if (!option.label?.trim()) {
849
+ throw new Error(
850
+ `[AttributeBuilder] Option "${option.id}" in "${attributeName}" has an empty or missing label.`
851
+ );
852
+ }
853
+ if (ids.has(option.id)) {
854
+ throw new Error(
855
+ `[AttributeBuilder] Duplicate option id "${option.id}" in "${attributeName}".`
856
+ );
857
+ }
858
+ ids.add(option.id);
859
+ if (values.has(option.value)) {
860
+ throw new Error(
861
+ `[AttributeBuilder] Duplicate option value "${option.value}" in "${attributeName}".`
862
+ );
863
+ }
864
+ values.add(option.value);
865
+ if (option.icon) {
866
+ validateIconName(option.icon, `option "${option.id}" of "${attributeName}"`);
867
+ }
868
+ }
869
+ }
870
+
871
+ // src/builders/attribute-builders.ts
872
+ var BaseAttributeBuilder = class {
873
+ constructor(type, name, label) {
874
+ validateAttributeName(name);
875
+ validateLabel(label);
876
+ this.attr = {
877
+ name,
878
+ label,
879
+ type,
880
+ required: false
881
+ };
882
+ }
883
+ setRequired(value) {
884
+ this.attr.required = value;
885
+ }
886
+ system() {
887
+ this.attr.system = true;
888
+ return this;
889
+ }
890
+ disabled() {
891
+ this.attr.disabled = true;
892
+ return this;
893
+ }
894
+ hidden() {
895
+ this.attr.hidden = true;
896
+ return this;
897
+ }
898
+ placeholder(value) {
899
+ this.attr.placeholder = value;
900
+ return this;
901
+ }
902
+ description(value) {
903
+ this.attr.description = value;
904
+ return this;
905
+ }
906
+ icon(value) {
907
+ validateIconName(value, `attribute "${this.attr.name}"`);
908
+ this.attr.icon = value;
909
+ return this;
910
+ }
911
+ order(value) {
912
+ this.attr.order = value;
913
+ return this;
914
+ }
915
+ defaultValue(value) {
916
+ this.attr.defaultValue = value;
917
+ return this;
918
+ }
919
+ metadata(value) {
920
+ this.attr.metadata = value;
921
+ return this;
922
+ }
923
+ build() {
924
+ return this.attr;
925
+ }
926
+ };
927
+ var TextAttributeBuilder = class extends BaseAttributeBuilder {
928
+ constructor(name, label) {
929
+ super("text", name, label);
930
+ }
931
+ minLength(value) {
932
+ this.attr.minLength = value;
933
+ return this;
934
+ }
935
+ maxLength(value) {
936
+ this.attr.maxLength = value;
937
+ return this;
938
+ }
939
+ pattern(value) {
940
+ this.attr.pattern = value;
941
+ return this;
942
+ }
943
+ required() {
944
+ this.setRequired(true);
945
+ return this;
946
+ }
947
+ optional() {
948
+ this.setRequired(false);
949
+ return this;
950
+ }
951
+ /**
952
+ * Set email validation pattern
953
+ */
954
+ email() {
955
+ this.attr.pattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
956
+ return this;
957
+ }
958
+ /**
959
+ * Set URL validation pattern
960
+ */
961
+ url() {
962
+ this.attr.pattern = "^https?:\\/\\/[\\w\\-]+(\\.[\\w\\-]+)+[/#?]?.*$";
963
+ return this;
964
+ }
965
+ /**
966
+ * Set slug validation pattern
967
+ */
968
+ slug() {
969
+ this.attr.pattern = "^[a-z0-9]+(?:-[a-z0-9]+)*$";
970
+ return this;
971
+ }
972
+ };
973
+ function text(config) {
974
+ return new TextAttributeBuilder(config.name, config.label);
975
+ }
976
+ var TextAreaAttributeBuilder = class extends BaseAttributeBuilder {
977
+ constructor(name, label) {
978
+ super("textarea", name, label);
979
+ }
980
+ required() {
981
+ this.setRequired(true);
982
+ return this;
983
+ }
984
+ optional() {
985
+ this.setRequired(false);
986
+ return this;
987
+ }
988
+ };
989
+ function textarea(config) {
990
+ return new TextAreaAttributeBuilder(config.name, config.label);
991
+ }
992
+ var NumberAttributeBuilder = class extends BaseAttributeBuilder {
993
+ constructor(name, label) {
994
+ super("number", name, label);
995
+ }
996
+ min(value) {
997
+ this.attr.min = value;
998
+ return this;
999
+ }
1000
+ max(value) {
1001
+ this.attr.max = value;
1002
+ return this;
1003
+ }
1004
+ integer() {
1005
+ this.attr.unit = "integer";
1006
+ this.attr.decimals = 0;
1007
+ return this;
1008
+ }
1009
+ decimal(decimals = 2) {
1010
+ this.attr.unit = "decimal";
1011
+ this.attr.decimals = decimals;
1012
+ return this;
1013
+ }
1014
+ percentage() {
1015
+ this.attr.unit = "percentage";
1016
+ return this;
1017
+ }
1018
+ required() {
1019
+ this.setRequired(true);
1020
+ return this;
1021
+ }
1022
+ optional() {
1023
+ this.setRequired(false);
1024
+ return this;
1025
+ }
1026
+ };
1027
+ function number(config) {
1028
+ return new NumberAttributeBuilder(config.name, config.label);
1029
+ }
1030
+ var CheckboxAttributeBuilder = class extends BaseAttributeBuilder {
1031
+ constructor(name, label) {
1032
+ super("checkbox", name, label);
1033
+ }
1034
+ required() {
1035
+ this.setRequired(true);
1036
+ return this;
1037
+ }
1038
+ optional() {
1039
+ this.setRequired(false);
1040
+ return this;
1041
+ }
1042
+ };
1043
+ function checkbox(config) {
1044
+ return new CheckboxAttributeBuilder(config.name, config.label);
1045
+ }
1046
+ var DateAttributeBuilder = class extends BaseAttributeBuilder {
1047
+ constructor(name, label) {
1048
+ super("date", name, label);
1049
+ }
1050
+ format(value) {
1051
+ this.attr.dateFormat = value;
1052
+ return this;
1053
+ }
1054
+ minDate(value) {
1055
+ this.attr.minDate = value;
1056
+ return this;
1057
+ }
1058
+ maxDate(value) {
1059
+ this.attr.maxDate = value;
1060
+ return this;
1061
+ }
1062
+ required() {
1063
+ this.setRequired(true);
1064
+ return this;
1065
+ }
1066
+ optional() {
1067
+ this.setRequired(false);
1068
+ return this;
1069
+ }
1070
+ };
1071
+ function date(config) {
1072
+ return new DateAttributeBuilder(config.name, config.label);
1073
+ }
1074
+ var PhoneAttributeBuilder = class extends BaseAttributeBuilder {
1075
+ constructor(name, label) {
1076
+ super("phone", name, label);
1077
+ }
1078
+ defaultCountry(value) {
1079
+ this.attr.defaultCountryCode = value;
1080
+ return this;
1081
+ }
1082
+ required() {
1083
+ this.setRequired(true);
1084
+ return this;
1085
+ }
1086
+ optional() {
1087
+ this.setRequired(false);
1088
+ return this;
1089
+ }
1090
+ };
1091
+ function phone(config) {
1092
+ return new PhoneAttributeBuilder(config.name, config.label);
1093
+ }
1094
+ var CurrencyAttributeBuilder = class extends BaseAttributeBuilder {
1095
+ constructor(name, label) {
1096
+ super("currency", name, label);
1097
+ }
1098
+ defaultCurrency(value) {
1099
+ this.attr.defaultCurrency = value;
1100
+ return this;
1101
+ }
1102
+ allowedCurrencies(value) {
1103
+ this.attr.allowedCurrencies = value;
1104
+ return this;
1105
+ }
1106
+ required() {
1107
+ this.setRequired(true);
1108
+ return this;
1109
+ }
1110
+ optional() {
1111
+ this.setRequired(false);
1112
+ return this;
1113
+ }
1114
+ };
1115
+ function currency(config) {
1116
+ return new CurrencyAttributeBuilder(config.name, config.label);
1117
+ }
1118
+ var StatusAttributeBuilder = class extends BaseAttributeBuilder {
1119
+ constructor(name, label) {
1120
+ super("status", name, label);
1121
+ }
1122
+ /**
1123
+ * Set all options at once (preserves literal types for values)
1124
+ */
1125
+ options(value) {
1126
+ validateOptions(value, this.attr.name ?? "unknown");
1127
+ this.attr.options = value;
1128
+ return this;
1129
+ }
1130
+ option(config) {
1131
+ if (!this.attr.options) {
1132
+ this.attr.options = [];
1133
+ }
1134
+ const allOptions = [...this.attr.options, config];
1135
+ validateOptions(allOptions, this.attr.name ?? "unknown");
1136
+ this.attr.options.push(config);
1137
+ return this;
1138
+ }
1139
+ required() {
1140
+ this.setRequired(true);
1141
+ return this;
1142
+ }
1143
+ optional() {
1144
+ this.setRequired(false);
1145
+ return this;
1146
+ }
1147
+ };
1148
+ function status(config) {
1149
+ return new StatusAttributeBuilder(config.name, config.label);
1150
+ }
1151
+ var SelectAttributeBuilder = class extends BaseAttributeBuilder {
1152
+ constructor(name, label) {
1153
+ super("select", name, label);
1154
+ }
1155
+ /**
1156
+ * Set all options at once (preserves literal types for values)
1157
+ */
1158
+ options(value) {
1159
+ validateOptions(value, this.attr.name ?? "unknown");
1160
+ this.attr.options = value;
1161
+ return this;
1162
+ }
1163
+ option(config) {
1164
+ if (!this.attr.options) {
1165
+ this.attr.options = [];
1166
+ }
1167
+ const allOptions = [...this.attr.options, config];
1168
+ validateOptions(allOptions, this.attr.name ?? "unknown");
1169
+ this.attr.options.push(config);
1170
+ return this;
1171
+ }
1172
+ required() {
1173
+ this.setRequired(true);
1174
+ return this;
1175
+ }
1176
+ optional() {
1177
+ this.setRequired(false);
1178
+ return this;
1179
+ }
1180
+ };
1181
+ function select(config) {
1182
+ return new SelectAttributeBuilder(config.name, config.label);
1183
+ }
1184
+ var MultiselectAttributeBuilder = class extends BaseAttributeBuilder {
1185
+ constructor(name, label) {
1186
+ super("multiselect", name, label);
1187
+ }
1188
+ /**
1189
+ * Set all options at once (preserves literal types for values)
1190
+ */
1191
+ options(value) {
1192
+ validateOptions(value, this.attr.name ?? "unknown");
1193
+ this.attr.options = value;
1194
+ return this;
1195
+ }
1196
+ option(config) {
1197
+ if (!this.attr.options) {
1198
+ this.attr.options = [];
1199
+ }
1200
+ const allOptions = [...this.attr.options, config];
1201
+ validateOptions(allOptions, this.attr.name ?? "unknown");
1202
+ this.attr.options.push(config);
1203
+ return this;
1204
+ }
1205
+ required() {
1206
+ this.setRequired(true);
1207
+ return this;
1208
+ }
1209
+ optional() {
1210
+ this.setRequired(false);
1211
+ return this;
1212
+ }
1213
+ };
1214
+ function multiselect(config) {
1215
+ return new MultiselectAttributeBuilder(config.name, config.label);
1216
+ }
1217
+ var LocationAttributeBuilder = class extends BaseAttributeBuilder {
1218
+ constructor(name, label) {
1219
+ super("location", name, label);
1220
+ }
1221
+ granularity(value) {
1222
+ this.attr.granularity = value;
1223
+ return this;
1224
+ }
1225
+ enableAutocomplete() {
1226
+ this.attr.enableAutocomplete = true;
1227
+ return this;
1228
+ }
1229
+ enableMap() {
1230
+ this.attr.enableMap = true;
1231
+ return this;
1232
+ }
1233
+ defaultCountry(value) {
1234
+ this.attr.defaultCountry = value;
1235
+ return this;
1236
+ }
1237
+ allowedCountries(value) {
1238
+ this.attr.allowedCountries = value;
1239
+ return this;
1240
+ }
1241
+ displayFormat(value) {
1242
+ this.attr.displayFormat = value;
1243
+ return this;
1244
+ }
1245
+ required() {
1246
+ this.setRequired(true);
1247
+ return this;
1248
+ }
1249
+ optional() {
1250
+ this.setRequired(false);
1251
+ return this;
1252
+ }
1253
+ };
1254
+ function location(config) {
1255
+ return new LocationAttributeBuilder(config.name, config.label);
1256
+ }
1257
+ var TimestampAttributeBuilder = class extends BaseAttributeBuilder {
1258
+ constructor(name, label) {
1259
+ super("timestamp", name, label);
1260
+ }
1261
+ autoUpdate() {
1262
+ this.attr.autoUpdate = true;
1263
+ return this;
1264
+ }
1265
+ required() {
1266
+ this.setRequired(true);
1267
+ return this;
1268
+ }
1269
+ optional() {
1270
+ this.setRequired(false);
1271
+ return this;
1272
+ }
1273
+ };
1274
+ function timestamp(config) {
1275
+ return new TimestampAttributeBuilder(config.name, config.label);
1276
+ }
1277
+ var FileAttributeBuilder = class extends BaseAttributeBuilder {
1278
+ constructor(name, label) {
1279
+ super("file", name, label);
1280
+ }
1281
+ maxFiles(value) {
1282
+ this.attr.maxFiles = value;
1283
+ return this;
1284
+ }
1285
+ maxSize(bytes) {
1286
+ this.attr.maxSize = bytes;
1287
+ return this;
1288
+ }
1289
+ allowedTypes(types) {
1290
+ this.attr.allowedTypes = types;
1291
+ return this;
1292
+ }
1293
+ verification(config) {
1294
+ this.attr.verification = config;
1295
+ return this;
1296
+ }
1297
+ required() {
1298
+ this.setRequired(true);
1299
+ return this;
1300
+ }
1301
+ optional() {
1302
+ this.setRequired(false);
1303
+ return this;
1304
+ }
1305
+ };
1306
+ function file(config) {
1307
+ return new FileAttributeBuilder(config.name, config.label);
1308
+ }
1309
+ var UserAttributeBuilder = class extends BaseAttributeBuilder {
1310
+ constructor(name, label) {
1311
+ super("user", name, label);
1312
+ }
1313
+ allowedRoles(roles) {
1314
+ this.attr.allowedRoles = roles;
1315
+ return this;
1316
+ }
1317
+ required() {
1318
+ this.setRequired(true);
1319
+ return this;
1320
+ }
1321
+ optional() {
1322
+ this.setRequired(false);
1323
+ return this;
1324
+ }
1325
+ };
1326
+ function user(config) {
1327
+ return new UserAttributeBuilder(config.name, config.label);
1328
+ }
1329
+ var SingleRelationAttributeBuilder = class extends BaseAttributeBuilder {
1330
+ constructor(name, label) {
1331
+ super("relation", name, label);
1332
+ this.attr.cardinality = "one";
1333
+ this.attr.targets = [];
1334
+ }
1335
+ /**
1336
+ * Add a target object that can be linked
1337
+ * @param objectName - Name of the object (e.g., "companies")
1338
+ * @param options - Display template and filter options
1339
+ */
1340
+ to(objectName, options) {
1341
+ const target = {
1342
+ object: objectName,
1343
+ ...options
1344
+ };
1345
+ this.attr.targets?.push(target);
1346
+ return this;
1347
+ }
1348
+ /**
1349
+ * Set the deletion strategy when target record is deleted
1350
+ * @param strategy - "restrict" (default), "cascade", or "set_null"
1351
+ */
1352
+ onDelete(strategy) {
1353
+ this.attr.onDelete = strategy;
1354
+ return this;
1355
+ }
1356
+ /**
1357
+ * Convert to a multi-relation (cardinality: "many")
1358
+ */
1359
+ many() {
1360
+ const multiBuilder = new MultiRelationAttributeBuilder(
1361
+ this.attr.name,
1362
+ this.attr.label ?? "",
1363
+ {
1364
+ targets: this.attr.targets,
1365
+ onDelete: this.attr.onDelete,
1366
+ isRequired: this.attr.required
1367
+ }
1368
+ );
1369
+ return multiBuilder;
1370
+ }
1371
+ required() {
1372
+ this.setRequired(true);
1373
+ return this;
1374
+ }
1375
+ optional() {
1376
+ this.setRequired(false);
1377
+ return this;
1378
+ }
1379
+ };
1380
+ var MultiRelationAttributeBuilder = class extends BaseAttributeBuilder {
1381
+ constructor(name, label, initOptions) {
1382
+ super("relation", name, label);
1383
+ this.attr.cardinality = "many";
1384
+ this.attr.targets = initOptions?.targets ?? [];
1385
+ this.attr.defaultValue = [];
1386
+ if (initOptions?.onDelete) {
1387
+ this.attr.onDelete = initOptions.onDelete;
1388
+ }
1389
+ if (initOptions?.isRequired) {
1390
+ this.setRequired(true);
1391
+ }
1392
+ }
1393
+ /**
1394
+ * Add a target object that can be linked
1395
+ * @param objectName - Name of the object (e.g., "companies")
1396
+ * @param options - Display template and filter options
1397
+ */
1398
+ to(objectName, options) {
1399
+ const target = {
1400
+ object: objectName,
1401
+ ...options
1402
+ };
1403
+ this.attr.targets?.push(target);
1404
+ return this;
1405
+ }
1406
+ /**
1407
+ * Set the deletion strategy when target record is deleted
1408
+ * @param strategy - "restrict" (default), "cascade", or "set_null"
1409
+ */
1410
+ onDelete(strategy) {
1411
+ this.attr.onDelete = strategy;
1412
+ return this;
1413
+ }
1414
+ /**
1415
+ * Set minimum number of relations required
1416
+ */
1417
+ minItems(count) {
1418
+ this.attr.minItems = count;
1419
+ return this;
1420
+ }
1421
+ /**
1422
+ * Set maximum number of relations allowed
1423
+ */
1424
+ maxItems(count) {
1425
+ this.attr.maxItems = count;
1426
+ return this;
1427
+ }
1428
+ required() {
1429
+ this.setRequired(true);
1430
+ return this;
1431
+ }
1432
+ optional() {
1433
+ this.setRequired(false);
1434
+ return this;
1435
+ }
1436
+ };
1437
+ function relation(config) {
1438
+ return new SingleRelationAttributeBuilder(config.name, config.label);
1439
+ }
1440
+ var RatingAttributeBuilder = class extends BaseAttributeBuilder {
1441
+ constructor(name, label) {
1442
+ super("rating", name, label);
1443
+ }
1444
+ max(value) {
1445
+ this.attr.max = value;
1446
+ return this;
1447
+ }
1448
+ iconType(value) {
1449
+ this.attr.iconType = value;
1450
+ return this;
1451
+ }
1452
+ required() {
1453
+ this.setRequired(true);
1454
+ return this;
1455
+ }
1456
+ optional() {
1457
+ this.setRequired(false);
1458
+ return this;
1459
+ }
1460
+ };
1461
+ function rating(config) {
1462
+ return new RatingAttributeBuilder(config.name, config.label);
1463
+ }
1464
+
1465
+ // src/builders/object-builder.ts
1466
+ import z from "zod";
1467
+ var ObjectBuilder = class {
1468
+ constructor(config) {
1469
+ this.validateName(config.name);
1470
+ this.obj = {
1471
+ name: config.name,
1472
+ label: config.label,
1473
+ attributes: [],
1474
+ system: false
1475
+ };
1476
+ }
1477
+ /**
1478
+ * Set object description
1479
+ */
1480
+ description(value) {
1481
+ this.obj.description = value;
1482
+ return this;
1483
+ }
1484
+ /**
1485
+ * Set object icon
1486
+ */
1487
+ icon(value) {
1488
+ this.obj.icon = value;
1489
+ return this;
1490
+ }
1491
+ /**
1492
+ * Mark as system/native object (defined in code, protected)
1493
+ * System objects cannot be deleted/modified by clients
1494
+ */
1495
+ system() {
1496
+ this.obj.system = true;
1497
+ return this;
1498
+ }
1499
+ /**
1500
+ * Add an attribute to the object with type accumulation
1501
+ *
1502
+ * The return type accumulates the attribute's name and value type
1503
+ * into the TRecord generic, enabling full inference.
1504
+ *
1505
+ * @param attr - Attribute definition or builder (auto-builds if builder)
1506
+ */
1507
+ attribute(attr) {
1508
+ if (!this.obj.attributes) {
1509
+ this.obj.attributes = [];
1510
+ }
1511
+ const finalAttr = "build" in attr && typeof attr.build === "function" ? attr.build() : attr;
1512
+ this.obj.attributes.push(finalAttr);
1513
+ return this;
1514
+ }
1515
+ /**
1516
+ * Add multiple attributes at once
1517
+ * Note: For full type inference, prefer chaining .attribute() calls
1518
+ */
1519
+ attributes(attrs) {
1520
+ if (!this.obj.attributes) {
1521
+ this.obj.attributes = [];
1522
+ }
1523
+ const finalAttrs = attrs.map((attr) => "build" in attr ? attr.build() : attr);
1524
+ this.obj.attributes.push(...finalAttrs);
1525
+ return this;
1526
+ }
1527
+ /**
1528
+ * Set metadata
1529
+ */
1530
+ metadata(value) {
1531
+ this.obj.metadata = value;
1532
+ return this;
1533
+ }
1534
+ /**
1535
+ * Set the title attribute (the text attribute used to display the object's name)
1536
+ * Must reference a text attribute that has been added to the object.
1537
+ * If not set, the first text attribute becomes the title attribute.
1538
+ *
1539
+ * @param attributeName - The name of a text attribute
1540
+ */
1541
+ titleAttribute(attributeName) {
1542
+ this._titleAttribute = attributeName;
1543
+ return this;
1544
+ }
1545
+ /**
1546
+ * Build the final ObjectDefinition
1547
+ * @throws Error if required fields are missing or invalid
1548
+ */
1549
+ build() {
1550
+ if (!this.obj.name) {
1551
+ throw new Error("[ObjectBuilder] Missing required field: name");
1552
+ }
1553
+ if (!this.obj.label) {
1554
+ throw new Error("[ObjectBuilder] Missing required field: label");
1555
+ }
1556
+ const textAttributes = (this.obj.attributes ?? []).filter((attr) => attr.type === "text");
1557
+ if (textAttributes.length === 0) {
1558
+ throw new Error(
1559
+ `[ObjectBuilder] Object "${this.obj.name}" must have at least one text attribute.
1560
+ A text attribute is required to serve as the object's title/display name.
1561
+ \u2705 Example: .attribute(text({ name: 'name', label: 'Name' }).required())`
1562
+ );
1563
+ }
1564
+ const titleAttrName = this._titleAttribute ?? textAttributes[0].name;
1565
+ const titleAttr = textAttributes.find((attr) => attr.name === titleAttrName);
1566
+ if (!titleAttr) {
1567
+ const availableTextAttrs = textAttributes.map((a) => `'${a.name}'`).join(", ");
1568
+ throw new Error(
1569
+ `[ObjectBuilder] titleAttribute "${titleAttrName}" must be a text attribute.
1570
+ Available text attributes: ${availableTextAttrs}`
1571
+ );
1572
+ }
1573
+ return {
1574
+ ...this.obj,
1575
+ titleAttribute: titleAttrName
1576
+ };
1577
+ }
1578
+ /**
1579
+ * Validate object name format
1580
+ * Must be kebab-case (slug format), max 63 characters
1581
+ * @internal
1582
+ */
1583
+ validateName(name) {
1584
+ if (name === void 0) {
1585
+ return;
1586
+ }
1587
+ const objectNameSchema = z.string().min(1, "Object name cannot be empty").max(63, "Object name is too long (max 63 characters)").regex(/^[a-z][a-z0-9-]*$/, {
1588
+ 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'"
1589
+ });
1590
+ try {
1591
+ objectNameSchema.parse(name);
1592
+ } catch (error) {
1593
+ if (error instanceof z.ZodError) {
1594
+ throw new Error(`[ObjectBuilder] ${error.errors[0].message}`);
1595
+ }
1596
+ throw error;
1597
+ }
1598
+ }
1599
+ };
1600
+ function object(config) {
1601
+ return new ObjectBuilder(config);
1602
+ }
1603
+
1604
+ // src/builders/view-builder.ts
1605
+ import { z as z2 } from "zod";
1606
+ var GroupBuilder = class {
1607
+ constructor(id, label) {
1608
+ this.data = { fields: [] };
1609
+ this.data.id = id;
1610
+ this.data.label = label;
1611
+ }
1612
+ /**
1613
+ * Set group description
1614
+ */
1615
+ description(value) {
1616
+ this.data.description = value;
1617
+ return this;
1618
+ }
1619
+ /**
1620
+ * Make group collapsible
1621
+ * @param collapsed - Initial collapsed state (default: false)
1622
+ */
1623
+ collapsible(collapsed = false) {
1624
+ this.data.collapsible = true;
1625
+ this.data.collapsed = collapsed;
1626
+ return this;
1627
+ }
1628
+ /**
1629
+ * Set display order
1630
+ */
1631
+ order(value) {
1632
+ this.data.order = value;
1633
+ return this;
1634
+ }
1635
+ /**
1636
+ * Add multiple fields with default options
1637
+ * @example .fields("name", "email", "phone")
1638
+ */
1639
+ fields(...names) {
1640
+ for (const name of names) {
1641
+ this.data.fields?.push({ attribute: name });
1642
+ }
1643
+ return this;
1644
+ }
1645
+ /**
1646
+ * Add a single field with options
1647
+ * @example .field("name", { span: 8, readOnly: true })
1648
+ */
1649
+ field(attribute, options) {
1650
+ this.data.fields?.push({ attribute, ...options });
1651
+ return this;
1652
+ }
1653
+ /**
1654
+ * Build the group definition
1655
+ */
1656
+ build() {
1657
+ if (!this.data.id) {
1658
+ throw new Error("[GroupBuilder] id is required");
1659
+ }
1660
+ if (!this.data.label) {
1661
+ throw new Error("[GroupBuilder] label is required");
1662
+ }
1663
+ if (!this.data.fields || this.data.fields.length === 0) {
1664
+ throw new Error("[GroupBuilder] At least one field is required");
1665
+ }
1666
+ return this.data;
1667
+ }
1668
+ };
1669
+ var TableTabConfig = class {
1670
+ /** @internal */
1671
+ constructor(view2, base, relation2) {
1672
+ this.view = view2;
1673
+ this.tabData = { ...base, type: "table", relation: relation2, columns: [] };
1674
+ }
1675
+ /**
1676
+ * Set columns to display
1677
+ * @example .columns("firstName", "lastName", "email")
1678
+ */
1679
+ columns(...names) {
1680
+ this.tabData.columns = names;
1681
+ return this;
1682
+ }
1683
+ /**
1684
+ * Allow creating new records
1685
+ */
1686
+ create() {
1687
+ this.tabData.allowCreate = true;
1688
+ return this;
1689
+ }
1690
+ /**
1691
+ * Allow inline editing
1692
+ */
1693
+ edit() {
1694
+ this.tabData.allowEdit = true;
1695
+ return this;
1696
+ }
1697
+ /**
1698
+ * Allow deleting records
1699
+ */
1700
+ delete() {
1701
+ this.tabData.allowDelete = true;
1702
+ return this;
1703
+ }
1704
+ /**
1705
+ * Enable all CRUD operations (create, edit, delete)
1706
+ */
1707
+ crud() {
1708
+ this.tabData.allowCreate = true;
1709
+ this.tabData.allowEdit = true;
1710
+ this.tabData.allowDelete = true;
1711
+ return this;
1712
+ }
1713
+ /**
1714
+ * Set default filters
1715
+ */
1716
+ filters(value) {
1717
+ this.tabData.filters = value;
1718
+ return this;
1719
+ }
1720
+ /**
1721
+ * Set default sort
1722
+ * @example .sort("lastName") or .sort("createdAt", "desc")
1723
+ */
1724
+ sort(field, order = "asc") {
1725
+ this.tabData.sort = { field, order };
1726
+ return this;
1727
+ }
1728
+ /**
1729
+ * Continue building with a new tab
1730
+ */
1731
+ tab(name, label) {
1732
+ this.finalize();
1733
+ return new TabBuilder(this.view, name, label);
1734
+ }
1735
+ /**
1736
+ * Finish this tab and return to ViewBuilder
1737
+ */
1738
+ done() {
1739
+ this.finalize();
1740
+ return this.view;
1741
+ }
1742
+ /**
1743
+ * Build the final view definition
1744
+ */
1745
+ build() {
1746
+ this.finalize();
1747
+ return this.view.build();
1748
+ }
1749
+ finalize() {
1750
+ if (!this.tabData.columns || this.tabData.columns.length === 0) {
1751
+ throw new Error(`[TableTabConfig] columns() is required for tab "${this.tabData.name}"`);
1752
+ }
1753
+ this.view._addTab(this.tabData);
1754
+ }
1755
+ };
1756
+ var CustomTabConfig = class {
1757
+ /** @internal */
1758
+ constructor(view2, base, component) {
1759
+ this.view = view2;
1760
+ this.tabData = { ...base, type: "custom", component };
1761
+ }
1762
+ /**
1763
+ * Set props to pass to the component
1764
+ */
1765
+ props(value) {
1766
+ this.tabData.props = value;
1767
+ return this;
1768
+ }
1769
+ /**
1770
+ * Continue building with a new tab
1771
+ */
1772
+ tab(name, label) {
1773
+ this.view._addTab(this.tabData);
1774
+ return new TabBuilder(this.view, name, label);
1775
+ }
1776
+ /**
1777
+ * Finish this tab and return to ViewBuilder
1778
+ */
1779
+ done() {
1780
+ this.view._addTab(this.tabData);
1781
+ return this.view;
1782
+ }
1783
+ /**
1784
+ * Build the final view definition
1785
+ */
1786
+ build() {
1787
+ this.view._addTab(this.tabData);
1788
+ return this.view.build();
1789
+ }
1790
+ };
1791
+ var TabBuilder = class {
1792
+ /** @internal */
1793
+ constructor(view2, name, label) {
1794
+ this.view = view2;
1795
+ this.base = {
1796
+ id: name,
1797
+ name,
1798
+ label
1799
+ };
1800
+ }
1801
+ /**
1802
+ * Set tab icon
1803
+ */
1804
+ icon(value) {
1805
+ this.base.icon = value;
1806
+ return this;
1807
+ }
1808
+ /**
1809
+ * Set display order
1810
+ */
1811
+ order(value) {
1812
+ this.base.order = value;
1813
+ return this;
1814
+ }
1815
+ /**
1816
+ * Mark as system tab (protected)
1817
+ */
1818
+ system() {
1819
+ this.base.system = true;
1820
+ return this;
1821
+ }
1822
+ // ─────────────────────────────────────────────────────────────────────────
1823
+ // TYPE DISCRIMINATORS
1824
+ // ─────────────────────────────────────────────────────────────────────────
1825
+ /**
1826
+ * Create a form tab with groups
1827
+ * @example .form(group("info", "Info").fields("name", "email"))
1828
+ */
1829
+ form(...groups) {
1830
+ if (groups.length === 0) {
1831
+ throw new Error(
1832
+ `[TabBuilder] form() requires at least one group for tab "${this.base.name}"`
1833
+ );
1834
+ }
1835
+ const tab = {
1836
+ ...this.base,
1837
+ type: "form",
1838
+ groups: groups.map((g) => g instanceof GroupBuilder ? g.build() : g)
1839
+ };
1840
+ return this.view._addTab(tab);
1841
+ }
1842
+ /**
1843
+ * Create a table tab for a relation
1844
+ * @example .table("contacts").columns("name", "email").crud()
1845
+ */
1846
+ table(relation2) {
1847
+ return new TableTabConfig(this.view, this.base, relation2);
1848
+ }
1849
+ /**
1850
+ * Create a custom tab with a component
1851
+ * @example .custom("AnalyticsWidget").props({ period: "12m" })
1852
+ */
1853
+ custom(component) {
1854
+ return new CustomTabConfig(this.view, this.base, component);
1855
+ }
1856
+ };
1857
+ var ViewBuilder = class {
1858
+ constructor(name, label) {
1859
+ this.data = { tabs: [] };
1860
+ this.validated = false;
1861
+ this.validateName(name);
1862
+ this.data.name = name;
1863
+ this.data.label = label;
1864
+ }
1865
+ /**
1866
+ * Set view description
1867
+ */
1868
+ description(value) {
1869
+ this.data.description = value;
1870
+ return this;
1871
+ }
1872
+ /**
1873
+ * Set view icon
1874
+ */
1875
+ icon(value) {
1876
+ this.data.icon = value;
1877
+ return this;
1878
+ }
1879
+ /**
1880
+ * Associate view with an object
1881
+ * @param objectName - Object name (kebab-case)
1882
+ */
1883
+ for(objectName) {
1884
+ this.data.object = objectName;
1885
+ return this;
1886
+ }
1887
+ /**
1888
+ * Mark as default view for the object
1889
+ */
1890
+ default() {
1891
+ this.data.default = true;
1892
+ return this;
1893
+ }
1894
+ /**
1895
+ * Mark as system view (protected, defined by developer)
1896
+ */
1897
+ system() {
1898
+ this.data.system = true;
1899
+ return this;
1900
+ }
1901
+ /**
1902
+ * Set metadata
1903
+ */
1904
+ metadata(value) {
1905
+ this.data.metadata = value;
1906
+ return this;
1907
+ }
1908
+ /**
1909
+ * Start building a new tab
1910
+ */
1911
+ tab(name, label) {
1912
+ return new TabBuilder(this, name, label);
1913
+ }
1914
+ /**
1915
+ * Add a pre-built tab
1916
+ */
1917
+ addTab(tab) {
1918
+ this.data.tabs?.push(tab);
1919
+ return this;
1920
+ }
1921
+ /**
1922
+ * @internal Used by TabBuilder to add tabs
1923
+ */
1924
+ _addTab(tab) {
1925
+ this.data.tabs?.push(tab);
1926
+ return this;
1927
+ }
1928
+ /**
1929
+ * Build the final view definition
1930
+ */
1931
+ build() {
1932
+ if (!this.data.object) {
1933
+ throw new Error("[ViewBuilder] for() is required - specify the target object");
1934
+ }
1935
+ if (!this.data.tabs || this.data.tabs.length === 0) {
1936
+ throw new Error("[ViewBuilder] At least one tab is required");
1937
+ }
1938
+ const tabNames = /* @__PURE__ */ new Set();
1939
+ for (const tab of this.data.tabs) {
1940
+ if (tabNames.has(tab.name)) {
1941
+ throw new Error(`[ViewBuilder] Duplicate tab name "${tab.name}"`);
1942
+ }
1943
+ tabNames.add(tab.name);
1944
+ }
1945
+ this.validated = true;
1946
+ return this.data;
1947
+ }
1948
+ /**
1949
+ * Validate view name format (kebab-case)
1950
+ */
1951
+ validateName(name) {
1952
+ const viewNameSchema = z2.string().min(1, "View name cannot be empty").max(63, "View name is too long (max 63 characters)").regex(/^[a-z][a-z0-9-]*$/, {
1953
+ message: "Invalid view name format.\nName must be in kebab-case:\n \u2705 Valid: 'detail', 'list-view', 'company-detail'\n \u274C Invalid: 'Detail', 'listView', 'list_view'"
1954
+ });
1955
+ try {
1956
+ viewNameSchema.parse(name);
1957
+ } catch (error) {
1958
+ if (error instanceof z2.ZodError) {
1959
+ throw new Error(`[ViewBuilder] ${error.errors[0].message}`);
1960
+ }
1961
+ throw error;
1962
+ }
1963
+ }
1964
+ };
1965
+ function view(name, label) {
1966
+ return new ViewBuilder(name, label);
1967
+ }
1968
+ function group(id, label) {
1969
+ return new GroupBuilder(id, label);
1970
+ }
1971
+
1972
+ // src/runtime/services/object-schema.service.ts
1973
+ var ObjectSchemaService = class {
1974
+ constructor(adapter, nativeRegistry) {
1975
+ this.adapter = adapter;
1976
+ this.nativeRegistry = nativeRegistry;
1977
+ }
1978
+ /**
1979
+ * Create a new custom object
1980
+ * Validates name format and ensures system=false
1981
+ *
1982
+ * @param definition - Object definition (attributes can be raw definitions or builders)
1983
+ * @param tenantId - Tenant ID owning the object
1984
+ * @returns Created ObjectDefinition
1985
+ */
1986
+ async createCustomObject(definition, tenantId) {
1987
+ const builder = object({
1988
+ name: definition.name,
1989
+ label: definition.label
1990
+ });
1991
+ if (definition.description) builder.description(definition.description);
1992
+ if (definition.icon) builder.icon(definition.icon);
1993
+ if (definition.metadata) builder.metadata(definition.metadata);
1994
+ if (definition.attributes && definition.attributes.length > 0) {
1995
+ builder.attributes(definition.attributes);
1996
+ }
1997
+ const objectDef = builder.build();
1998
+ const existing = await this.adapter.objects.findByName(tenantId, objectDef.name);
1999
+ if (existing) {
2000
+ throw new Error(`Object with name "${objectDef.name}" already exists`);
2001
+ }
2002
+ const metadata = {
2003
+ ...objectDef.metadata,
2004
+ icon: objectDef.icon
2005
+ };
2006
+ const dbObject = await this.adapter.objects.create({
2007
+ tenantId,
2008
+ name: objectDef.name,
2009
+ label: objectDef.label,
2010
+ description: objectDef.description,
2011
+ system: false,
2012
+ // Always false for custom objects
2013
+ metadata
2014
+ });
2015
+ const createdAttributes = [];
2016
+ if (objectDef.attributes.length > 0) {
2017
+ for (const attr of objectDef.attributes) {
2018
+ const dbAttr = await this.adapter.attributes.create({
2019
+ objectId: dbObject.id,
2020
+ name: attr.name,
2021
+ label: attr.label,
2022
+ type: attr.type,
2023
+ required: attr.required ?? false,
2024
+ system: false,
2025
+ // Always false for custom attributes
2026
+ config: {
2027
+ ...attr,
2028
+ // Remove common fields stored in columns
2029
+ id: void 0,
2030
+ name: void 0,
2031
+ label: void 0,
2032
+ type: void 0,
2033
+ required: void 0,
2034
+ system: void 0
2035
+ }
2036
+ });
2037
+ createdAttributes.push(this.convertDBAttributeToAttribute(dbAttr));
2038
+ }
2039
+ }
2040
+ return {
2041
+ ...objectDef,
2042
+ id: dbObject.id,
2043
+ attributes: createdAttributes,
2044
+ system: false
2045
+ };
2046
+ }
2047
+ /**
2048
+ * Add a custom attribute to an existing object
2049
+ * Can be used on both custom and native objects
2050
+ * Attributes added via API are always custom (system=false)
2051
+ *
2052
+ * @param objectId - Object UUID from database
2053
+ * @param attribute - Attribute definition
2054
+ * @returns Created Attribute
2055
+ */
2056
+ async addAttributeToObject(objectId, attribute) {
2057
+ this.validateAttributeName(attribute.name);
2058
+ const dbObject = await this.adapter.objects.findById(objectId);
2059
+ if (!dbObject) {
2060
+ throw new Error(`Object with id "${objectId}" not found`);
2061
+ }
2062
+ const existingAttributes = await this.adapter.attributes.findByObjectId(objectId);
2063
+ const duplicate = existingAttributes.find((attr) => attr.name === attribute.name);
2064
+ if (duplicate) {
2065
+ throw new Error(
2066
+ `Attribute with name "${attribute.name}" already exists on object "${dbObject.name}"`
2067
+ );
2068
+ }
2069
+ const dbAttr = await this.adapter.attributes.create({
2070
+ objectId,
2071
+ name: attribute.name,
2072
+ label: attribute.label,
2073
+ type: attribute.type,
2074
+ required: attribute.required ?? false,
2075
+ unique: attribute.unique ?? false,
2076
+ system: false,
2077
+ // Always false for attributes added via API
2078
+ config: {
2079
+ // Store all extra properties in config
2080
+ ...attribute,
2081
+ // Remove common fields stored in columns
2082
+ name: void 0,
2083
+ label: void 0,
2084
+ type: void 0,
2085
+ required: void 0,
2086
+ unique: void 0,
2087
+ system: void 0
2088
+ }
2089
+ });
2090
+ return this.convertDBAttributeToAttribute(dbAttr);
2091
+ }
2092
+ /**
2093
+ * Update an attribute
2094
+ * Can only update custom attributes (system=false)
2095
+ *
2096
+ * @param attributeId - Attribute UUID
2097
+ * @param updates - Partial attribute updates
2098
+ * @returns Updated Attribute
2099
+ */
2100
+ async updateAttribute(attributeId, updates) {
2101
+ const dbAttr = await this.adapter.attributes.findById(attributeId);
2102
+ if (!dbAttr) {
2103
+ throw new Error(`Attribute with id "${attributeId}" not found`);
2104
+ }
2105
+ if (dbAttr.system) {
2106
+ throw new Error(
2107
+ `Cannot modify system attribute "${dbAttr.name}". System attributes are protected.`
2108
+ );
2109
+ }
2110
+ if (updates.name && updates.name !== dbAttr.name) {
2111
+ throw new Error(
2112
+ "Attribute name cannot be changed after creation. Create a new attribute instead."
2113
+ );
2114
+ }
2115
+ if (updates.type && updates.type !== dbAttr.type) {
2116
+ throw new Error(
2117
+ "Attribute type cannot be changed after creation. Create a new attribute instead."
2118
+ );
2119
+ }
2120
+ const updatedDbAttr = await this.adapter.attributes.update(attributeId, {
2121
+ label: updates.label,
2122
+ required: updates.required,
2123
+ config: updates ? {
2124
+ ...dbAttr.config,
2125
+ ...updates,
2126
+ // Remove common fields
2127
+ name: void 0,
2128
+ label: void 0,
2129
+ type: void 0,
2130
+ required: void 0,
2131
+ unique: void 0,
2132
+ system: void 0
2133
+ } : dbAttr.config
2134
+ });
2135
+ return this.convertDBAttributeToAttribute(updatedDbAttr);
2136
+ }
2137
+ /**
2138
+ * Delete an attribute
2139
+ * Can only delete custom attributes (system=false)
2140
+ *
2141
+ * @param attributeId - Attribute UUID
2142
+ */
2143
+ async deleteAttribute(attributeId) {
2144
+ const dbAttr = await this.adapter.attributes.findById(attributeId);
2145
+ if (!dbAttr) {
2146
+ throw new Error(`Attribute with id "${attributeId}" not found`);
2147
+ }
2148
+ if (dbAttr.system) {
2149
+ throw new Error(
2150
+ `Cannot delete system attribute "${dbAttr.name}". System attributes are protected.`
2151
+ );
2152
+ }
2153
+ await this.adapter.attributes.delete(attributeId);
2154
+ }
2155
+ /**
2156
+ * List attributes for an object
2157
+ *
2158
+ * @param objectId - Object UUID
2159
+ * @param options - Filter options
2160
+ * @returns List of attributes
2161
+ */
2162
+ async listAttributes(objectId, options) {
2163
+ const dbAttributes = await this.adapter.attributes.findByObjectId(objectId);
2164
+ let filtered = dbAttributes;
2165
+ if (options?.systemOnly) {
2166
+ filtered = dbAttributes.filter((attr) => attr.system);
2167
+ } else if (options?.customOnly) {
2168
+ filtered = dbAttributes.filter((attr) => !attr.system);
2169
+ }
2170
+ return filtered.map((attr) => this.convertDBAttributeToAttribute(attr));
2171
+ }
2172
+ /**
2173
+ * Validate attribute name format (variable identifier)
2174
+ * @internal
2175
+ */
2176
+ validateAttributeName(name) {
2177
+ const variableNameRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
2178
+ if (!name || name.length === 0) {
2179
+ throw new Error("Attribute name cannot be empty");
2180
+ }
2181
+ if (name.length > 63) {
2182
+ throw new Error("Attribute name is too long (max 63 characters)");
2183
+ }
2184
+ if (!variableNameRegex.test(name)) {
2185
+ throw new Error(
2186
+ "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'"
2187
+ );
2188
+ }
2189
+ }
2190
+ /**
2191
+ * Get complete object schema (system + custom attributes)
2192
+ * If object is native, merges registry definition with DB custom attributes
2193
+ * If object is custom, returns DB definition only
2194
+ *
2195
+ * @param objectId - Object UUID from database
2196
+ * @returns Complete ObjectDefinition with all attributes
2197
+ *
2198
+ * @example
2199
+ * ```typescript
2200
+ * const service = new ObjectSchemaService(adapter, registry);
2201
+ * const productSchema = await service.getObjectSchema("obj-123");
2202
+ *
2203
+ * console.log(productSchema.attributes); // System + custom attributes
2204
+ * ```
2205
+ */
2206
+ async getObjectSchema(objectId) {
2207
+ const dbObject = await this.adapter.objects.findById(objectId);
2208
+ if (!dbObject) {
2209
+ throw new Error(`Object with id "${objectId}" not found`);
2210
+ }
2211
+ const dbAttributes = await this.adapter.attributes.findByObjectId(objectId);
2212
+ if (dbObject.system) {
2213
+ return this.mergeNativeObject(dbObject, dbAttributes);
2214
+ }
2215
+ return this.convertDBObjectToDefinition(dbObject, dbAttributes);
2216
+ }
2217
+ /**
2218
+ * Get object schema by name (for system/native objects)
2219
+ * @deprecated Use getObjectSchemaByNameForTenant for custom objects support
2220
+ */
2221
+ async getObjectSchemaByName(name) {
2222
+ const dbObject = await this.adapter.objects.findSystemByName(name);
2223
+ if (!dbObject) {
2224
+ throw new Error(`Native object "${name}" not found in database`);
2225
+ }
2226
+ const dbAttributes = await this.adapter.attributes.findByObjectId(dbObject.id);
2227
+ return this.mergeNativeObject(dbObject, dbAttributes);
2228
+ }
2229
+ /**
2230
+ * Get object schema by name for a tenant (supports both native and custom objects)
2231
+ */
2232
+ async getObjectSchemaByNameForTenant(name, tenantId) {
2233
+ let dbObject = await this.adapter.objects.findByName(tenantId, name);
2234
+ if (!dbObject) {
2235
+ dbObject = await this.adapter.objects.findSystemByName(name);
2236
+ }
2237
+ if (!dbObject) {
2238
+ throw new Error(`Object "${name}" not found`);
2239
+ }
2240
+ const dbAttributes = await this.adapter.attributes.findByObjectId(dbObject.id);
2241
+ if (dbObject.system) {
2242
+ return this.mergeNativeObject(dbObject, dbAttributes);
2243
+ }
2244
+ return this.convertDBObjectToDefinition(dbObject, dbAttributes);
2245
+ }
2246
+ /**
2247
+ * List all object schemas for a tenant
2248
+ */
2249
+ async listObjectSchemas(tenantId) {
2250
+ const dbObjects = await this.adapter.objects.list(tenantId);
2251
+ const schemas = await Promise.all(
2252
+ dbObjects.map(async (dbObject) => {
2253
+ const dbAttributes = await this.adapter.attributes.findByObjectId(dbObject.id);
2254
+ if (dbObject.system) {
2255
+ return this.mergeNativeObject(dbObject, dbAttributes);
2256
+ }
2257
+ return this.convertDBObjectToDefinition(dbObject, dbAttributes);
2258
+ })
2259
+ );
2260
+ return schemas;
2261
+ }
2262
+ /**
2263
+ * Merge native object from registry with custom attributes from DB
2264
+ * @internal
2265
+ */
2266
+ mergeNativeObject(dbObject, dbAttributes) {
2267
+ const nativeObject = this.nativeRegistry.getByName(dbObject.name);
2268
+ if (!nativeObject) {
2269
+ throw new Error(
2270
+ `Native object "${dbObject.name}" not found in registry. Make sure to register it before querying.`
2271
+ );
2272
+ }
2273
+ const systemAttributesFromDB = dbAttributes.filter((attr) => attr.system);
2274
+ const customAttributes = dbAttributes.filter((attr) => !attr.system);
2275
+ const dbAttrByName = new Map(systemAttributesFromDB.map((attr) => [attr.name, attr]));
2276
+ const systemAttrs = nativeObject.attributes.map((registryAttr) => {
2277
+ const dbAttr = dbAttrByName.get(registryAttr.name);
2278
+ if (dbAttr) {
2279
+ return {
2280
+ ...registryAttr,
2281
+ id: dbAttr.id
2282
+ };
2283
+ }
2284
+ return registryAttr;
2285
+ });
2286
+ const customAttrs = customAttributes.map(
2287
+ (dbAttr) => this.convertDBAttributeToAttribute(dbAttr)
2288
+ );
2289
+ return {
2290
+ ...nativeObject,
2291
+ id: dbObject.id,
2292
+ attributes: [
2293
+ ...systemAttrs,
2294
+ // System attributes from registry (with DB IDs if synced)
2295
+ ...customAttrs
2296
+ // Custom attributes from DB
2297
+ ]
2298
+ };
2299
+ }
2300
+ /**
2301
+ * Convert DB object + attributes to ObjectDefinition
2302
+ * @internal
2303
+ */
2304
+ convertDBObjectToDefinition(dbObject, dbAttributes) {
2305
+ const attributes = dbAttributes.map(
2306
+ (dbAttr) => this.convertDBAttributeToAttribute(dbAttr)
2307
+ );
2308
+ const titleAttribute = dbObject.metadata?.titleAttribute ?? attributes.find((attr) => attr.type === "text")?.name ?? attributes[0]?.name ?? "name";
2309
+ return {
2310
+ id: dbObject.id,
2311
+ name: dbObject.name,
2312
+ label: dbObject.label,
2313
+ description: dbObject.description,
2314
+ icon: dbObject.metadata?.icon,
2315
+ titleAttribute,
2316
+ attributes,
2317
+ system: dbObject.system,
2318
+ metadata: dbObject.metadata
2319
+ };
2320
+ }
2321
+ /**
2322
+ * Convert DB attribute to Attribute type
2323
+ * @internal
2324
+ */
2325
+ convertDBAttributeToAttribute(dbAttr) {
2326
+ const baseAttr = {
2327
+ ...dbAttr.config,
2328
+ id: dbAttr.id,
2329
+ name: dbAttr.name,
2330
+ label: dbAttr.label,
2331
+ type: dbAttr.type,
2332
+ required: dbAttr.required,
2333
+ system: dbAttr.system,
2334
+ unique: dbAttr.unique
2335
+ };
2336
+ return baseAttr;
2337
+ }
2338
+ };
2339
+
2340
+ // src/native/registry.ts
2341
+ var NativeObjectRegistryClass = class {
2342
+ constructor() {
2343
+ this.objects = /* @__PURE__ */ new Map();
2344
+ }
2345
+ /**
2346
+ * Register one or more native objects
2347
+ * Auto-builds if ObjectBuilder is passed instead of ObjectDefinition
2348
+ * @param objects - Single object/builder or array of objects/builders to register
2349
+ * @returns this (for chaining)
2350
+ * @throws Error if object is invalid or already registered
2351
+ *
2352
+ * @example
2353
+ * ```typescript
2354
+ * // No .build() needed - registry auto-builds!
2355
+ * const PRODUCT = object({ id: "obj-product", name: "products", label: "Product" })
2356
+ * .system()
2357
+ * .attribute(text({ id: "attr-name", name: "name", label: "Name" }));
2358
+ *
2359
+ * registry.register(PRODUCT); // ← Auto-builds here
2360
+ *
2361
+ * // Can still explicitly .build() if you want
2362
+ * registry.register(PRODUCT.build());
2363
+ *
2364
+ * // Register multiple
2365
+ * registry.register([PRODUCT, ORDER, CUSTOMER]);
2366
+ * ```
2367
+ */
2368
+ register(objects) {
2369
+ const objectsArray = Array.isArray(objects) ? objects : [objects];
2370
+ for (const obj of objectsArray) {
2371
+ const object2 = "build" in obj && typeof obj.build === "function" ? obj.build() : obj;
2372
+ this.validateAndRegister(object2);
2373
+ }
2374
+ return this;
2375
+ }
2376
+ /**
2377
+ * Validate and register a single object
2378
+ * @internal
2379
+ */
2380
+ validateAndRegister(object2) {
2381
+ if (!object2.system) {
2382
+ throw new Error(
2383
+ `[NativeObjectRegistry] Cannot register object "${object2.name}" (id: ${object2.id}): missing system flag.
2384
+ Native objects must have system=true. Did you forget to call .system() in your builder?`
2385
+ );
2386
+ }
2387
+ if (this.objects.has(object2.name)) {
2388
+ const existing = this.objects.get(object2.name);
2389
+ throw new Error(
2390
+ `[NativeObjectRegistry] Duplicate object name "${object2.name}":
2391
+ - Existing: "${existing?.label}" (id: ${existing?.id})
2392
+ - New: "${object2.label}" (id: ${object2.id})
2393
+ Please use unique names for each native object.`
2394
+ );
2395
+ }
2396
+ this.objects.set(object2.name, object2);
2397
+ }
2398
+ /**
2399
+ * Get a native object by its name
2400
+ * @param name - The object name
2401
+ * @returns The object definition or undefined if not found
2402
+ *
2403
+ * @example
2404
+ * ```typescript
2405
+ * const product = registry.getByName("products");
2406
+ * if (product) {
2407
+ * console.log(product.label); // "Product"
2408
+ * }
2409
+ * ```
2410
+ */
2411
+ getByName(name) {
2412
+ return this.objects.get(name);
2413
+ }
2414
+ /**
2415
+ * Get a native object or throw if not found
2416
+ * @param name - The object name
2417
+ * @returns The object definition
2418
+ * @throws Error if not found
2419
+ */
2420
+ getByNameOrThrow(name) {
2421
+ const object2 = this.objects.get(name);
2422
+ if (!object2) {
2423
+ throw new Error(
2424
+ `[NativeObjectRegistry] Native object "${name}" not found.
2425
+ Available objects: ${this.listNames().join(", ")}`
2426
+ );
2427
+ }
2428
+ return object2;
2429
+ }
2430
+ /**
2431
+ * Get all registered native objects
2432
+ * @returns Array of all registered object definitions
2433
+ */
2434
+ getAll() {
2435
+ return Array.from(this.objects.values());
2436
+ }
2437
+ /**
2438
+ * Get all registered native object names
2439
+ * @returns Array of object names
2440
+ */
2441
+ listNames() {
2442
+ return Array.from(this.objects.keys());
2443
+ }
2444
+ /**
2445
+ * Check if a native object is registered
2446
+ * @param name - The object name
2447
+ * @returns true if registered, false otherwise
2448
+ */
2449
+ has(name) {
2450
+ return this.objects.has(name);
2451
+ }
2452
+ /**
2453
+ * Get the number of registered objects
2454
+ */
2455
+ get size() {
2456
+ return this.objects.size;
2457
+ }
2458
+ /**
2459
+ * Clear all registered objects (useful for testing)
2460
+ * @internal
2461
+ */
2462
+ clear() {
2463
+ this.objects.clear();
2464
+ }
2465
+ /**
2466
+ * Get registry summary for debugging
2467
+ */
2468
+ summary() {
2469
+ const objects = this.getAll();
2470
+ return [
2471
+ `[NativeObjectRegistry] ${this.size} native object(s) registered:`,
2472
+ ...objects.map(
2473
+ (obj) => ` - ${obj.name}: "${obj.label}" (${obj.attributes.length} attributes)`
2474
+ )
2475
+ ].join("\n");
2476
+ }
2477
+ /**
2478
+ * Log registry summary to console
2479
+ */
2480
+ debug() {
2481
+ console.info(this.summary());
2482
+ }
2483
+ };
2484
+ var registry = new NativeObjectRegistryClass();
2485
+
2486
+ // src/validation/validators.ts
2487
+ import { z as z3 } from "zod";
2488
+ function createTextValidator(attr) {
2489
+ let schema = z3.string();
2490
+ if (attr.minLength !== void 0) {
2491
+ schema = schema.min(
2492
+ attr.minLength,
2493
+ `${attr.label} must be at least ${attr.minLength} characters`
2494
+ );
2495
+ }
2496
+ if (attr.maxLength !== void 0) {
2497
+ schema = schema.max(
2498
+ attr.maxLength,
2499
+ `${attr.label} must be at most ${attr.maxLength} characters`
2500
+ );
2501
+ }
2502
+ if (attr.pattern) {
2503
+ schema = schema.regex(new RegExp(attr.pattern), `${attr.label} format is invalid`);
2504
+ }
2505
+ return schema;
2506
+ }
2507
+ function createNumberValidator(attr) {
2508
+ let schema = z3.number();
2509
+ if (attr.min !== void 0) {
2510
+ schema = schema.min(attr.min, `${attr.label} must be at least ${attr.min}`);
2511
+ }
2512
+ if (attr.max !== void 0) {
2513
+ schema = schema.max(attr.max, `${attr.label} must be at most ${attr.max}`);
2514
+ }
2515
+ if (attr.unit === "integer") {
2516
+ schema = schema.int(`${attr.label} must be an integer`);
2517
+ }
2518
+ return schema;
2519
+ }
2520
+ function createCheckboxValidator(_attr) {
2521
+ return z3.boolean();
2522
+ }
2523
+ function createDateValidator(attr) {
2524
+ return z3.string().datetime({ message: `${attr.label} must be a valid ISO date` });
2525
+ }
2526
+ function createPhoneValidator(_attr) {
2527
+ return z3.object({
2528
+ countryCode: z3.string().length(3),
2529
+ phoneNumber: z3.string().min(1)
2530
+ });
2531
+ }
2532
+ function createCurrencyValidator(_attr) {
2533
+ return z3.object({
2534
+ code: z3.string().length(3),
2535
+ value: z3.number().min(0)
2536
+ });
2537
+ }
2538
+ function createStatusValidator(attr) {
2539
+ const validValues = attr.options.map((opt) => opt.value);
2540
+ return z3.enum(validValues, {
2541
+ errorMap: () => ({
2542
+ message: `${attr.label} must be one of: ${validValues.join(", ")}`
2543
+ })
2544
+ });
2545
+ }
2546
+ function createSelectValidator(attr) {
2547
+ const validValues = attr.options.map((opt) => opt.value);
2548
+ return z3.enum(validValues, {
2549
+ errorMap: () => ({
2550
+ message: `${attr.label} must be one of: ${validValues.join(", ")}`
2551
+ })
2552
+ });
2553
+ }
2554
+ function createMultiselectValidator(attr) {
2555
+ const validValues = attr.options.map((opt) => opt.value);
2556
+ return z3.array(
2557
+ z3.enum(validValues, {
2558
+ errorMap: () => ({
2559
+ message: `Each value must be one of: ${validValues.join(", ")}`
2560
+ })
2561
+ })
2562
+ );
2563
+ }
2564
+ function createLocationValidator(_attr) {
2565
+ return z3.object({
2566
+ address: z3.string().optional(),
2567
+ address2: z3.string().optional(),
2568
+ city: z3.string().optional(),
2569
+ state: z3.string().optional(),
2570
+ postalCode: z3.string().optional(),
2571
+ country: z3.string().length(3).optional(),
2572
+ latitude: z3.number().optional(),
2573
+ longitude: z3.number().optional()
2574
+ });
2575
+ }
2576
+ function createTimestampValidator(_attr) {
2577
+ return z3.number().int().positive();
2578
+ }
2579
+ function createFileValidator(_attr) {
2580
+ return z3.string().uuid();
2581
+ }
2582
+ function createUserValidator(_attr) {
2583
+ return z3.string().uuid();
2584
+ }
2585
+ function createSingleRelationValidator(attr) {
2586
+ const uuidSchema = z3.string().uuid({
2587
+ message: `${attr.label} must be a valid record ID`
2588
+ });
2589
+ return z3.union([uuidSchema, z3.null()]);
2590
+ }
2591
+ function createMultiRelationValidator(attr) {
2592
+ const uuidSchema = z3.string().uuid({
2593
+ message: `Each ${attr.label} item must be a valid record ID`
2594
+ });
2595
+ let arraySchema = z3.array(uuidSchema);
2596
+ if (attr.minItems !== void 0) {
2597
+ arraySchema = arraySchema.min(
2598
+ attr.minItems,
2599
+ `${attr.label} must have at least ${attr.minItems} item${attr.minItems > 1 ? "s" : ""}`
2600
+ );
2601
+ }
2602
+ if (attr.maxItems !== void 0) {
2603
+ arraySchema = arraySchema.max(
2604
+ attr.maxItems,
2605
+ `${attr.label} must have at most ${attr.maxItems} item${attr.maxItems > 1 ? "s" : ""}`
2606
+ );
2607
+ }
2608
+ return arraySchema;
2609
+ }
2610
+ function createRelationValidator(attr) {
2611
+ if (attr.cardinality === "many") {
2612
+ return createMultiRelationValidator(attr);
2613
+ }
2614
+ return createSingleRelationValidator(attr);
2615
+ }
2616
+ function createRatingValidator(attr) {
2617
+ let schema = z3.number().int().min(0);
2618
+ if (attr.max !== void 0) {
2619
+ schema = schema.max(attr.max, `${attr.label} must be at most ${attr.max}`);
2620
+ }
2621
+ return schema;
2622
+ }
2623
+ function createAttributeValidator(attr) {
2624
+ switch (attr.type) {
2625
+ case "text":
2626
+ return createTextValidator(attr);
2627
+ case "number":
2628
+ return createNumberValidator(attr);
2629
+ case "checkbox":
2630
+ return createCheckboxValidator(attr);
2631
+ case "date":
2632
+ return createDateValidator(attr);
2633
+ case "phone":
2634
+ return createPhoneValidator(attr);
2635
+ case "currency":
2636
+ return createCurrencyValidator(attr);
2637
+ case "status":
2638
+ return createStatusValidator(attr);
2639
+ case "location":
2640
+ return createLocationValidator(attr);
2641
+ case "timestamp":
2642
+ return createTimestampValidator(attr);
2643
+ case "select":
2644
+ return createSelectValidator(attr);
2645
+ case "multiselect":
2646
+ return createMultiselectValidator(attr);
2647
+ case "file":
2648
+ return createFileValidator(attr);
2649
+ case "user":
2650
+ return createUserValidator(attr);
2651
+ case "relation":
2652
+ return createRelationValidator(attr);
2653
+ case "rating":
2654
+ return createRatingValidator(attr);
2655
+ default:
2656
+ return z3.unknown();
2657
+ }
2658
+ }
2659
+ function createObjectValidator(objectDef) {
2660
+ const shape = {};
2661
+ for (const attr of objectDef.attributes) {
2662
+ let validator = createAttributeValidator(attr);
2663
+ if (!attr.required) {
2664
+ validator = validator.optional();
2665
+ }
2666
+ shape[attr.name] = validator;
2667
+ }
2668
+ return z3.object(shape);
2669
+ }
2670
+ function validateAttribute(attr, value) {
2671
+ const validator = createAttributeValidator(attr);
2672
+ if (!attr.required && (value === void 0 || value === null)) {
2673
+ return { success: true, data: { [attr.name]: value } };
2674
+ }
2675
+ const result = validator.safeParse(value);
2676
+ if (result.success) {
2677
+ return {
2678
+ success: true,
2679
+ data: { [attr.name]: result.data }
2680
+ };
2681
+ }
2682
+ return {
2683
+ success: false,
2684
+ errors: result.error.errors.map((err) => ({
2685
+ path: [attr.name, ...err.path.map(String)],
2686
+ message: err.message
2687
+ }))
2688
+ };
2689
+ }
2690
+ function validateObject(objectDef, data) {
2691
+ const validator = createObjectValidator(objectDef);
2692
+ const result = validator.safeParse(data);
2693
+ if (result.success) {
2694
+ return {
2695
+ success: true,
2696
+ data: result.data
2697
+ };
2698
+ }
2699
+ return {
2700
+ success: false,
2701
+ errors: result.error.errors.map((err) => ({
2702
+ path: err.path.map(String),
2703
+ message: err.message
2704
+ }))
2705
+ };
2706
+ }
2707
+ function validateObjectOrThrow(objectDef, data) {
2708
+ const result = validateObject(objectDef, data);
2709
+ if (!result.success) {
2710
+ const errorMessages = result.errors?.map((err) => `${err.path.join(".")}: ${err.message}`).join("\n") || "Unknown validation error";
2711
+ throw new Error(`Validation failed for ${objectDef.label}:
2712
+ ${errorMessages}`);
2713
+ }
2714
+ return result.data;
2715
+ }
2716
+ function createDraftValidator(objectDef) {
2717
+ const shape = {};
2718
+ for (const attr of objectDef.attributes) {
2719
+ const validator = createAttributeValidator(attr).optional();
2720
+ shape[attr.name] = validator;
2721
+ }
2722
+ return z3.object(shape);
2723
+ }
2724
+ function validateDraft(objectDef, data) {
2725
+ const validator = createDraftValidator(objectDef);
2726
+ const result = validator.safeParse(data);
2727
+ if (result.success) {
2728
+ return {
2729
+ success: true,
2730
+ data: result.data
2731
+ };
2732
+ }
2733
+ return {
2734
+ success: false,
2735
+ errors: result.error.errors.map((err) => ({
2736
+ path: err.path.map(String),
2737
+ message: err.message
2738
+ }))
2739
+ };
2740
+ }
2741
+ function validateDraftOrThrow(objectDef, data) {
2742
+ const result = validateDraft(objectDef, data);
2743
+ if (!result.success) {
2744
+ const errorMessages = result.errors?.map((err) => `${err.path.join(".")}: ${err.message}`).join("\n") || "Unknown validation error";
2745
+ throw new Error(`Draft validation failed for ${objectDef.label}:
2746
+ ${errorMessages}`);
2747
+ }
2748
+ return result.data;
2749
+ }
2750
+ function isValuePresent(value) {
2751
+ if (value === void 0 || value === null) {
2752
+ return false;
2753
+ }
2754
+ if (typeof value === "string" && value.trim() === "") {
2755
+ return false;
2756
+ }
2757
+ return true;
2758
+ }
2759
+ function getMissingRequiredAttributes(objectDef, data) {
2760
+ const missing = [];
2761
+ for (const attr of objectDef.attributes) {
2762
+ if (attr.required && !isValuePresent(data[attr.name])) {
2763
+ missing.push(attr);
2764
+ }
2765
+ }
2766
+ return missing;
2767
+ }
2768
+ function isRecordComplete(objectDef, data) {
2769
+ const missing = getMissingRequiredAttributes(objectDef, data);
2770
+ if (missing.length > 0) {
2771
+ return false;
2772
+ }
2773
+ const validation = validateObject(objectDef, data);
2774
+ return validation.success;
2775
+ }
2776
+ function computeRecordStatus(objectDef, data) {
2777
+ return isRecordComplete(objectDef, data) ? "complete" : "draft";
2778
+ }
2779
+
2780
+ // src/runtime/services/relation.service.ts
2781
+ var RelationService = class {
2782
+ constructor(adapter, nativeRegistry) {
2783
+ this.adapter = adapter;
2784
+ this.schemaService = new ObjectSchemaService(adapter, nativeRegistry);
2785
+ }
2786
+ /**
2787
+ * Validate all relation attributes in the data
2788
+ *
2789
+ * @param schema - Object schema containing attribute definitions
2790
+ * @param data - Record data to validate
2791
+ * @returns Validation result with errors if any
2792
+ *
2793
+ * @example
2794
+ * ```typescript
2795
+ * const result = await relationService.validateRelations(schema, {
2796
+ * company: "rec-123",
2797
+ * contacts: ["rec-456", "rec-789"]
2798
+ * });
2799
+ *
2800
+ * if (!result.valid) {
2801
+ * console.log(result.errors);
2802
+ * // [{ attribute: "company", message: "Record not found", invalidIds: ["rec-123"] }]
2803
+ * }
2804
+ * ```
2805
+ */
2806
+ async validateRelations(schema, data) {
2807
+ const errors = [];
2808
+ const relationAttrs = schema.attributes.filter(
2809
+ (attr) => attr.type === "relation"
2810
+ );
2811
+ for (const attr of relationAttrs) {
2812
+ const value = data[attr.name];
2813
+ if (value === void 0 || value === null) {
2814
+ continue;
2815
+ }
2816
+ const attrErrors = await this.validateRelationAttribute(attr, value);
2817
+ errors.push(...attrErrors);
2818
+ }
2819
+ return {
2820
+ valid: errors.length === 0,
2821
+ errors
2822
+ };
2823
+ }
2824
+ /**
2825
+ * Validate a single relation attribute value
2826
+ */
2827
+ async validateRelationAttribute(attr, value) {
2828
+ const errors = [];
2829
+ const ids = this.extractIds(attr, value);
2830
+ if (ids.length === 0) {
2831
+ return errors;
2832
+ }
2833
+ const validObjectIds = await this.getValidObjectIds(attr.targets);
2834
+ if (validObjectIds.size === 0) {
2835
+ errors.push({
2836
+ attribute: attr.name,
2837
+ message: `No valid target objects found for ${attr.label}`
2838
+ });
2839
+ return errors;
2840
+ }
2841
+ const invalidIds = [];
2842
+ for (const id of ids) {
2843
+ const record = await this.adapter.objectRecords.findById(id);
2844
+ if (!record) {
2845
+ invalidIds.push(id);
2846
+ continue;
2847
+ }
2848
+ if (!validObjectIds.has(record.objectId)) {
2849
+ invalidIds.push(id);
2850
+ }
2851
+ }
2852
+ if (invalidIds.length > 0) {
2853
+ errors.push({
2854
+ attribute: attr.name,
2855
+ message: `Invalid or non-existent records for ${attr.label}`,
2856
+ invalidIds
2857
+ });
2858
+ }
2859
+ return errors;
2860
+ }
2861
+ /**
2862
+ * Extract IDs from relation value based on cardinality
2863
+ */
2864
+ extractIds(attr, value) {
2865
+ if (attr.cardinality === "many") {
2866
+ if (!Array.isArray(value)) {
2867
+ return [];
2868
+ }
2869
+ return value.filter((v) => typeof v === "string");
2870
+ }
2871
+ if (typeof value === "string") {
2872
+ return [value];
2873
+ }
2874
+ return [];
2875
+ }
2876
+ /**
2877
+ * Get valid object IDs from relation targets
2878
+ */
2879
+ async getValidObjectIds(targets) {
2880
+ const objectIds = /* @__PURE__ */ new Set();
2881
+ for (const target of targets) {
2882
+ try {
2883
+ const objectSchema = await this.schemaService.getObjectSchemaByName(target.object);
2884
+ if (objectSchema?.id) {
2885
+ objectIds.add(objectSchema.id);
2886
+ }
2887
+ } catch {
2888
+ }
2889
+ }
2890
+ return objectIds;
2891
+ }
2892
+ /**
2893
+ * Validate relations and throw if invalid
2894
+ */
2895
+ async validateRelationsOrThrow(schema, data) {
2896
+ const result = await this.validateRelations(schema, data);
2897
+ if (!result.valid) {
2898
+ const messages = result.errors.map((e) => `${e.attribute}: ${e.message}`).join("; ");
2899
+ throw new Error(`Relation validation failed: ${messages}`);
2900
+ }
2901
+ }
2902
+ // ============================================================================
2903
+ // OPTIONS & RESOLUTION
2904
+ // ============================================================================
2905
+ /**
2906
+ * Get available options for a relation attribute
2907
+ * Searches across all target objects defined in the relation
2908
+ *
2909
+ * @param attribute - Relation attribute definition
2910
+ * @param tenantId - Tenant ID for multi-tenant isolation
2911
+ * @param params - Query parameters
2912
+ *
2913
+ * @example
2914
+ * ```typescript
2915
+ * const options = await relationService.getOptions(attribute, "tenant-1", {
2916
+ * query: "nike",
2917
+ * page: 1,
2918
+ * pageSize: 20
2919
+ * });
2920
+ * ```
2921
+ */
2922
+ async getOptions(attribute, tenantId, params = {}) {
2923
+ const { query = "", page = 1, pageSize = 20, targetObject } = params;
2924
+ const targets = attribute.targets;
2925
+ const filteredTargets = targetObject ? targets.filter((t) => t.object === targetObject) : targets;
2926
+ if (filteredTargets.length === 0) {
2927
+ return { options: [], hasMore: false, total: 0 };
2928
+ }
2929
+ const allOptions = [];
2930
+ let totalCount = 0;
2931
+ const recordService = new RecordService(this.adapter, tenantId);
2932
+ for (const target of filteredTargets) {
2933
+ const objectSchema = await this.schemaService.getObjectSchemaByName(target.object);
2934
+ if (!objectSchema?.id) {
2935
+ continue;
2936
+ }
2937
+ const result = query ? await recordService.searchRecords(objectSchema.id, query, {
2938
+ limit: pageSize,
2939
+ offset: (page - 1) * pageSize
2940
+ }) : await recordService.listRecords(objectSchema.id, {
2941
+ limit: pageSize,
2942
+ offset: (page - 1) * pageSize
2943
+ });
2944
+ totalCount += result.total;
2945
+ for (const record of result.records) {
2946
+ const label = this.resolveLabel(
2947
+ record.values,
2948
+ objectSchema.titleAttribute,
2949
+ target.displayTemplate
2950
+ );
2951
+ allOptions.push({
2952
+ id: record.id,
2953
+ objectId: objectSchema.id,
2954
+ objectName: objectSchema.name,
2955
+ objectLabel: objectSchema.label,
2956
+ objectIcon: objectSchema.icon,
2957
+ label,
2958
+ data: record.values
2959
+ });
2960
+ }
2961
+ }
2962
+ const hasMore = totalCount > page * pageSize;
2963
+ return {
2964
+ options: allOptions.slice(0, pageSize),
2965
+ hasMore,
2966
+ total: totalCount
2967
+ };
2968
+ }
2969
+ /**
2970
+ * Resolve record IDs to their display labels
2971
+ * Useful for displaying current values in the UI
2972
+ *
2973
+ * @param ids - Record IDs to resolve
2974
+ * @param tenantId - Tenant ID for multi-tenant isolation
2975
+ *
2976
+ * @example
2977
+ * ```typescript
2978
+ * const resolved = await relationService.resolveIds(["rec-1", "rec-2"], "tenant-1");
2979
+ * // [{ id: "rec-1", label: "Nike Air Max", objectName: "products", ... }]
2980
+ * ```
2981
+ */
2982
+ async resolveIds(ids, tenantId) {
2983
+ if (!ids || ids.length === 0) {
2984
+ return [];
2985
+ }
2986
+ const recordService = new RecordService(this.adapter, tenantId);
2987
+ const resolved = [];
2988
+ for (const id of ids) {
2989
+ const record = await recordService.getRecord(id);
2990
+ if (!record) {
2991
+ continue;
2992
+ }
2993
+ const objectSchema = await this.schemaService.getObjectSchema(record.objectId);
2994
+ if (!objectSchema) {
2995
+ continue;
2996
+ }
2997
+ const label = this.resolveLabel(record.values, objectSchema.titleAttribute);
2998
+ resolved.push({
2999
+ id: record.id,
3000
+ objectId: record.objectId,
3001
+ objectName: objectSchema.name,
3002
+ objectLabel: objectSchema.label,
3003
+ objectIcon: objectSchema.icon,
3004
+ label,
3005
+ data: record.values
3006
+ });
3007
+ }
3008
+ return resolved;
3009
+ }
3010
+ /**
3011
+ * Find a relation attribute by ID
3012
+ */
3013
+ async findAttributeById(attributeId) {
3014
+ const attribute = await this.adapter.attributes.findById(attributeId);
3015
+ if (!attribute || attribute.type !== "relation") {
3016
+ return null;
3017
+ }
3018
+ return {
3019
+ ...attribute.config,
3020
+ ...attribute
3021
+ };
3022
+ }
3023
+ /**
3024
+ * Resolve display label from record values
3025
+ * Uses displayTemplate if provided, otherwise falls back to titleAttribute
3026
+ */
3027
+ resolveLabel(values, titleAttribute, displayTemplate) {
3028
+ if (displayTemplate) {
3029
+ return displayTemplate.replace(/\{(\w+)\}/g, (_, key) => {
3030
+ const value = values[key];
3031
+ return value !== void 0 && value !== null ? String(value) : "";
3032
+ });
3033
+ }
3034
+ const titleValue = values[titleAttribute];
3035
+ return titleValue !== void 0 && titleValue !== null ? String(titleValue) : "(Untitled)";
3036
+ }
3037
+ };
3038
+
3039
+ // src/runtime/services/record.service.ts
3040
+ var RecordService = class {
3041
+ constructor(adapter, tenantId) {
3042
+ this.adapter = adapter;
3043
+ this.tenantId = tenantId;
3044
+ this.schemaService = new ObjectSchemaService(adapter, registry);
3045
+ this.relationService = new RelationService(adapter, registry);
3046
+ }
3047
+ /**
3048
+ * Create a new record with validation
3049
+ *
3050
+ * @param objectId - Object UUID
3051
+ * @param data - Record data (attribute values)
3052
+ * @param options - Creation options
3053
+ * @returns Created record with computed completionStatus
3054
+ *
3055
+ * @example
3056
+ * ```typescript
3057
+ * const service = new RecordService(adapter, "tenant-123");
3058
+ *
3059
+ * // Create a complete record (strict validation)
3060
+ * const product = await service.createRecord("obj-product", {
3061
+ * name: "Nike Air Max",
3062
+ * price: 129.99,
3063
+ * status: "active"
3064
+ * });
3065
+ * // → product.completionStatus = "complete"
3066
+ *
3067
+ * // Create a draft record (allows missing required fields)
3068
+ * const draft = await service.createRecord("obj-product", {
3069
+ * name: "Draft Product"
3070
+ * }, { allowDraft: true });
3071
+ * // → draft.completionStatus = "draft"
3072
+ * ```
3073
+ */
3074
+ async createRecord(objectId, data, options) {
3075
+ const schema = await this.schemaService.getObjectSchema(objectId);
3076
+ if (options?.validate !== false) {
3077
+ if (options?.allowDraft) {
3078
+ validateDraftOrThrow(schema, data);
3079
+ } else {
3080
+ validateObjectOrThrow(schema, data);
3081
+ }
3082
+ if (!options?.skipRelationValidation) {
3083
+ await this.relationService.validateRelationsOrThrow(schema, data);
3084
+ }
3085
+ }
3086
+ const completionStatus = computeRecordStatus(schema, data);
3087
+ const record = await this.adapter.objectRecords.create({
3088
+ tenantId: this.tenantId,
3089
+ objectId,
3090
+ data,
3091
+ completionStatus
3092
+ });
3093
+ return record;
3094
+ }
3095
+ /**
3096
+ * Get a record by ID
3097
+ *
3098
+ * @param recordId - Record UUID
3099
+ * @param options - Query options
3100
+ * @returns Record or null if not found
3101
+ */
3102
+ async getRecord(recordId, options) {
3103
+ const record = await this.adapter.objectRecords.findById(recordId);
3104
+ if (!record) {
3105
+ return null;
3106
+ }
3107
+ if (options?.includeSchema) {
3108
+ const schema = await this.schemaService.getObjectSchema(record.objectId);
3109
+ const recordWithSchema = record;
3110
+ recordWithSchema.schema = schema;
3111
+ return recordWithSchema;
3112
+ }
3113
+ return record;
3114
+ }
3115
+ /**
3116
+ * Get a record by ID or throw if not found
3117
+ */
3118
+ async getRecordOrThrow(recordId) {
3119
+ const record = await this.getRecord(recordId);
3120
+ if (!record) {
3121
+ throw new Error(`Record with id "${recordId}" not found`);
3122
+ }
3123
+ return record;
3124
+ }
3125
+ /**
3126
+ * Update a record with validation
3127
+ *
3128
+ * The completion status is automatically recalculated after each update.
3129
+ * A draft record becomes complete when all required fields are filled.
3130
+ *
3131
+ * @param recordId - Record UUID
3132
+ * @param data - Partial data to update
3133
+ * @param options - Update options
3134
+ * @returns Updated record with recalculated completionStatus
3135
+ *
3136
+ * @example
3137
+ * ```typescript
3138
+ * // Update a draft record to make it complete
3139
+ * const updated = await service.updateRecord(draftId, {
3140
+ * price: 99.99,
3141
+ * status: "active"
3142
+ * });
3143
+ * // → updated.completionStatus = "complete" if all required fields now present
3144
+ * ```
3145
+ */
3146
+ async updateRecord(recordId, data, options) {
3147
+ const existing = await this.getRecordOrThrow(recordId);
3148
+ const schema = await this.schemaService.getObjectSchema(existing.objectId);
3149
+ const mergedData = { ...existing.values, ...data };
3150
+ if (options?.validate !== false) {
3151
+ if (options?.partial) {
3152
+ validateDraftOrThrow(schema, mergedData);
3153
+ } else {
3154
+ validateObjectOrThrow(schema, mergedData);
3155
+ }
3156
+ if (!options?.skipRelationValidation) {
3157
+ await this.relationService.validateRelationsOrThrow(schema, data);
3158
+ }
3159
+ }
3160
+ const completionStatus = computeRecordStatus(schema, mergedData);
3161
+ const updated = await this.adapter.objectRecords.update(recordId, {
3162
+ ...data,
3163
+ __completionStatus: completionStatus
3164
+ });
3165
+ return updated;
3166
+ }
3167
+ /**
3168
+ * Delete a record
3169
+ *
3170
+ * @param recordId - Record UUID
3171
+ * @param options - Delete options
3172
+ */
3173
+ async deleteRecord(recordId, options) {
3174
+ if (options?.checkSystem) {
3175
+ const record = await this.getRecordOrThrow(recordId);
3176
+ const schema = await this.schemaService.getObjectSchema(record.objectId);
3177
+ if (schema.system) {
3178
+ throw new Error(`Cannot delete record of system object "${schema.label}"`);
3179
+ }
3180
+ }
3181
+ await this.adapter.objectRecords.delete(recordId);
3182
+ }
3183
+ /**
3184
+ * List records for an object with pagination
3185
+ *
3186
+ * @param objectId - Object UUID
3187
+ * @param options - List options
3188
+ * @returns Records and total count
3189
+ */
3190
+ async listRecords(objectId, options) {
3191
+ return await this.adapter.objectRecords.list(this.tenantId, objectId, options);
3192
+ }
3193
+ /**
3194
+ * Search records using full-text search
3195
+ *
3196
+ * @param objectId - Object UUID
3197
+ * @param query - Search query
3198
+ * @param options - Search options
3199
+ * @returns Matching records and total count
3200
+ */
3201
+ async searchRecords(objectId, query, options) {
3202
+ return await this.adapter.objectRecords.search(this.tenantId, objectId, query, options);
3203
+ }
3204
+ /**
3205
+ * Validate data against object schema without saving
3206
+ *
3207
+ * @param objectId - Object UUID
3208
+ * @param data - Data to validate
3209
+ * @returns Validation result
3210
+ */
3211
+ async validateData(objectId, data) {
3212
+ const schema = await this.schemaService.getObjectSchema(objectId);
3213
+ return validateObject(schema, data);
3214
+ }
3215
+ /**
3216
+ * Compute the completion status for given data without saving.
3217
+ * Useful for UI to show draft/complete status before submitting.
3218
+ *
3219
+ * @param objectId - Object UUID
3220
+ * @param data - Data to check
3221
+ * @returns Computed completion status
3222
+ */
3223
+ async computeStatus(objectId, data) {
3224
+ const schema = await this.schemaService.getObjectSchema(objectId);
3225
+ return computeRecordStatus(schema, data);
3226
+ }
3227
+ /**
3228
+ * Refresh the completion status of an existing record.
3229
+ * Useful when schema changes and you need to recompute statuses.
3230
+ *
3231
+ * @param recordId - Record UUID
3232
+ * @returns Updated completion status
3233
+ */
3234
+ async refreshRecordStatus(recordId) {
3235
+ const record = await this.getRecordOrThrow(recordId);
3236
+ const schema = await this.schemaService.getObjectSchema(record.objectId);
3237
+ const newStatus = computeRecordStatus(schema, record.values);
3238
+ if (record.completionStatus !== newStatus) {
3239
+ await this.adapter.objectRecords.update(recordId, {
3240
+ __completionStatus: newStatus
3241
+ });
3242
+ }
3243
+ return newStatus;
3244
+ }
3245
+ };
3246
+
3247
+ // src/runtime/services/user-profile.service.ts
3248
+ var UserProfileService = class {
3249
+ constructor(adapter, tenantId) {
3250
+ this.adapter = adapter;
3251
+ this.tenantId = tenantId;
3252
+ }
3253
+ /**
3254
+ * Create a new user profile (typically after first auth)
3255
+ *
3256
+ * @param data - User profile creation data
3257
+ * @returns Created user profile
3258
+ *
3259
+ * @example
3260
+ * ```typescript
3261
+ * const service = new UserProfileService(adapter, "tenant-123");
3262
+ *
3263
+ * // After Supabase auth
3264
+ * const profile = await service.createProfile({
3265
+ * tenantId: "tenant-123",
3266
+ * authId: authUser.id,
3267
+ * email: authUser.email,
3268
+ * firstName: authUser.user_metadata.first_name,
3269
+ * lastName: authUser.user_metadata.last_name,
3270
+ * role: "member",
3271
+ * status: "active"
3272
+ * });
3273
+ * ```
3274
+ */
3275
+ async createProfile(data) {
3276
+ if (data.tenantId !== this.tenantId) {
3277
+ throw new Error(
3278
+ `Tenant mismatch: service initialized with "${this.tenantId}" but data has "${data.tenantId}"`
3279
+ );
3280
+ }
3281
+ const existing = await this.adapter.userProfiles.findByAuthId(data.authId);
3282
+ if (existing) {
3283
+ throw new Error(`User profile with authId "${data.authId}" already exists`);
3284
+ }
3285
+ const existingEmail = await this.adapter.userProfiles.findByEmail(this.tenantId, data.email);
3286
+ if (existingEmail) {
3287
+ throw new Error(`User profile with email "${data.email}" already exists in this tenant`);
3288
+ }
3289
+ return await this.adapter.userProfiles.create(data);
3290
+ }
3291
+ /**
3292
+ * Get user profile by ID
3293
+ */
3294
+ async getProfile(profileId) {
3295
+ return await this.adapter.userProfiles.findById(profileId);
3296
+ }
3297
+ /**
3298
+ * Get user profile by ID or throw
3299
+ */
3300
+ async getProfileOrThrow(profileId) {
3301
+ const profile = await this.getProfile(profileId);
3302
+ if (!profile) {
3303
+ throw new Error(`User profile with id "${profileId}" not found`);
3304
+ }
3305
+ return profile;
3306
+ }
3307
+ /**
3308
+ * Get user profile by auth provider ID
3309
+ *
3310
+ * @param authId - Auth provider user ID (Supabase, Clerk, etc.)
3311
+ * @returns User profile or null
3312
+ */
3313
+ async getProfileByAuthId(authId) {
3314
+ return await this.adapter.userProfiles.findByAuthId(authId);
3315
+ }
3316
+ /**
3317
+ * Get or create user profile (idempotent operation)
3318
+ * Useful for auth callbacks - ensures profile exists
3319
+ *
3320
+ * @param authId - Auth provider user ID
3321
+ * @param data - Profile data to create if doesn't exist
3322
+ * @returns Existing or newly created profile
3323
+ *
3324
+ * @example
3325
+ * ```typescript
3326
+ * // In Supabase auth callback
3327
+ * const profile = await service.getOrCreateProfile(
3328
+ * authUser.id,
3329
+ * {
3330
+ * tenantId: "tenant-123",
3331
+ * authId: authUser.id,
3332
+ * email: authUser.email,
3333
+ * role: "member",
3334
+ * status: "active"
3335
+ * }
3336
+ * );
3337
+ * ```
3338
+ */
3339
+ async getOrCreateProfile(authId, data) {
3340
+ const existing = await this.getProfileByAuthId(authId);
3341
+ if (existing) {
3342
+ return existing;
3343
+ }
3344
+ return await this.createProfile(data);
3345
+ }
3346
+ /**
3347
+ * Update user profile
3348
+ */
3349
+ async updateProfile(profileId, data) {
3350
+ await this.getProfileOrThrow(profileId);
3351
+ return await this.adapter.userProfiles.update(profileId, data);
3352
+ }
3353
+ /**
3354
+ * Delete user profile
3355
+ *
3356
+ * @param profileId - Profile UUID
3357
+ * @param options - Delete options
3358
+ */
3359
+ async deleteProfile(profileId, options) {
3360
+ if (options?.checkAdmin) {
3361
+ const profile = await this.getProfileOrThrow(profileId);
3362
+ if (profile.role === "admin") {
3363
+ const allProfiles = await this.listProfiles();
3364
+ const adminCount = allProfiles.filter((p) => p.role === "admin").length;
3365
+ if (adminCount <= 1) {
3366
+ throw new Error("Cannot delete the last admin user");
3367
+ }
3368
+ }
3369
+ }
3370
+ await this.adapter.userProfiles.delete(profileId);
3371
+ }
3372
+ /**
3373
+ * List all user profiles for the tenant
3374
+ */
3375
+ async listProfiles(options) {
3376
+ return await this.adapter.userProfiles.list(this.tenantId, options);
3377
+ }
3378
+ /**
3379
+ * Update last login timestamp
3380
+ *
3381
+ * @param profileId - Profile UUID
3382
+ *
3383
+ * @example
3384
+ * ```typescript
3385
+ * // After successful auth
3386
+ * await service.updateLastLogin(profile.id);
3387
+ * ```
3388
+ */
3389
+ async updateLastLogin(profileId) {
3390
+ await this.adapter.userProfiles.updateLastLogin(profileId);
3391
+ }
3392
+ /**
3393
+ * Change user role
3394
+ *
3395
+ * @param profileId - Profile UUID
3396
+ * @param newRole - New role
3397
+ */
3398
+ async changeRole(profileId, newRole) {
3399
+ return await this.updateProfile(profileId, { role: newRole });
3400
+ }
3401
+ /**
3402
+ * Change user status
3403
+ *
3404
+ * @param profileId - Profile UUID
3405
+ * @param newStatus - New status
3406
+ */
3407
+ async changeStatus(profileId, newStatus) {
3408
+ return await this.updateProfile(profileId, { status: newStatus });
3409
+ }
3410
+ /**
3411
+ * Get user by email
3412
+ */
3413
+ async getProfileByEmail(email) {
3414
+ return await this.adapter.userProfiles.findByEmail(this.tenantId, email);
3415
+ }
3416
+ /**
3417
+ * Check if user has role
3418
+ */
3419
+ async hasRole(profileId, role) {
3420
+ const profile = await this.getProfile(profileId);
3421
+ return profile?.role === role;
3422
+ }
3423
+ /**
3424
+ * Check if user is admin
3425
+ */
3426
+ async isAdmin(profileId) {
3427
+ return await this.hasRole(profileId, "admin");
3428
+ }
3429
+ };
3430
+
3431
+ // src/runtime/services/view.service.ts
3432
+ var ViewService = class {
3433
+ constructor(adapter, nativeViews) {
3434
+ this.adapter = adapter;
3435
+ this.nativeViews = nativeViews;
3436
+ }
3437
+ /**
3438
+ * Get all views for an object (native + custom)
3439
+ *
3440
+ * @param objectName - Object name
3441
+ * @param tenantId - Tenant ID
3442
+ * @returns All views for the object
3443
+ */
3444
+ async getViewsForObject(objectName, tenantId) {
3445
+ const nativeViewDefs = this.nativeViews.getByObjectName(objectName);
3446
+ const dbViews = await this.adapter.views.findByObjectName(tenantId, objectName);
3447
+ const customViews = dbViews.filter((v) => !v.system).map(this.convertDBViewToDefinition);
3448
+ return [...nativeViewDefs, ...customViews];
3449
+ }
3450
+ /**
3451
+ * Get a specific view by name
3452
+ *
3453
+ * @param objectName - Object name
3454
+ * @param viewName - View name
3455
+ * @param tenantId - Tenant ID
3456
+ * @returns View definition or null
3457
+ */
3458
+ async getView(objectName, viewName, tenantId) {
3459
+ const nativeView = this.nativeViews.get(objectName, viewName);
3460
+ if (nativeView) {
3461
+ return nativeView;
3462
+ }
3463
+ const dbView = await this.adapter.views.findByName(tenantId, objectName, viewName);
3464
+ if (dbView) {
3465
+ return this.convertDBViewToDefinition(dbView);
3466
+ }
3467
+ return null;
3468
+ }
3469
+ /**
3470
+ * Get the default view for an object
3471
+ *
3472
+ * Priority:
3473
+ * 1. Custom view marked as default
3474
+ * 2. Native view marked as default
3475
+ * 3. First available view
3476
+ *
3477
+ * @param objectName - Object name
3478
+ * @param tenantId - Tenant ID
3479
+ * @returns Default view or null
3480
+ */
3481
+ async getDefaultView(objectName, tenantId) {
3482
+ const views = await this.getViewsForObject(objectName, tenantId);
3483
+ const customDefault = views.find((v) => v.default && !v.system);
3484
+ if (customDefault) return customDefault;
3485
+ const nativeDefault = views.find((v) => v.default && v.system);
3486
+ if (nativeDefault) return nativeDefault;
3487
+ return views[0] ?? null;
3488
+ }
3489
+ /**
3490
+ * Create a custom view
3491
+ *
3492
+ * @param input - View definition
3493
+ * @param tenantId - Tenant ID
3494
+ * @returns Created view
3495
+ */
3496
+ async createView(input, tenantId) {
3497
+ this.validateViewName(input.name);
3498
+ const existing = await this.adapter.views.findByName(tenantId, input.objectName, input.name);
3499
+ if (existing) {
3500
+ throw new Error(`View "${input.name}" already exists for object "${input.objectName}"`);
3501
+ }
3502
+ if (this.nativeViews.has(input.objectName, input.name)) {
3503
+ throw new Error(
3504
+ `Cannot create view "${input.name}": a system view with this name already exists`
3505
+ );
3506
+ }
3507
+ if (!input.tabs || input.tabs.length === 0) {
3508
+ throw new Error("View must have at least one tab");
3509
+ }
3510
+ const dbView = await this.adapter.views.create({
3511
+ tenantId,
3512
+ objectName: input.objectName,
3513
+ name: input.name,
3514
+ label: input.label,
3515
+ description: input.description,
3516
+ icon: input.icon,
3517
+ tabs: input.tabs,
3518
+ default: input.default ?? false,
3519
+ system: false,
3520
+ // Custom views are never system
3521
+ metadata: input.metadata
3522
+ });
3523
+ return this.convertDBViewToDefinition(dbView);
3524
+ }
3525
+ /**
3526
+ * Update a custom view
3527
+ *
3528
+ * @param viewId - View ID
3529
+ * @param input - Update data
3530
+ * @returns Updated view
3531
+ */
3532
+ async updateView(viewId, input) {
3533
+ const dbView = await this.adapter.views.findById(viewId);
3534
+ if (!dbView) {
3535
+ throw new Error(`View with id "${viewId}" not found`);
3536
+ }
3537
+ if (dbView.system) {
3538
+ throw new Error("Cannot modify system views. System views are protected.");
3539
+ }
3540
+ if (input.tabs && input.tabs.length === 0) {
3541
+ throw new Error("View must have at least one tab");
3542
+ }
3543
+ const updated = await this.adapter.views.update(viewId, {
3544
+ label: input.label,
3545
+ description: input.description,
3546
+ icon: input.icon,
3547
+ tabs: input.tabs,
3548
+ default: input.default,
3549
+ metadata: input.metadata
3550
+ });
3551
+ return this.convertDBViewToDefinition(updated);
3552
+ }
3553
+ /**
3554
+ * Delete a custom view
3555
+ *
3556
+ * @param viewId - View ID
3557
+ */
3558
+ async deleteView(viewId) {
3559
+ const dbView = await this.adapter.views.findById(viewId);
3560
+ if (!dbView) {
3561
+ throw new Error(`View with id "${viewId}" not found`);
3562
+ }
3563
+ if (dbView.system) {
3564
+ throw new Error("Cannot delete system views. System views are protected.");
3565
+ }
3566
+ await this.adapter.views.delete(viewId);
3567
+ }
3568
+ /**
3569
+ * Set a view as default for its object
3570
+ *
3571
+ * @param viewId - View ID
3572
+ * @param tenantId - Tenant ID
3573
+ * @returns Updated view
3574
+ */
3575
+ async setDefaultView(viewId, tenantId) {
3576
+ const dbView = await this.adapter.views.findById(viewId);
3577
+ if (!dbView) {
3578
+ throw new Error(`View with id "${viewId}" not found`);
3579
+ }
3580
+ const currentViews = await this.adapter.views.findByObjectName(tenantId, dbView.objectName);
3581
+ for (const v of currentViews) {
3582
+ if (v.default && v.id !== viewId && !v.system) {
3583
+ await this.adapter.views.update(v.id, { default: false });
3584
+ }
3585
+ }
3586
+ const updated = await this.adapter.views.update(viewId, { default: true });
3587
+ return this.convertDBViewToDefinition(updated);
3588
+ }
3589
+ // ============================================================================
3590
+ // PRIVATE HELPERS
3591
+ // ============================================================================
3592
+ /**
3593
+ * Validate view name format (kebab-case)
3594
+ */
3595
+ validateViewName(name) {
3596
+ if (!name || name.length === 0) {
3597
+ throw new Error("View name cannot be empty");
3598
+ }
3599
+ if (name.length > 63) {
3600
+ throw new Error("View name is too long (max 63 characters)");
3601
+ }
3602
+ const kebabCaseRegex = /^[a-z][a-z0-9-]*$/;
3603
+ if (!kebabCaseRegex.test(name)) {
3604
+ throw new Error(
3605
+ "Invalid view name format. Name must be in kebab-case (e.g., 'detail', 'list-view')"
3606
+ );
3607
+ }
3608
+ }
3609
+ /**
3610
+ * Convert database view to ViewDefinition
3611
+ */
3612
+ convertDBViewToDefinition(dbView) {
3613
+ return {
3614
+ id: dbView.id,
3615
+ name: dbView.name,
3616
+ label: dbView.label,
3617
+ description: dbView.description,
3618
+ icon: dbView.icon,
3619
+ object: dbView.objectName,
3620
+ tabs: dbView.tabs,
3621
+ default: dbView.default,
3622
+ system: dbView.system,
3623
+ metadata: dbView.metadata
3624
+ };
3625
+ }
3626
+ };
3627
+
3628
+ // src/runtime/view-sync.ts
3629
+ async function syncNativeViews(adapter, nativeViewRegistry, options = {}) {
3630
+ const result = {
3631
+ success: true,
3632
+ viewsSynced: 0,
3633
+ viewsCreated: 0,
3634
+ viewsUpdated: 0,
3635
+ viewsDeleted: 0,
3636
+ errors: []
3637
+ };
3638
+ const nativeViews = nativeViewRegistry.getAll();
3639
+ if (options.verbose) {
3640
+ console.info(`[ViewSync] Starting sync for ${nativeViews.length} native views...`);
3641
+ }
3642
+ try {
3643
+ await adapter.transaction(async (tx) => {
3644
+ const viewsByObject = await syncAllViews(tx, nativeViews, result, options);
3645
+ await cleanupRemovedViews(tx, viewsByObject, result, options);
3646
+ });
3647
+ } catch (error) {
3648
+ handleTransactionError(result, error);
3649
+ }
3650
+ logSyncComplete(result, options);
3651
+ return result;
3652
+ }
3653
+ async function syncAllViews(tx, nativeViews, result, options) {
3654
+ const viewsByObject = /* @__PURE__ */ new Map();
3655
+ for (const nativeView of nativeViews) {
3656
+ try {
3657
+ await syncSingleView(tx, nativeView, result, options);
3658
+ trackViewByObject(viewsByObject, nativeView);
3659
+ } catch (error) {
3660
+ handleViewSyncError(result, nativeView, error, options);
3661
+ }
3662
+ }
3663
+ return viewsByObject;
3664
+ }
3665
+ function trackViewByObject(viewsByObject, nativeView) {
3666
+ const objectViews = viewsByObject.get(nativeView.object) ?? [];
3667
+ objectViews.push(nativeView.name);
3668
+ viewsByObject.set(nativeView.object, objectViews);
3669
+ }
3670
+ function handleViewSyncError(result, nativeView, error, options) {
3671
+ result.success = false;
3672
+ result.errors.push({
3673
+ viewName: nativeView.name,
3674
+ objectName: nativeView.object,
3675
+ error: error instanceof Error ? error.message : String(error)
3676
+ });
3677
+ if (options.verbose) {
3678
+ console.error(`[ViewSync] \u2717 Failed to sync ${nativeView.object}:${nativeView.name}:`, error);
3679
+ }
3680
+ }
3681
+ async function cleanupRemovedViews(tx, viewsByObject, result, options) {
3682
+ if (options.dryRun) return;
3683
+ for (const [objectName, viewNames] of viewsByObject) {
3684
+ const deletedCount = await tx.views.deleteNotIn(objectName, viewNames);
3685
+ result.viewsDeleted += deletedCount;
3686
+ if (options.verbose && deletedCount > 0) {
3687
+ console.info(`[ViewSync] Deleted ${deletedCount} obsolete views for ${objectName}`);
3688
+ }
3689
+ }
3690
+ }
3691
+ function handleTransactionError(result, error) {
3692
+ result.success = false;
3693
+ result.errors.push({
3694
+ viewName: "transaction",
3695
+ objectName: "",
3696
+ error: error instanceof Error ? error.message : String(error)
3697
+ });
3698
+ }
3699
+ function logSyncComplete(result, options) {
3700
+ if (options.verbose) {
3701
+ console.info(
3702
+ `[ViewSync] ${result.success ? "\u2713" : "\u2717"} Sync complete:
3703
+ Views: ${result.viewsCreated} created, ${result.viewsUpdated} updated, ${result.viewsDeleted} deleted
3704
+ Errors: ${result.errors.length}`
3705
+ );
3706
+ }
3707
+ }
3708
+ async function syncSingleView(adapter, nativeView, result, options) {
3709
+ if (!nativeView.system) {
3710
+ throw new Error(`View ${nativeView.name} is not marked as system`);
3711
+ }
3712
+ const existingView = await adapter.views.findSystemByName(nativeView.object, nativeView.name);
3713
+ const isNew = !existingView;
3714
+ if (isNew) {
3715
+ result.viewsCreated++;
3716
+ } else {
3717
+ result.viewsUpdated++;
3718
+ }
3719
+ result.viewsSynced++;
3720
+ if (options.dryRun) {
3721
+ if (options.verbose) {
3722
+ console.info(
3723
+ `[ViewSync] Would ${isNew ? "create" : "update"} view: ${nativeView.object}:${nativeView.name}`
3724
+ );
3725
+ }
3726
+ return;
3727
+ }
3728
+ await adapter.views.upsert({
3729
+ tenantId: options.tenantId || "default",
3730
+ objectName: nativeView.object,
3731
+ name: nativeView.name,
3732
+ label: nativeView.label,
3733
+ description: nativeView.description,
3734
+ icon: nativeView.icon,
3735
+ tabs: nativeView.tabs,
3736
+ default: nativeView.default ?? false,
3737
+ system: true,
3738
+ metadata: nativeView.metadata
3739
+ });
3740
+ if (options.verbose) {
3741
+ console.info(
3742
+ `[ViewSync] \u2713 Synced ${nativeView.object}:${nativeView.name}: ${nativeView.tabs.length} tabs`
3743
+ );
3744
+ }
3745
+ }
3746
+ async function verifyNativeViewsSync(adapter, nativeViewRegistry) {
3747
+ const nativeViews = nativeViewRegistry.getAll();
3748
+ for (const view2 of nativeViews) {
3749
+ if (!view2.system) continue;
3750
+ const existing = await adapter.views.findSystemByName(view2.object, view2.name);
3751
+ if (!existing) {
3752
+ return false;
3753
+ }
3754
+ }
3755
+ return true;
3756
+ }
3757
+ async function getViewSyncPreview(adapter, nativeViewRegistry) {
3758
+ return await syncNativeViews(adapter, nativeViewRegistry, { dryRun: true });
3759
+ }
3760
+
3761
+ // src/runtime/sync.ts
3762
+ var BASE_ATTRIBUTE_KEYS = /* @__PURE__ */ new Set([
3763
+ "id",
3764
+ "name",
3765
+ "label",
3766
+ "type",
3767
+ "required",
3768
+ "system",
3769
+ "unique",
3770
+ "order"
3771
+ ]);
3772
+ function extractAttributeConfig(attr) {
3773
+ return Object.fromEntries(
3774
+ Object.entries(attr).filter(
3775
+ ([key, value]) => !BASE_ATTRIBUTE_KEYS.has(key) && value !== void 0
3776
+ )
3777
+ );
3778
+ }
3779
+ async function syncNativeObjects(adapter, nativeRegistry, options = {}) {
3780
+ const result = {
3781
+ success: true,
3782
+ objectsSynced: 0,
3783
+ attributesSynced: 0,
3784
+ objectsCreated: 0,
3785
+ objectsUpdated: 0,
3786
+ attributesCreated: 0,
3787
+ attributesUpdated: 0,
3788
+ attributesDeleted: 0,
3789
+ errors: []
3790
+ };
3791
+ const nativeObjects = nativeRegistry.getAll();
3792
+ if (options.verbose) {
3793
+ console.info(`[SyncService] Starting sync for ${nativeObjects.length} native objects...`);
3794
+ }
3795
+ try {
3796
+ await adapter.transaction(async (tx) => {
3797
+ for (const nativeObject of nativeObjects) {
3798
+ try {
3799
+ await syncSingleObject(tx, nativeObject, result, options);
3800
+ } catch (error) {
3801
+ result.success = false;
3802
+ result.errors.push({
3803
+ objectName: nativeObject.name,
3804
+ error: error instanceof Error ? error.message : String(error)
3805
+ });
3806
+ if (options.verbose) {
3807
+ console.error(`[SyncService] \u2717 Failed to sync ${nativeObject.name}:`, error);
3808
+ }
3809
+ }
3810
+ }
3811
+ });
3812
+ } catch (error) {
3813
+ result.success = false;
3814
+ result.errors.push({
3815
+ objectName: "transaction",
3816
+ error: error instanceof Error ? error.message : String(error)
3817
+ });
3818
+ }
3819
+ if (options.verbose) {
3820
+ console.info(
3821
+ `[SyncService] ${result.success ? "\u2713" : "\u2717"} Sync complete:
3822
+ Objects: ${result.objectsCreated} created, ${result.objectsUpdated} updated
3823
+ Attributes: ${result.attributesCreated} created, ${result.attributesUpdated} updated, ${result.attributesDeleted} deleted
3824
+ Errors: ${result.errors.length}`
3825
+ );
3826
+ }
3827
+ return result;
3828
+ }
3829
+ async function syncSingleObject(adapter, nativeObject, result, options) {
3830
+ if (!nativeObject.system) {
3831
+ throw new Error(`Object ${nativeObject.name} is not marked as system`);
3832
+ }
3833
+ const existingObject = await adapter.objects.findSystemByName(nativeObject.name);
3834
+ const isNew = !existingObject;
3835
+ updateObjectStats(result, isNew);
3836
+ if (options.dryRun) {
3837
+ await handleDryRun(adapter, nativeObject, existingObject, result, options, isNew);
3838
+ return;
3839
+ }
3840
+ const dbObject = await upsertObject(adapter, nativeObject, options);
3841
+ await syncAttributes(adapter, nativeObject, dbObject, existingObject, result);
3842
+ if (!isNew) {
3843
+ await cleanupAttributes(adapter, dbObject.id, nativeObject, result);
3844
+ }
3845
+ logSyncSuccess(nativeObject, options);
3846
+ }
3847
+ function updateObjectStats(result, isNew) {
3848
+ if (isNew) {
3849
+ result.objectsCreated++;
3850
+ } else {
3851
+ result.objectsUpdated++;
3852
+ }
3853
+ result.objectsSynced++;
3854
+ }
3855
+ async function handleDryRun(adapter, nativeObject, existingObject, result, options, isNew) {
3856
+ if (options.verbose) {
3857
+ console.info(`[SyncService] Would ${isNew ? "create" : "update"} object: ${nativeObject.name}`);
3858
+ }
3859
+ for (const attr of nativeObject.attributes) {
3860
+ const existingAttr = existingObject ? await adapter.attributes.findByObjectId(existingObject.id).then((attrs) => attrs.find((a) => a.name === attr.name)) : null;
3861
+ if (existingAttr) {
3862
+ result.attributesUpdated++;
3863
+ } else {
3864
+ result.attributesCreated++;
3865
+ }
3866
+ result.attributesSynced++;
3867
+ }
3868
+ }
3869
+ async function upsertObject(adapter, nativeObject, options) {
3870
+ return await adapter.objects.upsert({
3871
+ tenantId: options.tenantId || "default",
3872
+ system: true,
3873
+ name: nativeObject.name,
3874
+ label: nativeObject.label,
3875
+ description: nativeObject.description,
3876
+ metadata: nativeObject.metadata
3877
+ });
3878
+ }
3879
+ async function syncAttributes(adapter, nativeObject, dbObject, existingObject, result) {
3880
+ for (const [index, attr] of nativeObject.attributes.entries()) {
3881
+ const existingAttr = existingObject ? await adapter.attributes.findByObjectId(dbObject.id).then((attrs) => attrs.find((a) => a.name === attr.name)) : null;
3882
+ await adapter.attributes.upsert({
3883
+ objectId: dbObject.id,
3884
+ name: attr.name,
3885
+ label: attr.label,
3886
+ type: attr.type,
3887
+ description: attr.description,
3888
+ icon: attr.icon,
3889
+ system: attr.system ?? true,
3890
+ required: attr.required ?? false,
3891
+ order: attr.order ?? index,
3892
+ hidden: attr.hidden,
3893
+ archived: attr.archived,
3894
+ deprecated: attr.deprecated,
3895
+ defaultValue: attr.defaultValue,
3896
+ config: extractAttributeConfig(attr)
3897
+ });
3898
+ if (existingAttr) {
3899
+ result.attributesUpdated++;
3900
+ } else {
3901
+ result.attributesCreated++;
3902
+ }
3903
+ result.attributesSynced++;
3904
+ }
3905
+ }
3906
+ async function cleanupAttributes(adapter, objectId, nativeObject, result) {
3907
+ const attributeNames = nativeObject.attributes.map((attr) => attr.name);
3908
+ const deletedCount = await adapter.attributes.deleteByNames(objectId, attributeNames);
3909
+ result.attributesDeleted += deletedCount;
3910
+ }
3911
+ function logSyncSuccess(nativeObject, options) {
3912
+ if (options.verbose) {
3913
+ console.info(
3914
+ `[SyncService] \u2713 Synced ${nativeObject.name}: ${nativeObject.attributes.length} attributes`
3915
+ );
3916
+ }
3917
+ }
3918
+ async function verifyNativeObjectsSync(adapter, nativeRegistry) {
3919
+ const nativeObjects = nativeRegistry.getAll();
3920
+ for (const obj of nativeObjects) {
3921
+ if (!obj.system) continue;
3922
+ const existing = await adapter.objects.findSystemByName(obj.name);
3923
+ if (!existing) {
3924
+ return false;
3925
+ }
3926
+ }
3927
+ return true;
3928
+ }
3929
+ async function getSyncPreview(adapter, nativeRegistry) {
3930
+ return await syncNativeObjects(adapter, nativeRegistry, { dryRun: true });
3931
+ }
3932
+ async function syncAll(adapter, objectRegistry, nativeViewRegistry, options = {}) {
3933
+ if (options.verbose) {
3934
+ console.info("[SyncAll] Starting full sync...");
3935
+ }
3936
+ const objectsResult = await syncNativeObjects(adapter, objectRegistry, options);
3937
+ const viewsResult = await syncNativeViews(adapter, nativeViewRegistry, options);
3938
+ const result = {
3939
+ success: objectsResult.success && viewsResult.success,
3940
+ objects: objectsResult,
3941
+ views: viewsResult
3942
+ };
3943
+ if (options.verbose) {
3944
+ console.info(
3945
+ `[SyncAll] ${result.success ? "\u2713" : "\u2717"} Full sync complete:
3946
+ Objects: ${objectsResult.objectsSynced} synced (${objectsResult.objectsCreated} created, ${objectsResult.objectsUpdated} updated)
3947
+ Views: ${viewsResult.viewsSynced} synced (${viewsResult.viewsCreated} created, ${viewsResult.viewsUpdated} updated)
3948
+ Errors: ${objectsResult.errors.length + viewsResult.errors.length}`
3949
+ );
3950
+ }
3951
+ return result;
3952
+ }
3953
+
3954
+ // src/types/geocoding.ts
3955
+ var NoopGeocodingAdapter = class {
3956
+ async autocomplete() {
3957
+ return await Promise.resolve([]);
3958
+ }
3959
+ async reverse() {
3960
+ return await Promise.resolve(null);
3961
+ }
3962
+ async geocode() {
3963
+ return await Promise.resolve(null);
3964
+ }
3965
+ };
3966
+
3967
+ export {
3968
+ NoopGeocodingAdapter,
3969
+ generateId,
3970
+ generatePrefixedId,
3971
+ text,
3972
+ textarea,
3973
+ number,
3974
+ checkbox,
3975
+ date,
3976
+ phone,
3977
+ currency,
3978
+ status,
3979
+ select,
3980
+ multiselect,
3981
+ location,
3982
+ timestamp,
3983
+ file,
3984
+ user,
3985
+ relation,
3986
+ rating,
3987
+ ObjectBuilder,
3988
+ object,
3989
+ GroupBuilder,
3990
+ TableTabConfig,
3991
+ CustomTabConfig,
3992
+ TabBuilder,
3993
+ ViewBuilder,
3994
+ view,
3995
+ group,
3996
+ registry,
3997
+ createTextValidator,
3998
+ createNumberValidator,
3999
+ createCheckboxValidator,
4000
+ createDateValidator,
4001
+ createPhoneValidator,
4002
+ createCurrencyValidator,
4003
+ createStatusValidator,
4004
+ createSelectValidator,
4005
+ createMultiselectValidator,
4006
+ createLocationValidator,
4007
+ createTimestampValidator,
4008
+ createFileValidator,
4009
+ createUserValidator,
4010
+ createSingleRelationValidator,
4011
+ createMultiRelationValidator,
4012
+ createRelationValidator,
4013
+ createRatingValidator,
4014
+ createAttributeValidator,
4015
+ createObjectValidator,
4016
+ validateAttribute,
4017
+ validateObject,
4018
+ validateObjectOrThrow,
4019
+ createDraftValidator,
4020
+ validateDraft,
4021
+ validateDraftOrThrow,
4022
+ getMissingRequiredAttributes,
4023
+ isRecordComplete,
4024
+ computeRecordStatus,
4025
+ createMockAdapter,
4026
+ FileService,
4027
+ GeocodingService,
4028
+ ObjectSchemaService,
4029
+ RelationService,
4030
+ RecordService,
4031
+ UserProfileService,
4032
+ ViewService,
4033
+ syncNativeViews,
4034
+ verifyNativeViewsSync,
4035
+ getViewSyncPreview,
4036
+ syncNativeObjects,
4037
+ verifyNativeObjectsSync,
4038
+ getSyncPreview,
4039
+ syncAll
4040
+ };