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