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