@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,4474 @@
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/validation/validators.ts
2160
+ import { z as z3 } from "zod";
2161
+ var baseConfigSchema = z3.object({
2162
+ disabled: z3.boolean().optional(),
2163
+ placeholder: z3.string().optional(),
2164
+ description: z3.string().optional(),
2165
+ defaultValue: z3.unknown().optional(),
2166
+ icon: z3.string().optional(),
2167
+ order: z3.number().int().optional(),
2168
+ hidden: z3.boolean().optional(),
2169
+ archived: z3.boolean().optional(),
2170
+ deprecated: z3.boolean().optional(),
2171
+ metadata: z3.record(z3.unknown()).optional()
2172
+ });
2173
+ var optionSchema = z3.object({
2174
+ id: z3.string().min(1),
2175
+ label: z3.string().min(1),
2176
+ value: z3.string().min(1),
2177
+ color: z3.string().optional(),
2178
+ icon: z3.string().optional(),
2179
+ description: z3.string().optional(),
2180
+ group: z3.enum(["idle", "in_progress", "finished"]).optional()
2181
+ });
2182
+ var relationTargetSchema = z3.object({
2183
+ object: z3.string().min(1),
2184
+ displayTemplate: z3.string().optional(),
2185
+ filter: z3.record(z3.unknown()).optional()
2186
+ });
2187
+ var documentTypeConfigSchema = z3.object({
2188
+ type: z3.enum([
2189
+ "id_card",
2190
+ "passport",
2191
+ "incorporation_certificate",
2192
+ "driver_license",
2193
+ "birth_certificate",
2194
+ "residence_permit",
2195
+ "bank_statement",
2196
+ "proof_of_address",
2197
+ "custom"
2198
+ ]),
2199
+ label: z3.string(),
2200
+ faces: z3.array(z3.enum(["front", "back", "single"])),
2201
+ attributeMapping: z3.array(
2202
+ z3.object({
2203
+ attributeId: z3.string(),
2204
+ extractedKey: z3.string(),
2205
+ face: z3.enum(["front", "back", "single"]).optional(),
2206
+ required: z3.boolean().optional()
2207
+ })
2208
+ ).optional()
2209
+ });
2210
+ var fileVerificationConfigSchema = z3.object({
2211
+ enabled: z3.boolean(),
2212
+ documentTypes: z3.array(documentTypeConfigSchema),
2213
+ autoExtract: z3.boolean().optional(),
2214
+ autoValidate: z3.boolean().optional()
2215
+ });
2216
+ var textConfigSchema = baseConfigSchema.extend({
2217
+ minLength: z3.number().int().min(0).optional(),
2218
+ maxLength: z3.number().int().min(1).optional(),
2219
+ pattern: z3.string().optional()
2220
+ });
2221
+ var textareaConfigSchema = baseConfigSchema;
2222
+ var numberConfigSchema = baseConfigSchema.extend({
2223
+ min: z3.number().optional(),
2224
+ max: z3.number().optional(),
2225
+ unit: z3.enum(["integer", "decimal", "percentage"]).optional(),
2226
+ decimals: z3.number().int().min(0).optional()
2227
+ });
2228
+ var checkboxConfigSchema = baseConfigSchema;
2229
+ var dateConfigSchema = baseConfigSchema.extend({
2230
+ dateFormat: z3.enum(["short", "long", "full", "relative"]).optional(),
2231
+ minDate: z3.string().optional(),
2232
+ maxDate: z3.string().optional()
2233
+ });
2234
+ var phoneConfigSchema = baseConfigSchema.extend({
2235
+ defaultCountryCode: z3.string().length(3).optional()
2236
+ });
2237
+ var currencyConfigSchema = baseConfigSchema.extend({
2238
+ defaultCurrency: z3.string().length(3).optional(),
2239
+ allowedCurrencies: z3.array(z3.string().length(3)).optional()
2240
+ });
2241
+ var statusConfigSchema = baseConfigSchema.extend({
2242
+ options: z3.array(optionSchema).min(1)
2243
+ });
2244
+ var locationConfigSchema = baseConfigSchema.extend({
2245
+ granularity: z3.enum(["full", "address", "city", "state", "country", "coordinates"]),
2246
+ enableAutocomplete: z3.boolean().optional(),
2247
+ enableMap: z3.boolean().optional(),
2248
+ defaultCountry: z3.string().length(3).optional(),
2249
+ allowedCountries: z3.array(z3.string().length(3)).optional(),
2250
+ displayFormat: z3.enum(["single_line", "multi_line", "compact"]).optional()
2251
+ });
2252
+ var timestampConfigSchema = baseConfigSchema.extend({
2253
+ autoUpdate: z3.boolean().optional()
2254
+ });
2255
+ var selectConfigSchema = baseConfigSchema.extend({
2256
+ options: z3.array(optionSchema).min(1)
2257
+ });
2258
+ var multiselectConfigSchema = baseConfigSchema.extend({
2259
+ options: z3.array(optionSchema).min(1)
2260
+ });
2261
+ var fileConfigSchema = baseConfigSchema.extend({
2262
+ maxFiles: z3.number().int().min(1).optional(),
2263
+ maxSize: z3.number().int().min(1).optional(),
2264
+ allowedTypes: z3.array(z3.string()).optional(),
2265
+ verification: fileVerificationConfigSchema.optional()
2266
+ });
2267
+ var userConfigSchema = baseConfigSchema.extend({
2268
+ allowedRoles: z3.array(z3.string()).optional()
2269
+ });
2270
+ var relationConfigSchema = baseConfigSchema.extend({
2271
+ targets: z3.array(relationTargetSchema).min(1),
2272
+ onDelete: z3.enum(["restrict", "cascade", "set_null"]).optional(),
2273
+ cardinality: z3.enum(["one", "many"]),
2274
+ minItems: z3.number().int().min(0).optional(),
2275
+ maxItems: z3.number().int().min(1).optional()
2276
+ });
2277
+ var ratingConfigSchema = baseConfigSchema.extend({
2278
+ max: z3.number().int().min(1).optional(),
2279
+ iconType: z3.enum(["star", "heart", "thumbs", "number"]).optional()
2280
+ });
2281
+ var attributeConfigSchemas = {
2282
+ text: textConfigSchema,
2283
+ textarea: textareaConfigSchema,
2284
+ number: numberConfigSchema,
2285
+ checkbox: checkboxConfigSchema,
2286
+ date: dateConfigSchema,
2287
+ phone: phoneConfigSchema,
2288
+ currency: currencyConfigSchema,
2289
+ status: statusConfigSchema,
2290
+ location: locationConfigSchema,
2291
+ timestamp: timestampConfigSchema,
2292
+ select: selectConfigSchema,
2293
+ multiselect: multiselectConfigSchema,
2294
+ file: fileConfigSchema,
2295
+ user: userConfigSchema,
2296
+ relation: relationConfigSchema,
2297
+ rating: ratingConfigSchema
2298
+ };
2299
+ function getAttributeConfigSchema(type) {
2300
+ return attributeConfigSchemas[type];
2301
+ }
2302
+ function validateAttributeConfig(type, config) {
2303
+ const schema = getAttributeConfigSchema(type);
2304
+ const result = schema.safeParse(config);
2305
+ if (result.success) {
2306
+ return { success: true, data: result.data };
2307
+ }
2308
+ return {
2309
+ success: false,
2310
+ errors: result.error.errors.map((err) => `${err.path.join(".")}: ${err.message}`)
2311
+ };
2312
+ }
2313
+ function parseAttributeConfig(type, config) {
2314
+ const schema = getAttributeConfigSchema(type);
2315
+ return schema.strip().parse(config);
2316
+ }
2317
+ function safeParseAttributeConfig(type, config) {
2318
+ const schema = getAttributeConfigSchema(type);
2319
+ const result = schema.strip().safeParse(config);
2320
+ return result.success ? result.data : void 0;
2321
+ }
2322
+ function createTextValidator(attr) {
2323
+ let schema = z3.string();
2324
+ if (attr.minLength !== void 0) {
2325
+ schema = schema.min(
2326
+ attr.minLength,
2327
+ `${attr.label} must be at least ${attr.minLength} characters`
2328
+ );
2329
+ }
2330
+ if (attr.maxLength !== void 0) {
2331
+ schema = schema.max(
2332
+ attr.maxLength,
2333
+ `${attr.label} must be at most ${attr.maxLength} characters`
2334
+ );
2335
+ }
2336
+ if (attr.pattern) {
2337
+ schema = schema.regex(new RegExp(attr.pattern), `${attr.label} format is invalid`);
2338
+ }
2339
+ return schema;
2340
+ }
2341
+ function createNumberValidator(attr) {
2342
+ let schema = z3.number();
2343
+ if (attr.min !== void 0) {
2344
+ schema = schema.min(attr.min, `${attr.label} must be at least ${attr.min}`);
2345
+ }
2346
+ if (attr.max !== void 0) {
2347
+ schema = schema.max(attr.max, `${attr.label} must be at most ${attr.max}`);
2348
+ }
2349
+ if (attr.unit === "integer") {
2350
+ schema = schema.int(`${attr.label} must be an integer`);
2351
+ }
2352
+ return schema;
2353
+ }
2354
+ function createCheckboxValidator(_attr) {
2355
+ return z3.boolean();
2356
+ }
2357
+ function createDateValidator(attr) {
2358
+ return z3.string().datetime({ message: `${attr.label} must be a valid ISO date` });
2359
+ }
2360
+ function createPhoneValidator(_attr) {
2361
+ return z3.object({
2362
+ countryCode: z3.string().length(3),
2363
+ phoneNumber: z3.string().min(1)
2364
+ });
2365
+ }
2366
+ function createCurrencyValidator(_attr) {
2367
+ return z3.object({
2368
+ code: z3.string().length(3),
2369
+ value: z3.number().min(0)
2370
+ });
2371
+ }
2372
+ function createStatusValidator(attr) {
2373
+ const validValues = attr.options.map((opt) => opt.value);
2374
+ return z3.enum(validValues, {
2375
+ errorMap: () => ({
2376
+ message: `${attr.label} must be one of: ${validValues.join(", ")}`
2377
+ })
2378
+ });
2379
+ }
2380
+ function createSelectValidator(attr) {
2381
+ const validValues = attr.options.map((opt) => opt.value);
2382
+ return z3.enum(validValues, {
2383
+ errorMap: () => ({
2384
+ message: `${attr.label} must be one of: ${validValues.join(", ")}`
2385
+ })
2386
+ });
2387
+ }
2388
+ function createMultiselectValidator(attr) {
2389
+ const validValues = attr.options.map((opt) => opt.value);
2390
+ return z3.array(
2391
+ z3.enum(validValues, {
2392
+ errorMap: () => ({
2393
+ message: `Each value must be one of: ${validValues.join(", ")}`
2394
+ })
2395
+ })
2396
+ );
2397
+ }
2398
+ function createLocationValidator(_attr) {
2399
+ return z3.object({
2400
+ address: z3.string().optional(),
2401
+ address2: z3.string().optional(),
2402
+ city: z3.string().optional(),
2403
+ state: z3.string().optional(),
2404
+ postalCode: z3.string().optional(),
2405
+ country: z3.string().length(3).optional(),
2406
+ latitude: z3.number().optional(),
2407
+ longitude: z3.number().optional()
2408
+ });
2409
+ }
2410
+ function createTimestampValidator(_attr) {
2411
+ return z3.number().int().positive();
2412
+ }
2413
+ function createFileValidator(_attr) {
2414
+ return z3.string().uuid();
2415
+ }
2416
+ function createUserValidator(_attr) {
2417
+ return z3.string().uuid();
2418
+ }
2419
+ function createSingleRelationValidator(attr) {
2420
+ const uuidSchema = z3.string().uuid({
2421
+ message: `${attr.label} must be a valid record ID`
2422
+ });
2423
+ return z3.union([uuidSchema, z3.null()]);
2424
+ }
2425
+ function createMultiRelationValidator(attr) {
2426
+ const uuidSchema = z3.string().uuid({
2427
+ message: `Each ${attr.label} item must be a valid record ID`
2428
+ });
2429
+ let arraySchema = z3.array(uuidSchema);
2430
+ if (attr.minItems !== void 0) {
2431
+ arraySchema = arraySchema.min(
2432
+ attr.minItems,
2433
+ `${attr.label} must have at least ${attr.minItems} item${attr.minItems > 1 ? "s" : ""}`
2434
+ );
2435
+ }
2436
+ if (attr.maxItems !== void 0) {
2437
+ arraySchema = arraySchema.max(
2438
+ attr.maxItems,
2439
+ `${attr.label} must have at most ${attr.maxItems} item${attr.maxItems > 1 ? "s" : ""}`
2440
+ );
2441
+ }
2442
+ return arraySchema;
2443
+ }
2444
+ function createRelationValidator(attr) {
2445
+ if (attr.cardinality === "many") {
2446
+ return createMultiRelationValidator(attr);
2447
+ }
2448
+ return createSingleRelationValidator(attr);
2449
+ }
2450
+ function createRatingValidator(attr) {
2451
+ let schema = z3.number().int().min(0);
2452
+ if (attr.max !== void 0) {
2453
+ schema = schema.max(attr.max, `${attr.label} must be at most ${attr.max}`);
2454
+ }
2455
+ return schema;
2456
+ }
2457
+ function createAttributeValidator(attr) {
2458
+ switch (attr.type) {
2459
+ case "text":
2460
+ return createTextValidator(attr);
2461
+ case "number":
2462
+ return createNumberValidator(attr);
2463
+ case "checkbox":
2464
+ return createCheckboxValidator(attr);
2465
+ case "date":
2466
+ return createDateValidator(attr);
2467
+ case "phone":
2468
+ return createPhoneValidator(attr);
2469
+ case "currency":
2470
+ return createCurrencyValidator(attr);
2471
+ case "status":
2472
+ return createStatusValidator(attr);
2473
+ case "location":
2474
+ return createLocationValidator(attr);
2475
+ case "timestamp":
2476
+ return createTimestampValidator(attr);
2477
+ case "select":
2478
+ return createSelectValidator(attr);
2479
+ case "multiselect":
2480
+ return createMultiselectValidator(attr);
2481
+ case "file":
2482
+ return createFileValidator(attr);
2483
+ case "user":
2484
+ return createUserValidator(attr);
2485
+ case "relation":
2486
+ return createRelationValidator(attr);
2487
+ case "rating":
2488
+ return createRatingValidator(attr);
2489
+ default:
2490
+ return z3.unknown();
2491
+ }
2492
+ }
2493
+ function createObjectValidator(objectDef) {
2494
+ const shape = {};
2495
+ for (const attr of objectDef.attributes) {
2496
+ let validator = createAttributeValidator(attr);
2497
+ if (!attr.required) {
2498
+ validator = validator.optional();
2499
+ }
2500
+ shape[attr.name] = validator;
2501
+ }
2502
+ return z3.object(shape);
2503
+ }
2504
+ function validateAttribute(attr, value) {
2505
+ const validator = createAttributeValidator(attr);
2506
+ if (!attr.required && (value === void 0 || value === null)) {
2507
+ return { success: true, data: { [attr.name]: value } };
2508
+ }
2509
+ const result = validator.safeParse(value);
2510
+ if (result.success) {
2511
+ return {
2512
+ success: true,
2513
+ data: { [attr.name]: result.data }
2514
+ };
2515
+ }
2516
+ return {
2517
+ success: false,
2518
+ errors: result.error.errors.map((err) => ({
2519
+ path: [attr.name, ...err.path.map(String)],
2520
+ message: err.message
2521
+ }))
2522
+ };
2523
+ }
2524
+ function validateObject(objectDef, data) {
2525
+ const validator = createObjectValidator(objectDef);
2526
+ const result = validator.safeParse(data);
2527
+ if (result.success) {
2528
+ return {
2529
+ success: true,
2530
+ data: result.data
2531
+ };
2532
+ }
2533
+ return {
2534
+ success: false,
2535
+ errors: result.error.errors.map((err) => ({
2536
+ path: err.path.map(String),
2537
+ message: err.message
2538
+ }))
2539
+ };
2540
+ }
2541
+ function validateObjectOrThrow(objectDef, data) {
2542
+ const result = validateObject(objectDef, data);
2543
+ if (!result.success) {
2544
+ const errorMessages = result.errors?.map((err) => `${err.path.join(".")}: ${err.message}`).join("\n") || "Unknown validation error";
2545
+ throw new Error(`Validation failed for ${objectDef.label}:
2546
+ ${errorMessages}`);
2547
+ }
2548
+ return result.data;
2549
+ }
2550
+ function createDraftValidator(objectDef) {
2551
+ const shape = {};
2552
+ for (const attr of objectDef.attributes) {
2553
+ const validator = createAttributeValidator(attr).optional();
2554
+ shape[attr.name] = validator;
2555
+ }
2556
+ return z3.object(shape);
2557
+ }
2558
+ function validateDraft(objectDef, data) {
2559
+ const validator = createDraftValidator(objectDef);
2560
+ const result = validator.safeParse(data);
2561
+ if (result.success) {
2562
+ return {
2563
+ success: true,
2564
+ data: result.data
2565
+ };
2566
+ }
2567
+ return {
2568
+ success: false,
2569
+ errors: result.error.errors.map((err) => ({
2570
+ path: err.path.map(String),
2571
+ message: err.message
2572
+ }))
2573
+ };
2574
+ }
2575
+ function validateDraftOrThrow(objectDef, data) {
2576
+ const result = validateDraft(objectDef, data);
2577
+ if (!result.success) {
2578
+ const errorMessages = result.errors?.map((err) => `${err.path.join(".")}: ${err.message}`).join("\n") || "Unknown validation error";
2579
+ throw new Error(`Draft validation failed for ${objectDef.label}:
2580
+ ${errorMessages}`);
2581
+ }
2582
+ return result.data;
2583
+ }
2584
+ function isValuePresent(value) {
2585
+ if (value === void 0 || value === null) {
2586
+ return false;
2587
+ }
2588
+ if (typeof value === "string" && value.trim() === "") {
2589
+ return false;
2590
+ }
2591
+ return true;
2592
+ }
2593
+ function getMissingRequiredAttributes(objectDef, data) {
2594
+ const missing = [];
2595
+ for (const attr of objectDef.attributes) {
2596
+ if (attr.required && !isValuePresent(data[attr.name])) {
2597
+ missing.push(attr);
2598
+ }
2599
+ }
2600
+ return missing;
2601
+ }
2602
+ function isRecordComplete(objectDef, data) {
2603
+ const missing = getMissingRequiredAttributes(objectDef, data);
2604
+ if (missing.length > 0) {
2605
+ return false;
2606
+ }
2607
+ const validation = validateObject(objectDef, data);
2608
+ return validation.success;
2609
+ }
2610
+ function computeRecordStatus(objectDef, data) {
2611
+ return isRecordComplete(objectDef, data) ? "complete" : "draft";
2612
+ }
2613
+
2614
+ // src/runtime/services/object-schema.service.ts
2615
+ var ObjectSchemaService = class {
2616
+ constructor(adapter, nativeRegistry) {
2617
+ this.adapter = adapter;
2618
+ this.nativeRegistry = nativeRegistry;
2619
+ }
2620
+ /**
2621
+ * Create a new custom object
2622
+ * Validates name format and ensures system=false
2623
+ *
2624
+ * @param definition - Object definition (attributes can be raw definitions or builders)
2625
+ * @param tenantId - Tenant ID owning the object
2626
+ * @returns Created ObjectDefinition
2627
+ */
2628
+ async createCustomObject(definition, tenantId) {
2629
+ const builder = object({
2630
+ name: definition.name,
2631
+ label: definition.label
2632
+ });
2633
+ if (definition.description) builder.description(definition.description);
2634
+ if (definition.icon) builder.icon(definition.icon);
2635
+ if (definition.metadata) builder.metadata(definition.metadata);
2636
+ builder.labelExpression(definition.labelExpression);
2637
+ if (definition.attributes && definition.attributes.length > 0) {
2638
+ builder.attributes(definition.attributes);
2639
+ }
2640
+ const objectDef = builder.build();
2641
+ const existing = await this.adapter.objects.findByName(tenantId, objectDef.name);
2642
+ if (existing) {
2643
+ throw new Error(`Object with name "${objectDef.name}" already exists`);
2644
+ }
2645
+ const validatedConfigs = [];
2646
+ if (objectDef.attributes.length > 0) {
2647
+ for (const attr of objectDef.attributes) {
2648
+ const config = await this.validateAttributeInput(
2649
+ attr,
2650
+ tenantId
2651
+ );
2652
+ validatedConfigs.push(config);
2653
+ }
2654
+ }
2655
+ const metadata = {
2656
+ ...objectDef.metadata,
2657
+ icon: objectDef.icon
2658
+ };
2659
+ const dbObject = await this.adapter.objects.create({
2660
+ tenantId,
2661
+ name: objectDef.name,
2662
+ label: objectDef.label,
2663
+ description: objectDef.description,
2664
+ labelExpression: objectDef.labelExpression,
2665
+ system: false,
2666
+ // Always false for custom objects
2667
+ metadata
2668
+ });
2669
+ const createdAttributes = [];
2670
+ if (objectDef.attributes.length > 0) {
2671
+ for (let i = 0; i < objectDef.attributes.length; i++) {
2672
+ const attr = objectDef.attributes[i];
2673
+ const config = validatedConfigs[i];
2674
+ const dbAttr = await this.adapter.attributes.create({
2675
+ objectId: dbObject.id,
2676
+ name: attr.name,
2677
+ label: attr.label,
2678
+ type: attr.type,
2679
+ required: attr.required ?? false,
2680
+ unique: false,
2681
+ system: false,
2682
+ config
2683
+ });
2684
+ createdAttributes.push(this.convertDBAttributeToAttribute(dbAttr));
2685
+ }
2686
+ }
2687
+ return {
2688
+ ...objectDef,
2689
+ id: dbObject.id,
2690
+ attributes: createdAttributes,
2691
+ system: false
2692
+ };
2693
+ }
2694
+ /**
2695
+ * Add a custom attribute to an existing object
2696
+ * Can be used on both custom and native objects
2697
+ * Attributes added via API are always custom (system=false)
2698
+ *
2699
+ * @param objectId - Object UUID from database
2700
+ * @param attribute - Attribute definition
2701
+ * @param tenantId - Tenant ID (required for relation validation)
2702
+ * @returns Created Attribute
2703
+ */
2704
+ async addAttributeToObject(objectId, attribute, tenantId) {
2705
+ const dbObject = await this.adapter.objects.findById(objectId);
2706
+ if (!dbObject) {
2707
+ throw new Error(`Object with id "${objectId}" not found`);
2708
+ }
2709
+ const existingAttributes = await this.adapter.attributes.findByObjectId(objectId);
2710
+ const duplicate = existingAttributes.find((attr) => attr.name === attribute.name);
2711
+ if (duplicate) {
2712
+ throw new Error(
2713
+ `Attribute with name "${attribute.name}" already exists on object "${dbObject.name}"`
2714
+ );
2715
+ }
2716
+ const config = await this.validateAttributeInput(attribute, tenantId);
2717
+ const dbAttr = await this.adapter.attributes.create({
2718
+ objectId,
2719
+ name: attribute.name,
2720
+ label: attribute.label,
2721
+ type: attribute.type,
2722
+ required: attribute.required ?? false,
2723
+ unique: attribute.unique ?? false,
2724
+ system: false,
2725
+ // Always false for attributes added via API
2726
+ config
2727
+ });
2728
+ return this.convertDBAttributeToAttribute(dbAttr);
2729
+ }
2730
+ /**
2731
+ * Update an attribute
2732
+ * Can only update custom attributes (system=false)
2733
+ *
2734
+ * @param attributeId - Attribute UUID
2735
+ * @param updates - Partial attribute updates
2736
+ * @param tenantId - Tenant ID (required for relation validation)
2737
+ * @returns Updated Attribute
2738
+ */
2739
+ async updateAttribute(attributeId, updates, tenantId) {
2740
+ const dbAttr = await this.adapter.attributes.findById(attributeId);
2741
+ if (!dbAttr) {
2742
+ throw new Error(`Attribute with id "${attributeId}" not found`);
2743
+ }
2744
+ if (dbAttr.system) {
2745
+ throw new Error(
2746
+ `Cannot modify system attribute "${dbAttr.name}". System attributes are protected.`
2747
+ );
2748
+ }
2749
+ if (updates.name && updates.name !== dbAttr.name) {
2750
+ throw new Error(
2751
+ "Attribute name cannot be changed after creation. Create a new attribute instead."
2752
+ );
2753
+ }
2754
+ if (updates.type && updates.type !== dbAttr.type) {
2755
+ throw new Error(
2756
+ "Attribute type cannot be changed after creation. Create a new attribute instead."
2757
+ );
2758
+ }
2759
+ const mergedInput = {
2760
+ name: dbAttr.name,
2761
+ label: updates.label ?? dbAttr.label,
2762
+ type: dbAttr.type,
2763
+ required: updates.required ?? dbAttr.required,
2764
+ ...dbAttr.config,
2765
+ ...updates
2766
+ };
2767
+ const config = this.buildAttributeConfig(mergedInput);
2768
+ if (dbAttr.type === "relation" && updates.targets) {
2769
+ await this.validateRelationTargets(mergedInput, tenantId);
2770
+ }
2771
+ const updatedDbAttr = await this.adapter.attributes.update(attributeId, {
2772
+ label: updates.label,
2773
+ required: updates.required,
2774
+ config
2775
+ });
2776
+ return this.convertDBAttributeToAttribute(updatedDbAttr);
2777
+ }
2778
+ /**
2779
+ * Delete an attribute
2780
+ * Can only delete custom attributes (system=false)
2781
+ *
2782
+ * @param attributeId - Attribute UUID
2783
+ */
2784
+ async deleteAttribute(attributeId) {
2785
+ const dbAttr = await this.adapter.attributes.findById(attributeId);
2786
+ if (!dbAttr) {
2787
+ throw new Error(`Attribute with id "${attributeId}" not found`);
2788
+ }
2789
+ if (dbAttr.system) {
2790
+ throw new Error(
2791
+ `Cannot delete system attribute "${dbAttr.name}". System attributes are protected.`
2792
+ );
2793
+ }
2794
+ await this.adapter.attributes.delete(attributeId);
2795
+ }
2796
+ /**
2797
+ * List attributes for an object
2798
+ *
2799
+ * @param objectId - Object UUID
2800
+ * @param options - Filter options
2801
+ * @returns List of attributes
2802
+ */
2803
+ async listAttributes(objectId, options) {
2804
+ const dbAttributes = await this.adapter.attributes.findByObjectId(objectId);
2805
+ let filtered = dbAttributes;
2806
+ if (options?.systemOnly) {
2807
+ filtered = dbAttributes.filter((attr) => attr.system);
2808
+ } else if (options?.customOnly) {
2809
+ filtered = dbAttributes.filter((attr) => !attr.system);
2810
+ }
2811
+ return filtered.map((attr) => this.convertDBAttributeToAttribute(attr));
2812
+ }
2813
+ /**
2814
+ * Validate attribute name format (variable identifier)
2815
+ * @internal
2816
+ */
2817
+ validateAttributeName(name) {
2818
+ const variableNameRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
2819
+ if (!name || name.length === 0) {
2820
+ throw new Error("Attribute name cannot be empty");
2821
+ }
2822
+ if (name.length > 63) {
2823
+ throw new Error("Attribute name is too long (max 63 characters)");
2824
+ }
2825
+ if (!variableNameRegex.test(name)) {
2826
+ throw new Error(
2827
+ "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'"
2828
+ );
2829
+ }
2830
+ }
2831
+ /**
2832
+ * Get complete object schema (system + custom attributes)
2833
+ * If object is native, merges registry definition with DB custom attributes
2834
+ * If object is custom, returns DB definition only
2835
+ *
2836
+ * @param objectId - Object UUID from database
2837
+ * @returns Complete ObjectDefinition with all attributes
2838
+ *
2839
+ * @example
2840
+ * ```typescript
2841
+ * const service = new ObjectSchemaService(adapter, registry);
2842
+ * const productSchema = await service.getObjectSchema("obj-123");
2843
+ *
2844
+ * console.log(productSchema.attributes); // System + custom attributes
2845
+ * ```
2846
+ */
2847
+ async getObjectSchema(objectId) {
2848
+ const dbObject = await this.adapter.objects.findById(objectId);
2849
+ if (!dbObject) {
2850
+ throw new Error(`Object with id "${objectId}" not found`);
2851
+ }
2852
+ const dbAttributes = await this.adapter.attributes.findByObjectId(objectId);
2853
+ if (dbObject.system) {
2854
+ return this.mergeNativeObject(dbObject, dbAttributes);
2855
+ }
2856
+ return this.convertDBObjectToDefinition(dbObject, dbAttributes);
2857
+ }
2858
+ /**
2859
+ * Get object schema by name (for system/native objects)
2860
+ * @deprecated Use getObjectSchemaByNameForTenant for custom objects support
2861
+ */
2862
+ async getObjectSchemaByName(name) {
2863
+ const dbObject = await this.adapter.objects.findSystemByName(name);
2864
+ if (!dbObject) {
2865
+ throw new Error(`Native object "${name}" not found in database`);
2866
+ }
2867
+ const dbAttributes = await this.adapter.attributes.findByObjectId(dbObject.id);
2868
+ return this.mergeNativeObject(dbObject, dbAttributes);
2869
+ }
2870
+ /**
2871
+ * Get object schema by name for a tenant (supports both native and custom objects)
2872
+ */
2873
+ async getObjectSchemaByNameForTenant(name, tenantId) {
2874
+ let dbObject = await this.adapter.objects.findByName(tenantId, name);
2875
+ if (!dbObject) {
2876
+ dbObject = await this.adapter.objects.findSystemByName(name);
2877
+ }
2878
+ if (!dbObject) {
2879
+ throw new Error(`Object "${name}" not found`);
2880
+ }
2881
+ const dbAttributes = await this.adapter.attributes.findByObjectId(dbObject.id);
2882
+ if (dbObject.system) {
2883
+ return this.mergeNativeObject(dbObject, dbAttributes);
2884
+ }
2885
+ return this.convertDBObjectToDefinition(dbObject, dbAttributes);
2886
+ }
2887
+ /**
2888
+ * List all object schemas for a tenant
2889
+ */
2890
+ async listObjectSchemas(tenantId) {
2891
+ const dbObjects = await this.adapter.objects.list(tenantId);
2892
+ const schemas = await Promise.all(
2893
+ dbObjects.map(async (dbObject) => {
2894
+ const dbAttributes = await this.adapter.attributes.findByObjectId(dbObject.id);
2895
+ if (dbObject.system) {
2896
+ return this.mergeNativeObject(dbObject, dbAttributes);
2897
+ }
2898
+ return this.convertDBObjectToDefinition(dbObject, dbAttributes);
2899
+ })
2900
+ );
2901
+ return schemas;
2902
+ }
2903
+ /**
2904
+ * Merge native object from registry with custom attributes from DB
2905
+ * @internal
2906
+ */
2907
+ mergeNativeObject(dbObject, dbAttributes) {
2908
+ const nativeObject = this.nativeRegistry.getByName(dbObject.name);
2909
+ if (!nativeObject) {
2910
+ throw new Error(
2911
+ `Native object "${dbObject.name}" not found in registry. Make sure to register it before querying.`
2912
+ );
2913
+ }
2914
+ const systemAttributesFromDB = dbAttributes.filter((attr) => attr.system);
2915
+ const customAttributes = dbAttributes.filter((attr) => !attr.system);
2916
+ const dbAttrByName = new Map(systemAttributesFromDB.map((attr) => [attr.name, attr]));
2917
+ const systemAttrs = nativeObject.attributes.map((registryAttr) => {
2918
+ const dbAttr = dbAttrByName.get(registryAttr.name);
2919
+ if (dbAttr) {
2920
+ return {
2921
+ ...registryAttr,
2922
+ id: dbAttr.id
2923
+ };
2924
+ }
2925
+ return registryAttr;
2926
+ });
2927
+ const customAttrs = customAttributes.map(
2928
+ (dbAttr) => this.convertDBAttributeToAttribute(dbAttr)
2929
+ );
2930
+ return {
2931
+ ...nativeObject,
2932
+ id: dbObject.id,
2933
+ attributes: [
2934
+ ...systemAttrs,
2935
+ // System attributes from registry (with DB IDs if synced)
2936
+ ...customAttrs
2937
+ // Custom attributes from DB
2938
+ ]
2939
+ };
2940
+ }
2941
+ /**
2942
+ * Convert DB object + attributes to ObjectDefinition
2943
+ * @internal
2944
+ */
2945
+ convertDBObjectToDefinition(dbObject, dbAttributes) {
2946
+ const attributes = dbAttributes.map(
2947
+ (dbAttr) => this.convertDBAttributeToAttribute(dbAttr)
2948
+ );
2949
+ return {
2950
+ id: dbObject.id,
2951
+ name: dbObject.name,
2952
+ label: dbObject.label,
2953
+ description: dbObject.description,
2954
+ icon: dbObject.metadata?.icon,
2955
+ labelExpression: dbObject.labelExpression,
2956
+ attributes,
2957
+ system: dbObject.system,
2958
+ metadata: dbObject.metadata
2959
+ };
2960
+ }
2961
+ /**
2962
+ * Validate attribute input and return parsed config
2963
+ * Validates: name format, config schema, relation targets
2964
+ * @internal
2965
+ */
2966
+ async validateAttributeInput(attribute, tenantId) {
2967
+ this.validateAttributeName(attribute.name);
2968
+ const config = this.buildAttributeConfig(attribute);
2969
+ if (attribute.type === "relation") {
2970
+ await this.validateRelationTargets(attribute, tenantId);
2971
+ }
2972
+ return config;
2973
+ }
2974
+ /**
2975
+ * Build and validate attribute config from input
2976
+ * Uses Zod schema to validate and strip unknown properties
2977
+ * @internal
2978
+ */
2979
+ buildAttributeConfig(attribute) {
2980
+ const {
2981
+ name: _,
2982
+ label: __,
2983
+ type: ___,
2984
+ required: ____,
2985
+ unique: _____,
2986
+ ...configInput
2987
+ } = attribute;
2988
+ try {
2989
+ return parseAttributeConfig(attribute.type, configInput);
2990
+ } catch (error) {
2991
+ if (error instanceof Error) {
2992
+ throw new Error(`Invalid config for ${attribute.type} attribute: ${error.message}`);
2993
+ }
2994
+ throw error;
2995
+ }
2996
+ }
2997
+ /**
2998
+ * Validate that relation target objects exist
2999
+ * @internal
3000
+ */
3001
+ async validateRelationTargets(attribute, tenantId) {
3002
+ const targets = attribute.targets;
3003
+ if (!targets || targets.length === 0) {
3004
+ throw new Error("Relation attribute must have at least one target object");
3005
+ }
3006
+ const cardinality = attribute.cardinality;
3007
+ if (!(cardinality && ["one", "many"].includes(cardinality))) {
3008
+ throw new Error("Relation attribute must specify cardinality: 'one' or 'many'");
3009
+ }
3010
+ for (const target of targets) {
3011
+ if (!target.object) {
3012
+ throw new Error("Each relation target must specify an object name");
3013
+ }
3014
+ let targetObject = tenantId ? await this.adapter.objects.findByName(tenantId, target.object) : null;
3015
+ if (!targetObject) {
3016
+ targetObject = await this.adapter.objects.findSystemByName(target.object);
3017
+ }
3018
+ if (!targetObject) {
3019
+ const nativeObject = this.nativeRegistry.getByName(target.object);
3020
+ if (!nativeObject) {
3021
+ throw new Error(
3022
+ `Relation target object "${target.object}" does not exist. Make sure the object is created before adding a relation to it.`
3023
+ );
3024
+ }
3025
+ }
3026
+ }
3027
+ }
3028
+ /**
3029
+ * Convert DB attribute to Attribute type
3030
+ * @internal
3031
+ */
3032
+ convertDBAttributeToAttribute(dbAttr) {
3033
+ const baseAttr = {
3034
+ ...dbAttr.config,
3035
+ id: dbAttr.id,
3036
+ name: dbAttr.name,
3037
+ label: dbAttr.label,
3038
+ type: dbAttr.type,
3039
+ required: dbAttr.required,
3040
+ system: dbAttr.system,
3041
+ unique: dbAttr.unique
3042
+ };
3043
+ return baseAttr;
3044
+ }
3045
+ };
3046
+
3047
+ // src/native/registry.ts
3048
+ var NativeObjectRegistryClass = class {
3049
+ constructor() {
3050
+ this.objects = /* @__PURE__ */ new Map();
3051
+ }
3052
+ /**
3053
+ * Register one or more native objects
3054
+ * Auto-builds if ObjectBuilder is passed instead of ObjectDefinition
3055
+ * @param objects - Single object/builder or array of objects/builders to register
3056
+ * @returns this (for chaining)
3057
+ * @throws Error if object is invalid or already registered
3058
+ *
3059
+ * @example
3060
+ * ```typescript
3061
+ * // No .build() needed - registry auto-builds!
3062
+ * const PRODUCT = object({ id: "obj-product", name: "products", label: "Product" })
3063
+ * .system()
3064
+ * .attribute(text({ id: "attr-name", name: "name", label: "Name" }));
3065
+ *
3066
+ * registry.register(PRODUCT); // ← Auto-builds here
3067
+ *
3068
+ * // Can still explicitly .build() if you want
3069
+ * registry.register(PRODUCT.build());
3070
+ *
3071
+ * // Register multiple
3072
+ * registry.register([PRODUCT, ORDER, CUSTOMER]);
3073
+ * ```
3074
+ */
3075
+ register(objects) {
3076
+ const objectsArray = Array.isArray(objects) ? objects : [objects];
3077
+ for (const obj of objectsArray) {
3078
+ const object2 = "build" in obj && typeof obj.build === "function" ? obj.build() : obj;
3079
+ this.validateAndRegister(object2);
3080
+ }
3081
+ return this;
3082
+ }
3083
+ /**
3084
+ * Validate and register a single object
3085
+ * @internal
3086
+ */
3087
+ validateAndRegister(object2) {
3088
+ if (!object2.system) {
3089
+ throw new Error(
3090
+ `[NativeObjectRegistry] Cannot register object "${object2.name}" (id: ${object2.id}): missing system flag.
3091
+ Native objects must have system=true. Did you forget to call .system() in your builder?`
3092
+ );
3093
+ }
3094
+ if (this.objects.has(object2.name)) {
3095
+ const existing = this.objects.get(object2.name);
3096
+ throw new Error(
3097
+ `[NativeObjectRegistry] Duplicate object name "${object2.name}":
3098
+ - Existing: "${existing?.label}" (id: ${existing?.id})
3099
+ - New: "${object2.label}" (id: ${object2.id})
3100
+ Please use unique names for each native object.`
3101
+ );
3102
+ }
3103
+ this.objects.set(object2.name, object2);
3104
+ }
3105
+ /**
3106
+ * Get a native object by its name
3107
+ * @param name - The object name
3108
+ * @returns The object definition or undefined if not found
3109
+ *
3110
+ * @example
3111
+ * ```typescript
3112
+ * const product = registry.getByName("products");
3113
+ * if (product) {
3114
+ * console.log(product.label); // "Product"
3115
+ * }
3116
+ * ```
3117
+ */
3118
+ getByName(name) {
3119
+ return this.objects.get(name);
3120
+ }
3121
+ /**
3122
+ * Get a native object or throw if not found
3123
+ * @param name - The object name
3124
+ * @returns The object definition
3125
+ * @throws Error if not found
3126
+ */
3127
+ getByNameOrThrow(name) {
3128
+ const object2 = this.objects.get(name);
3129
+ if (!object2) {
3130
+ throw new Error(
3131
+ `[NativeObjectRegistry] Native object "${name}" not found.
3132
+ Available objects: ${this.listNames().join(", ")}`
3133
+ );
3134
+ }
3135
+ return object2;
3136
+ }
3137
+ /**
3138
+ * Get all registered native objects
3139
+ * @returns Array of all registered object definitions
3140
+ */
3141
+ getAll() {
3142
+ return Array.from(this.objects.values());
3143
+ }
3144
+ /**
3145
+ * Get all registered native object names
3146
+ * @returns Array of object names
3147
+ */
3148
+ listNames() {
3149
+ return Array.from(this.objects.keys());
3150
+ }
3151
+ /**
3152
+ * Check if a native object is registered
3153
+ * @param name - The object name
3154
+ * @returns true if registered, false otherwise
3155
+ */
3156
+ has(name) {
3157
+ return this.objects.has(name);
3158
+ }
3159
+ /**
3160
+ * Get the number of registered objects
3161
+ */
3162
+ get size() {
3163
+ return this.objects.size;
3164
+ }
3165
+ /**
3166
+ * Clear all registered objects (useful for testing)
3167
+ * @internal
3168
+ */
3169
+ clear() {
3170
+ this.objects.clear();
3171
+ }
3172
+ /**
3173
+ * Get registry summary for debugging
3174
+ */
3175
+ summary() {
3176
+ const objects = this.getAll();
3177
+ return [
3178
+ `[NativeObjectRegistry] ${this.size} native object(s) registered:`,
3179
+ ...objects.map(
3180
+ (obj) => ` - ${obj.name}: "${obj.label}" (${obj.attributes.length} attributes)`
3181
+ )
3182
+ ].join("\n");
3183
+ }
3184
+ /**
3185
+ * Log registry summary to console
3186
+ */
3187
+ debug() {
3188
+ console.info(this.summary());
3189
+ }
3190
+ };
3191
+ var registry = new NativeObjectRegistryClass();
3192
+
3193
+ // src/runtime/services/relation.service.ts
3194
+ var RelationService = class {
3195
+ constructor(adapter, nativeRegistry) {
3196
+ this.adapter = adapter;
3197
+ this.schemaService = new ObjectSchemaService(adapter, nativeRegistry);
3198
+ }
3199
+ /**
3200
+ * Validate all relation attributes in the data
3201
+ *
3202
+ * @param schema - Object schema containing attribute definitions
3203
+ * @param data - Record data to validate
3204
+ * @returns Validation result with errors if any
3205
+ *
3206
+ * @example
3207
+ * ```typescript
3208
+ * const result = await relationService.validateRelations(schema, {
3209
+ * company: "rec-123",
3210
+ * contacts: ["rec-456", "rec-789"]
3211
+ * });
3212
+ *
3213
+ * if (!result.valid) {
3214
+ * console.log(result.errors);
3215
+ * // [{ attribute: "company", message: "Record not found", invalidIds: ["rec-123"] }]
3216
+ * }
3217
+ * ```
3218
+ */
3219
+ async validateRelations(schema, data) {
3220
+ const errors = [];
3221
+ const relationAttrs = schema.attributes.filter(
3222
+ (attr) => attr.type === "relation"
3223
+ );
3224
+ for (const attr of relationAttrs) {
3225
+ const value = data[attr.name];
3226
+ if (value === void 0 || value === null) {
3227
+ continue;
3228
+ }
3229
+ const attrErrors = await this.validateRelationAttribute(attr, value);
3230
+ errors.push(...attrErrors);
3231
+ }
3232
+ return {
3233
+ valid: errors.length === 0,
3234
+ errors
3235
+ };
3236
+ }
3237
+ /**
3238
+ * Validate a single relation attribute value
3239
+ */
3240
+ async validateRelationAttribute(attr, value) {
3241
+ const errors = [];
3242
+ const ids = this.extractIds(attr, value);
3243
+ if (ids.length === 0) {
3244
+ return errors;
3245
+ }
3246
+ const validObjectIds = await this.getValidObjectIds(attr.targets);
3247
+ if (validObjectIds.size === 0) {
3248
+ errors.push({
3249
+ attribute: attr.name,
3250
+ message: `No valid target objects found for ${attr.label}`
3251
+ });
3252
+ return errors;
3253
+ }
3254
+ const invalidIds = [];
3255
+ for (const id of ids) {
3256
+ const record = await this.adapter.objectRecords.findById(id);
3257
+ if (!record) {
3258
+ invalidIds.push(id);
3259
+ continue;
3260
+ }
3261
+ if (!validObjectIds.has(record.objectId)) {
3262
+ invalidIds.push(id);
3263
+ }
3264
+ }
3265
+ if (invalidIds.length > 0) {
3266
+ errors.push({
3267
+ attribute: attr.name,
3268
+ message: `Invalid or non-existent records for ${attr.label}`,
3269
+ invalidIds
3270
+ });
3271
+ }
3272
+ return errors;
3273
+ }
3274
+ /**
3275
+ * Extract IDs from relation value based on cardinality
3276
+ */
3277
+ extractIds(attr, value) {
3278
+ if (attr.cardinality === "many") {
3279
+ if (!Array.isArray(value)) {
3280
+ return [];
3281
+ }
3282
+ return value.filter((v) => typeof v === "string");
3283
+ }
3284
+ if (typeof value === "string") {
3285
+ return [value];
3286
+ }
3287
+ return [];
3288
+ }
3289
+ /**
3290
+ * Get valid object IDs from relation targets
3291
+ */
3292
+ async getValidObjectIds(targets) {
3293
+ const objectIds = /* @__PURE__ */ new Set();
3294
+ for (const target of targets) {
3295
+ try {
3296
+ const objectSchema = await this.schemaService.getObjectSchemaByName(target.object);
3297
+ if (objectSchema?.id) {
3298
+ objectIds.add(objectSchema.id);
3299
+ }
3300
+ } catch {
3301
+ }
3302
+ }
3303
+ return objectIds;
3304
+ }
3305
+ /**
3306
+ * Validate relations and throw if invalid
3307
+ */
3308
+ async validateRelationsOrThrow(schema, data) {
3309
+ const result = await this.validateRelations(schema, data);
3310
+ if (!result.valid) {
3311
+ const messages = result.errors.map((e) => `${e.attribute}: ${e.message}`).join("; ");
3312
+ throw new Error(`Relation validation failed: ${messages}`);
3313
+ }
3314
+ }
3315
+ // ============================================================================
3316
+ // OPTIONS & RESOLUTION
3317
+ // ============================================================================
3318
+ /**
3319
+ * Get available options for a relation attribute
3320
+ * Searches across all target objects defined in the relation
3321
+ *
3322
+ * @param attribute - Relation attribute definition
3323
+ * @param tenantId - Tenant ID for multi-tenant isolation
3324
+ * @param params - Query parameters
3325
+ *
3326
+ * @example
3327
+ * ```typescript
3328
+ * const options = await relationService.getOptions(attribute, "tenant-1", {
3329
+ * query: "nike",
3330
+ * page: 1,
3331
+ * pageSize: 20
3332
+ * });
3333
+ * ```
3334
+ */
3335
+ async getOptions(attribute, tenantId, params = {}) {
3336
+ const { query = "", page = 1, pageSize = 20, targetObject } = params;
3337
+ const targets = attribute.targets;
3338
+ const filteredTargets = targetObject ? targets.filter((t) => t.object === targetObject) : targets;
3339
+ if (filteredTargets.length === 0) {
3340
+ return { options: [], hasMore: false, total: 0 };
3341
+ }
3342
+ const allOptions = [];
3343
+ let totalCount = 0;
3344
+ const recordService = new RecordService(this.adapter, tenantId);
3345
+ for (const target of filteredTargets) {
3346
+ const objectSchema = await this.schemaService.getObjectSchemaByName(target.object);
3347
+ if (!objectSchema?.id) {
3348
+ continue;
3349
+ }
3350
+ const result = query ? await recordService.searchRecords(objectSchema.id, query, {
3351
+ limit: pageSize,
3352
+ offset: (page - 1) * pageSize
3353
+ }) : await recordService.listRecords(objectSchema.id, {
3354
+ limit: pageSize,
3355
+ offset: (page - 1) * pageSize
3356
+ });
3357
+ totalCount += result.total;
3358
+ for (const record of result.records) {
3359
+ const template = target.displayTemplate ?? objectSchema.labelExpression;
3360
+ const label = renderLabelExpression(template, record.values);
3361
+ allOptions.push({
3362
+ id: record.id,
3363
+ objectId: objectSchema.id,
3364
+ objectName: objectSchema.name,
3365
+ objectLabel: objectSchema.label,
3366
+ objectIcon: objectSchema.icon,
3367
+ label,
3368
+ data: record.values
3369
+ });
3370
+ }
3371
+ }
3372
+ const hasMore = totalCount > page * pageSize;
3373
+ return {
3374
+ options: allOptions.slice(0, pageSize),
3375
+ hasMore,
3376
+ total: totalCount
3377
+ };
3378
+ }
3379
+ /**
3380
+ * Resolve record IDs to their display labels
3381
+ * Useful for displaying current values in the UI
3382
+ *
3383
+ * @param ids - Record IDs to resolve
3384
+ * @param tenantId - Tenant ID for multi-tenant isolation
3385
+ *
3386
+ * @example
3387
+ * ```typescript
3388
+ * const resolved = await relationService.resolveIds(["rec-1", "rec-2"], "tenant-1");
3389
+ * // [{ id: "rec-1", label: "Nike Air Max", objectName: "products", ... }]
3390
+ * ```
3391
+ */
3392
+ async resolveIds(ids, tenantId) {
3393
+ if (!ids || ids.length === 0) {
3394
+ return [];
3395
+ }
3396
+ const recordService = new RecordService(this.adapter, tenantId);
3397
+ const resolved = [];
3398
+ for (const id of ids) {
3399
+ const record = await recordService.getRecord(id);
3400
+ if (!record) {
3401
+ continue;
3402
+ }
3403
+ const objectSchema = await this.schemaService.getObjectSchema(record.objectId);
3404
+ if (!objectSchema) {
3405
+ continue;
3406
+ }
3407
+ const label = renderLabelExpression(objectSchema.labelExpression, record.values);
3408
+ resolved.push({
3409
+ id: record.id,
3410
+ objectId: record.objectId,
3411
+ objectName: objectSchema.name,
3412
+ objectLabel: objectSchema.label,
3413
+ objectIcon: objectSchema.icon,
3414
+ label,
3415
+ data: record.values
3416
+ });
3417
+ }
3418
+ return resolved;
3419
+ }
3420
+ /**
3421
+ * Find a relation attribute by ID
3422
+ */
3423
+ async findAttributeById(attributeId) {
3424
+ const attribute = await this.adapter.attributes.findById(attributeId);
3425
+ if (!attribute || attribute.type !== "relation") {
3426
+ return null;
3427
+ }
3428
+ return {
3429
+ ...attribute.config,
3430
+ ...attribute
3431
+ };
3432
+ }
3433
+ };
3434
+
3435
+ // src/runtime/services/record.service.ts
3436
+ var RecordService = class {
3437
+ constructor(adapter, tenantId) {
3438
+ this.adapter = adapter;
3439
+ this.tenantId = tenantId;
3440
+ this.schemaService = new ObjectSchemaService(adapter, registry);
3441
+ this.relationService = new RelationService(adapter, registry);
3442
+ }
3443
+ /**
3444
+ * Compute display label from schema expression
3445
+ * @internal
3446
+ */
3447
+ computeLabel(schema, values) {
3448
+ return renderLabelExpression(schema.labelExpression, values);
3449
+ }
3450
+ /**
3451
+ * Create a new record with validation
3452
+ *
3453
+ * @param objectId - Object UUID
3454
+ * @param data - Record data (attribute values)
3455
+ * @param options - Creation options
3456
+ * @returns Created record with computed completionStatus
3457
+ *
3458
+ * @example
3459
+ * ```typescript
3460
+ * const service = new RecordService(adapter, "tenant-123");
3461
+ *
3462
+ * // Create a complete record (strict validation)
3463
+ * const product = await service.createRecord("obj-product", {
3464
+ * name: "Nike Air Max",
3465
+ * price: 129.99,
3466
+ * status: "active"
3467
+ * });
3468
+ * // → product.completionStatus = "complete"
3469
+ *
3470
+ * // Create a draft record (allows missing required fields)
3471
+ * const draft = await service.createRecord("obj-product", {
3472
+ * name: "Draft Product"
3473
+ * }, { allowDraft: true });
3474
+ * // → draft.completionStatus = "draft"
3475
+ * ```
3476
+ */
3477
+ async createRecord(objectId, data, options) {
3478
+ const schema = await this.schemaService.getObjectSchema(objectId);
3479
+ if (options?.validate !== false) {
3480
+ if (options?.allowDraft) {
3481
+ validateDraftOrThrow(schema, data);
3482
+ } else {
3483
+ validateObjectOrThrow(schema, data);
3484
+ }
3485
+ if (!options?.skipRelationValidation) {
3486
+ await this.relationService.validateRelationsOrThrow(schema, data);
3487
+ }
3488
+ }
3489
+ const completionStatus = computeRecordStatus(schema, data);
3490
+ const label = this.computeLabel(schema, data);
3491
+ const record = await this.adapter.objectRecords.create({
3492
+ tenantId: this.tenantId,
3493
+ objectId,
3494
+ data,
3495
+ label,
3496
+ completionStatus
3497
+ });
3498
+ return record;
3499
+ }
3500
+ /**
3501
+ * Get a record by ID
3502
+ *
3503
+ * @param recordId - Record UUID
3504
+ * @param options - Query options
3505
+ * @returns Record or null if not found
3506
+ */
3507
+ async getRecord(recordId, options) {
3508
+ const record = await this.adapter.objectRecords.findById(recordId);
3509
+ if (!record) {
3510
+ return null;
3511
+ }
3512
+ if (options?.includeSchema) {
3513
+ const schema = await this.schemaService.getObjectSchema(record.objectId);
3514
+ const recordWithSchema = record;
3515
+ recordWithSchema.schema = schema;
3516
+ return recordWithSchema;
3517
+ }
3518
+ return record;
3519
+ }
3520
+ /**
3521
+ * Get a record by ID or throw if not found
3522
+ */
3523
+ async getRecordOrThrow(recordId) {
3524
+ const record = await this.getRecord(recordId);
3525
+ if (!record) {
3526
+ throw new Error(`Record with id "${recordId}" not found`);
3527
+ }
3528
+ return record;
3529
+ }
3530
+ /**
3531
+ * Update a record with validation
3532
+ *
3533
+ * The completion status is automatically recalculated after each update.
3534
+ * A draft record becomes complete when all required fields are filled.
3535
+ *
3536
+ * @param recordId - Record UUID
3537
+ * @param data - Partial data to update
3538
+ * @param options - Update options
3539
+ * @returns Updated record with recalculated completionStatus
3540
+ *
3541
+ * @example
3542
+ * ```typescript
3543
+ * // Update a draft record to make it complete
3544
+ * const updated = await service.updateRecord(draftId, {
3545
+ * price: 99.99,
3546
+ * status: "active"
3547
+ * });
3548
+ * // → updated.completionStatus = "complete" if all required fields now present
3549
+ * ```
3550
+ */
3551
+ async updateRecord(recordId, data, options) {
3552
+ const existing = await this.getRecordOrThrow(recordId);
3553
+ const schema = await this.schemaService.getObjectSchema(existing.objectId);
3554
+ const mergedData = { ...existing.values, ...data };
3555
+ if (options?.validate !== false) {
3556
+ if (options?.partial) {
3557
+ validateDraftOrThrow(schema, mergedData);
3558
+ } else {
3559
+ validateObjectOrThrow(schema, mergedData);
3560
+ }
3561
+ if (!options?.skipRelationValidation) {
3562
+ await this.relationService.validateRelationsOrThrow(schema, data);
3563
+ }
3564
+ }
3565
+ const completionStatus = computeRecordStatus(schema, mergedData);
3566
+ const label = this.computeLabel(schema, mergedData);
3567
+ const updated = await this.adapter.objectRecords.update(recordId, {
3568
+ ...data,
3569
+ __completionStatus: completionStatus,
3570
+ __label: label
3571
+ });
3572
+ return updated;
3573
+ }
3574
+ /**
3575
+ * Delete a record
3576
+ *
3577
+ * @param recordId - Record UUID
3578
+ * @param options - Delete options
3579
+ */
3580
+ async deleteRecord(recordId, options) {
3581
+ if (options?.checkSystem) {
3582
+ const record = await this.getRecordOrThrow(recordId);
3583
+ const schema = await this.schemaService.getObjectSchema(record.objectId);
3584
+ if (schema.system) {
3585
+ throw new Error(`Cannot delete record of system object "${schema.label}"`);
3586
+ }
3587
+ }
3588
+ await this.adapter.objectRecords.delete(recordId);
3589
+ }
3590
+ /**
3591
+ * List records for an object with pagination
3592
+ *
3593
+ * @param objectId - Object UUID
3594
+ * @param options - List options
3595
+ * @returns Records and total count
3596
+ */
3597
+ async listRecords(objectId, options) {
3598
+ return await this.adapter.objectRecords.list(this.tenantId, objectId, options);
3599
+ }
3600
+ /**
3601
+ * Search records using full-text search
3602
+ *
3603
+ * @param objectId - Object UUID
3604
+ * @param query - Search query
3605
+ * @param options - Search options
3606
+ * @returns Matching records and total count
3607
+ */
3608
+ async searchRecords(objectId, query, options) {
3609
+ return await this.adapter.objectRecords.search(this.tenantId, objectId, query, options);
3610
+ }
3611
+ /**
3612
+ * Validate data against object schema without saving
3613
+ *
3614
+ * @param objectId - Object UUID
3615
+ * @param data - Data to validate
3616
+ * @returns Validation result
3617
+ */
3618
+ async validateData(objectId, data) {
3619
+ const schema = await this.schemaService.getObjectSchema(objectId);
3620
+ return validateObject(schema, data);
3621
+ }
3622
+ /**
3623
+ * Compute the completion status for given data without saving.
3624
+ * Useful for UI to show draft/complete status before submitting.
3625
+ *
3626
+ * @param objectId - Object UUID
3627
+ * @param data - Data to check
3628
+ * @returns Computed completion status
3629
+ */
3630
+ async computeStatus(objectId, data) {
3631
+ const schema = await this.schemaService.getObjectSchema(objectId);
3632
+ return computeRecordStatus(schema, data);
3633
+ }
3634
+ /**
3635
+ * Refresh the completion status of an existing record.
3636
+ * Useful when schema changes and you need to recompute statuses.
3637
+ *
3638
+ * @param recordId - Record UUID
3639
+ * @returns Updated completion status
3640
+ */
3641
+ async refreshRecordStatus(recordId) {
3642
+ const record = await this.getRecordOrThrow(recordId);
3643
+ const schema = await this.schemaService.getObjectSchema(record.objectId);
3644
+ const newStatus = computeRecordStatus(schema, record.values);
3645
+ if (record.completionStatus !== newStatus) {
3646
+ await this.adapter.objectRecords.update(recordId, {
3647
+ __completionStatus: newStatus
3648
+ });
3649
+ }
3650
+ return newStatus;
3651
+ }
3652
+ };
3653
+
3654
+ // src/runtime/services/user-profile.service.ts
3655
+ var UserProfileService = class {
3656
+ constructor(adapter, tenantId) {
3657
+ this.adapter = adapter;
3658
+ this.tenantId = tenantId;
3659
+ }
3660
+ /**
3661
+ * Create a new user profile (typically after first auth)
3662
+ *
3663
+ * @param data - User profile creation data
3664
+ * @returns Created user profile
3665
+ *
3666
+ * @example
3667
+ * ```typescript
3668
+ * const service = new UserProfileService(adapter, "tenant-123");
3669
+ *
3670
+ * // After Supabase auth
3671
+ * const profile = await service.createProfile({
3672
+ * tenantId: "tenant-123",
3673
+ * authId: authUser.id,
3674
+ * email: authUser.email,
3675
+ * firstName: authUser.user_metadata.first_name,
3676
+ * lastName: authUser.user_metadata.last_name,
3677
+ * role: "member",
3678
+ * status: "active"
3679
+ * });
3680
+ * ```
3681
+ */
3682
+ async createProfile(data) {
3683
+ if (data.tenantId !== this.tenantId) {
3684
+ throw new Error(
3685
+ `Tenant mismatch: service initialized with "${this.tenantId}" but data has "${data.tenantId}"`
3686
+ );
3687
+ }
3688
+ const existing = await this.adapter.userProfiles.findByAuthId(data.authId);
3689
+ if (existing) {
3690
+ throw new Error(`User profile with authId "${data.authId}" already exists`);
3691
+ }
3692
+ const existingEmail = await this.adapter.userProfiles.findByEmail(this.tenantId, data.email);
3693
+ if (existingEmail) {
3694
+ throw new Error(`User profile with email "${data.email}" already exists in this tenant`);
3695
+ }
3696
+ return await this.adapter.userProfiles.create(data);
3697
+ }
3698
+ /**
3699
+ * Get user profile by ID
3700
+ */
3701
+ async getProfile(profileId) {
3702
+ return await this.adapter.userProfiles.findById(profileId);
3703
+ }
3704
+ /**
3705
+ * Get user profile by ID or throw
3706
+ */
3707
+ async getProfileOrThrow(profileId) {
3708
+ const profile = await this.getProfile(profileId);
3709
+ if (!profile) {
3710
+ throw new Error(`User profile with id "${profileId}" not found`);
3711
+ }
3712
+ return profile;
3713
+ }
3714
+ /**
3715
+ * Get user profile by auth provider ID
3716
+ *
3717
+ * @param authId - Auth provider user ID (Supabase, Clerk, etc.)
3718
+ * @returns User profile or null
3719
+ */
3720
+ async getProfileByAuthId(authId) {
3721
+ return await this.adapter.userProfiles.findByAuthId(authId);
3722
+ }
3723
+ /**
3724
+ * Get or create user profile (idempotent operation)
3725
+ * Useful for auth callbacks - ensures profile exists
3726
+ *
3727
+ * @param authId - Auth provider user ID
3728
+ * @param data - Profile data to create if doesn't exist
3729
+ * @returns Existing or newly created profile
3730
+ *
3731
+ * @example
3732
+ * ```typescript
3733
+ * // In Supabase auth callback
3734
+ * const profile = await service.getOrCreateProfile(
3735
+ * authUser.id,
3736
+ * {
3737
+ * tenantId: "tenant-123",
3738
+ * authId: authUser.id,
3739
+ * email: authUser.email,
3740
+ * role: "member",
3741
+ * status: "active"
3742
+ * }
3743
+ * );
3744
+ * ```
3745
+ */
3746
+ async getOrCreateProfile(authId, data) {
3747
+ const existing = await this.getProfileByAuthId(authId);
3748
+ if (existing) {
3749
+ return existing;
3750
+ }
3751
+ return await this.createProfile(data);
3752
+ }
3753
+ /**
3754
+ * Update user profile
3755
+ */
3756
+ async updateProfile(profileId, data) {
3757
+ await this.getProfileOrThrow(profileId);
3758
+ return await this.adapter.userProfiles.update(profileId, data);
3759
+ }
3760
+ /**
3761
+ * Delete user profile
3762
+ *
3763
+ * @param profileId - Profile UUID
3764
+ * @param options - Delete options
3765
+ */
3766
+ async deleteProfile(profileId, options) {
3767
+ if (options?.checkAdmin) {
3768
+ const profile = await this.getProfileOrThrow(profileId);
3769
+ if (profile.role === "admin") {
3770
+ const allProfiles = await this.listProfiles();
3771
+ const adminCount = allProfiles.filter((p) => p.role === "admin").length;
3772
+ if (adminCount <= 1) {
3773
+ throw new Error("Cannot delete the last admin user");
3774
+ }
3775
+ }
3776
+ }
3777
+ await this.adapter.userProfiles.delete(profileId);
3778
+ }
3779
+ /**
3780
+ * List all user profiles for the tenant
3781
+ */
3782
+ async listProfiles(options) {
3783
+ return await this.adapter.userProfiles.list(this.tenantId, options);
3784
+ }
3785
+ /**
3786
+ * Update last login timestamp
3787
+ *
3788
+ * @param profileId - Profile UUID
3789
+ *
3790
+ * @example
3791
+ * ```typescript
3792
+ * // After successful auth
3793
+ * await service.updateLastLogin(profile.id);
3794
+ * ```
3795
+ */
3796
+ async updateLastLogin(profileId) {
3797
+ await this.adapter.userProfiles.updateLastLogin(profileId);
3798
+ }
3799
+ /**
3800
+ * Change user role
3801
+ *
3802
+ * @param profileId - Profile UUID
3803
+ * @param newRole - New role
3804
+ */
3805
+ async changeRole(profileId, newRole) {
3806
+ return await this.updateProfile(profileId, { role: newRole });
3807
+ }
3808
+ /**
3809
+ * Change user status
3810
+ *
3811
+ * @param profileId - Profile UUID
3812
+ * @param newStatus - New status
3813
+ */
3814
+ async changeStatus(profileId, newStatus) {
3815
+ return await this.updateProfile(profileId, { status: newStatus });
3816
+ }
3817
+ /**
3818
+ * Get user by email
3819
+ */
3820
+ async getProfileByEmail(email) {
3821
+ return await this.adapter.userProfiles.findByEmail(this.tenantId, email);
3822
+ }
3823
+ /**
3824
+ * Check if user has role
3825
+ */
3826
+ async hasRole(profileId, role) {
3827
+ const profile = await this.getProfile(profileId);
3828
+ return profile?.role === role;
3829
+ }
3830
+ /**
3831
+ * Check if user is admin
3832
+ */
3833
+ async isAdmin(profileId) {
3834
+ return await this.hasRole(profileId, "admin");
3835
+ }
3836
+ };
3837
+
3838
+ // src/runtime/services/view.service.ts
3839
+ var ViewService = class {
3840
+ constructor(adapter, nativeViews) {
3841
+ this.adapter = adapter;
3842
+ this.nativeViews = nativeViews;
3843
+ }
3844
+ /**
3845
+ * Get all views for an object (native + custom)
3846
+ *
3847
+ * @param objectName - Object name
3848
+ * @param tenantId - Tenant ID
3849
+ * @returns All views for the object
3850
+ */
3851
+ async getViewsForObject(objectName, tenantId) {
3852
+ const nativeViewDefs = this.nativeViews.getByObjectName(objectName);
3853
+ const dbViews = await this.adapter.views.findByObjectName(tenantId, objectName);
3854
+ const customViews = dbViews.filter((v) => !v.system).map(this.convertDBViewToDefinition);
3855
+ return [...nativeViewDefs, ...customViews];
3856
+ }
3857
+ /**
3858
+ * Get a specific view by name
3859
+ *
3860
+ * @param objectName - Object name
3861
+ * @param viewName - View name
3862
+ * @param tenantId - Tenant ID
3863
+ * @returns View definition or null
3864
+ */
3865
+ async getView(objectName, viewName, tenantId) {
3866
+ const nativeView = this.nativeViews.get(objectName, viewName);
3867
+ if (nativeView) {
3868
+ return nativeView;
3869
+ }
3870
+ const dbView = await this.adapter.views.findByName(tenantId, objectName, viewName);
3871
+ if (dbView) {
3872
+ return this.convertDBViewToDefinition(dbView);
3873
+ }
3874
+ return null;
3875
+ }
3876
+ /**
3877
+ * Get the default view for an object
3878
+ *
3879
+ * Priority:
3880
+ * 1. Custom view marked as default
3881
+ * 2. Native view marked as default
3882
+ * 3. First available view
3883
+ *
3884
+ * @param objectName - Object name
3885
+ * @param tenantId - Tenant ID
3886
+ * @returns Default view or null
3887
+ */
3888
+ async getDefaultView(objectName, tenantId) {
3889
+ const views = await this.getViewsForObject(objectName, tenantId);
3890
+ const customDefault = views.find((v) => v.default && !v.system);
3891
+ if (customDefault) return customDefault;
3892
+ const nativeDefault = views.find((v) => v.default && v.system);
3893
+ if (nativeDefault) return nativeDefault;
3894
+ return views[0] ?? null;
3895
+ }
3896
+ /**
3897
+ * Create a custom view
3898
+ *
3899
+ * @param input - View definition
3900
+ * @param tenantId - Tenant ID
3901
+ * @returns Created view
3902
+ */
3903
+ async createView(input, tenantId) {
3904
+ this.validateViewName(input.name);
3905
+ const existing = await this.adapter.views.findByName(tenantId, input.objectName, input.name);
3906
+ if (existing) {
3907
+ throw new Error(`View "${input.name}" already exists for object "${input.objectName}"`);
3908
+ }
3909
+ if (this.nativeViews.has(input.objectName, input.name)) {
3910
+ throw new Error(
3911
+ `Cannot create view "${input.name}": a system view with this name already exists`
3912
+ );
3913
+ }
3914
+ if (!input.tabs || input.tabs.length === 0) {
3915
+ throw new Error("View must have at least one tab");
3916
+ }
3917
+ const dbView = await this.adapter.views.create({
3918
+ tenantId,
3919
+ objectName: input.objectName,
3920
+ name: input.name,
3921
+ label: input.label,
3922
+ description: input.description,
3923
+ icon: input.icon,
3924
+ tabs: input.tabs,
3925
+ default: input.default ?? false,
3926
+ system: false,
3927
+ // Custom views are never system
3928
+ metadata: input.metadata
3929
+ });
3930
+ return this.convertDBViewToDefinition(dbView);
3931
+ }
3932
+ /**
3933
+ * Update a custom view
3934
+ *
3935
+ * @param viewId - View ID
3936
+ * @param input - Update data
3937
+ * @returns Updated view
3938
+ */
3939
+ async updateView(viewId, input) {
3940
+ const dbView = await this.adapter.views.findById(viewId);
3941
+ if (!dbView) {
3942
+ throw new Error(`View with id "${viewId}" not found`);
3943
+ }
3944
+ if (dbView.system) {
3945
+ throw new Error("Cannot modify system views. System views are protected.");
3946
+ }
3947
+ if (input.tabs && input.tabs.length === 0) {
3948
+ throw new Error("View must have at least one tab");
3949
+ }
3950
+ const updated = await this.adapter.views.update(viewId, {
3951
+ label: input.label,
3952
+ description: input.description,
3953
+ icon: input.icon,
3954
+ tabs: input.tabs,
3955
+ default: input.default,
3956
+ metadata: input.metadata
3957
+ });
3958
+ return this.convertDBViewToDefinition(updated);
3959
+ }
3960
+ /**
3961
+ * Delete a custom view
3962
+ *
3963
+ * @param viewId - View ID
3964
+ */
3965
+ async deleteView(viewId) {
3966
+ const dbView = await this.adapter.views.findById(viewId);
3967
+ if (!dbView) {
3968
+ throw new Error(`View with id "${viewId}" not found`);
3969
+ }
3970
+ if (dbView.system) {
3971
+ throw new Error("Cannot delete system views. System views are protected.");
3972
+ }
3973
+ await this.adapter.views.delete(viewId);
3974
+ }
3975
+ /**
3976
+ * Set a view as default for its object
3977
+ *
3978
+ * @param viewId - View ID
3979
+ * @param tenantId - Tenant ID
3980
+ * @returns Updated view
3981
+ */
3982
+ async setDefaultView(viewId, tenantId) {
3983
+ const dbView = await this.adapter.views.findById(viewId);
3984
+ if (!dbView) {
3985
+ throw new Error(`View with id "${viewId}" not found`);
3986
+ }
3987
+ const currentViews = await this.adapter.views.findByObjectName(tenantId, dbView.objectName);
3988
+ for (const v of currentViews) {
3989
+ if (v.default && v.id !== viewId && !v.system) {
3990
+ await this.adapter.views.update(v.id, { default: false });
3991
+ }
3992
+ }
3993
+ const updated = await this.adapter.views.update(viewId, { default: true });
3994
+ return this.convertDBViewToDefinition(updated);
3995
+ }
3996
+ // ============================================================================
3997
+ // PRIVATE HELPERS
3998
+ // ============================================================================
3999
+ /**
4000
+ * Validate view name format (kebab-case)
4001
+ */
4002
+ validateViewName(name) {
4003
+ if (!name || name.length === 0) {
4004
+ throw new Error("View name cannot be empty");
4005
+ }
4006
+ if (name.length > 63) {
4007
+ throw new Error("View name is too long (max 63 characters)");
4008
+ }
4009
+ const kebabCaseRegex = /^[a-z][a-z0-9-]*$/;
4010
+ if (!kebabCaseRegex.test(name)) {
4011
+ throw new Error(
4012
+ "Invalid view name format. Name must be in kebab-case (e.g., 'detail', 'list-view')"
4013
+ );
4014
+ }
4015
+ }
4016
+ /**
4017
+ * Convert database view to ViewDefinition
4018
+ */
4019
+ convertDBViewToDefinition(dbView) {
4020
+ return {
4021
+ id: dbView.id,
4022
+ name: dbView.name,
4023
+ label: dbView.label,
4024
+ description: dbView.description,
4025
+ icon: dbView.icon,
4026
+ object: dbView.objectName,
4027
+ tabs: dbView.tabs,
4028
+ default: dbView.default,
4029
+ system: dbView.system,
4030
+ metadata: dbView.metadata
4031
+ };
4032
+ }
4033
+ };
4034
+
4035
+ // src/runtime/view-sync.ts
4036
+ async function syncNativeViews(adapter, nativeViewRegistry, options = {}) {
4037
+ const result = {
4038
+ success: true,
4039
+ viewsSynced: 0,
4040
+ viewsCreated: 0,
4041
+ viewsUpdated: 0,
4042
+ viewsDeleted: 0,
4043
+ errors: []
4044
+ };
4045
+ const nativeViews = nativeViewRegistry.getAll();
4046
+ if (options.verbose) {
4047
+ console.info(`[ViewSync] Starting sync for ${nativeViews.length} native views...`);
4048
+ }
4049
+ try {
4050
+ await adapter.transaction(async (tx) => {
4051
+ const viewsByObject = await syncAllViews(tx, nativeViews, result, options);
4052
+ await cleanupRemovedViews(tx, viewsByObject, result, options);
4053
+ });
4054
+ } catch (error) {
4055
+ handleTransactionError(result, error);
4056
+ }
4057
+ logSyncComplete(result, options);
4058
+ return result;
4059
+ }
4060
+ async function syncAllViews(tx, nativeViews, result, options) {
4061
+ const viewsByObject = /* @__PURE__ */ new Map();
4062
+ for (const nativeView of nativeViews) {
4063
+ try {
4064
+ await syncSingleView(tx, nativeView, result, options);
4065
+ trackViewByObject(viewsByObject, nativeView);
4066
+ } catch (error) {
4067
+ handleViewSyncError(result, nativeView, error, options);
4068
+ }
4069
+ }
4070
+ return viewsByObject;
4071
+ }
4072
+ function trackViewByObject(viewsByObject, nativeView) {
4073
+ const objectViews = viewsByObject.get(nativeView.object) ?? [];
4074
+ objectViews.push(nativeView.name);
4075
+ viewsByObject.set(nativeView.object, objectViews);
4076
+ }
4077
+ function handleViewSyncError(result, nativeView, error, options) {
4078
+ result.success = false;
4079
+ result.errors.push({
4080
+ viewName: nativeView.name,
4081
+ objectName: nativeView.object,
4082
+ error: error instanceof Error ? error.message : String(error)
4083
+ });
4084
+ if (options.verbose) {
4085
+ console.error(`[ViewSync] \u2717 Failed to sync ${nativeView.object}:${nativeView.name}:`, error);
4086
+ }
4087
+ }
4088
+ async function cleanupRemovedViews(tx, viewsByObject, result, options) {
4089
+ if (options.dryRun) return;
4090
+ for (const [objectName, viewNames] of viewsByObject) {
4091
+ const deletedCount = await tx.views.deleteNotIn(objectName, viewNames);
4092
+ result.viewsDeleted += deletedCount;
4093
+ if (options.verbose && deletedCount > 0) {
4094
+ console.info(`[ViewSync] Deleted ${deletedCount} obsolete views for ${objectName}`);
4095
+ }
4096
+ }
4097
+ }
4098
+ function handleTransactionError(result, error) {
4099
+ result.success = false;
4100
+ result.errors.push({
4101
+ viewName: "transaction",
4102
+ objectName: "",
4103
+ error: error instanceof Error ? error.message : String(error)
4104
+ });
4105
+ }
4106
+ function logSyncComplete(result, options) {
4107
+ if (options.verbose) {
4108
+ console.info(
4109
+ `[ViewSync] ${result.success ? "\u2713" : "\u2717"} Sync complete:
4110
+ Views: ${result.viewsCreated} created, ${result.viewsUpdated} updated, ${result.viewsDeleted} deleted
4111
+ Errors: ${result.errors.length}`
4112
+ );
4113
+ }
4114
+ }
4115
+ async function syncSingleView(adapter, nativeView, result, options) {
4116
+ if (!nativeView.system) {
4117
+ throw new Error(`View ${nativeView.name} is not marked as system`);
4118
+ }
4119
+ const existingView = await adapter.views.findSystemByName(nativeView.object, nativeView.name);
4120
+ const isNew = !existingView;
4121
+ if (isNew) {
4122
+ result.viewsCreated++;
4123
+ } else {
4124
+ result.viewsUpdated++;
4125
+ }
4126
+ result.viewsSynced++;
4127
+ if (options.dryRun) {
4128
+ if (options.verbose) {
4129
+ console.info(
4130
+ `[ViewSync] Would ${isNew ? "create" : "update"} view: ${nativeView.object}:${nativeView.name}`
4131
+ );
4132
+ }
4133
+ return;
4134
+ }
4135
+ await adapter.views.upsert({
4136
+ tenantId: options.tenantId || "default",
4137
+ objectName: nativeView.object,
4138
+ name: nativeView.name,
4139
+ label: nativeView.label,
4140
+ description: nativeView.description,
4141
+ icon: nativeView.icon,
4142
+ tabs: nativeView.tabs,
4143
+ default: nativeView.default ?? false,
4144
+ system: true,
4145
+ metadata: nativeView.metadata
4146
+ });
4147
+ if (options.verbose) {
4148
+ console.info(
4149
+ `[ViewSync] \u2713 Synced ${nativeView.object}:${nativeView.name}: ${nativeView.tabs.length} tabs`
4150
+ );
4151
+ }
4152
+ }
4153
+ async function verifyNativeViewsSync(adapter, nativeViewRegistry) {
4154
+ const nativeViews = nativeViewRegistry.getAll();
4155
+ for (const view2 of nativeViews) {
4156
+ if (!view2.system) continue;
4157
+ const existing = await adapter.views.findSystemByName(view2.object, view2.name);
4158
+ if (!existing) {
4159
+ return false;
4160
+ }
4161
+ }
4162
+ return true;
4163
+ }
4164
+ async function getViewSyncPreview(adapter, nativeViewRegistry) {
4165
+ return await syncNativeViews(adapter, nativeViewRegistry, { dryRun: true });
4166
+ }
4167
+
4168
+ // src/runtime/sync.ts
4169
+ var BASE_ATTRIBUTE_KEYS = /* @__PURE__ */ new Set([
4170
+ "id",
4171
+ "name",
4172
+ "label",
4173
+ "type",
4174
+ "required",
4175
+ "system",
4176
+ "unique",
4177
+ "order"
4178
+ ]);
4179
+ function extractAttributeConfig(attr) {
4180
+ return Object.fromEntries(
4181
+ Object.entries(attr).filter(
4182
+ ([key, value]) => !BASE_ATTRIBUTE_KEYS.has(key) && value !== void 0
4183
+ )
4184
+ );
4185
+ }
4186
+ async function syncNativeObjects(adapter, nativeRegistry, options = {}) {
4187
+ const result = {
4188
+ success: true,
4189
+ objectsSynced: 0,
4190
+ attributesSynced: 0,
4191
+ objectsCreated: 0,
4192
+ objectsUpdated: 0,
4193
+ attributesCreated: 0,
4194
+ attributesUpdated: 0,
4195
+ attributesDeleted: 0,
4196
+ errors: []
4197
+ };
4198
+ const nativeObjects = nativeRegistry.getAll();
4199
+ if (options.verbose) {
4200
+ console.info(`[SyncService] Starting sync for ${nativeObjects.length} native objects...`);
4201
+ }
4202
+ try {
4203
+ await adapter.transaction(async (tx) => {
4204
+ for (const nativeObject of nativeObjects) {
4205
+ try {
4206
+ await syncSingleObject(tx, nativeObject, result, options);
4207
+ } catch (error) {
4208
+ result.success = false;
4209
+ result.errors.push({
4210
+ objectName: nativeObject.name,
4211
+ error: error instanceof Error ? error.message : String(error)
4212
+ });
4213
+ if (options.verbose) {
4214
+ console.error(`[SyncService] \u2717 Failed to sync ${nativeObject.name}:`, error);
4215
+ }
4216
+ }
4217
+ }
4218
+ });
4219
+ } catch (error) {
4220
+ result.success = false;
4221
+ result.errors.push({
4222
+ objectName: "transaction",
4223
+ error: error instanceof Error ? error.message : String(error)
4224
+ });
4225
+ }
4226
+ if (options.verbose) {
4227
+ console.info(
4228
+ `[SyncService] ${result.success ? "\u2713" : "\u2717"} Sync complete:
4229
+ Objects: ${result.objectsCreated} created, ${result.objectsUpdated} updated
4230
+ Attributes: ${result.attributesCreated} created, ${result.attributesUpdated} updated, ${result.attributesDeleted} deleted
4231
+ Errors: ${result.errors.length}`
4232
+ );
4233
+ }
4234
+ return result;
4235
+ }
4236
+ async function syncSingleObject(adapter, nativeObject, result, options) {
4237
+ if (!nativeObject.system) {
4238
+ throw new Error(`Object ${nativeObject.name} is not marked as system`);
4239
+ }
4240
+ const existingObject = await adapter.objects.findSystemByName(nativeObject.name);
4241
+ const isNew = !existingObject;
4242
+ updateObjectStats(result, isNew);
4243
+ if (options.dryRun) {
4244
+ await handleDryRun(adapter, nativeObject, existingObject, result, options, isNew);
4245
+ return;
4246
+ }
4247
+ const dbObject = await upsertObject(adapter, nativeObject, options);
4248
+ await syncAttributes(adapter, nativeObject, dbObject, existingObject, result);
4249
+ if (!isNew) {
4250
+ await cleanupAttributes(adapter, dbObject.id, nativeObject, result);
4251
+ }
4252
+ logSyncSuccess(nativeObject, options);
4253
+ }
4254
+ function updateObjectStats(result, isNew) {
4255
+ if (isNew) {
4256
+ result.objectsCreated++;
4257
+ } else {
4258
+ result.objectsUpdated++;
4259
+ }
4260
+ result.objectsSynced++;
4261
+ }
4262
+ async function handleDryRun(adapter, nativeObject, existingObject, result, options, isNew) {
4263
+ if (options.verbose) {
4264
+ console.info(`[SyncService] Would ${isNew ? "create" : "update"} object: ${nativeObject.name}`);
4265
+ }
4266
+ for (const attr of nativeObject.attributes) {
4267
+ const existingAttr = existingObject ? await adapter.attributes.findByObjectId(existingObject.id).then((attrs) => attrs.find((a) => a.name === attr.name)) : null;
4268
+ if (existingAttr) {
4269
+ result.attributesUpdated++;
4270
+ } else {
4271
+ result.attributesCreated++;
4272
+ }
4273
+ result.attributesSynced++;
4274
+ }
4275
+ }
4276
+ async function upsertObject(adapter, nativeObject, options) {
4277
+ return await adapter.objects.upsert({
4278
+ tenantId: options.tenantId || "default",
4279
+ system: true,
4280
+ name: nativeObject.name,
4281
+ label: nativeObject.label,
4282
+ description: nativeObject.description,
4283
+ labelExpression: nativeObject.labelExpression,
4284
+ metadata: nativeObject.metadata
4285
+ });
4286
+ }
4287
+ async function syncAttributes(adapter, nativeObject, dbObject, existingObject, result) {
4288
+ for (const [index, attr] of nativeObject.attributes.entries()) {
4289
+ const existingAttr = existingObject ? await adapter.attributes.findByObjectId(dbObject.id).then((attrs) => attrs.find((a) => a.name === attr.name)) : null;
4290
+ await adapter.attributes.upsert({
4291
+ objectId: dbObject.id,
4292
+ name: attr.name,
4293
+ label: attr.label,
4294
+ type: attr.type,
4295
+ description: attr.description,
4296
+ icon: attr.icon,
4297
+ system: attr.system ?? true,
4298
+ required: attr.required ?? false,
4299
+ order: attr.order ?? index,
4300
+ hidden: attr.hidden,
4301
+ archived: attr.archived,
4302
+ deprecated: attr.deprecated,
4303
+ defaultValue: attr.defaultValue,
4304
+ config: extractAttributeConfig(attr)
4305
+ });
4306
+ if (existingAttr) {
4307
+ result.attributesUpdated++;
4308
+ } else {
4309
+ result.attributesCreated++;
4310
+ }
4311
+ result.attributesSynced++;
4312
+ }
4313
+ }
4314
+ async function cleanupAttributes(adapter, objectId, nativeObject, result) {
4315
+ const attributeNames = nativeObject.attributes.map((attr) => attr.name);
4316
+ const deletedCount = await adapter.attributes.deleteByNames(objectId, attributeNames);
4317
+ result.attributesDeleted += deletedCount;
4318
+ }
4319
+ function logSyncSuccess(nativeObject, options) {
4320
+ if (options.verbose) {
4321
+ console.info(
4322
+ `[SyncService] \u2713 Synced ${nativeObject.name}: ${nativeObject.attributes.length} attributes`
4323
+ );
4324
+ }
4325
+ }
4326
+ async function verifyNativeObjectsSync(adapter, nativeRegistry) {
4327
+ const nativeObjects = nativeRegistry.getAll();
4328
+ for (const obj of nativeObjects) {
4329
+ if (!obj.system) continue;
4330
+ const existing = await adapter.objects.findSystemByName(obj.name);
4331
+ if (!existing) {
4332
+ return false;
4333
+ }
4334
+ }
4335
+ return true;
4336
+ }
4337
+ async function getSyncPreview(adapter, nativeRegistry) {
4338
+ return await syncNativeObjects(adapter, nativeRegistry, { dryRun: true });
4339
+ }
4340
+ async function syncAll(adapter, objectRegistry, nativeViewRegistry, options = {}) {
4341
+ if (options.verbose) {
4342
+ console.info("[SyncAll] Starting full sync...");
4343
+ }
4344
+ const objectsResult = await syncNativeObjects(adapter, objectRegistry, options);
4345
+ const viewsResult = await syncNativeViews(adapter, nativeViewRegistry, options);
4346
+ const result = {
4347
+ success: objectsResult.success && viewsResult.success,
4348
+ objects: objectsResult,
4349
+ views: viewsResult
4350
+ };
4351
+ if (options.verbose) {
4352
+ console.info(
4353
+ `[SyncAll] ${result.success ? "\u2713" : "\u2717"} Full sync complete:
4354
+ Objects: ${objectsResult.objectsSynced} synced (${objectsResult.objectsCreated} created, ${objectsResult.objectsUpdated} updated)
4355
+ Views: ${viewsResult.viewsSynced} synced (${viewsResult.viewsCreated} created, ${viewsResult.viewsUpdated} updated)
4356
+ Errors: ${objectsResult.errors.length + viewsResult.errors.length}`
4357
+ );
4358
+ }
4359
+ return result;
4360
+ }
4361
+
4362
+ // src/types/geocoding.ts
4363
+ var NoopGeocodingAdapter = class {
4364
+ async autocomplete() {
4365
+ return await Promise.resolve([]);
4366
+ }
4367
+ async reverse() {
4368
+ return await Promise.resolve(null);
4369
+ }
4370
+ async geocode() {
4371
+ return await Promise.resolve(null);
4372
+ }
4373
+ };
4374
+
4375
+ export {
4376
+ NoopGeocodingAdapter,
4377
+ generateId,
4378
+ generatePrefixedId,
4379
+ text,
4380
+ textarea,
4381
+ number,
4382
+ checkbox,
4383
+ date,
4384
+ phone,
4385
+ currency,
4386
+ status,
4387
+ select,
4388
+ multiselect,
4389
+ location,
4390
+ timestamp,
4391
+ file,
4392
+ user,
4393
+ relation,
4394
+ rating,
4395
+ ObjectBuilder,
4396
+ object,
4397
+ GroupBuilder,
4398
+ TableTabConfig,
4399
+ CustomTabConfig,
4400
+ TabBuilder,
4401
+ ViewBuilder,
4402
+ view,
4403
+ group,
4404
+ registry,
4405
+ textConfigSchema,
4406
+ textareaConfigSchema,
4407
+ numberConfigSchema,
4408
+ checkboxConfigSchema,
4409
+ dateConfigSchema,
4410
+ phoneConfigSchema,
4411
+ currencyConfigSchema,
4412
+ statusConfigSchema,
4413
+ locationConfigSchema,
4414
+ timestampConfigSchema,
4415
+ selectConfigSchema,
4416
+ multiselectConfigSchema,
4417
+ fileConfigSchema,
4418
+ userConfigSchema,
4419
+ relationConfigSchema,
4420
+ ratingConfigSchema,
4421
+ attributeConfigSchemas,
4422
+ getAttributeConfigSchema,
4423
+ validateAttributeConfig,
4424
+ parseAttributeConfig,
4425
+ safeParseAttributeConfig,
4426
+ createTextValidator,
4427
+ createNumberValidator,
4428
+ createCheckboxValidator,
4429
+ createDateValidator,
4430
+ createPhoneValidator,
4431
+ createCurrencyValidator,
4432
+ createStatusValidator,
4433
+ createSelectValidator,
4434
+ createMultiselectValidator,
4435
+ createLocationValidator,
4436
+ createTimestampValidator,
4437
+ createFileValidator,
4438
+ createUserValidator,
4439
+ createSingleRelationValidator,
4440
+ createMultiRelationValidator,
4441
+ createRelationValidator,
4442
+ createRatingValidator,
4443
+ createAttributeValidator,
4444
+ createObjectValidator,
4445
+ validateAttribute,
4446
+ validateObject,
4447
+ validateObjectOrThrow,
4448
+ createDraftValidator,
4449
+ validateDraft,
4450
+ validateDraftOrThrow,
4451
+ getMissingRequiredAttributes,
4452
+ isRecordComplete,
4453
+ computeRecordStatus,
4454
+ DEFAULT_LABEL_FALLBACK,
4455
+ renderLabelExpression,
4456
+ isLabelExpression,
4457
+ extractAttributeNames,
4458
+ createMockAdapter,
4459
+ FileService,
4460
+ GeocodingService,
4461
+ GlobalSearchService,
4462
+ ObjectSchemaService,
4463
+ RelationService,
4464
+ RecordService,
4465
+ UserProfileService,
4466
+ ViewService,
4467
+ syncNativeViews,
4468
+ verifyNativeViewsSync,
4469
+ getViewSyncPreview,
4470
+ syncNativeObjects,
4471
+ verifyNativeObjectsSync,
4472
+ getSyncPreview,
4473
+ syncAll
4474
+ };