@reopt-ai/brandapp-sdk 3.0.0

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 (76) hide show
  1. package/CHANGELOG.md +574 -0
  2. package/LICENSE +21 -0
  3. package/README.md +468 -0
  4. package/dist/ai/index.d.ts +314 -0
  5. package/dist/ai/index.js +7 -0
  6. package/dist/ai-provider/index.d.ts +196 -0
  7. package/dist/ai-provider/index.js +703 -0
  8. package/dist/auth/index.d.ts +76 -0
  9. package/dist/auth/index.js +40 -0
  10. package/dist/better-auth/client.d.ts +29 -0
  11. package/dist/better-auth/client.js +10 -0
  12. package/dist/better-auth/index.d.ts +82 -0
  13. package/dist/better-auth/index.js +145 -0
  14. package/dist/chunk-6FLYVNZI.js +32 -0
  15. package/dist/chunk-6KPKZ7ZB.js +49 -0
  16. package/dist/chunk-DI6QJPTQ.js +449 -0
  17. package/dist/chunk-E457LO5A.js +599 -0
  18. package/dist/chunk-F7BXBTZI.js +54 -0
  19. package/dist/chunk-J5Y2GSJF.js +443 -0
  20. package/dist/chunk-K3YVJE6E.js +96 -0
  21. package/dist/chunk-KU2LN5SE.js +350 -0
  22. package/dist/chunk-L4DHB36G.js +75 -0
  23. package/dist/chunk-PJZB4VP7.js +63 -0
  24. package/dist/chunk-REIKXSMY.js +7 -0
  25. package/dist/chunk-T2WXHAAC.js +54 -0
  26. package/dist/chunk-TUKIYH4Q.js +112 -0
  27. package/dist/chunk-WSEROZVO.js +81 -0
  28. package/dist/chunk-YRGLBM6V.js +157 -0
  29. package/dist/client-BkcO-0C2.d.ts +216 -0
  30. package/dist/client-CN5_tNOC.d.ts +147 -0
  31. package/dist/client-DttyeM_h.d.ts +102 -0
  32. package/dist/cms/index.d.ts +137 -0
  33. package/dist/cms/index.js +101 -0
  34. package/dist/config-CtxyJsDR.d.ts +397 -0
  35. package/dist/dev/index.d.ts +509 -0
  36. package/dist/dev/index.js +3071 -0
  37. package/dist/eav/coerce.d.ts +42 -0
  38. package/dist/eav/coerce.js +65 -0
  39. package/dist/eav/index.d.ts +214 -0
  40. package/dist/eav/index.js +147 -0
  41. package/dist/eav/migrate.d.ts +236 -0
  42. package/dist/eav/migrate.js +219 -0
  43. package/dist/eav/schema.d.ts +260 -0
  44. package/dist/eav/schema.js +656 -0
  45. package/dist/errors-5hd5ZR-M.d.ts +158 -0
  46. package/dist/feedback/index.d.ts +132 -0
  47. package/dist/feedback/index.js +5 -0
  48. package/dist/files/index.d.ts +54 -0
  49. package/dist/files/index.js +31 -0
  50. package/dist/index.d.ts +221 -0
  51. package/dist/index.js +84 -0
  52. package/dist/plans/index.d.ts +140 -0
  53. package/dist/plans/index.js +5 -0
  54. package/dist/push/index.d.ts +79 -0
  55. package/dist/push/index.js +5 -0
  56. package/dist/react/hooks.d.ts +376 -0
  57. package/dist/react/hooks.js +421 -0
  58. package/dist/terms/index.d.ts +79 -0
  59. package/dist/terms/index.js +5 -0
  60. package/dist/testing/index.d.ts +154 -0
  61. package/dist/testing/index.js +81 -0
  62. package/dist/typed-client-BxOVIiMU.d.ts +40 -0
  63. package/dist/types-6E3ZLL9X.d.ts +24 -0
  64. package/dist/types-DskYLVb8.d.ts +104 -0
  65. package/dist/types-ckmDDW3N.d.ts +129 -0
  66. package/dist/webhooks/index.d.ts +140 -0
  67. package/dist/webhooks/index.js +142 -0
  68. package/docs/api-reference.md +557 -0
  69. package/docs/cms.md +318 -0
  70. package/docs/dev-server.md +164 -0
  71. package/docs/environment.md +211 -0
  72. package/docs/errors.md +290 -0
  73. package/docs/files.md +272 -0
  74. package/docs/migration.md +315 -0
  75. package/docs/testing.md +163 -0
  76. package/package.json +173 -0
@@ -0,0 +1,656 @@
1
+ // src/eav/schema/validate.ts
2
+ var IDENTIFIER_RE = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
3
+ function validateEntityDef(key, def) {
4
+ if (!def.name || typeof def.name !== "string") {
5
+ throw new Error(`Entity "${key}": name is required and must be a string.`);
6
+ }
7
+ const attrEntries = Object.entries(def.attributes);
8
+ if (attrEntries.length === 0) {
9
+ throw new Error(`Entity "${key}": must have at least one attribute.`);
10
+ }
11
+ for (const [attrName, attrDef] of attrEntries) {
12
+ validateAttributeName(key, attrName);
13
+ validateAttributeDef(key, attrName, attrDef);
14
+ }
15
+ }
16
+ function validateAttributeName(entityKey, name) {
17
+ if (!IDENTIFIER_RE.test(name)) {
18
+ throw new Error(
19
+ `Entity "${entityKey}", attribute "${name}": name must be a valid identifier (letters, numbers, underscores, starting with a letter or underscore).`
20
+ );
21
+ }
22
+ }
23
+ function validateAttributeDef(entityKey, attrName, def) {
24
+ const prefix = `Entity "${entityKey}", attribute "${attrName}"`;
25
+ if (def.dataType === "select" || def.dataType === "multiselect") {
26
+ if (!def.options || def.options.length === 0) {
27
+ throw new Error(
28
+ `${prefix}: dataType "${def.dataType}" requires at least one option.`
29
+ );
30
+ }
31
+ }
32
+ if (def.options && def.options.length > 0 && def.dataType !== "select" && def.dataType !== "multiselect") {
33
+ throw new Error(
34
+ `${prefix}: options are only allowed for "select" or "multiselect" dataType, got "${def.dataType}".`
35
+ );
36
+ }
37
+ }
38
+ function validateSchemaDef(def) {
39
+ const entityEntries = Object.entries(def.entities);
40
+ const namesSeen = /* @__PURE__ */ new Map();
41
+ for (const [key, entityDef] of entityEntries) {
42
+ validateEntityDef(key, entityDef);
43
+ const existing = namesSeen.get(entityDef.name);
44
+ if (existing) {
45
+ throw new Error(
46
+ `Duplicate entity name "${entityDef.name}" found in keys "${existing}" and "${key}".`
47
+ );
48
+ }
49
+ namesSeen.set(entityDef.name, key);
50
+ }
51
+ }
52
+
53
+ // src/eav/schema/define.ts
54
+ function defineEntity(def) {
55
+ validateEntityDef(def.name, def);
56
+ return def;
57
+ }
58
+ function defineSchema(def) {
59
+ validateSchemaDef(def);
60
+ return def;
61
+ }
62
+
63
+ // src/eav/schema/diff.ts
64
+ function assignAutoSortOrder(schemaDefs) {
65
+ const result = {};
66
+ let autoSort = 0;
67
+ for (const [name, def] of Object.entries(schemaDefs)) {
68
+ result[name] = def.sortOrder !== void 0 ? def : { ...def, sortOrder: autoSort };
69
+ autoSort++;
70
+ }
71
+ return result;
72
+ }
73
+ function computeAttributeChanges(def, server) {
74
+ const changes = {};
75
+ const oldValues = {};
76
+ if (def.label !== server.label) {
77
+ changes.label = def.label;
78
+ oldValues.label = server.label;
79
+ }
80
+ if (def.dataType !== server.dataType) {
81
+ changes.dataType = def.dataType;
82
+ oldValues.dataType = server.dataType;
83
+ }
84
+ if ((def.isRequired ?? false) !== server.isRequired) {
85
+ changes.isRequired = def.isRequired ?? false;
86
+ oldValues.isRequired = server.isRequired;
87
+ }
88
+ if ((def.isUnique ?? false) !== server.isUnique) {
89
+ changes.isUnique = def.isUnique ?? false;
90
+ oldValues.isUnique = server.isUnique;
91
+ }
92
+ if ((def.defaultValue ?? null) !== server.defaultValue) {
93
+ changes.defaultValue = def.defaultValue ?? null;
94
+ oldValues.defaultValue = server.defaultValue;
95
+ }
96
+ const defOptions = def.options ? [...def.options] : null;
97
+ const serverOptions = server.options;
98
+ if (JSON.stringify(defOptions) !== JSON.stringify(serverOptions)) {
99
+ changes.options = defOptions;
100
+ oldValues.options = serverOptions;
101
+ }
102
+ const defValidation = def.validation ?? null;
103
+ if (JSON.stringify(defValidation) !== JSON.stringify(server.validation)) {
104
+ changes.validation = defValidation;
105
+ oldValues.validation = server.validation;
106
+ }
107
+ if (def.sortOrder !== void 0 && def.sortOrder !== server.sortOrder) {
108
+ changes.sortOrder = def.sortOrder;
109
+ oldValues.sortOrder = server.sortOrder;
110
+ }
111
+ return { changes, oldValues };
112
+ }
113
+ function diffAttributes(rawSchemaDefs, serverAttrs, deleteOrphans, lockfileAttrs) {
114
+ const schemaDefs = assignAutoSortOrder(rawSchemaDefs);
115
+ const actions = [];
116
+ const serverByName = new Map(serverAttrs.map((a) => [a.name, a]));
117
+ const serverById = new Map(serverAttrs.map((a) => [a.id, a]));
118
+ const claimedServerIds = /* @__PURE__ */ new Set();
119
+ for (const [name, def] of Object.entries(schemaDefs)) {
120
+ let server;
121
+ if (def.id) {
122
+ const candidate = serverById.get(def.id);
123
+ if (candidate && !claimedServerIds.has(candidate.id)) {
124
+ server = candidate;
125
+ }
126
+ }
127
+ if (!server) {
128
+ server = serverByName.get(name);
129
+ }
130
+ if (!server && def.previousNames && def.previousNames.length > 0) {
131
+ for (const previous of def.previousNames) {
132
+ const candidate = serverByName.get(previous);
133
+ if (candidate && !claimedServerIds.has(candidate.id)) {
134
+ server = candidate;
135
+ break;
136
+ }
137
+ }
138
+ }
139
+ if (!server && lockfileAttrs) {
140
+ const trackedId = lockfileAttrs[name];
141
+ if (trackedId) {
142
+ const candidate = serverById.get(trackedId);
143
+ if (candidate && !claimedServerIds.has(candidate.id)) {
144
+ server = candidate;
145
+ }
146
+ }
147
+ }
148
+ if (!server) {
149
+ actions.push({ type: "create", name, def });
150
+ continue;
151
+ }
152
+ claimedServerIds.add(server.id);
153
+ const { changes, oldValues } = computeAttributeChanges(def, server);
154
+ if (server.name !== name) {
155
+ changes.name = name;
156
+ oldValues.name = server.name;
157
+ }
158
+ if (Object.keys(changes).length > 0) {
159
+ actions.push({
160
+ type: "update",
161
+ name,
162
+ attributeId: server.id,
163
+ changes,
164
+ oldValues
165
+ });
166
+ } else {
167
+ actions.push({ type: "unchanged", name, attributeId: server.id });
168
+ }
169
+ }
170
+ for (const server of serverAttrs) {
171
+ if (claimedServerIds.has(server.id)) continue;
172
+ if (deleteOrphans) {
173
+ actions.push({
174
+ type: "delete",
175
+ name: server.name,
176
+ attributeId: server.id
177
+ });
178
+ }
179
+ }
180
+ return actions;
181
+ }
182
+ function diffEntity(key, def, server, deleteOrphans, lockfileAttrs) {
183
+ if (!server) {
184
+ const withSortOrder = assignAutoSortOrder(def.attributes);
185
+ const attributes2 = Object.entries(withSortOrder).map(
186
+ ([name, attrDef]) => ({ type: "create", name, def: attrDef })
187
+ );
188
+ return { type: "create", key, def, attributes: attributes2 };
189
+ }
190
+ const changes = {};
191
+ if (def.name !== server.name) changes.name = def.name;
192
+ if ((def.description ?? null) !== server.description)
193
+ changes.description = def.description ?? null;
194
+ if ((def.icon ?? null) !== server.icon) changes.icon = def.icon ?? null;
195
+ const attributes = diffAttributes(
196
+ def.attributes,
197
+ server.attributes,
198
+ deleteOrphans,
199
+ lockfileAttrs
200
+ );
201
+ const hasAttrChanges = attributes.some((a) => a.type !== "unchanged");
202
+ if (Object.keys(changes).length > 0) {
203
+ return { type: "update", key, entityId: server.id, changes, attributes };
204
+ }
205
+ if (hasAttrChanges) {
206
+ return {
207
+ type: "update",
208
+ key,
209
+ entityId: server.id,
210
+ changes: {},
211
+ attributes
212
+ };
213
+ }
214
+ return { type: "unchanged", key, entityId: server.id, attributes };
215
+ }
216
+ function computeDiff(schema, serverEntities, options = {}) {
217
+ const { deleteOrphans = false, lockfile } = options;
218
+ const serverByName = new Map(serverEntities.map((e) => [e.name, e]));
219
+ const serverById = new Map(serverEntities.map((e) => [e.id, e]));
220
+ const entities = [];
221
+ const claimedServerIds = /* @__PURE__ */ new Set();
222
+ for (const [key, def] of Object.entries(schema.entities)) {
223
+ let server;
224
+ const lockEntry = lockfile?.entities[key];
225
+ if (lockEntry) {
226
+ server = serverById.get(lockEntry.id);
227
+ }
228
+ if (!server) {
229
+ server = serverByName.get(def.name);
230
+ }
231
+ if (server) claimedServerIds.add(server.id);
232
+ entities.push(
233
+ diffEntity(key, def, server, deleteOrphans, lockEntry?.attributes)
234
+ );
235
+ }
236
+ if (deleteOrphans) {
237
+ for (const server of serverEntities) {
238
+ if (claimedServerIds.has(server.id)) continue;
239
+ entities.push({
240
+ type: "delete",
241
+ key: server.name,
242
+ entityId: server.id
243
+ });
244
+ }
245
+ }
246
+ const hasChanges = entities.some((e) => e.type !== "unchanged");
247
+ return { entities, hasChanges };
248
+ }
249
+
250
+ // src/eav/schema/json-schema.ts
251
+ function entityToJsonSchema(entity) {
252
+ const properties = {};
253
+ const required = [];
254
+ for (const [key, attr] of Object.entries(entity.attributes)) {
255
+ properties[key] = attributeToJsonSchema(attr);
256
+ if (attr.isRequired) {
257
+ required.push(key);
258
+ }
259
+ }
260
+ return {
261
+ type: "object",
262
+ title: entity.name,
263
+ ...entity.description ? { description: entity.description } : {},
264
+ properties,
265
+ ...required.length > 0 ? { required } : {}
266
+ };
267
+ }
268
+ function schemaToJsonSchema(schema) {
269
+ const properties = {};
270
+ for (const [key, entity] of Object.entries(schema.entities)) {
271
+ properties[key] = entityToJsonSchema(entity);
272
+ }
273
+ return {
274
+ $schema: "http://json-schema.org/draft-07/schema#",
275
+ type: "object",
276
+ properties
277
+ };
278
+ }
279
+ function attributeToJsonSchema(attr) {
280
+ const schema = {};
281
+ const v = attr.validation;
282
+ switch (attr.dataType) {
283
+ case "string":
284
+ case "textarea":
285
+ schema.type = "string";
286
+ if (v?.minLength != null) schema.minLength = v.minLength;
287
+ if (v?.maxLength != null) schema.maxLength = v.maxLength;
288
+ if (v?.pattern) schema.pattern = v.pattern;
289
+ break;
290
+ case "number":
291
+ schema.type = "number";
292
+ if (v?.min != null) schema.minimum = v.min;
293
+ if (v?.max != null) schema.maximum = v.max;
294
+ break;
295
+ case "boolean":
296
+ schema.type = "boolean";
297
+ break;
298
+ case "date":
299
+ schema.type = "string";
300
+ schema.format = "date-time";
301
+ break;
302
+ case "email":
303
+ schema.type = "string";
304
+ schema.format = "email";
305
+ break;
306
+ case "url":
307
+ schema.type = "string";
308
+ schema.format = "uri";
309
+ break;
310
+ case "select":
311
+ schema.type = "string";
312
+ if (attr.options?.length) {
313
+ schema.enum = attr.options.map((o) => o.value);
314
+ }
315
+ break;
316
+ case "multiselect":
317
+ schema.type = "array";
318
+ if (attr.options?.length) {
319
+ schema.items = {
320
+ type: "string",
321
+ enum: attr.options.map((o) => o.value)
322
+ };
323
+ } else {
324
+ schema.items = { type: "string" };
325
+ }
326
+ break;
327
+ default: {
328
+ attr.dataType;
329
+ break;
330
+ }
331
+ }
332
+ schema.title = attr.label;
333
+ if (attr.defaultValue != null) {
334
+ schema.default = attr.dataType === "number" ? Number(attr.defaultValue) : attr.dataType === "boolean" ? attr.defaultValue === "true" : attr.defaultValue;
335
+ }
336
+ if (v?.customMessage) {
337
+ schema["x-validation-message"] = v.customMessage;
338
+ }
339
+ return schema;
340
+ }
341
+
342
+ // src/eav/schema/compatibility.ts
343
+ var COMPATIBLE_TARGETS = {
344
+ // Same storage column (textValue), wider acceptance.
345
+ string: ["textarea"],
346
+ textarea: ["string"],
347
+ // Tighter types relaxing into plain string — no validation tightening.
348
+ email: ["string", "textarea"],
349
+ url: ["string", "textarea"],
350
+ select: ["string", "textarea"],
351
+ // Different storage column — no safe in-place conversion.
352
+ multiselect: [],
353
+ number: [],
354
+ boolean: [],
355
+ date: []
356
+ };
357
+ function isCompatibleDataTypeChange(from, to) {
358
+ if (from === to) return true;
359
+ return COMPATIBLE_TARGETS[from]?.includes(to) ?? false;
360
+ }
361
+ function assessCompatibility(diff) {
362
+ const issues = [];
363
+ for (const action of diff.entities) {
364
+ if (action.type === "delete") {
365
+ issues.push({
366
+ severity: "destructive",
367
+ entityKey: action.key,
368
+ code: "ENTITY_DELETE",
369
+ message: `Entity '${action.key}' will be deleted along with all of its records.`,
370
+ fix: "Run with allowDestructive: true if intentional, or remove deleteOrphans from your sync options."
371
+ });
372
+ continue;
373
+ }
374
+ const attributes = action.attributes;
375
+ for (const attr of attributes) {
376
+ if (attr.type === "delete") {
377
+ issues.push({
378
+ severity: "destructive",
379
+ entityKey: action.key,
380
+ attributeName: attr.name,
381
+ code: "ATTRIBUTE_DELETE",
382
+ message: `Attribute '${action.key}.${attr.name}' will be deleted; existing values will be lost.`,
383
+ fix: "Remove the schema-side deletion, or run with allowDestructive: true to confirm."
384
+ });
385
+ continue;
386
+ }
387
+ if (attr.type !== "update") continue;
388
+ const { changes, oldValues } = attr;
389
+ if ("dataType" in changes) {
390
+ const from = oldValues.dataType;
391
+ const to = changes.dataType;
392
+ const compatible = isCompatibleDataTypeChange(from, to);
393
+ issues.push({
394
+ severity: compatible ? "warning" : "destructive",
395
+ entityKey: action.key,
396
+ attributeName: attr.name,
397
+ code: compatible ? "COMPATIBLE_DATATYPE_CHANGE" : "INCOMPATIBLE_DATATYPE",
398
+ message: `dataType changes from '${from}' to '${to}'${compatible ? " (storage column compatible)." : "; existing values may fail validation or be dropped."}`,
399
+ fix: compatible ? "Safe \u2014 but double-check downstream consumers expect the new type." : "Migrate values explicitly (write a migration), or accept loss with allowDestructive: true."
400
+ });
401
+ }
402
+ if (changes.isRequired === true && oldValues.isRequired === false) {
403
+ issues.push({
404
+ severity: "destructive",
405
+ entityKey: action.key,
406
+ attributeName: attr.name,
407
+ code: "REQUIRED_TIGHTENED",
408
+ message: `Attribute '${action.key}.${attr.name}' is becoming required; rows missing this value will fail to update.`,
409
+ fix: "Backfill the column first, then re-run sync. Or pass allowDestructive: true to proceed."
410
+ });
411
+ }
412
+ if (changes.isUnique === true && oldValues.isUnique === false) {
413
+ issues.push({
414
+ severity: "destructive",
415
+ entityKey: action.key,
416
+ attributeName: attr.name,
417
+ code: "UNIQUE_TIGHTENED",
418
+ message: `Attribute '${action.key}.${attr.name}' is becoming unique; existing duplicates will block the migration.`,
419
+ fix: "Deduplicate rows first, then re-run sync. Or pass allowDestructive: true."
420
+ });
421
+ }
422
+ if ("options" in changes) {
423
+ const oldOpts = oldValues.options ?? [];
424
+ const newOpts = changes.options ?? [];
425
+ const newSet = new Set((newOpts ?? []).map((o) => o.value));
426
+ const removed = oldOpts.filter((o) => !newSet.has(o.value));
427
+ if (removed.length > 0) {
428
+ issues.push({
429
+ severity: "warning",
430
+ entityKey: action.key,
431
+ attributeName: attr.name,
432
+ code: "OPTIONS_REMOVED",
433
+ message: `Options removed from '${action.key}.${attr.name}': ${removed.map((o) => o.value).join(", ")}. Existing rows may still hold these values.`,
434
+ fix: "Audit existing rows or migrate them to the new option set before removing."
435
+ });
436
+ }
437
+ }
438
+ }
439
+ }
440
+ return issues;
441
+ }
442
+
443
+ // src/eav/schema/sync.ts
444
+ var SchemaCompatibilityError = class extends Error {
445
+ issues;
446
+ constructor(issues) {
447
+ const destructive = issues.filter((i) => i.severity === "destructive");
448
+ const summary = destructive.slice(0, 3).map((i) => `- ${i.code}: ${i.message}`).join("\n");
449
+ const more = destructive.length > 3 ? `
450
+ \u2026and ${destructive.length - 3} more` : "";
451
+ super(
452
+ `Schema sync blocked by ${destructive.length} destructive change(s):
453
+ ${summary}${more}
454
+
455
+ Pass { allowDestructive: true } to override.`
456
+ );
457
+ this.name = "SchemaCompatibilityError";
458
+ this.issues = issues;
459
+ }
460
+ };
461
+ function emit(onProgress, event) {
462
+ if (onProgress) onProgress(event);
463
+ }
464
+ async function syncAttributes(eav, entityId, entityKey, actions, onProgress) {
465
+ const attributes = [];
466
+ const errors = [];
467
+ for (const action of actions) {
468
+ try {
469
+ switch (action.type) {
470
+ case "create": {
471
+ const attr = await eav.attributes.create(entityId, {
472
+ name: action.name,
473
+ label: action.def.label,
474
+ dataType: action.def.dataType,
475
+ isRequired: action.def.isRequired,
476
+ isUnique: action.def.isUnique,
477
+ defaultValue: action.def.defaultValue,
478
+ validation: action.def.validation,
479
+ options: action.def.options ? [...action.def.options] : void 0,
480
+ sortOrder: action.def.sortOrder
481
+ });
482
+ emit(onProgress, {
483
+ type: "created",
484
+ key: `${entityKey}.${action.name}`,
485
+ detail: ` ${action.name} \u2014 created (dataType: ${action.def.dataType})`
486
+ });
487
+ attributes.push({ name: action.name, attributeId: attr.id });
488
+ break;
489
+ }
490
+ case "update": {
491
+ await eav.attributes.update(
492
+ entityId,
493
+ action.attributeId,
494
+ action.changes
495
+ );
496
+ emit(onProgress, {
497
+ type: "updated",
498
+ key: `${entityKey}.${action.name}`,
499
+ detail: ` ${action.name} \u2014 updated (${Object.keys(action.changes).join(", ")})`
500
+ });
501
+ attributes.push({
502
+ name: action.name,
503
+ attributeId: action.attributeId
504
+ });
505
+ break;
506
+ }
507
+ case "delete": {
508
+ await eav.attributes.delete(entityId, action.attributeId);
509
+ emit(onProgress, {
510
+ type: "deleted",
511
+ key: `${entityKey}.${action.name}`,
512
+ detail: ` ${action.name} \u2014 deleted`
513
+ });
514
+ break;
515
+ }
516
+ case "unchanged": {
517
+ attributes.push({
518
+ name: action.name,
519
+ attributeId: action.attributeId
520
+ });
521
+ break;
522
+ }
523
+ }
524
+ } catch (error) {
525
+ const msg = error instanceof Error ? error.message : String(error);
526
+ emit(onProgress, {
527
+ type: "error",
528
+ key: `${entityKey}.${action.name}`,
529
+ detail: ` ${action.name} \u2014 failed: ${msg}`
530
+ });
531
+ errors.push({ key: `${entityKey}.${action.name}`, message: msg });
532
+ if (action.type === "update" || action.type === "unchanged") {
533
+ attributes.push({
534
+ name: action.name,
535
+ attributeId: action.attributeId
536
+ });
537
+ }
538
+ }
539
+ }
540
+ return { attributes, errors };
541
+ }
542
+ async function syncEntity(eav, action, onProgress) {
543
+ switch (action.type) {
544
+ case "create": {
545
+ const entity = await eav.entities.create({
546
+ name: action.def.name,
547
+ description: action.def.description,
548
+ icon: action.def.icon
549
+ });
550
+ emit(onProgress, {
551
+ type: "created",
552
+ key: action.key,
553
+ detail: `${action.key} \u2014 created`
554
+ });
555
+ const { attributes, errors } = await syncAttributes(
556
+ eav,
557
+ entity.id,
558
+ action.key,
559
+ action.attributes,
560
+ onProgress
561
+ );
562
+ return {
563
+ entity: { key: action.key, entityId: entity.id, attributes },
564
+ errors
565
+ };
566
+ }
567
+ case "update": {
568
+ if (Object.keys(action.changes).length > 0) {
569
+ await eav.entities.update(action.entityId, action.changes);
570
+ emit(onProgress, {
571
+ type: "updated",
572
+ key: action.key,
573
+ detail: `${action.key} \u2014 updated (${Object.keys(action.changes).join(", ")})`
574
+ });
575
+ }
576
+ const { attributes, errors } = await syncAttributes(
577
+ eav,
578
+ action.entityId,
579
+ action.key,
580
+ action.attributes,
581
+ onProgress
582
+ );
583
+ return {
584
+ entity: { key: action.key, entityId: action.entityId, attributes },
585
+ errors
586
+ };
587
+ }
588
+ case "unchanged": {
589
+ const attrCount = action.attributes.length;
590
+ emit(onProgress, {
591
+ type: "unchanged",
592
+ key: action.key,
593
+ detail: `${action.key} \u2014 unchanged (${attrCount} attributes)`
594
+ });
595
+ const { attributes, errors } = await syncAttributes(
596
+ eav,
597
+ action.entityId,
598
+ action.key,
599
+ action.attributes,
600
+ onProgress
601
+ );
602
+ return {
603
+ entity: { key: action.key, entityId: action.entityId, attributes },
604
+ errors
605
+ };
606
+ }
607
+ case "delete": {
608
+ await eav.entities.delete(action.entityId);
609
+ emit(onProgress, {
610
+ type: "deleted",
611
+ key: action.key,
612
+ detail: `${action.key} \u2014 deleted`
613
+ });
614
+ return { entity: null, errors: [] };
615
+ }
616
+ }
617
+ }
618
+ async function applySync(eav, diff, onProgress) {
619
+ const entities = [];
620
+ const allErrors = [];
621
+ for (const action of diff.entities) {
622
+ try {
623
+ const { entity, errors } = await syncEntity(eav, action, onProgress);
624
+ if (entity) entities.push(entity);
625
+ allErrors.push(...errors);
626
+ } catch (error) {
627
+ const msg = error instanceof Error ? error.message : String(error);
628
+ emit(onProgress, {
629
+ type: "error",
630
+ key: action.key,
631
+ detail: `${action.key} \u2014 failed: ${msg}`
632
+ });
633
+ allErrors.push({ key: action.key, message: msg });
634
+ }
635
+ }
636
+ return { entities, errors: allErrors, warnings: assessCompatibility(diff) };
637
+ }
638
+ async function syncSchema(eav, schema, options = {}) {
639
+ const entityList = await eav.entities.list();
640
+ const serverEntities = await Promise.all(
641
+ entityList.map((e) => eav.entities.get(e.id))
642
+ );
643
+ const diff = computeDiff(schema, serverEntities, {
644
+ deleteOrphans: options.deleteOrphans,
645
+ lockfile: options.lockfile
646
+ });
647
+ const issues = assessCompatibility(diff);
648
+ if (!options.allowDestructive && issues.some((i) => i.severity === "destructive")) {
649
+ throw new SchemaCompatibilityError(issues);
650
+ }
651
+ return applySync(eav, diff, options.onProgress);
652
+ }
653
+
654
+ export { SchemaCompatibilityError, applySync, assessCompatibility, computeDiff, defineEntity, defineSchema, entityToJsonSchema, isCompatibleDataTypeChange, schemaToJsonSchema, syncSchema };
655
+ //# sourceMappingURL=schema.js.map
656
+ //# sourceMappingURL=schema.js.map