@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,3071 @@
1
+ import { createServer } from 'http';
2
+ import { readFile, mkdir, writeFile } from 'fs/promises';
3
+ import { dirname } from 'path';
4
+ import { Hono } from 'hono';
5
+ import { randomUUID } from 'crypto';
6
+
7
+ // src/dev/index.ts
8
+ var InMemoryStore = class {
9
+ entities = /* @__PURE__ */ new Map();
10
+ attributes = /* @__PURE__ */ new Map();
11
+ records = /* @__PURE__ */ new Map();
12
+ authUsers = /* @__PURE__ */ new Map();
13
+ authSessions = /* @__PURE__ */ new Map();
14
+ authAccounts = /* @__PURE__ */ new Map();
15
+ authVerifications = /* @__PURE__ */ new Map();
16
+ files = /* @__PURE__ */ new Map();
17
+ posts = /* @__PURE__ */ new Map();
18
+ postGroups = /* @__PURE__ */ new Map();
19
+ terms = /* @__PURE__ */ new Map();
20
+ termsVersions = /* @__PURE__ */ new Map();
21
+ termsConsents = /* @__PURE__ */ new Map();
22
+ generateId() {
23
+ return randomUUID();
24
+ }
25
+ now() {
26
+ return /* @__PURE__ */ new Date();
27
+ }
28
+ // ==================== Query Helpers ====================
29
+ findMany(map, predicate) {
30
+ const results = [];
31
+ for (const item of map.values()) {
32
+ if (predicate(item)) results.push(item);
33
+ }
34
+ return results;
35
+ }
36
+ findFirst(map, predicate) {
37
+ for (const item of map.values()) {
38
+ if (predicate(item)) return item;
39
+ }
40
+ return null;
41
+ }
42
+ count(map, predicate) {
43
+ let count = 0;
44
+ for (const item of map.values()) {
45
+ if (predicate(item)) count++;
46
+ }
47
+ return count;
48
+ }
49
+ // ==================== Entity helpers ====================
50
+ getEntitiesByBrandapp(brandappId) {
51
+ return this.findMany(
52
+ this.entities,
53
+ (e) => e.brandappId === brandappId
54
+ ).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
55
+ }
56
+ getAttributesByEntity(entityId) {
57
+ return this.findMany(this.attributes, (a) => a.entityId === entityId).sort(
58
+ (a, b) => a.sortOrder - b.sortOrder
59
+ );
60
+ }
61
+ getRecordsByEntity(entityId) {
62
+ return this.findMany(this.records, (r) => r.entityId === entityId);
63
+ }
64
+ getRecordValues(recordId) {
65
+ const record = this.records.get(recordId);
66
+ return record?.values ?? [];
67
+ }
68
+ // ==================== Serialization ====================
69
+ /**
70
+ * Produce a snapshot that is safe to mutate without affecting the store.
71
+ * Dates are preserved by reconstructing them after a structuredClone.
72
+ */
73
+ toSnapshot() {
74
+ const clone = (items) => Array.from(items, (item) => structuredClone(item));
75
+ return {
76
+ entities: clone(this.entities.values()),
77
+ attributes: clone(this.attributes.values()),
78
+ records: clone(this.records.values()),
79
+ authUsers: clone(this.authUsers.values()),
80
+ authSessions: clone(this.authSessions.values()),
81
+ authAccounts: clone(this.authAccounts.values()),
82
+ authVerifications: clone(this.authVerifications.values()),
83
+ files: clone(this.files.values()),
84
+ posts: clone(this.posts.values()),
85
+ postGroups: clone(this.postGroups.values()),
86
+ terms: clone(this.terms.values()),
87
+ termsVersions: clone(this.termsVersions.values()),
88
+ termsConsents: clone(this.termsConsents.values())
89
+ };
90
+ }
91
+ toJSON() {
92
+ return JSON.stringify(
93
+ this.toSnapshot(),
94
+ (_key, value) => {
95
+ if (value instanceof Date) return value.toISOString();
96
+ return value;
97
+ },
98
+ 2
99
+ );
100
+ }
101
+ fromSnapshot(snapshot) {
102
+ this.clear();
103
+ const toDate = (v) => v instanceof Date ? v : new Date(v);
104
+ const slugifySnapshot = (value) => value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "post";
105
+ for (const e of snapshot.entities) {
106
+ e.createdAt = toDate(e.createdAt);
107
+ e.updatedAt = toDate(e.updatedAt);
108
+ this.entities.set(e.id, e);
109
+ }
110
+ for (const a of snapshot.attributes) {
111
+ a.createdAt = toDate(a.createdAt);
112
+ a.updatedAt = toDate(a.updatedAt);
113
+ this.attributes.set(a.id, a);
114
+ }
115
+ for (const r of snapshot.records) {
116
+ r.createdAt = toDate(r.createdAt);
117
+ r.updatedAt = toDate(r.updatedAt);
118
+ this.records.set(r.id, r);
119
+ }
120
+ for (const u of snapshot.authUsers) {
121
+ u.createdAt = toDate(u.createdAt);
122
+ u.updatedAt = toDate(u.updatedAt);
123
+ this.authUsers.set(u.id, u);
124
+ }
125
+ for (const s of snapshot.authSessions) {
126
+ s.createdAt = toDate(s.createdAt);
127
+ s.updatedAt = toDate(s.updatedAt);
128
+ s.expiresAt = toDate(s.expiresAt);
129
+ this.authSessions.set(s.id, s);
130
+ }
131
+ for (const a of snapshot.authAccounts) {
132
+ a.createdAt = toDate(a.createdAt);
133
+ a.updatedAt = toDate(a.updatedAt);
134
+ if (a.accessTokenExpiresAt)
135
+ a.accessTokenExpiresAt = toDate(a.accessTokenExpiresAt);
136
+ if (a.refreshTokenExpiresAt)
137
+ a.refreshTokenExpiresAt = toDate(a.refreshTokenExpiresAt);
138
+ this.authAccounts.set(a.id, a);
139
+ }
140
+ for (const v of snapshot.authVerifications) {
141
+ v.createdAt = toDate(v.createdAt);
142
+ v.updatedAt = toDate(v.updatedAt);
143
+ v.expiresAt = toDate(v.expiresAt);
144
+ this.authVerifications.set(v.id, v);
145
+ }
146
+ for (const f of snapshot.files) {
147
+ f.createdAt = toDate(f.createdAt);
148
+ f.updatedAt = toDate(f.updatedAt);
149
+ this.files.set(f.id, f);
150
+ }
151
+ for (const p of snapshot.posts) {
152
+ p.createdAt = toDate(p.createdAt);
153
+ p.updatedAt = toDate(p.updatedAt);
154
+ if (p.publishedAt) p.publishedAt = toDate(p.publishedAt);
155
+ p.slug = p.slug ?? slugifySnapshot(p.title);
156
+ p.contentRich = p.contentRich ?? null;
157
+ p.status = p.status ?? "draft";
158
+ p.groupId = p.groupId ?? null;
159
+ p.publishedAt = p.publishedAt ?? null;
160
+ p.coverImage = p.coverImage ?? null;
161
+ p.author = p.author ?? { id: "dev-user", name: "Dev User", image: null };
162
+ p.icon = p.icon ?? null;
163
+ p.tags = p.tags ?? [];
164
+ p.seo = p.seo ?? {
165
+ metaTitle: null,
166
+ metaDescription: null,
167
+ metaKeywords: null
168
+ };
169
+ this.posts.set(p.id, p);
170
+ }
171
+ for (const g of snapshot.postGroups) {
172
+ g.createdAt = toDate(g.createdAt);
173
+ g.updatedAt = toDate(g.updatedAt);
174
+ g.slug = g.slug ?? null;
175
+ g.color = g.color ?? "indigo";
176
+ g.brand = g.brand ?? null;
177
+ this.postGroups.set(g.id, g);
178
+ }
179
+ for (const t of snapshot.terms ?? []) {
180
+ t.createdAt = toDate(t.createdAt);
181
+ t.updatedAt = toDate(t.updatedAt);
182
+ t.jurisdiction = t.jurisdiction ?? "KR";
183
+ this.terms.set(t.id, t);
184
+ }
185
+ for (const v of snapshot.termsVersions ?? []) {
186
+ v.createdAt = toDate(v.createdAt);
187
+ v.publishedAt = toDate(v.publishedAt);
188
+ if (v.reConsentDeadline)
189
+ v.reConsentDeadline = toDate(v.reConsentDeadline);
190
+ v.locale = v.locale ?? "ko-KR";
191
+ this.termsVersions.set(v.id, v);
192
+ }
193
+ for (const c of snapshot.termsConsents ?? []) {
194
+ c.createdAt = toDate(c.createdAt);
195
+ c.consentedAt = toDate(c.consentedAt);
196
+ if (c.withdrawnAt) c.withdrawnAt = toDate(c.withdrawnAt);
197
+ c.userAgent = c.userAgent ?? null;
198
+ c.consentCountry = c.consentCountry ?? null;
199
+ c.consentLocale = c.consentLocale ?? null;
200
+ this.termsConsents.set(c.id, c);
201
+ }
202
+ }
203
+ fromJSON(json) {
204
+ this.fromSnapshot(JSON.parse(json));
205
+ }
206
+ clear() {
207
+ this.entities.clear();
208
+ this.attributes.clear();
209
+ this.records.clear();
210
+ this.authUsers.clear();
211
+ this.authSessions.clear();
212
+ this.authAccounts.clear();
213
+ this.authVerifications.clear();
214
+ this.files.clear();
215
+ this.posts.clear();
216
+ this.postGroups.clear();
217
+ this.terms.clear();
218
+ this.termsVersions.clear();
219
+ this.termsConsents.clear();
220
+ }
221
+ };
222
+ var LIMITS = {
223
+ ENTITIES_PER_BRANDAPP: 50,
224
+ ATTRIBUTES_PER_ENTITY: 100,
225
+ RECORDS_PER_ENTITY: 1e4,
226
+ /** Max records per bulk operation (matches production API). */
227
+ BULK_BATCH_SIZE: 100
228
+ };
229
+ function bulkSizeError(op, got) {
230
+ return {
231
+ ok: false,
232
+ error: {
233
+ code: "REQUEST_ERROR",
234
+ message: `${op} accepts at most ${LIMITS.BULK_BATCH_SIZE} records per call (got ${got})`
235
+ }
236
+ };
237
+ }
238
+ function checkBrandappAuthUserCreate(store, brandappId, entityId, authUserId) {
239
+ if (!authUserId) {
240
+ return {
241
+ ok: false,
242
+ status: 400,
243
+ error: "authUserId is required for brandappAuthUser-linked entities"
244
+ };
245
+ }
246
+ const user = store.findFirst(
247
+ store.authUsers,
248
+ (u) => u.id === authUserId && u.brandappId === brandappId
249
+ );
250
+ if (!user) {
251
+ return {
252
+ ok: false,
253
+ status: 422,
254
+ error: "Auth user not found in this brandapp"
255
+ };
256
+ }
257
+ const existing = store.findFirst(
258
+ store.records,
259
+ (r) => r.entityId === entityId && r.brandappAuthUserId === authUserId
260
+ );
261
+ if (existing) {
262
+ return {
263
+ ok: false,
264
+ status: 409,
265
+ error: "Auth user already has a record for this entity"
266
+ };
267
+ }
268
+ return { ok: true };
269
+ }
270
+ function validateRequiredFields(values, attributes) {
271
+ const errors = [];
272
+ for (const attr of attributes) {
273
+ if (!attr.isRequired) continue;
274
+ const v = values[attr.id];
275
+ if (v === void 0 || v === null || v === "") {
276
+ errors.push({
277
+ field: attr.name,
278
+ message: `"${attr.name}" is required`,
279
+ code: "required"
280
+ });
281
+ }
282
+ }
283
+ return errors;
284
+ }
285
+ function validationErrorResponse(fields) {
286
+ return {
287
+ ok: false,
288
+ error: {
289
+ code: "VALIDATION_ERROR",
290
+ message: "Validation failed",
291
+ fields
292
+ }
293
+ };
294
+ }
295
+ function parseStoredValue(value) {
296
+ try {
297
+ return JSON.parse(value);
298
+ } catch {
299
+ return value;
300
+ }
301
+ }
302
+ function serializeValue(value) {
303
+ if (value === void 0) return "";
304
+ return typeof value === "string" ? value : JSON.stringify(value);
305
+ }
306
+ function getRecordValue(record, attributeId) {
307
+ const matched = record.values.find((v) => v.attributeId === attributeId);
308
+ if (!matched) return { exists: false, value: void 0 };
309
+ return { exists: true, value: parseStoredValue(matched.value) };
310
+ }
311
+ function toNumber(value) {
312
+ if (typeof value === "number" && Number.isFinite(value)) return value;
313
+ if (typeof value === "string" && value.trim() !== "") {
314
+ const parsed = Number(value);
315
+ if (Number.isFinite(parsed)) return parsed;
316
+ }
317
+ return null;
318
+ }
319
+ function toDateTimestamp(value) {
320
+ if (value instanceof Date && !Number.isNaN(value.getTime()))
321
+ return value.getTime();
322
+ if (typeof value === "string" && value.trim() !== "") {
323
+ const parsed = Date.parse(value);
324
+ if (!Number.isNaN(parsed)) return parsed;
325
+ }
326
+ return null;
327
+ }
328
+ function compareOrderableValues(left, right, mode) {
329
+ if (mode === "date_only") {
330
+ const ld2 = toDateTimestamp(left);
331
+ const rd2 = toDateTimestamp(right);
332
+ if (ld2 === null || rd2 === null) return null;
333
+ return ld2 - rd2;
334
+ }
335
+ const ln = toNumber(left);
336
+ const rn = toNumber(right);
337
+ if (ln !== null && rn !== null) return ln - rn;
338
+ const ld = toDateTimestamp(left);
339
+ const rd = toDateTimestamp(right);
340
+ if (ld !== null && rd !== null) return ld - rd;
341
+ if (typeof left === "string" && typeof right === "string")
342
+ return left.localeCompare(right);
343
+ return null;
344
+ }
345
+ function matchesFilter(record, filter) {
346
+ const { exists, value } = getRecordValue(record, filter.attributeId);
347
+ switch (filter.operator) {
348
+ case "eq":
349
+ return exists && serializeValue(value) === serializeValue(filter.value);
350
+ case "neq":
351
+ return !exists || serializeValue(value) !== serializeValue(filter.value);
352
+ case "contains":
353
+ return exists && serializeValue(value).includes(serializeValue(filter.value));
354
+ case "gt": {
355
+ const c = compareOrderableValues(value, filter.value, "general");
356
+ return exists && c !== null && c > 0;
357
+ }
358
+ case "lt": {
359
+ const c = compareOrderableValues(value, filter.value, "general");
360
+ return exists && c !== null && c < 0;
361
+ }
362
+ case "gte": {
363
+ const c = compareOrderableValues(value, filter.value, "general");
364
+ return exists && c !== null && c >= 0;
365
+ }
366
+ case "lte": {
367
+ const c = compareOrderableValues(value, filter.value, "general");
368
+ return exists && c !== null && c <= 0;
369
+ }
370
+ case "after": {
371
+ const c = compareOrderableValues(value, filter.value, "date_only");
372
+ return exists && c !== null && c > 0;
373
+ }
374
+ case "before": {
375
+ const c = compareOrderableValues(value, filter.value, "date_only");
376
+ return exists && c !== null && c < 0;
377
+ }
378
+ case "is_null":
379
+ return !exists || value === null;
380
+ case "is_not_null":
381
+ return exists && value !== null;
382
+ default:
383
+ return true;
384
+ }
385
+ }
386
+ function filterRecords(records, filters) {
387
+ if (filters.length === 0) return records;
388
+ return records.filter((r) => filters.every((f) => matchesFilter(r, f)));
389
+ }
390
+ function sortRecords(records, sortBy, sortOrder) {
391
+ const sorted = [...records];
392
+ const dir = sortOrder === "asc" ? 1 : -1;
393
+ sorted.sort((a, b) => {
394
+ if (!sortBy || sortBy === "createdAt" || sortBy === "updatedAt") {
395
+ const field = sortBy ?? "createdAt";
396
+ const cmp = a[field].getTime() - b[field].getTime();
397
+ if (cmp !== 0) return cmp * dir;
398
+ } else {
399
+ const av = getRecordValue(a, sortBy);
400
+ const bv = getRecordValue(b, sortBy);
401
+ if (!av.exists && !bv.exists) ; else if (!av.exists) return 1;
402
+ else if (!bv.exists) return -1;
403
+ else {
404
+ const cmp = compareOrderableValues(av.value, bv.value, "general");
405
+ if (cmp !== null && cmp !== 0) return cmp * dir;
406
+ const sv = serializeValue(av.value).localeCompare(
407
+ serializeValue(bv.value)
408
+ );
409
+ if (sv !== 0) return sv * dir;
410
+ }
411
+ }
412
+ const tb = a.createdAt.getTime() - b.createdAt.getTime();
413
+ if (tb !== 0) return tb * dir;
414
+ return a.id.localeCompare(b.id) * dir;
415
+ });
416
+ return sorted;
417
+ }
418
+ function transformRecord(record) {
419
+ const values = {};
420
+ for (const v of record.values) {
421
+ values[v.attributeId] = parseStoredValue(v.value);
422
+ }
423
+ return {
424
+ id: record.id,
425
+ entityId: record.entityId,
426
+ authUserId: record.brandappAuthUserId,
427
+ values,
428
+ createdAt: record.createdAt,
429
+ updatedAt: record.updatedAt
430
+ };
431
+ }
432
+ function parseFilters(filtersJson) {
433
+ if (!filtersJson) return [];
434
+ try {
435
+ const parsed = JSON.parse(filtersJson);
436
+ return Array.isArray(parsed) ? parsed : [];
437
+ } catch {
438
+ return [];
439
+ }
440
+ }
441
+ function createEavRoutes(store, brandappId) {
442
+ const app = new Hono();
443
+ app.get("/entities", (c) => {
444
+ const entities = store.getEntitiesByBrandapp(brandappId);
445
+ return c.json({ ok: true, data: entities });
446
+ });
447
+ app.post("/entities", async (c) => {
448
+ const body = await c.req.json();
449
+ const count = store.count(
450
+ store.entities,
451
+ (e) => e.brandappId === brandappId
452
+ );
453
+ if (count >= LIMITS.ENTITIES_PER_BRANDAPP) {
454
+ return c.json(
455
+ {
456
+ ok: false,
457
+ error: {
458
+ code: "REQUEST_ERROR",
459
+ message: `Maximum ${LIMITS.ENTITIES_PER_BRANDAPP} entities per brandapp`
460
+ }
461
+ },
462
+ 422
463
+ );
464
+ }
465
+ const now = store.now();
466
+ const entity = {
467
+ id: store.generateId(),
468
+ brandappId,
469
+ name: body.name,
470
+ description: body.description ?? null,
471
+ icon: body.icon ?? "\u{1F4CA}",
472
+ linkedTo: body.linkedTo ?? "brandapp",
473
+ maxRecords: LIMITS.RECORDS_PER_ENTITY,
474
+ createdAt: now,
475
+ updatedAt: now
476
+ };
477
+ store.entities.set(entity.id, entity);
478
+ return c.json({ ok: true, data: entity }, 201);
479
+ });
480
+ app.get("/entities/:entityId", (c) => {
481
+ const entityId = c.req.param("entityId");
482
+ const entity = store.entities.get(entityId);
483
+ if (!entity || entity.brandappId !== brandappId) {
484
+ return c.json(
485
+ {
486
+ ok: false,
487
+ error: { code: "NOT_FOUND", message: "Entity not found" }
488
+ },
489
+ 404
490
+ );
491
+ }
492
+ const attributes = store.getAttributesByEntity(entityId).map((a) => ({ ...a }));
493
+ return c.json({ ok: true, data: { ...entity, attributes } });
494
+ });
495
+ app.put("/entities/:entityId", async (c) => {
496
+ const entityId = c.req.param("entityId");
497
+ const entity = store.entities.get(entityId);
498
+ if (!entity || entity.brandappId !== brandappId) {
499
+ return c.json(
500
+ {
501
+ ok: false,
502
+ error: { code: "NOT_FOUND", message: "Entity not found" }
503
+ },
504
+ 404
505
+ );
506
+ }
507
+ const body = await c.req.json();
508
+ if (body.name !== void 0) entity.name = body.name;
509
+ if (body.description !== void 0) entity.description = body.description;
510
+ if (body.icon !== void 0) entity.icon = body.icon ?? entity.icon;
511
+ entity.updatedAt = store.now();
512
+ return c.json({ ok: true, data: entity });
513
+ });
514
+ app.delete("/entities/:entityId", (c) => {
515
+ const entityId = c.req.param("entityId");
516
+ const entity = store.entities.get(entityId);
517
+ if (!entity || entity.brandappId !== brandappId) {
518
+ return c.json(
519
+ {
520
+ ok: false,
521
+ error: { code: "NOT_FOUND", message: "Entity not found" }
522
+ },
523
+ 404
524
+ );
525
+ }
526
+ for (const attr of store.getAttributesByEntity(entityId)) {
527
+ store.attributes.delete(attr.id);
528
+ }
529
+ for (const rec of store.getRecordsByEntity(entityId)) {
530
+ store.records.delete(rec.id);
531
+ }
532
+ store.entities.delete(entityId);
533
+ return c.json({ ok: true, data: null });
534
+ });
535
+ app.post("/entities/:entityId/attributes", async (c) => {
536
+ const entityId = c.req.param("entityId");
537
+ const entity = store.entities.get(entityId);
538
+ if (!entity || entity.brandappId !== brandappId) {
539
+ return c.json(
540
+ {
541
+ ok: false,
542
+ error: { code: "NOT_FOUND", message: "Entity not found" }
543
+ },
544
+ 404
545
+ );
546
+ }
547
+ const attrCount = store.count(
548
+ store.attributes,
549
+ (a) => a.entityId === entityId
550
+ );
551
+ if (attrCount >= LIMITS.ATTRIBUTES_PER_ENTITY) {
552
+ return c.json(
553
+ {
554
+ ok: false,
555
+ error: {
556
+ code: "REQUEST_ERROR",
557
+ message: `Maximum ${LIMITS.ATTRIBUTES_PER_ENTITY} attributes per entity`
558
+ }
559
+ },
560
+ 422
561
+ );
562
+ }
563
+ const body = await c.req.json();
564
+ const now = store.now();
565
+ const attr = {
566
+ id: store.generateId(),
567
+ entityId,
568
+ name: body.name,
569
+ label: body.label,
570
+ dataType: body.dataType,
571
+ isRequired: body.isRequired ?? false,
572
+ isUnique: body.isUnique ?? false,
573
+ defaultValue: body.defaultValue ?? null,
574
+ validation: body.validation ?? null,
575
+ options: body.options ?? null,
576
+ sortOrder: body.sortOrder ?? 0,
577
+ createdAt: now,
578
+ updatedAt: now
579
+ };
580
+ store.attributes.set(attr.id, attr);
581
+ return c.json({ ok: true, data: attr }, 201);
582
+ });
583
+ app.put("/entities/:entityId/attributes/:id", async (c) => {
584
+ const entityId = c.req.param("entityId");
585
+ const attrId = c.req.param("id");
586
+ const entity = store.entities.get(entityId);
587
+ if (!entity || entity.brandappId !== brandappId) {
588
+ return c.json(
589
+ {
590
+ ok: false,
591
+ error: { code: "NOT_FOUND", message: "Attribute not found" }
592
+ },
593
+ 404
594
+ );
595
+ }
596
+ const attr = store.attributes.get(attrId);
597
+ if (!attr || attr.entityId !== entityId) {
598
+ return c.json(
599
+ {
600
+ ok: false,
601
+ error: { code: "NOT_FOUND", message: "Attribute not found" }
602
+ },
603
+ 404
604
+ );
605
+ }
606
+ const body = await c.req.json();
607
+ if (body.name !== void 0) attr.name = body.name;
608
+ if (body.label !== void 0) attr.label = body.label;
609
+ if (body.dataType !== void 0) attr.dataType = body.dataType;
610
+ if (body.isRequired !== void 0)
611
+ attr.isRequired = body.isRequired;
612
+ if (body.isUnique !== void 0) attr.isUnique = body.isUnique;
613
+ if (body.defaultValue !== void 0)
614
+ attr.defaultValue = body.defaultValue;
615
+ if (body.validation !== void 0) attr.validation = body.validation;
616
+ if (body.options !== void 0) attr.options = body.options;
617
+ if (body.sortOrder !== void 0) attr.sortOrder = body.sortOrder;
618
+ attr.updatedAt = store.now();
619
+ return c.json({ ok: true, data: attr });
620
+ });
621
+ app.delete("/entities/:entityId/attributes/:id", (c) => {
622
+ const entityId = c.req.param("entityId");
623
+ const attrId = c.req.param("id");
624
+ const entity = store.entities.get(entityId);
625
+ if (!entity || entity.brandappId !== brandappId) {
626
+ return c.json(
627
+ {
628
+ ok: false,
629
+ error: { code: "NOT_FOUND", message: "Attribute not found" }
630
+ },
631
+ 404
632
+ );
633
+ }
634
+ const attr = store.attributes.get(attrId);
635
+ if (!attr || attr.entityId !== entityId) {
636
+ return c.json(
637
+ {
638
+ ok: false,
639
+ error: { code: "NOT_FOUND", message: "Attribute not found" }
640
+ },
641
+ 404
642
+ );
643
+ }
644
+ for (const record of store.records.values()) {
645
+ record.values = record.values.filter((v) => v.attributeId !== attrId);
646
+ }
647
+ store.attributes.delete(attrId);
648
+ return c.json({ ok: true, data: null });
649
+ });
650
+ app.get("/entities/:entityId/records/count", (c) => {
651
+ const entityId = c.req.param("entityId");
652
+ const entity = store.entities.get(entityId);
653
+ if (!entity || entity.brandappId !== brandappId) {
654
+ return c.json(
655
+ {
656
+ ok: false,
657
+ error: { code: "NOT_FOUND", message: "Entity not found" }
658
+ },
659
+ 404
660
+ );
661
+ }
662
+ const authUserId = c.req.query("authUserId");
663
+ const filtersJson = c.req.query("filters");
664
+ let records = store.getRecordsByEntity(entityId);
665
+ if (authUserId)
666
+ records = records.filter((r) => r.brandappAuthUserId === authUserId);
667
+ records = filterRecords(records, parseFilters(filtersJson));
668
+ return c.json({ ok: true, data: { total: records.length } });
669
+ });
670
+ app.get("/entities/:entityId/records", (c) => {
671
+ const entityId = c.req.param("entityId");
672
+ const entity = store.entities.get(entityId);
673
+ if (!entity || entity.brandappId !== brandappId) {
674
+ return c.json(
675
+ {
676
+ ok: false,
677
+ error: { code: "NOT_FOUND", message: "Entity not found" }
678
+ },
679
+ 404
680
+ );
681
+ }
682
+ const page = Number(c.req.query("page") || "1");
683
+ const limit = Math.min(Number(c.req.query("limit") || "50"), 100);
684
+ const authUserId = c.req.query("authUserId");
685
+ const sortBy = c.req.query("sortBy");
686
+ const sortOrder = c.req.query("sortOrder") || "desc";
687
+ const filtersJson = c.req.query("filters");
688
+ let records = store.getRecordsByEntity(entityId);
689
+ if (authUserId)
690
+ records = records.filter((r) => r.brandappAuthUserId === authUserId);
691
+ records = filterRecords(records, parseFilters(filtersJson));
692
+ records = sortRecords(records, sortBy, sortOrder);
693
+ const total = records.length;
694
+ const paged = records.slice((page - 1) * limit, page * limit);
695
+ return c.json({
696
+ ok: true,
697
+ data: {
698
+ records: paged.map(transformRecord),
699
+ total,
700
+ page,
701
+ limit,
702
+ totalPages: Math.ceil(total / limit)
703
+ }
704
+ });
705
+ });
706
+ app.post("/entities/:entityId/records", async (c) => {
707
+ const entityId = c.req.param("entityId");
708
+ const entity = store.entities.get(entityId);
709
+ if (!entity || entity.brandappId !== brandappId) {
710
+ return c.json(
711
+ {
712
+ ok: false,
713
+ error: { code: "NOT_FOUND", message: "Entity not found" }
714
+ },
715
+ 404
716
+ );
717
+ }
718
+ const body = await c.req.json();
719
+ const attrs = store.getAttributesByEntity(entityId);
720
+ const missing = validateRequiredFields(body.values ?? {}, attrs);
721
+ if (missing.length > 0) {
722
+ return c.json(validationErrorResponse(missing), 422);
723
+ }
724
+ const isAuthUserLinked = entity.linkedTo === "brandappAuthUser";
725
+ if (isAuthUserLinked) {
726
+ const check = checkBrandappAuthUserCreate(
727
+ store,
728
+ brandappId,
729
+ entityId,
730
+ body.authUserId
731
+ );
732
+ if (!check.ok) {
733
+ return c.json(
734
+ { ok: false, error: { code: "REQUEST_ERROR", message: check.error } },
735
+ check.status
736
+ );
737
+ }
738
+ } else {
739
+ const maxRecords = entity.maxRecords ?? LIMITS.RECORDS_PER_ENTITY;
740
+ const recordCount = store.count(
741
+ store.records,
742
+ (r) => r.entityId === entityId
743
+ );
744
+ if (recordCount >= maxRecords) {
745
+ return c.json(
746
+ {
747
+ ok: false,
748
+ error: {
749
+ code: "REQUEST_ERROR",
750
+ message: `Maximum ${maxRecords} records per entity`
751
+ }
752
+ },
753
+ 422
754
+ );
755
+ }
756
+ }
757
+ const now = store.now();
758
+ const recordId = isAuthUserLinked && body.authUserId ? body.authUserId : store.generateId();
759
+ const record = {
760
+ id: recordId,
761
+ entityId,
762
+ brandappAuthUserId: body.authUserId ?? null,
763
+ createdAt: now,
764
+ updatedAt: now,
765
+ values: Object.entries(body.values).map(([attributeId, value]) => ({
766
+ recordId: "",
767
+ attributeId,
768
+ value: typeof value === "string" ? value : JSON.stringify(value)
769
+ }))
770
+ };
771
+ record.values.forEach((v) => v.recordId = record.id);
772
+ store.records.set(record.id, record);
773
+ return c.json({ ok: true, data: transformRecord(record) }, 201);
774
+ });
775
+ app.get("/entities/:entityId/records/:id", (c) => {
776
+ const entityId = c.req.param("entityId");
777
+ const recordId = c.req.param("id");
778
+ const entity = store.entities.get(entityId);
779
+ if (!entity || entity.brandappId !== brandappId) {
780
+ return c.json(
781
+ {
782
+ ok: false,
783
+ error: { code: "NOT_FOUND", message: "Record not found" }
784
+ },
785
+ 404
786
+ );
787
+ }
788
+ const record = store.records.get(recordId);
789
+ if (!record || record.entityId !== entityId) {
790
+ return c.json(
791
+ {
792
+ ok: false,
793
+ error: { code: "NOT_FOUND", message: "Record not found" }
794
+ },
795
+ 404
796
+ );
797
+ }
798
+ return c.json({ ok: true, data: transformRecord(record) });
799
+ });
800
+ app.patch("/entities/:entityId/records/:id", async (c) => {
801
+ const entityId = c.req.param("entityId");
802
+ const recordId = c.req.param("id");
803
+ const entity = store.entities.get(entityId);
804
+ if (!entity || entity.brandappId !== brandappId) {
805
+ return c.json(
806
+ {
807
+ ok: false,
808
+ error: { code: "NOT_FOUND", message: "Record not found" }
809
+ },
810
+ 404
811
+ );
812
+ }
813
+ const record = store.records.get(recordId);
814
+ if (!record || record.entityId !== entityId) {
815
+ return c.json(
816
+ {
817
+ ok: false,
818
+ error: { code: "NOT_FOUND", message: "Record not found" }
819
+ },
820
+ 404
821
+ );
822
+ }
823
+ const body = await c.req.json();
824
+ for (const [attributeId, value] of Object.entries(body.values)) {
825
+ const serialized = typeof value === "string" ? value : JSON.stringify(value);
826
+ const existing = record.values.find((v) => v.attributeId === attributeId);
827
+ if (existing) {
828
+ existing.value = serialized;
829
+ } else {
830
+ record.values.push({ recordId, attributeId, value: serialized });
831
+ }
832
+ }
833
+ record.updatedAt = store.now();
834
+ return c.json({ ok: true, data: transformRecord(record) });
835
+ });
836
+ app.delete("/entities/:entityId/records/:id", (c) => {
837
+ const entityId = c.req.param("entityId");
838
+ const recordId = c.req.param("id");
839
+ const entity = store.entities.get(entityId);
840
+ if (!entity || entity.brandappId !== brandappId) {
841
+ return c.json(
842
+ {
843
+ ok: false,
844
+ error: { code: "NOT_FOUND", message: "Record not found" }
845
+ },
846
+ 404
847
+ );
848
+ }
849
+ const record = store.records.get(recordId);
850
+ if (!record || record.entityId !== entityId) {
851
+ return c.json(
852
+ {
853
+ ok: false,
854
+ error: { code: "NOT_FOUND", message: "Record not found" }
855
+ },
856
+ 404
857
+ );
858
+ }
859
+ store.records.delete(recordId);
860
+ return c.json({ ok: true, data: null });
861
+ });
862
+ app.post("/entities/:entityId/records/bulk", async (c) => {
863
+ const entityId = c.req.param("entityId");
864
+ const entity = store.entities.get(entityId);
865
+ if (!entity || entity.brandappId !== brandappId) {
866
+ return c.json(
867
+ {
868
+ ok: false,
869
+ error: { code: "NOT_FOUND", message: "Entity not found" }
870
+ },
871
+ 404
872
+ );
873
+ }
874
+ const body = await c.req.json();
875
+ if (body.records.length > LIMITS.BULK_BATCH_SIZE) {
876
+ return c.json(bulkSizeError("bulkCreate", body.records.length), 422);
877
+ }
878
+ const isAuthUserLinked = entity.linkedTo === "brandappAuthUser";
879
+ const attrs = store.getAttributesByEntity(entityId);
880
+ for (let i = 0; i < body.records.length; i++) {
881
+ const missing = validateRequiredFields(
882
+ body.records[i].values ?? {},
883
+ attrs
884
+ );
885
+ if (missing.length > 0) {
886
+ return c.json(
887
+ validationErrorResponse(
888
+ missing.map((m) => ({
889
+ ...m,
890
+ field: `records[${i}].${m.field}`
891
+ }))
892
+ ),
893
+ 422
894
+ );
895
+ }
896
+ }
897
+ if (isAuthUserLinked) {
898
+ const seen = /* @__PURE__ */ new Set();
899
+ for (let i = 0; i < body.records.length; i++) {
900
+ const r = body.records[i];
901
+ if (r.authUserId && seen.has(r.authUserId)) {
902
+ return c.json(
903
+ {
904
+ ok: false,
905
+ error: {
906
+ code: "REQUEST_ERROR",
907
+ message: "Duplicate authUserId in bulk create"
908
+ }
909
+ },
910
+ 409
911
+ );
912
+ }
913
+ if (r.authUserId) seen.add(r.authUserId);
914
+ const check = checkBrandappAuthUserCreate(
915
+ store,
916
+ brandappId,
917
+ entityId,
918
+ r.authUserId
919
+ );
920
+ if (!check.ok) {
921
+ return c.json(
922
+ {
923
+ ok: false,
924
+ error: { code: "REQUEST_ERROR", message: check.error }
925
+ },
926
+ check.status
927
+ );
928
+ }
929
+ }
930
+ } else {
931
+ const maxRecords = entity.maxRecords ?? LIMITS.RECORDS_PER_ENTITY;
932
+ const currentCount = store.count(
933
+ store.records,
934
+ (r) => r.entityId === entityId
935
+ );
936
+ if (currentCount + body.records.length > maxRecords) {
937
+ return c.json(
938
+ {
939
+ ok: false,
940
+ error: {
941
+ code: "REQUEST_ERROR",
942
+ message: `Would exceed maximum ${maxRecords} records per entity`
943
+ }
944
+ },
945
+ 422
946
+ );
947
+ }
948
+ }
949
+ const created = [];
950
+ for (const r of body.records) {
951
+ const now = store.now();
952
+ const recordId = isAuthUserLinked && r.authUserId ? r.authUserId : store.generateId();
953
+ const record = {
954
+ id: recordId,
955
+ entityId,
956
+ brandappAuthUserId: r.authUserId ?? null,
957
+ createdAt: now,
958
+ updatedAt: now,
959
+ values: Object.entries(r.values).map(([attributeId, value]) => ({
960
+ recordId: "",
961
+ attributeId,
962
+ value: typeof value === "string" ? value : JSON.stringify(value)
963
+ }))
964
+ };
965
+ record.values.forEach((v) => v.recordId = record.id);
966
+ store.records.set(record.id, record);
967
+ created.push(transformRecord(record));
968
+ }
969
+ return c.json({ ok: true, data: created }, 201);
970
+ });
971
+ app.patch("/entities/:entityId/records", async (c) => {
972
+ const entityId = c.req.param("entityId");
973
+ const entity = store.entities.get(entityId);
974
+ if (!entity || entity.brandappId !== brandappId) {
975
+ return c.json(
976
+ {
977
+ ok: false,
978
+ error: { code: "NOT_FOUND", message: "Entity not found" }
979
+ },
980
+ 404
981
+ );
982
+ }
983
+ const body = await c.req.json();
984
+ if (body.updates.length > LIMITS.BULK_BATCH_SIZE) {
985
+ return c.json(bulkSizeError("bulkUpdate", body.updates.length), 422);
986
+ }
987
+ const results = [];
988
+ for (const u of body.updates) {
989
+ const record = store.records.get(u.id);
990
+ if (!record || record.entityId !== entityId) {
991
+ return c.json(
992
+ {
993
+ ok: false,
994
+ error: { code: "REQUEST_ERROR", message: "Some records not found" }
995
+ },
996
+ 400
997
+ );
998
+ }
999
+ for (const [attributeId, value] of Object.entries(u.values)) {
1000
+ const serialized = typeof value === "string" ? value : JSON.stringify(value);
1001
+ const existing = record.values.find(
1002
+ (v) => v.attributeId === attributeId
1003
+ );
1004
+ if (existing) {
1005
+ existing.value = serialized;
1006
+ } else {
1007
+ record.values.push({
1008
+ recordId: record.id,
1009
+ attributeId,
1010
+ value: serialized
1011
+ });
1012
+ }
1013
+ }
1014
+ record.updatedAt = store.now();
1015
+ results.push(transformRecord(record));
1016
+ }
1017
+ return c.json({ ok: true, data: results });
1018
+ });
1019
+ app.delete("/entities/:entityId/records", async (c) => {
1020
+ const entityId = c.req.param("entityId");
1021
+ const entity = store.entities.get(entityId);
1022
+ if (!entity || entity.brandappId !== brandappId) {
1023
+ return c.json(
1024
+ {
1025
+ ok: false,
1026
+ error: { code: "NOT_FOUND", message: "Entity not found" }
1027
+ },
1028
+ 404
1029
+ );
1030
+ }
1031
+ const body = await c.req.json();
1032
+ if (body.ids.length > LIMITS.BULK_BATCH_SIZE) {
1033
+ return c.json(bulkSizeError("bulkDelete", body.ids.length), 422);
1034
+ }
1035
+ let count = 0;
1036
+ for (const id of body.ids) {
1037
+ const record = store.records.get(id);
1038
+ if (record && record.entityId === entityId) {
1039
+ store.records.delete(id);
1040
+ count++;
1041
+ }
1042
+ }
1043
+ return c.json({ ok: true, data: { count } });
1044
+ });
1045
+ app.put("/entities/:entityId/records/upsert", async (c) => {
1046
+ const entityId = c.req.param("entityId");
1047
+ const entity = store.entities.get(entityId);
1048
+ if (!entity || entity.brandappId !== brandappId) {
1049
+ return c.json(
1050
+ {
1051
+ ok: false,
1052
+ error: { code: "NOT_FOUND", message: "Entity not found" }
1053
+ },
1054
+ 404
1055
+ );
1056
+ }
1057
+ const body = await c.req.json();
1058
+ const isAuthUserLinked = entity.linkedTo === "brandappAuthUser";
1059
+ if (isAuthUserLinked) {
1060
+ if (!body.authUserId) {
1061
+ return c.json(
1062
+ {
1063
+ ok: false,
1064
+ error: {
1065
+ code: "REQUEST_ERROR",
1066
+ message: "authUserId is required for brandappAuthUser-linked entities"
1067
+ }
1068
+ },
1069
+ 400
1070
+ );
1071
+ }
1072
+ const user = store.findFirst(
1073
+ store.authUsers,
1074
+ (u) => u.id === body.authUserId && u.brandappId === brandappId
1075
+ );
1076
+ if (!user) {
1077
+ return c.json(
1078
+ {
1079
+ ok: false,
1080
+ error: {
1081
+ code: "REQUEST_ERROR",
1082
+ message: "Auth user not found in this brandapp"
1083
+ }
1084
+ },
1085
+ 422
1086
+ );
1087
+ }
1088
+ }
1089
+ let candidates = store.getRecordsByEntity(entityId);
1090
+ if (body.authUserId) {
1091
+ candidates = candidates.filter(
1092
+ (r) => r.brandappAuthUserId === body.authUserId
1093
+ );
1094
+ }
1095
+ const matched = isAuthUserLinked ? candidates[0] : filterRecords(candidates, body.filters)[0];
1096
+ if (matched) {
1097
+ for (const [attributeId, value] of Object.entries(body.values)) {
1098
+ const serialized = typeof value === "string" ? value : JSON.stringify(value);
1099
+ const existing = matched.values.find(
1100
+ (v) => v.attributeId === attributeId
1101
+ );
1102
+ if (existing) {
1103
+ existing.value = serialized;
1104
+ } else {
1105
+ matched.values.push({
1106
+ recordId: matched.id,
1107
+ attributeId,
1108
+ value: serialized
1109
+ });
1110
+ }
1111
+ }
1112
+ matched.updatedAt = store.now();
1113
+ return c.json({
1114
+ ok: true,
1115
+ data: { record: transformRecord(matched), created: false }
1116
+ });
1117
+ }
1118
+ if (!isAuthUserLinked) {
1119
+ const maxRecords = entity.maxRecords ?? LIMITS.RECORDS_PER_ENTITY;
1120
+ const recordCount = store.count(
1121
+ store.records,
1122
+ (r) => r.entityId === entityId
1123
+ );
1124
+ if (recordCount >= maxRecords) {
1125
+ return c.json(
1126
+ {
1127
+ ok: false,
1128
+ error: {
1129
+ code: "REQUEST_ERROR",
1130
+ message: `Maximum ${maxRecords} records per entity`
1131
+ }
1132
+ },
1133
+ 422
1134
+ );
1135
+ }
1136
+ }
1137
+ const now = store.now();
1138
+ const newRecordId = isAuthUserLinked && body.authUserId ? body.authUserId : store.generateId();
1139
+ const newRecord = {
1140
+ id: newRecordId,
1141
+ entityId,
1142
+ brandappAuthUserId: body.authUserId ?? null,
1143
+ createdAt: now,
1144
+ updatedAt: now,
1145
+ values: Object.entries(body.values).map(([attributeId, value]) => ({
1146
+ recordId: "",
1147
+ attributeId,
1148
+ value: typeof value === "string" ? value : JSON.stringify(value)
1149
+ }))
1150
+ };
1151
+ newRecord.values.forEach((v) => v.recordId = newRecord.id);
1152
+ store.records.set(newRecord.id, newRecord);
1153
+ return c.json(
1154
+ { ok: true, data: { record: transformRecord(newRecord), created: true } },
1155
+ 201
1156
+ );
1157
+ });
1158
+ app.post("/entities/:entityId/records/delete-where", async (c) => {
1159
+ const entityId = c.req.param("entityId");
1160
+ const entity = store.entities.get(entityId);
1161
+ if (!entity || entity.brandappId !== brandappId) {
1162
+ return c.json(
1163
+ {
1164
+ ok: false,
1165
+ error: { code: "NOT_FOUND", message: "Entity not found" }
1166
+ },
1167
+ 404
1168
+ );
1169
+ }
1170
+ const body = await c.req.json();
1171
+ let candidates = store.getRecordsByEntity(entityId);
1172
+ if (body.authUserId) {
1173
+ candidates = candidates.filter(
1174
+ (r) => r.brandappAuthUserId === body.authUserId
1175
+ );
1176
+ }
1177
+ const matching = filterRecords(candidates, body.filters);
1178
+ for (const r of matching) store.records.delete(r.id);
1179
+ return c.json({ ok: true, data: { count: matching.length } });
1180
+ });
1181
+ app.get("/users/:authUserId/records", (c) => {
1182
+ const authUserId = c.req.param("authUserId");
1183
+ const user = store.findFirst(
1184
+ store.authUsers,
1185
+ (u) => u.id === authUserId && u.brandappId === brandappId
1186
+ );
1187
+ if (!user) {
1188
+ return c.json(
1189
+ { ok: false, error: { code: "NOT_FOUND", message: "User not found" } },
1190
+ 404
1191
+ );
1192
+ }
1193
+ const page = Number(c.req.query("page") || "1");
1194
+ const limit = Math.min(Number(c.req.query("limit") || "50"), 100);
1195
+ const sortOrder = c.req.query("sortOrder") || "desc";
1196
+ const entityIds = new Set(
1197
+ store.getEntitiesByBrandapp(brandappId).map((e) => e.id)
1198
+ );
1199
+ let records = store.findMany(
1200
+ store.records,
1201
+ (r) => r.brandappAuthUserId === authUserId && entityIds.has(r.entityId)
1202
+ );
1203
+ records = sortRecords(records, "createdAt", sortOrder);
1204
+ const total = records.length;
1205
+ const paged = records.slice((page - 1) * limit, page * limit);
1206
+ return c.json({
1207
+ ok: true,
1208
+ data: {
1209
+ records: paged.map(transformRecord),
1210
+ total,
1211
+ page,
1212
+ limit,
1213
+ totalPages: Math.ceil(total / limit)
1214
+ }
1215
+ });
1216
+ });
1217
+ return app;
1218
+ }
1219
+ var MODEL_MAP = {
1220
+ user: "authUsers",
1221
+ session: "authSessions",
1222
+ account: "authAccounts",
1223
+ verification: "authVerifications"
1224
+ };
1225
+ function matchesWhere(item, whereList) {
1226
+ for (const w of whereList) {
1227
+ const fieldValue = item[w.field];
1228
+ const operator = w.operator ?? "eq";
1229
+ switch (operator) {
1230
+ case "eq":
1231
+ if (fieldValue !== w.value) return false;
1232
+ break;
1233
+ case "ne":
1234
+ if (fieldValue === w.value) return false;
1235
+ break;
1236
+ case "in":
1237
+ if (!Array.isArray(w.value) || !w.value.includes(fieldValue))
1238
+ return false;
1239
+ break;
1240
+ case "contains":
1241
+ if (typeof fieldValue !== "string" || typeof w.value !== "string" || !fieldValue.includes(w.value))
1242
+ return false;
1243
+ break;
1244
+ case "starts_with":
1245
+ if (typeof fieldValue !== "string" || typeof w.value !== "string" || !fieldValue.startsWith(w.value))
1246
+ return false;
1247
+ break;
1248
+ case "ends_with":
1249
+ if (typeof fieldValue !== "string" || typeof w.value !== "string" || !fieldValue.endsWith(w.value))
1250
+ return false;
1251
+ break;
1252
+ case "gt":
1253
+ if (fieldValue === void 0 || fieldValue === null) return false;
1254
+ if (fieldValue <= w.value) return false;
1255
+ break;
1256
+ case "gte":
1257
+ if (fieldValue === void 0 || fieldValue === null) return false;
1258
+ if (fieldValue < w.value) return false;
1259
+ break;
1260
+ case "lt":
1261
+ if (fieldValue === void 0 || fieldValue === null) return false;
1262
+ if (fieldValue >= w.value) return false;
1263
+ break;
1264
+ case "lte":
1265
+ if (fieldValue === void 0 || fieldValue === null) return false;
1266
+ if (fieldValue > w.value) return false;
1267
+ break;
1268
+ default:
1269
+ if (fieldValue !== w.value) return false;
1270
+ }
1271
+ }
1272
+ return true;
1273
+ }
1274
+ function applySelect(item, select) {
1275
+ if (!select || select.length === 0) return item;
1276
+ const result = {};
1277
+ for (const field of select) {
1278
+ result[field] = item[field];
1279
+ }
1280
+ return result;
1281
+ }
1282
+ function createAuthRoutes(store, brandappId) {
1283
+ const app = new Hono();
1284
+ app.post("/adapter", async (c) => {
1285
+ const request = await c.req.json();
1286
+ const {
1287
+ operation,
1288
+ model,
1289
+ data,
1290
+ where,
1291
+ update,
1292
+ select,
1293
+ limit,
1294
+ offset,
1295
+ sortBy
1296
+ } = request;
1297
+ if (!model || !(model in MODEL_MAP)) {
1298
+ return c.json(
1299
+ {
1300
+ error: {
1301
+ code: "REQUEST_ERROR",
1302
+ message: `Model "${String(model)}" not supported`
1303
+ }
1304
+ },
1305
+ 400
1306
+ );
1307
+ }
1308
+ const storeKey = MODEL_MAP[model];
1309
+ const map = store[storeKey];
1310
+ const enrichedWhere = [
1311
+ ...where ?? [],
1312
+ { field: "brandappId", value: brandappId }
1313
+ ];
1314
+ switch (operation) {
1315
+ case "create": {
1316
+ const { id: _ignoredId, ...restData } = data ?? {};
1317
+ const now = store.now();
1318
+ const newItem = {
1319
+ ...restData,
1320
+ id: store.generateId(),
1321
+ brandappId,
1322
+ createdAt: now,
1323
+ updatedAt: now
1324
+ };
1325
+ map.set(newItem.id, newItem);
1326
+ return c.json({ data: applySelect(newItem, select) });
1327
+ }
1328
+ case "findOne": {
1329
+ for (const item of map.values()) {
1330
+ if (matchesWhere(item, enrichedWhere)) {
1331
+ return c.json({ data: applySelect(item, select) });
1332
+ }
1333
+ }
1334
+ return c.json({ data: null });
1335
+ }
1336
+ case "findMany": {
1337
+ const results = [];
1338
+ for (const item of map.values()) {
1339
+ if (matchesWhere(item, enrichedWhere)) {
1340
+ results.push(applySelect(item, select));
1341
+ }
1342
+ }
1343
+ if (sortBy?.field) {
1344
+ const dir = sortBy.direction === "desc" ? -1 : 1;
1345
+ results.sort((a, b) => {
1346
+ const av = a[sortBy.field];
1347
+ const bv = b[sortBy.field];
1348
+ if (av === bv) return 0;
1349
+ if (av === void 0 || av === null) return 1;
1350
+ if (bv === void 0 || bv === null) return -1;
1351
+ if (av instanceof Date && bv instanceof Date)
1352
+ return (av.getTime() - bv.getTime()) * dir;
1353
+ return String(av).localeCompare(String(bv)) * dir;
1354
+ });
1355
+ }
1356
+ const start = offset ?? 0;
1357
+ const end = start + (limit ?? 100);
1358
+ return c.json({ data: results.slice(start, end) });
1359
+ }
1360
+ case "update": {
1361
+ for (const item of map.values()) {
1362
+ if (matchesWhere(item, enrichedWhere)) {
1363
+ Object.assign(item, update, { updatedAt: store.now() });
1364
+ return c.json({ data: applySelect(item, select) });
1365
+ }
1366
+ }
1367
+ return c.json({ data: null });
1368
+ }
1369
+ case "updateMany": {
1370
+ let count = 0;
1371
+ for (const item of map.values()) {
1372
+ if (matchesWhere(item, enrichedWhere)) {
1373
+ Object.assign(item, update, { updatedAt: store.now() });
1374
+ count++;
1375
+ }
1376
+ }
1377
+ return c.json({ data: count });
1378
+ }
1379
+ case "delete": {
1380
+ const hasId = where?.some((w) => w.field === "id");
1381
+ if (!hasId) {
1382
+ const toDelete = [];
1383
+ for (const item of map.values()) {
1384
+ if (matchesWhere(item, enrichedWhere)) {
1385
+ toDelete.push(item.id);
1386
+ }
1387
+ }
1388
+ for (const id of toDelete) map.delete(id);
1389
+ return c.json({ data: null });
1390
+ }
1391
+ for (const item of map.values()) {
1392
+ if (matchesWhere(item, enrichedWhere)) {
1393
+ map.delete(item.id);
1394
+ return c.json({ data: null });
1395
+ }
1396
+ }
1397
+ return c.json({ data: null });
1398
+ }
1399
+ case "deleteMany": {
1400
+ const toDelete = [];
1401
+ for (const item of map.values()) {
1402
+ if (matchesWhere(item, enrichedWhere)) {
1403
+ toDelete.push(item.id);
1404
+ }
1405
+ }
1406
+ for (const id of toDelete) map.delete(id);
1407
+ return c.json({ data: toDelete.length });
1408
+ }
1409
+ case "count": {
1410
+ let count = 0;
1411
+ for (const item of map.values()) {
1412
+ if (matchesWhere(item, enrichedWhere)) count++;
1413
+ }
1414
+ return c.json({ data: count });
1415
+ }
1416
+ default:
1417
+ return c.json(
1418
+ {
1419
+ error: {
1420
+ code: "REQUEST_ERROR",
1421
+ message: `Unsupported operation: ${operation}`
1422
+ }
1423
+ },
1424
+ 400
1425
+ );
1426
+ }
1427
+ });
1428
+ return app;
1429
+ }
1430
+ var MOCK_MODELS = [
1431
+ {
1432
+ id: "anthropic/claude-haiku-4.5",
1433
+ tier: "standard",
1434
+ tierLabel: "Standard",
1435
+ inputRate: 0.25,
1436
+ outputRate: 1.25
1437
+ },
1438
+ {
1439
+ id: "openai/gpt-4o-mini",
1440
+ tier: "economy",
1441
+ tierLabel: "Economy",
1442
+ inputRate: 0.15,
1443
+ outputRate: 0.6
1444
+ }
1445
+ ];
1446
+ var INITIAL_CREDIT_LIMIT = 1e4;
1447
+ var COMPLETION_COST = 1;
1448
+ var IMAGE_COST = 10;
1449
+ function generateMockResponse(messages) {
1450
+ const lastMessage = messages[messages.length - 1];
1451
+ const content = lastMessage?.content ?? "";
1452
+ return `[Dev Mode] Mock response. You said: "${content.slice(0, 100)}${content.length > 100 ? "..." : ""}"`;
1453
+ }
1454
+ function creditStatus(balance, limit) {
1455
+ const used = 1 - balance / limit;
1456
+ const percentage = Math.min(1, Math.max(0, used));
1457
+ const status = percentage >= 1 ? "exhausted" : percentage >= 0.95 ? "critical" : percentage >= 0.8 ? "warning" : "normal";
1458
+ return {
1459
+ balance,
1460
+ limit,
1461
+ percentage: Math.round(percentage * 1e4) / 1e4,
1462
+ resetAt: null,
1463
+ status
1464
+ };
1465
+ }
1466
+ function createAiRoutes() {
1467
+ const app = new Hono();
1468
+ let creditsRemaining = INITIAL_CREDIT_LIMIT;
1469
+ app.get("/models", (c) => c.json({ ok: true, data: MOCK_MODELS }));
1470
+ app.get(
1471
+ "/credits",
1472
+ (c) => c.json({
1473
+ ok: true,
1474
+ data: creditStatus(creditsRemaining, INITIAL_CREDIT_LIMIT)
1475
+ })
1476
+ );
1477
+ app.get("/agents", (c) => c.json({ ok: true, data: [] }));
1478
+ app.post("/chat/completions", async (c) => {
1479
+ const body = await c.req.json();
1480
+ const responseText = generateMockResponse(body.messages);
1481
+ const promptTokens = body.messages.reduce(
1482
+ (n, m) => n + Math.ceil(m.content.length / 4),
1483
+ 0
1484
+ );
1485
+ const completionTokens = Math.ceil(responseText.length / 4);
1486
+ creditsRemaining = Math.max(0, creditsRemaining - COMPLETION_COST);
1487
+ const usage = {
1488
+ promptTokens,
1489
+ completionTokens,
1490
+ creditCost: COMPLETION_COST
1491
+ };
1492
+ const modelId = body.model ?? MOCK_MODELS[0].id;
1493
+ if (body.stream) {
1494
+ const encoder = new TextEncoder();
1495
+ const stream = new ReadableStream({
1496
+ start(controller) {
1497
+ const words = responseText.split(/(\s+)/);
1498
+ for (const word of words) {
1499
+ if (!word) continue;
1500
+ controller.enqueue(
1501
+ encoder.encode(`event: text-delta
1502
+ data: ${word}
1503
+
1504
+ `)
1505
+ );
1506
+ }
1507
+ controller.enqueue(
1508
+ encoder.encode(
1509
+ `event: done
1510
+ data: ${JSON.stringify({ usage, creditsRemaining })}
1511
+
1512
+ `
1513
+ )
1514
+ );
1515
+ controller.close();
1516
+ }
1517
+ });
1518
+ return new Response(stream, {
1519
+ headers: {
1520
+ "Content-Type": "text/event-stream",
1521
+ "Cache-Control": "no-cache",
1522
+ Connection: "keep-alive"
1523
+ }
1524
+ });
1525
+ }
1526
+ return c.json({
1527
+ ok: true,
1528
+ data: {
1529
+ id: `dev_chat_${Date.now()}`,
1530
+ model: modelId,
1531
+ message: { role: "assistant", content: responseText },
1532
+ usage,
1533
+ creditsRemaining
1534
+ }
1535
+ });
1536
+ });
1537
+ app.post("/images/generate", async (c) => {
1538
+ await c.req.json();
1539
+ creditsRemaining = Math.max(0, creditsRemaining - IMAGE_COST);
1540
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256"><rect width="256" height="256" fill="#f0f0f0"/><text x="128" y="128" text-anchor="middle" fill="#666" font-size="14">Dev Mode</text></svg>`;
1541
+ const dataUrl = `data:image/svg+xml,${encodeURIComponent(svg)}`;
1542
+ return c.json({
1543
+ ok: true,
1544
+ data: {
1545
+ id: `dev_img_${Date.now()}`,
1546
+ url: dataUrl,
1547
+ size: svg.length,
1548
+ contentType: "image/svg+xml",
1549
+ usage: { creditCost: IMAGE_COST },
1550
+ creditsRemaining
1551
+ }
1552
+ });
1553
+ });
1554
+ return app;
1555
+ }
1556
+ function toFileInfo(f) {
1557
+ return {
1558
+ id: f.id,
1559
+ name: f.name,
1560
+ url: f.url,
1561
+ size: f.size,
1562
+ contentType: f.contentType,
1563
+ pathname: `dev/${f.id}/${f.name}`,
1564
+ createdAt: f.createdAt.toISOString(),
1565
+ updatedAt: f.updatedAt.toISOString()
1566
+ };
1567
+ }
1568
+ function createFilesRoutes(store, brandappId) {
1569
+ const fileContents = /* @__PURE__ */ new Map();
1570
+ const app = new Hono();
1571
+ app.get("/", (c) => {
1572
+ const page = Number(c.req.query("page") || "1");
1573
+ const limit = Math.min(Number(c.req.query("limit") || "50"), 100);
1574
+ const files = store.findMany(store.files, (f) => f.brandappId === brandappId).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
1575
+ const total = files.length;
1576
+ const paged = files.slice((page - 1) * limit, page * limit);
1577
+ return c.json({
1578
+ data: paged.map(toFileInfo),
1579
+ meta: { page, limit, total }
1580
+ });
1581
+ });
1582
+ app.get("/:fileId", (c) => {
1583
+ const fileId = c.req.param("fileId");
1584
+ const file = store.files.get(fileId);
1585
+ if (!file || file.brandappId !== brandappId) {
1586
+ return c.json(
1587
+ { error: { code: "NOT_FOUND", message: "File not found" } },
1588
+ 404
1589
+ );
1590
+ }
1591
+ return c.json({ data: toFileInfo(file) });
1592
+ });
1593
+ app.post("/upload", async (c) => {
1594
+ const contentType = c.req.header("content-type") || "";
1595
+ let name = "untitled";
1596
+ let fileContentType = "application/octet-stream";
1597
+ let buffer;
1598
+ if (contentType.includes("multipart/form-data")) {
1599
+ const formData = await c.req.formData();
1600
+ const file = formData.get("file");
1601
+ if (!file) {
1602
+ return c.json(
1603
+ {
1604
+ error: { code: "VALIDATION_ERROR", message: "No file provided" }
1605
+ },
1606
+ 400
1607
+ );
1608
+ }
1609
+ name = file.name;
1610
+ fileContentType = file.type || "application/octet-stream";
1611
+ buffer = await file.arrayBuffer();
1612
+ } else {
1613
+ buffer = await c.req.arrayBuffer();
1614
+ name = c.req.query("name") || "untitled";
1615
+ fileContentType = contentType || "application/octet-stream";
1616
+ }
1617
+ const now = store.now();
1618
+ const fileRecord = {
1619
+ id: store.generateId(),
1620
+ brandappId,
1621
+ name,
1622
+ contentType: fileContentType,
1623
+ size: buffer.byteLength,
1624
+ url: `http://localhost/dev-files/${store.generateId()}`,
1625
+ createdAt: now,
1626
+ updatedAt: now
1627
+ };
1628
+ store.files.set(fileRecord.id, fileRecord);
1629
+ fileContents.set(fileRecord.id, buffer);
1630
+ return c.json({ data: toFileInfo(fileRecord) }, 201);
1631
+ });
1632
+ app.delete("/:fileId", (c) => {
1633
+ const fileId = c.req.param("fileId");
1634
+ const file = store.files.get(fileId);
1635
+ if (!file || file.brandappId !== brandappId) {
1636
+ return c.json(
1637
+ { error: { code: "NOT_FOUND", message: "File not found" } },
1638
+ 404
1639
+ );
1640
+ }
1641
+ store.files.delete(fileId);
1642
+ fileContents.delete(fileId);
1643
+ return c.json({ data: null });
1644
+ });
1645
+ return app;
1646
+ }
1647
+ function slugify(s) {
1648
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "post";
1649
+ }
1650
+ var EMPTY_EDITOR_SPEC = { root: [], elements: {}, version: 1 };
1651
+ function toPost(p, group) {
1652
+ return {
1653
+ id: p.id,
1654
+ slug: p.slug,
1655
+ title: p.title,
1656
+ status: p.status ?? "draft",
1657
+ publishedAt: p.publishedAt ? p.publishedAt.toISOString() : null,
1658
+ createdAt: p.createdAt.toISOString(),
1659
+ updatedAt: p.updatedAt.toISOString(),
1660
+ author: p.author,
1661
+ icon: p.icon,
1662
+ coverImage: p.coverImage,
1663
+ group: group ? { id: group.id, name: group.name } : { id: "", name: "" },
1664
+ tags: p.tags,
1665
+ seo: p.seo
1666
+ };
1667
+ }
1668
+ function toPostDetail(p, group) {
1669
+ return {
1670
+ ...toPost(p, group),
1671
+ document: {
1672
+ id: p.id,
1673
+ content: p.content,
1674
+ contentRich: p.contentRich ?? EMPTY_EDITOR_SPEC
1675
+ }
1676
+ };
1677
+ }
1678
+ function toPostGroup(g, postCount) {
1679
+ return {
1680
+ id: g.id,
1681
+ name: g.name,
1682
+ slug: g.slug,
1683
+ color: g.color,
1684
+ createdAt: g.createdAt.toISOString(),
1685
+ updatedAt: g.updatedAt.toISOString(),
1686
+ brand: g.brand,
1687
+ postCount
1688
+ };
1689
+ }
1690
+ function createCmsRoutes(store, brandappId) {
1691
+ const app = new Hono();
1692
+ function findGroup(post) {
1693
+ return post.groupId ? store.postGroups.get(post.groupId) ?? null : null;
1694
+ }
1695
+ function matchGroupSlug(post, slug) {
1696
+ const g = findGroup(post);
1697
+ return g?.slug === slug;
1698
+ }
1699
+ app.get("/posts", (c) => {
1700
+ const status = c.req.query("status");
1701
+ const groupId = c.req.query("groupId");
1702
+ const groupSlug = c.req.query("groupSlug");
1703
+ const page = Number(c.req.query("page") || "1");
1704
+ const limit = Math.min(Number(c.req.query("limit") || "50"), 100);
1705
+ let posts = store.findMany(store.posts, (p) => p.brandappId === brandappId);
1706
+ if (status) posts = posts.filter((p) => p.status === status);
1707
+ if (groupId) posts = posts.filter((p) => p.groupId === groupId);
1708
+ if (groupSlug) posts = posts.filter((p) => matchGroupSlug(p, groupSlug));
1709
+ const search = c.req.query("search");
1710
+ if (search) {
1711
+ const q = search.toLowerCase();
1712
+ posts = posts.filter(
1713
+ (p) => p.title.toLowerCase().includes(q) || p.content.toLowerCase().includes(q)
1714
+ );
1715
+ }
1716
+ const tagsParam = c.req.query("tags");
1717
+ if (tagsParam) {
1718
+ let wanted;
1719
+ try {
1720
+ const parsed = JSON.parse(tagsParam);
1721
+ wanted = Array.isArray(parsed) ? parsed.map(String) : [String(parsed)];
1722
+ } catch {
1723
+ wanted = tagsParam.split(",").map((t) => t.trim()).filter(Boolean);
1724
+ }
1725
+ if (wanted.length > 0) {
1726
+ posts = posts.filter(
1727
+ (p) => p.tags.some((t) => wanted.includes(t.text))
1728
+ );
1729
+ }
1730
+ }
1731
+ posts.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
1732
+ const total = posts.length;
1733
+ const paged = posts.slice((page - 1) * limit, page * limit);
1734
+ const records = paged.map((p) => toPost(p, findGroup(p)));
1735
+ return c.json({
1736
+ ok: true,
1737
+ data: {
1738
+ records,
1739
+ total,
1740
+ page,
1741
+ limit,
1742
+ totalPages: Math.ceil(total / limit)
1743
+ }
1744
+ });
1745
+ });
1746
+ app.get("/posts/by-slug/:slug", (c) => {
1747
+ const slug = c.req.param("slug");
1748
+ const groupId = c.req.query("groupId");
1749
+ const groupSlug = c.req.query("groupSlug");
1750
+ const post = store.findFirst(
1751
+ store.posts,
1752
+ (p) => p.brandappId === brandappId && p.slug === slug && (groupId ? p.groupId === groupId : true) && (groupSlug ? matchGroupSlug(p, groupSlug) : true)
1753
+ );
1754
+ if (!post) {
1755
+ return c.json(
1756
+ { ok: false, error: { code: "NOT_FOUND", message: "Post not found" } },
1757
+ 404
1758
+ );
1759
+ }
1760
+ return c.json({ ok: true, data: toPostDetail(post, findGroup(post)) });
1761
+ });
1762
+ app.get("/posts/:postId", (c) => {
1763
+ const postId = c.req.param("postId");
1764
+ const post = store.posts.get(postId);
1765
+ if (!post || post.brandappId !== brandappId) {
1766
+ return c.json(
1767
+ { ok: false, error: { code: "NOT_FOUND", message: "Post not found" } },
1768
+ 404
1769
+ );
1770
+ }
1771
+ return c.json({ ok: true, data: toPostDetail(post, findGroup(post)) });
1772
+ });
1773
+ app.post("/posts", async (c) => {
1774
+ const body = await c.req.json();
1775
+ const now = store.now();
1776
+ const post = {
1777
+ id: store.generateId(),
1778
+ brandappId,
1779
+ slug: body.slug ?? slugify(body.title),
1780
+ title: body.title,
1781
+ content: body.content ?? "",
1782
+ contentRich: null,
1783
+ status: body.status ?? "draft",
1784
+ groupId: body.groupId ?? null,
1785
+ publishedAt: null,
1786
+ coverImage: null,
1787
+ author: { id: "dev-user", name: "Dev User", image: null },
1788
+ icon: null,
1789
+ tags: (body.tags ?? []).map(
1790
+ (t) => typeof t === "string" ? { id: `tag:${t}`, text: t } : t
1791
+ ),
1792
+ seo: { metaTitle: null, metaDescription: null, metaKeywords: null },
1793
+ createdAt: now,
1794
+ updatedAt: now
1795
+ };
1796
+ store.posts.set(post.id, post);
1797
+ return c.json({ ok: true, data: toPostDetail(post, findGroup(post)) }, 201);
1798
+ });
1799
+ app.put("/posts/:postId", async (c) => {
1800
+ const postId = c.req.param("postId");
1801
+ const post = store.posts.get(postId);
1802
+ if (!post || post.brandappId !== brandappId) {
1803
+ return c.json(
1804
+ { ok: false, error: { code: "NOT_FOUND", message: "Post not found" } },
1805
+ 404
1806
+ );
1807
+ }
1808
+ const body = await c.req.json();
1809
+ if (body.title !== void 0) post.title = body.title;
1810
+ if (body.slug !== void 0) post.slug = body.slug;
1811
+ if (body.content !== void 0) post.content = body.content;
1812
+ if (body.status !== void 0) post.status = body.status;
1813
+ if (body.groupId !== void 0)
1814
+ post.groupId = body.groupId;
1815
+ if (body.tags !== void 0) {
1816
+ const raw = body.tags;
1817
+ post.tags = raw.map(
1818
+ (t) => typeof t === "string" ? { id: `tag:${t}`, text: t } : t
1819
+ );
1820
+ }
1821
+ post.updatedAt = store.now();
1822
+ return c.json({ ok: true, data: toPostDetail(post, findGroup(post)) });
1823
+ });
1824
+ app.delete("/posts/:postId", (c) => {
1825
+ const postId = c.req.param("postId");
1826
+ const post = store.posts.get(postId);
1827
+ if (!post || post.brandappId !== brandappId) {
1828
+ return c.json(
1829
+ { ok: false, error: { code: "NOT_FOUND", message: "Post not found" } },
1830
+ 404
1831
+ );
1832
+ }
1833
+ store.posts.delete(postId);
1834
+ return c.json({ ok: true, data: null });
1835
+ });
1836
+ app.get("/post-groups", (c) => {
1837
+ const page = Number(c.req.query("page") || "1");
1838
+ const limit = Math.min(Number(c.req.query("limit") || "50"), 100);
1839
+ const groups = store.findMany(store.postGroups, (g) => g.brandappId === brandappId).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
1840
+ const total = groups.length;
1841
+ const paged = groups.slice((page - 1) * limit, page * limit);
1842
+ const records = paged.map(
1843
+ (g) => toPostGroup(
1844
+ g,
1845
+ store.count(
1846
+ store.posts,
1847
+ (p) => p.brandappId === brandappId && p.groupId === g.id
1848
+ )
1849
+ )
1850
+ );
1851
+ return c.json({
1852
+ ok: true,
1853
+ data: {
1854
+ records,
1855
+ total,
1856
+ page,
1857
+ limit,
1858
+ totalPages: Math.ceil(total / limit)
1859
+ }
1860
+ });
1861
+ });
1862
+ app.get("/post-groups/by-slug/:slug", (c) => {
1863
+ const slug = c.req.param("slug");
1864
+ const group = store.findFirst(
1865
+ store.postGroups,
1866
+ (g) => g.brandappId === brandappId && g.slug === slug
1867
+ );
1868
+ if (!group) {
1869
+ return c.json(
1870
+ { ok: false, error: { code: "NOT_FOUND", message: "Group not found" } },
1871
+ 404
1872
+ );
1873
+ }
1874
+ const postCount = store.count(
1875
+ store.posts,
1876
+ (p) => p.brandappId === brandappId && p.groupId === group.id
1877
+ );
1878
+ return c.json({ ok: true, data: toPostGroup(group, postCount) });
1879
+ });
1880
+ app.get("/post-groups/:groupId", (c) => {
1881
+ const groupId = c.req.param("groupId");
1882
+ const group = store.postGroups.get(groupId);
1883
+ if (!group || group.brandappId !== brandappId) {
1884
+ return c.json(
1885
+ { ok: false, error: { code: "NOT_FOUND", message: "Group not found" } },
1886
+ 404
1887
+ );
1888
+ }
1889
+ const postCount = store.count(
1890
+ store.posts,
1891
+ (p) => p.brandappId === brandappId && p.groupId === group.id
1892
+ );
1893
+ return c.json({ ok: true, data: toPostGroup(group, postCount) });
1894
+ });
1895
+ app.post("/post-groups", async (c) => {
1896
+ const body = await c.req.json();
1897
+ const now = store.now();
1898
+ const group = {
1899
+ id: store.generateId(),
1900
+ brandappId,
1901
+ slug: body.slug ?? null,
1902
+ name: body.name,
1903
+ description: body.description ?? null,
1904
+ color: body.color ?? "indigo",
1905
+ brand: null,
1906
+ createdAt: now,
1907
+ updatedAt: now
1908
+ };
1909
+ store.postGroups.set(group.id, group);
1910
+ return c.json({ ok: true, data: toPostGroup(group, 0) }, 201);
1911
+ });
1912
+ app.put("/post-groups/:groupId", async (c) => {
1913
+ const groupId = c.req.param("groupId");
1914
+ const group = store.postGroups.get(groupId);
1915
+ if (!group || group.brandappId !== brandappId) {
1916
+ return c.json(
1917
+ { ok: false, error: { code: "NOT_FOUND", message: "Group not found" } },
1918
+ 404
1919
+ );
1920
+ }
1921
+ const body = await c.req.json();
1922
+ if (body.name !== void 0) group.name = body.name;
1923
+ if (body.slug !== void 0) group.slug = body.slug;
1924
+ if (body.description !== void 0)
1925
+ group.description = body.description;
1926
+ if (body.color !== void 0) group.color = body.color;
1927
+ group.updatedAt = store.now();
1928
+ const postCount = store.count(
1929
+ store.posts,
1930
+ (p) => p.brandappId === brandappId && p.groupId === group.id
1931
+ );
1932
+ return c.json({ ok: true, data: toPostGroup(group, postCount) });
1933
+ });
1934
+ app.delete("/post-groups/:groupId", (c) => {
1935
+ const groupId = c.req.param("groupId");
1936
+ const group = store.postGroups.get(groupId);
1937
+ if (!group || group.brandappId !== brandappId) {
1938
+ return c.json(
1939
+ { ok: false, error: { code: "NOT_FOUND", message: "Group not found" } },
1940
+ 404
1941
+ );
1942
+ }
1943
+ store.postGroups.delete(groupId);
1944
+ return c.json({ ok: true, data: null });
1945
+ });
1946
+ app.get("/tags", (c) => {
1947
+ const groupId = c.req.query("groupId");
1948
+ const groupSlug = c.req.query("groupSlug");
1949
+ const counts = /* @__PURE__ */ new Map();
1950
+ for (const post of store.posts.values()) {
1951
+ if (post.brandappId !== brandappId) continue;
1952
+ if (groupId && post.groupId !== groupId) continue;
1953
+ if (groupSlug && !matchGroupSlug(post, groupSlug)) continue;
1954
+ for (const t of post.tags) {
1955
+ const cur = counts.get(t.text);
1956
+ counts.set(t.text, {
1957
+ text: t.text,
1958
+ count: (cur?.count ?? 0) + 1
1959
+ });
1960
+ }
1961
+ }
1962
+ const records = Array.from(counts.values()).sort((a, b) => a.text.localeCompare(b.text)).map(({ text, count }) => ({
1963
+ id: `tag:${text}`,
1964
+ text,
1965
+ postCount: count
1966
+ }));
1967
+ return c.json({ ok: true, data: records });
1968
+ });
1969
+ return app;
1970
+ }
1971
+ function createProxyRoutes(options) {
1972
+ const { remoteUrl, remoteBrandappId, authHeader } = options;
1973
+ const app = new Hono();
1974
+ app.all("/*", async (c) => {
1975
+ const path = c.req.path;
1976
+ const remoteUrlFull = `${remoteUrl}${path.replace(/\/api\/v1\/brandapp\/[^/]+/, `/api/v1/brandapp/${remoteBrandappId}`)}`;
1977
+ const query = c.req.url.includes("?") ? "?" + c.req.url.split("?")[1] : "";
1978
+ const headers = new Headers();
1979
+ headers.set("Authorization", `Basic ${authHeader}`);
1980
+ headers.set(
1981
+ "Content-Type",
1982
+ c.req.header("content-type") || "application/json"
1983
+ );
1984
+ const bodyMethods = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
1985
+ let body;
1986
+ if (bodyMethods.has(c.req.method)) {
1987
+ body = await c.req.text();
1988
+ }
1989
+ try {
1990
+ const response = await fetch(remoteUrlFull + query, {
1991
+ method: c.req.method,
1992
+ headers,
1993
+ body
1994
+ });
1995
+ const contentType = response.headers.get("content-type") || "";
1996
+ if (contentType.includes("text/event-stream")) {
1997
+ return new Response(response.body, {
1998
+ status: response.status,
1999
+ headers: {
2000
+ "Content-Type": "text/event-stream",
2001
+ "Cache-Control": "no-cache",
2002
+ Connection: "keep-alive"
2003
+ }
2004
+ });
2005
+ }
2006
+ const data = await response.text();
2007
+ return new Response(data, {
2008
+ status: response.status,
2009
+ headers: {
2010
+ "Content-Type": contentType || "application/json"
2011
+ }
2012
+ });
2013
+ } catch (err) {
2014
+ return c.json(
2015
+ {
2016
+ ok: false,
2017
+ error: {
2018
+ code: "PROXY_ERROR",
2019
+ message: `Failed to proxy to ${remoteUrl}: ${err}`
2020
+ }
2021
+ },
2022
+ 502
2023
+ );
2024
+ }
2025
+ });
2026
+ return app;
2027
+ }
2028
+
2029
+ // src/dev/markdown-to-editor-spec.ts
2030
+ var cached = null;
2031
+ async function loadOptEditor() {
2032
+ if (cached) return cached;
2033
+ try {
2034
+ const mod = await import('@reopt-ai/opt-editor');
2035
+ cached = mod;
2036
+ return mod;
2037
+ } catch (err) {
2038
+ throw new Error(
2039
+ `markdownToEditorSpec requires @reopt-ai/opt-editor to be installed (it's an optional peer dependency). Install it as a devDependency in your project: \`pnpm add -D @reopt-ai/opt-editor\`. Original error: ${err instanceof Error ? err.message : String(err)}`
2040
+ );
2041
+ }
2042
+ }
2043
+ async function markdownToEditorSpec(markdown) {
2044
+ const { markdownToSpec } = await loadOptEditor();
2045
+ return markdownToSpec(markdown);
2046
+ }
2047
+ async function markdownToEditorSpecMany(markdowns) {
2048
+ const { markdownToSpec } = await loadOptEditor();
2049
+ return markdowns.map((md) => markdownToSpec(md));
2050
+ }
2051
+
2052
+ // src/dev/terms-handler.ts
2053
+ var DEV_CUSTOMER_ID = (brandappId) => `dev-customer:${brandappId}`;
2054
+ var EU_COUNTRIES = /* @__PURE__ */ new Set([
2055
+ "AT",
2056
+ "BE",
2057
+ "BG",
2058
+ "HR",
2059
+ "CY",
2060
+ "CZ",
2061
+ "DK",
2062
+ "EE",
2063
+ "FI",
2064
+ "FR",
2065
+ "DE",
2066
+ "GR",
2067
+ "HU",
2068
+ "IS",
2069
+ "IE",
2070
+ "IT",
2071
+ "LV",
2072
+ "LI",
2073
+ "LT",
2074
+ "LU",
2075
+ "MT",
2076
+ "NL",
2077
+ "NO",
2078
+ "PL",
2079
+ "PT",
2080
+ "RO",
2081
+ "SK",
2082
+ "SI",
2083
+ "ES",
2084
+ "SE"
2085
+ ]);
2086
+ var COUNTRY_TO_JURISDICTION = {
2087
+ KR: "KR",
2088
+ US: "US",
2089
+ GB: "GB",
2090
+ JP: "JP",
2091
+ CN: "CN",
2092
+ BR: "BR",
2093
+ CA: "CA",
2094
+ AU: "AU"
2095
+ };
2096
+ function parseAcceptLanguage(value) {
2097
+ if (!value) return null;
2098
+ const first = value.split(",")[0]?.trim();
2099
+ if (!first) return null;
2100
+ return first.split(";")[0]?.trim() || null;
2101
+ }
2102
+ function resolveTermsMeta(c) {
2103
+ const explicitJurisdiction = c.req.query("jurisdiction");
2104
+ const country = c.req.query("country")?.toUpperCase() ?? null;
2105
+ const locale = c.req.query("locale") ?? parseAcceptLanguage(c.req.header("accept-language"));
2106
+ if (explicitJurisdiction) {
2107
+ return {
2108
+ jurisdiction: explicitJurisdiction,
2109
+ jurisdictionSource: "explicit",
2110
+ country,
2111
+ locale
2112
+ };
2113
+ }
2114
+ if (country) {
2115
+ return {
2116
+ jurisdiction: EU_COUNTRIES.has(country) ? "EU" : COUNTRY_TO_JURISDICTION[country] ?? "global",
2117
+ jurisdictionSource: "country",
2118
+ country,
2119
+ locale
2120
+ };
2121
+ }
2122
+ return {
2123
+ jurisdiction: "KR",
2124
+ jurisdictionSource: "brandapp_default",
2125
+ country: null,
2126
+ locale
2127
+ };
2128
+ }
2129
+ function languageOf(locale) {
2130
+ return locale.split("-")[0]?.toLowerCase() ?? locale.toLowerCase();
2131
+ }
2132
+ function inlineText(text) {
2133
+ return [{ text, marks: [] }];
2134
+ }
2135
+ function fallbackContentRich(content) {
2136
+ const blocks = content.split(/\n{2,}/).map((part) => part.trim()).filter(Boolean);
2137
+ if (blocks.length > 0) {
2138
+ const root = [];
2139
+ const elements = {};
2140
+ blocks.forEach((block, index) => {
2141
+ const id = `b${index + 1}`;
2142
+ root.push(id);
2143
+ const heading = /^(#{1,3})\s+(.+)$/.exec(block);
2144
+ if (heading) {
2145
+ const marker = heading[1] ?? "#";
2146
+ const text = heading[2] ?? "";
2147
+ elements[id] = {
2148
+ id,
2149
+ type: "heading",
2150
+ attrs: { level: marker.length },
2151
+ content: inlineText(text)
2152
+ };
2153
+ return;
2154
+ }
2155
+ elements[id] = {
2156
+ id,
2157
+ type: "paragraph",
2158
+ attrs: {},
2159
+ content: inlineText(block)
2160
+ };
2161
+ });
2162
+ return { root, elements, version: 1 };
2163
+ }
2164
+ return {
2165
+ root: ["p1"],
2166
+ elements: {
2167
+ p1: {
2168
+ id: "p1",
2169
+ type: "paragraph",
2170
+ attrs: {},
2171
+ content: inlineText(content)
2172
+ }
2173
+ },
2174
+ version: 1
2175
+ };
2176
+ }
2177
+ async function toContentRich(content) {
2178
+ try {
2179
+ return await markdownToEditorSpec(content);
2180
+ } catch {
2181
+ return fallbackContentRich(content);
2182
+ }
2183
+ }
2184
+ function createTermsRoutes(store, brandappId) {
2185
+ const app = new Hono();
2186
+ app.get("/", async (c) => {
2187
+ const meta = resolveTermsMeta(c);
2188
+ const items = await Promise.all(
2189
+ store.findMany(
2190
+ store.terms,
2191
+ (t) => t.brandappId === brandappId && t.isActive && (t.jurisdiction === meta.jurisdiction || t.jurisdiction === "global")
2192
+ ).sort((a, b) => a.sortOrder - b.sortOrder).map(async (t) => {
2193
+ const currentVersions = store.findMany(
2194
+ store.termsVersions,
2195
+ (v) => v.termsId === t.id && v.isCurrent
2196
+ );
2197
+ const requestedLocale = meta.locale?.toLowerCase();
2198
+ const current = (requestedLocale ? currentVersions.find(
2199
+ (v) => v.locale.toLowerCase() === requestedLocale
2200
+ ) ?? currentVersions.find(
2201
+ (v) => languageOf(v.locale) === languageOf(requestedLocale) || v.locale.toLowerCase() === "en-us"
2202
+ ) : null) ?? currentVersions[0] ?? null;
2203
+ return {
2204
+ id: t.id,
2205
+ title: t.title,
2206
+ type: t.type,
2207
+ jurisdiction: t.jurisdiction,
2208
+ isRequired: t.isRequired,
2209
+ sortOrder: t.sortOrder,
2210
+ currentVersion: current ? {
2211
+ id: current.id,
2212
+ version: current.version,
2213
+ locale: current.locale,
2214
+ content: current.content,
2215
+ contentRich: await toContentRich(current.content),
2216
+ publishedAt: current.publishedAt.toISOString(),
2217
+ changeSummary: current.changeSummary,
2218
+ reConsentDeadline: current.reConsentDeadline?.toISOString() ?? null
2219
+ } : null
2220
+ };
2221
+ })
2222
+ );
2223
+ return c.json({ data: { ...meta, terms: items } });
2224
+ });
2225
+ app.get("/me/consents", (c) => {
2226
+ const customerId = DEV_CUSTOMER_ID(brandappId);
2227
+ const versions = new Map(
2228
+ store.findMany(store.termsVersions, () => true).map((v) => [v.id, v])
2229
+ );
2230
+ const items = store.findMany(store.termsConsents, (c2) => c2.customerId === customerId).filter((c2) => {
2231
+ const v = versions.get(c2.versionId);
2232
+ if (!v) return false;
2233
+ const t = store.terms.get(v.termsId);
2234
+ return t?.brandappId === brandappId;
2235
+ }).sort((a, b) => b.consentedAt.getTime() - a.consentedAt.getTime()).map((c2) => {
2236
+ const v = versions.get(c2.versionId);
2237
+ return {
2238
+ id: c2.id,
2239
+ status: c2.status,
2240
+ consentedAt: c2.consentedAt.toISOString(),
2241
+ withdrawnAt: c2.withdrawnAt?.toISOString() ?? null,
2242
+ source: c2.source,
2243
+ versionId: c2.versionId,
2244
+ termsId: v.termsId,
2245
+ consentCountry: c2.consentCountry,
2246
+ consentLocale: c2.consentLocale
2247
+ };
2248
+ });
2249
+ return c.json({ data: items });
2250
+ });
2251
+ app.post("/me/consents", async (c) => {
2252
+ let body;
2253
+ try {
2254
+ body = await c.req.json();
2255
+ } catch {
2256
+ return c.json(
2257
+ { error: { code: "BAD_REQUEST", message: "Invalid JSON body" } },
2258
+ 400
2259
+ );
2260
+ }
2261
+ if (!body.consents || body.consents.length === 0) {
2262
+ return c.json(
2263
+ {
2264
+ error: {
2265
+ code: "VALIDATION_ERROR",
2266
+ message: "consents must be a non-empty array"
2267
+ }
2268
+ },
2269
+ 422
2270
+ );
2271
+ }
2272
+ const requestedIds = body.consents.map((x) => x.versionId);
2273
+ const versions = requestedIds.map((id) => store.termsVersions.get(id));
2274
+ if (versions.some((v) => !v)) {
2275
+ return c.json(
2276
+ {
2277
+ error: {
2278
+ code: "NOT_FOUND",
2279
+ message: "One or more terms versions not found"
2280
+ }
2281
+ },
2282
+ 404
2283
+ );
2284
+ }
2285
+ for (const v of versions) {
2286
+ const t = store.terms.get(v.termsId);
2287
+ if (!t || t.brandappId !== brandappId) {
2288
+ return c.json(
2289
+ {
2290
+ error: {
2291
+ code: "NOT_FOUND",
2292
+ message: "One or more terms versions not found"
2293
+ }
2294
+ },
2295
+ 404
2296
+ );
2297
+ }
2298
+ }
2299
+ for (let i = 0; i < versions.length; i++) {
2300
+ const v = versions[i];
2301
+ const terms = store.terms.get(v.termsId);
2302
+ if (terms.isRequired && !body.consents[i].consented) {
2303
+ return c.json(
2304
+ {
2305
+ error: {
2306
+ code: "REQUIRED_NOT_CONSENTED",
2307
+ message: "All required terms must be consented"
2308
+ }
2309
+ },
2310
+ 422
2311
+ );
2312
+ }
2313
+ }
2314
+ const customerId = DEV_CUSTOMER_ID(brandappId);
2315
+ let count = 0;
2316
+ const consentCountry = body.country?.toUpperCase() ?? c.req.header("x-vercel-ip-country") ?? null;
2317
+ const consentLocale = body.locale ?? parseAcceptLanguage(c.req.header("accept-language"));
2318
+ const userAgent = body.userAgent ?? c.req.header("user-agent") ?? null;
2319
+ for (const input of body.consents) {
2320
+ if (!input.consented) continue;
2321
+ const id = store.generateId();
2322
+ const now = store.now();
2323
+ store.termsConsents.set(id, {
2324
+ id,
2325
+ versionId: input.versionId,
2326
+ customerId,
2327
+ status: "granted",
2328
+ consentedAt: now,
2329
+ withdrawnAt: null,
2330
+ source: body.source ?? "sdk",
2331
+ ipAddress: body.ipAddress ?? null,
2332
+ userAgent,
2333
+ consentCountry,
2334
+ consentLocale,
2335
+ createdAt: now
2336
+ });
2337
+ count++;
2338
+ }
2339
+ return c.json({ data: { count } }, 201);
2340
+ });
2341
+ app.delete("/me/consents/:consentId", (c) => {
2342
+ const consentId = c.req.param("consentId");
2343
+ const consent = store.termsConsents.get(consentId);
2344
+ if (!consent) {
2345
+ return c.json(
2346
+ { error: { code: "NOT_FOUND", message: "Consent not found" } },
2347
+ 404
2348
+ );
2349
+ }
2350
+ const version = store.termsVersions.get(consent.versionId);
2351
+ const terms = version ? store.terms.get(version.termsId) : null;
2352
+ if (!terms || terms.brandappId !== brandappId) {
2353
+ return c.json(
2354
+ { error: { code: "NOT_FOUND", message: "Consent not found" } },
2355
+ 404
2356
+ );
2357
+ }
2358
+ if (consent.customerId !== DEV_CUSTOMER_ID(brandappId)) {
2359
+ return c.json(
2360
+ {
2361
+ error: {
2362
+ code: "FORBIDDEN",
2363
+ message: "Cannot withdraw a consent owned by another user"
2364
+ }
2365
+ },
2366
+ 403
2367
+ );
2368
+ }
2369
+ if (terms.isRequired) {
2370
+ return c.json(
2371
+ {
2372
+ error: {
2373
+ code: "CONFLICT",
2374
+ message: "Required terms cannot be withdrawn"
2375
+ }
2376
+ },
2377
+ 409
2378
+ );
2379
+ }
2380
+ if (consent.status === "withdrawn") {
2381
+ return c.json(
2382
+ {
2383
+ error: { code: "CONFLICT", message: "Consent already withdrawn" }
2384
+ },
2385
+ 409
2386
+ );
2387
+ }
2388
+ consent.status = "withdrawn";
2389
+ consent.withdrawnAt = store.now();
2390
+ return c.json({ data: { id: consentId } });
2391
+ });
2392
+ return app;
2393
+ }
2394
+
2395
+ // src/dev/index.ts
2396
+ function seedSchema(store, brandappId, schema) {
2397
+ for (const [key, entityDef] of Object.entries(schema.entities)) {
2398
+ const now = store.now();
2399
+ const entityId = store.generateId();
2400
+ store.entities.set(entityId, {
2401
+ id: entityId,
2402
+ brandappId,
2403
+ name: entityDef.name ?? key,
2404
+ description: entityDef.description ?? null,
2405
+ icon: entityDef.icon ?? "\u{1F4CA}",
2406
+ linkedTo: "brandapp",
2407
+ maxRecords: entityDef.maxRecords ?? 1e4,
2408
+ createdAt: now,
2409
+ updatedAt: now
2410
+ });
2411
+ let sortOrder = 0;
2412
+ for (const [attrKey, attrDef] of Object.entries(entityDef.attributes)) {
2413
+ const attrId = attrKey;
2414
+ store.attributes.set(attrId, {
2415
+ id: attrId,
2416
+ entityId,
2417
+ name: attrKey,
2418
+ label: attrDef.label ?? attrKey,
2419
+ dataType: attrDef.dataType ?? "text",
2420
+ isRequired: attrDef.isRequired ?? false,
2421
+ isUnique: attrDef.isUnique ?? false,
2422
+ defaultValue: attrDef.defaultValue ?? null,
2423
+ validation: null,
2424
+ options: attrDef.options ?? null,
2425
+ sortOrder: sortOrder++,
2426
+ createdAt: now,
2427
+ updatedAt: now
2428
+ });
2429
+ }
2430
+ }
2431
+ }
2432
+ function findEntityByName(store, name) {
2433
+ return store.findFirst(store.entities, (e) => e.name === name);
2434
+ }
2435
+ function toSeedValue(value) {
2436
+ return typeof value === "string" ? value : JSON.stringify(value);
2437
+ }
2438
+ function normalizeUpsertKey(key) {
2439
+ if (!key) return [];
2440
+ return Array.isArray(key) ? key : [key];
2441
+ }
2442
+ function getProvidedUniqueKeys(store, entity, values) {
2443
+ return [...store.attributes.values()].filter((attr) => attr.entityId === entity.id && attr.isUnique).map((attr) => attr.id).filter((key) => values[key] !== void 0);
2444
+ }
2445
+ function getSeedUpsertKeys(store, entity, input, options) {
2446
+ const explicit = normalizeUpsertKey(input.upsertKey ?? options?.upsertKey);
2447
+ if (explicit.length > 0) return explicit;
2448
+ const unique = getProvidedUniqueKeys(store, entity, input.values);
2449
+ if (unique.length > 0) return unique;
2450
+ return Object.keys(input.values).sort();
2451
+ }
2452
+ function getRecordValues(record) {
2453
+ return Object.fromEntries(record.values.map((v) => [v.attributeId, v.value]));
2454
+ }
2455
+ function findSeedRecordByKeys(store, entity, input, keys) {
2456
+ if (keys.length === 0) return null;
2457
+ if (keys.some((key) => input.values[key] === void 0)) return null;
2458
+ return store.findFirst(store.records, (record) => {
2459
+ if (record.entityId !== entity.id) return false;
2460
+ const existingValues = getRecordValues(record);
2461
+ return keys.every(
2462
+ (key) => existingValues[key] === toSeedValue(input.values[key])
2463
+ );
2464
+ }) ?? null;
2465
+ }
2466
+ function buildSeedValues(recordId, values) {
2467
+ return Object.entries(values).map(([key, value]) => ({
2468
+ recordId,
2469
+ attributeId: key,
2470
+ value: toSeedValue(value)
2471
+ }));
2472
+ }
2473
+ function assertNotProduction() {
2474
+ if (typeof process === "undefined") return;
2475
+ const isProd = process.env?.NODE_ENV === "production";
2476
+ const allow = process.env?.REOPT_DEV_SERVER_ALLOW_PRODUCTION === "1";
2477
+ if (isProd && !allow) {
2478
+ throw new Error(
2479
+ "[@reopt-ai/brandapp-sdk/dev] createDevServer() refuses to start with NODE_ENV=production. It is an unauthenticated in-memory dev API and must never be exposed in production. Set REOPT_DEV_SERVER_ALLOW_PRODUCTION=1 to override (not recommended)."
2480
+ );
2481
+ }
2482
+ }
2483
+ async function createDevServer(options = {}) {
2484
+ assertNotProduction();
2485
+ const {
2486
+ port: requestedPort = 0,
2487
+ brandappId = "dev-brandapp",
2488
+ dataPath,
2489
+ schema,
2490
+ verbose = false,
2491
+ proxy
2492
+ } = options;
2493
+ const store = new InMemoryStore();
2494
+ if (dataPath) {
2495
+ try {
2496
+ const json = await readFile(dataPath, "utf-8");
2497
+ store.fromJSON(json);
2498
+ if (verbose) console.log(`[reopt-dev] Loaded data from ${dataPath}`);
2499
+ } catch {
2500
+ }
2501
+ }
2502
+ if (schema && store.entities.size === 0) {
2503
+ seedSchema(store, brandappId, schema);
2504
+ if (verbose)
2505
+ console.log(
2506
+ `[reopt-dev] Seeded ${Object.keys(schema.entities).length} entities from schema`
2507
+ );
2508
+ }
2509
+ const app = new Hono();
2510
+ app.use("/api/v1/brandapp/*", async (c, next) => {
2511
+ const match = new URL(c.req.url).pathname.match(
2512
+ /^\/api\/v1\/brandapp\/([^/]+)/
2513
+ );
2514
+ if (match && match[1] !== brandappId) {
2515
+ return c.json(
2516
+ {
2517
+ error: {
2518
+ code: "NOT_FOUND",
2519
+ message: `Dev server is configured for brandappId "${brandappId}", but received "${match[1]}". Create a new dev server instance for each brandappId, or reconfigure this one.`
2520
+ }
2521
+ },
2522
+ 404
2523
+ );
2524
+ }
2525
+ if (verbose && !c.req.header("Authorization")) {
2526
+ console.warn(
2527
+ `[reopt-dev] ${c.req.method} ${c.req.url} \u2014 missing Authorization header (ok in dev, rejected in prod)`
2528
+ );
2529
+ }
2530
+ await next();
2531
+ });
2532
+ const proxyRoutes = proxy?.routes ?? {};
2533
+ const proxyOpts = proxy ? {
2534
+ remoteUrl: proxy.remoteUrl.replace(/\/$/, ""),
2535
+ remoteBrandappId: proxy.remoteCredentials.brandappId,
2536
+ authHeader: btoa(
2537
+ `${proxy.remoteCredentials.clientId}:${proxy.remoteCredentials.clientSecret}`
2538
+ )
2539
+ } : null;
2540
+ function routeFor(module, localHandler) {
2541
+ const strategy = proxyRoutes[module] ?? "local";
2542
+ if (strategy === "passthrough" && proxyOpts) {
2543
+ if (verbose)
2544
+ console.log(
2545
+ `[reopt-dev] ${module}: proxying to ${proxyOpts.remoteUrl}`
2546
+ );
2547
+ return createProxyRoutes(proxyOpts);
2548
+ }
2549
+ return localHandler;
2550
+ }
2551
+ const basePath = `/api/v1/brandapp/${brandappId}`;
2552
+ app.route(
2553
+ `${basePath}/eav`,
2554
+ routeFor("eav", createEavRoutes(store, brandappId))
2555
+ );
2556
+ app.route(
2557
+ `${basePath}/auth`,
2558
+ routeFor("auth", createAuthRoutes(store, brandappId))
2559
+ );
2560
+ app.route(`${basePath}/ai`, routeFor("ai", createAiRoutes()));
2561
+ app.route(
2562
+ `${basePath}/files`,
2563
+ routeFor("files", createFilesRoutes(store, brandappId))
2564
+ );
2565
+ app.route(
2566
+ `${basePath}/cms`,
2567
+ routeFor("cms", createCmsRoutes(store, brandappId))
2568
+ );
2569
+ app.route(
2570
+ `${basePath}/terms`,
2571
+ routeFor("terms", createTermsRoutes(store, brandappId))
2572
+ );
2573
+ app.route(
2574
+ "/api/v1/brandapp/:brandappId/eav",
2575
+ routeFor("eav", createEavRoutes(store, brandappId))
2576
+ );
2577
+ app.route(
2578
+ "/api/v1/brandapp/:brandappId/auth",
2579
+ routeFor("auth", createAuthRoutes(store, brandappId))
2580
+ );
2581
+ app.route(
2582
+ "/api/v1/brandapp/:brandappId/ai",
2583
+ routeFor("ai", createAiRoutes())
2584
+ );
2585
+ app.route(
2586
+ "/api/v1/brandapp/:brandappId/files",
2587
+ routeFor("files", createFilesRoutes(store, brandappId))
2588
+ );
2589
+ app.route(
2590
+ "/api/v1/brandapp/:brandappId/cms",
2591
+ routeFor("cms", createCmsRoutes(store, brandappId))
2592
+ );
2593
+ app.route(
2594
+ "/api/v1/brandapp/:brandappId/terms",
2595
+ routeFor("terms", createTermsRoutes(store, brandappId))
2596
+ );
2597
+ app.get("/", (c) => {
2598
+ const entityCount = store.entities.size;
2599
+ const recordCount = store.records.size;
2600
+ const fileCount = store.files.size;
2601
+ const postCount = store.posts.size;
2602
+ const userCount = store.authUsers.size;
2603
+ const entities = Array.from(store.entities.values()).map((e) => {
2604
+ const attrs = Array.from(store.attributes.values()).filter(
2605
+ (a) => a.entityId === e.id
2606
+ );
2607
+ const records = Array.from(store.records.values()).filter(
2608
+ (r) => r.entityId === e.id
2609
+ );
2610
+ return {
2611
+ name: e.name,
2612
+ icon: e.icon,
2613
+ attrs: attrs.length,
2614
+ records: records.length
2615
+ };
2616
+ });
2617
+ const baseUrl = `http://localhost:${actualPort}`;
2618
+ const apiBase = `${baseUrl}/api/v1/brandapp/${brandappId}`;
2619
+ return c.html(`<!DOCTYPE html>
2620
+ <html lang="en">
2621
+ <head>
2622
+ <meta charset="utf-8" />
2623
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
2624
+ <title>BrandApp Dev Server</title>
2625
+ <style>
2626
+ * { margin: 0; padding: 0; box-sizing: border-box; }
2627
+ body { font-family: system-ui, -apple-system, sans-serif; background: #fafafa; color: #1a1a1a; padding: 2rem; max-width: 720px; margin: 0 auto; }
2628
+ h1 { font-size: 1.5rem; font-weight: 700; margin-bottom: 0.25rem; }
2629
+ .subtitle { color: #666; font-size: 0.875rem; margin-bottom: 2rem; }
2630
+ .badge { display: inline-block; background: #dcfce7; color: #166534; font-size: 0.75rem; font-weight: 600; padding: 0.125rem 0.5rem; border-radius: 9999px; margin-left: 0.5rem; }
2631
+ .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 0.75rem; margin-bottom: 2rem; }
2632
+ .stat { background: #fff; border: 1px solid #e5e7eb; border-radius: 0.5rem; padding: 1rem; }
2633
+ .stat-value { font-size: 1.5rem; font-weight: 700; }
2634
+ .stat-label { font-size: 0.75rem; color: #666; margin-top: 0.125rem; }
2635
+ h2 { font-size: 1rem; font-weight: 600; margin-bottom: 0.75rem; color: #333; }
2636
+ .section { margin-bottom: 2rem; }
2637
+ table { width: 100%; border-collapse: collapse; background: #fff; border: 1px solid #e5e7eb; border-radius: 0.5rem; overflow: hidden; font-size: 0.875rem; }
2638
+ th { text-align: left; padding: 0.5rem 0.75rem; background: #f9fafb; font-weight: 600; color: #666; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; }
2639
+ td { padding: 0.5rem 0.75rem; border-top: 1px solid #f3f4f6; }
2640
+ code { font-family: "JetBrains Mono", monospace; font-size: 0.8rem; background: #f3f4f6; padding: 0.125rem 0.375rem; border-radius: 0.25rem; }
2641
+ a { color: #2563eb; text-decoration: none; }
2642
+ a:hover { text-decoration: underline; }
2643
+ .endpoint { display: flex; align-items: center; gap: 0.5rem; }
2644
+ .method { font-size: 0.625rem; font-weight: 700; padding: 0.125rem 0.375rem; border-radius: 0.25rem; color: #fff; flex-shrink: 0; }
2645
+ .method-get { background: #22c55e; }
2646
+ .method-post { background: #3b82f6; }
2647
+ .method-put { background: #f59e0b; }
2648
+ .method-del { background: #ef4444; }
2649
+ .footer { color: #999; font-size: 0.75rem; margin-top: 2rem; padding-top: 1rem; border-top: 1px solid #e5e7eb; }
2650
+ </style>
2651
+ </head>
2652
+ <body>
2653
+ <h1>BrandApp Dev Server <span class="badge">Running</span></h1>
2654
+ <p class="subtitle">${baseUrl} &mdash; In-memory API for <code>@reopt-ai/brandapp-sdk</code></p>
2655
+
2656
+ <div class="stats">
2657
+ <div class="stat"><div class="stat-value">${entityCount}</div><div class="stat-label">Entities</div></div>
2658
+ <div class="stat"><div class="stat-value">${recordCount}</div><div class="stat-label">Records</div></div>
2659
+ <div class="stat"><div class="stat-value">${fileCount}</div><div class="stat-label">Files</div></div>
2660
+ <div class="stat"><div class="stat-value">${postCount}</div><div class="stat-label">Posts</div></div>
2661
+ <div class="stat"><div class="stat-value">${userCount}</div><div class="stat-label">Users</div></div>
2662
+ </div>
2663
+
2664
+ ${entities.length > 0 ? `<div class="section">
2665
+ <h2>EAV Entities</h2>
2666
+ <table>
2667
+ <tr><th>Entity</th><th>Attributes</th><th>Records</th></tr>
2668
+ ${entities.map((e) => `<tr><td>${e.icon ?? ""} ${e.name}</td><td>${e.attrs}</td><td>${e.records}</td></tr>`).join("")}
2669
+ </table>
2670
+ </div>` : ""}
2671
+
2672
+ <div class="section">
2673
+ <h2>API Endpoints</h2>
2674
+ <table>
2675
+ <tr><th>Module</th><th>Base Path</th></tr>
2676
+ <tr><td>EAV</td><td><code><a href="${apiBase}/eav/entities">${apiBase}/eav</a></code></td></tr>
2677
+ <tr><td>AI</td><td><code>${apiBase}/ai</code></td></tr>
2678
+ <tr><td>Files</td><td><code><a href="${apiBase}/files">${apiBase}/files</a></code></td></tr>
2679
+ <tr><td>CMS</td><td><code><a href="${apiBase}/cms/posts">${apiBase}/cms</a></code></td></tr>
2680
+ <tr><td>Terms</td><td><code><a href="${apiBase}/terms">${apiBase}/terms</a></code></td></tr>
2681
+ <tr><td>Auth</td><td><code>${apiBase}/auth</code></td></tr>
2682
+ </table>
2683
+ </div>
2684
+
2685
+ <div class="section">
2686
+ <h2>Quick Reference</h2>
2687
+ <table>
2688
+ <tr><th>Action</th><th>Endpoint</th></tr>
2689
+ <tr><td>Health Check</td><td><a href="${baseUrl}/health"><code>GET /health</code></a></td></tr>
2690
+ <tr><td>List Entities</td><td><a href="${apiBase}/eav/entities"><code>GET /eav/entities</code></a></td></tr>
2691
+ <tr><td>List Files</td><td><a href="${apiBase}/files"><code>GET /files</code></a></td></tr>
2692
+ <tr><td>List Posts</td><td><a href="${apiBase}/cms/posts"><code>GET /cms/posts</code></a></td></tr>
2693
+ <tr><td>AI Models</td><td><a href="${apiBase}/ai/models"><code>GET /ai/models</code></a></td></tr>
2694
+ <tr><td>AI Credits</td><td><a href="${apiBase}/ai/credits"><code>GET /ai/credits</code></a></td></tr>
2695
+ </table>
2696
+ </div>
2697
+
2698
+ <div class="footer">
2699
+ @reopt-ai/brandapp-sdk dev server &mdash; BrandApp ID: <code>${brandappId}</code>
2700
+ </div>
2701
+ </body>
2702
+ </html>`);
2703
+ });
2704
+ app.get("/health", (c) => c.json({ ok: true, mode: "dev" }));
2705
+ app.get("/api/auth/.well-known/openid-configuration", (c) => {
2706
+ const baseUrl = `http://localhost:${actualPort}`;
2707
+ return c.json({
2708
+ issuer: baseUrl,
2709
+ authorization_endpoint: `${baseUrl}/api/auth/authorize`,
2710
+ token_endpoint: `${baseUrl}/api/auth/token`,
2711
+ userinfo_endpoint: `${baseUrl}/api/auth/userinfo`,
2712
+ jwks_uri: `${baseUrl}/api/auth/jwks`,
2713
+ response_types_supported: ["code"],
2714
+ subject_types_supported: ["public"],
2715
+ id_token_signing_alg_values_supported: ["RS256"],
2716
+ scopes_supported: ["openid", "profile", "email"],
2717
+ token_endpoint_auth_methods_supported: [
2718
+ "client_secret_basic",
2719
+ "client_secret_post"
2720
+ ],
2721
+ grant_types_supported: ["authorization_code", "refresh_token"],
2722
+ code_challenge_methods_supported: ["S256"]
2723
+ });
2724
+ });
2725
+ app.post("/api/auth/token", async (c) => {
2726
+ return c.json({
2727
+ access_token: `dev-access-token-${store.generateId()}`,
2728
+ token_type: "Bearer",
2729
+ expires_in: 3600,
2730
+ refresh_token: `dev-refresh-token-${store.generateId()}`,
2731
+ id_token: "dev-id-token",
2732
+ scope: "openid profile email"
2733
+ });
2734
+ });
2735
+ app.get("/api/auth/userinfo", (c) => {
2736
+ return c.json({
2737
+ sub: "dev-user-id",
2738
+ email: "dev@example.com",
2739
+ email_verified: true,
2740
+ name: "Dev User",
2741
+ picture: null
2742
+ });
2743
+ });
2744
+ let actualPort = requestedPort;
2745
+ const server = createServer(async (req, res) => {
2746
+ const url2 = new URL(req.url ?? "/", `http://localhost:${actualPort}`);
2747
+ const headers = new Headers();
2748
+ for (let i = 0; i < (req.rawHeaders?.length ?? 0); i += 2) {
2749
+ headers.append(req.rawHeaders[i], req.rawHeaders[i + 1]);
2750
+ }
2751
+ const bodyMethods = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
2752
+ const hasBody = bodyMethods.has(req.method ?? "GET");
2753
+ let body = null;
2754
+ if (hasBody) {
2755
+ body = new ReadableStream({
2756
+ start(controller) {
2757
+ req.on(
2758
+ "data",
2759
+ (chunk) => controller.enqueue(new Uint8Array(chunk))
2760
+ );
2761
+ req.on("end", () => controller.close());
2762
+ req.on("error", (err) => controller.error(err));
2763
+ }
2764
+ });
2765
+ }
2766
+ const fetchRequest = new Request(url2.toString(), {
2767
+ method: req.method,
2768
+ headers,
2769
+ body,
2770
+ // @ts-expect-error -- duplex is needed for streaming request bodies
2771
+ duplex: hasBody ? "half" : void 0
2772
+ });
2773
+ try {
2774
+ const response = await app.fetch(fetchRequest);
2775
+ const headerEntries = [];
2776
+ response.headers.forEach(
2777
+ (value, key) => headerEntries.push([key, value])
2778
+ );
2779
+ res.writeHead(response.status, Object.fromEntries(headerEntries));
2780
+ if (response.body) {
2781
+ const reader = response.body.getReader();
2782
+ const pump = async () => {
2783
+ while (true) {
2784
+ const { done, value } = await reader.read();
2785
+ if (done) break;
2786
+ res.write(value);
2787
+ }
2788
+ res.end();
2789
+ };
2790
+ await pump();
2791
+ } else {
2792
+ res.end();
2793
+ }
2794
+ } catch {
2795
+ res.writeHead(500);
2796
+ res.end(JSON.stringify({ ok: false, error: "Internal server error" }));
2797
+ }
2798
+ });
2799
+ await new Promise((resolve, reject) => {
2800
+ const onError = (error) => {
2801
+ server.off("listening", onListening);
2802
+ reject(error);
2803
+ };
2804
+ const onListening = () => {
2805
+ server.off("error", onError);
2806
+ const addr = server.address();
2807
+ if (addr && typeof addr === "object") {
2808
+ actualPort = addr.port;
2809
+ }
2810
+ resolve();
2811
+ };
2812
+ server.once("error", onError);
2813
+ server.listen(requestedPort, onListening);
2814
+ });
2815
+ const url = `http://localhost:${actualPort}`;
2816
+ if (verbose) {
2817
+ console.log(`[reopt-dev] Dev server running at ${url}`);
2818
+ console.log(`[reopt-dev] BrandApp ID: ${brandappId}`);
2819
+ console.log(`[reopt-dev] API base: ${url}/api/v1/brandapp/${brandappId}`);
2820
+ }
2821
+ let persistTimer = null;
2822
+ const persistIfNeeded = () => {
2823
+ if (!dataPath) return;
2824
+ if (persistTimer) clearTimeout(persistTimer);
2825
+ persistTimer = setTimeout(async () => {
2826
+ try {
2827
+ await mkdir(dirname(dataPath), { recursive: true });
2828
+ await writeFile(dataPath, store.toJSON(), "utf-8");
2829
+ } catch {
2830
+ }
2831
+ }, 1e3);
2832
+ };
2833
+ const devServer = {
2834
+ url,
2835
+ port: actualPort,
2836
+ store,
2837
+ async seed(data, options2) {
2838
+ let changed = false;
2839
+ for (const [entityName, records] of Object.entries(data)) {
2840
+ const entity = findEntityByName(store, entityName);
2841
+ if (!entity) {
2842
+ console.warn(
2843
+ `[reopt-dev] Entity "${entityName}" not found. Available: ${[...store.entities.values()].map((e) => e.name).join(", ")}`
2844
+ );
2845
+ continue;
2846
+ }
2847
+ for (const r of records) {
2848
+ const now = store.now();
2849
+ const upsertKeys = options2?.mode === "upsert" ? getSeedUpsertKeys(store, entity, r, options2) : [];
2850
+ const existing = options2?.mode === "upsert" ? findSeedRecordByKeys(store, entity, r, upsertKeys) : null;
2851
+ if (existing) {
2852
+ const nextValues = buildSeedValues(existing.id, r.values);
2853
+ const nextAuthUserId = r.authUserId ?? null;
2854
+ const hasChanged = existing.brandappAuthUserId !== nextAuthUserId || JSON.stringify(existing.values) !== JSON.stringify(nextValues);
2855
+ if (hasChanged) {
2856
+ existing.brandappAuthUserId = nextAuthUserId;
2857
+ existing.values = nextValues;
2858
+ existing.updatedAt = now;
2859
+ changed = true;
2860
+ }
2861
+ continue;
2862
+ }
2863
+ const record = {
2864
+ id: store.generateId(),
2865
+ entityId: entity.id,
2866
+ brandappAuthUserId: r.authUserId ?? null,
2867
+ createdAt: now,
2868
+ updatedAt: now,
2869
+ values: buildSeedValues("", r.values)
2870
+ };
2871
+ record.values.forEach((v) => v.recordId = record.id);
2872
+ store.records.set(record.id, record);
2873
+ changed = true;
2874
+ }
2875
+ }
2876
+ if (changed) persistIfNeeded();
2877
+ },
2878
+ async seedPostGroups(items) {
2879
+ let changed = false;
2880
+ for (const item of items) {
2881
+ const existing = store.findFirst(
2882
+ store.postGroups,
2883
+ (g) => g.brandappId === brandappId && g.slug === item.slug
2884
+ );
2885
+ const now = store.now();
2886
+ if (existing) {
2887
+ const nextDescription = item.description !== void 0 ? item.description : existing.description;
2888
+ const nextColor = item.color !== void 0 ? item.color : existing.color;
2889
+ if (existing.name !== item.name || existing.description !== nextDescription || existing.color !== nextColor) {
2890
+ existing.name = item.name;
2891
+ existing.description = nextDescription;
2892
+ existing.color = nextColor;
2893
+ existing.updatedAt = now;
2894
+ changed = true;
2895
+ }
2896
+ continue;
2897
+ }
2898
+ const id = store.generateId();
2899
+ const group = {
2900
+ id,
2901
+ brandappId,
2902
+ slug: item.slug,
2903
+ name: item.name,
2904
+ description: item.description ?? null,
2905
+ color: item.color ?? "indigo",
2906
+ brand: null,
2907
+ createdAt: now,
2908
+ updatedAt: now
2909
+ };
2910
+ store.postGroups.set(id, group);
2911
+ changed = true;
2912
+ }
2913
+ if (changed) persistIfNeeded();
2914
+ },
2915
+ async seedPosts(items) {
2916
+ let changed = false;
2917
+ for (const item of items) {
2918
+ const group = store.findFirst(
2919
+ store.postGroups,
2920
+ (g) => g.brandappId === brandappId && g.slug === item.groupSlug
2921
+ );
2922
+ if (!group) {
2923
+ console.warn(
2924
+ `[reopt-dev] seedPosts: PostGroup with slug "${item.groupSlug}" not found. Available: ${[...store.postGroups.values()].filter((g) => g.brandappId === brandappId).map((g) => g.slug ?? "(unset)").join(", ")}. Call seedPostGroups first or use seedAll.`
2925
+ );
2926
+ continue;
2927
+ }
2928
+ const existing = store.findFirst(
2929
+ store.posts,
2930
+ (p) => p.brandappId === brandappId && p.groupId === group.id && p.slug === item.slug
2931
+ );
2932
+ const normalizedTags = (item.tags ?? []).map(
2933
+ (t) => typeof t === "string" ? { id: `tag:${t}`, text: t } : t
2934
+ );
2935
+ const publishedAt = item.publishedAt instanceof Date ? item.publishedAt : typeof item.publishedAt === "string" ? new Date(item.publishedAt) : null;
2936
+ const coverImage = item.coverImage ? {
2937
+ id: item.coverImage.id ?? `cover:${item.slug}`,
2938
+ url: item.coverImage.url
2939
+ } : null;
2940
+ const author = {
2941
+ id: item.author?.id ?? "dev-user",
2942
+ name: item.author?.name ?? "Dev User",
2943
+ image: item.author?.image ?? null
2944
+ };
2945
+ const seo = {
2946
+ metaTitle: item.seo?.metaTitle ?? null,
2947
+ metaDescription: item.seo?.metaDescription ?? null,
2948
+ metaKeywords: item.seo?.metaKeywords ?? null
2949
+ };
2950
+ const now = store.now();
2951
+ if (existing) {
2952
+ const nextContent = item.content ?? "";
2953
+ const nextContentRich = item.contentRich ?? null;
2954
+ const nextStatus = item.status ?? "draft";
2955
+ const nextIcon = item.icon ?? null;
2956
+ const hasChanged = existing.title !== item.title || existing.content !== nextContent || JSON.stringify(existing.contentRich) !== JSON.stringify(nextContentRich) || existing.status !== nextStatus || (existing.publishedAt?.getTime() ?? null) !== (publishedAt?.getTime() ?? null) || JSON.stringify(existing.coverImage) !== JSON.stringify(coverImage) || JSON.stringify(existing.author) !== JSON.stringify(author) || existing.icon !== nextIcon || JSON.stringify(existing.tags) !== JSON.stringify(normalizedTags) || JSON.stringify(existing.seo) !== JSON.stringify(seo);
2957
+ if (hasChanged) {
2958
+ existing.title = item.title;
2959
+ existing.content = nextContent;
2960
+ existing.contentRich = nextContentRich;
2961
+ existing.status = nextStatus;
2962
+ existing.publishedAt = publishedAt;
2963
+ existing.coverImage = coverImage;
2964
+ existing.author = author;
2965
+ existing.icon = nextIcon;
2966
+ existing.tags = normalizedTags;
2967
+ existing.seo = seo;
2968
+ existing.updatedAt = now;
2969
+ changed = true;
2970
+ }
2971
+ continue;
2972
+ }
2973
+ const id = store.generateId();
2974
+ const post = {
2975
+ id,
2976
+ brandappId,
2977
+ slug: item.slug,
2978
+ title: item.title,
2979
+ content: item.content ?? "",
2980
+ contentRich: item.contentRich ?? null,
2981
+ status: item.status ?? "draft",
2982
+ groupId: group.id,
2983
+ publishedAt,
2984
+ coverImage,
2985
+ author,
2986
+ icon: item.icon ?? null,
2987
+ tags: normalizedTags,
2988
+ seo,
2989
+ createdAt: now,
2990
+ updatedAt: now
2991
+ };
2992
+ store.posts.set(id, post);
2993
+ changed = true;
2994
+ }
2995
+ if (changed) persistIfNeeded();
2996
+ },
2997
+ async seedAll(input) {
2998
+ if (input.postGroups) await this.seedPostGroups(input.postGroups);
2999
+ if (input.posts) await this.seedPosts(input.posts);
3000
+ if (input.entities) await this.seed(input.entities);
3001
+ if (input.terms) await this.seedTerms(input.terms);
3002
+ },
3003
+ async seedTerms(items) {
3004
+ let nextOrder = 0;
3005
+ for (const item of items) {
3006
+ const now = store.now();
3007
+ const termsId = store.generateId();
3008
+ store.terms.set(termsId, {
3009
+ id: termsId,
3010
+ brandappId,
3011
+ title: item.title,
3012
+ type: item.type ?? "custom",
3013
+ jurisdiction: item.jurisdiction ?? "KR",
3014
+ isRequired: item.isRequired ?? false,
3015
+ isActive: true,
3016
+ sortOrder: item.sortOrder ?? nextOrder++,
3017
+ createdAt: now,
3018
+ updatedAt: now
3019
+ });
3020
+ const versionId = store.generateId();
3021
+ store.termsVersions.set(versionId, {
3022
+ id: versionId,
3023
+ termsId,
3024
+ version: 1,
3025
+ locale: item.locale ?? "ko-KR",
3026
+ content: item.content,
3027
+ changeSummary: item.changeSummary ?? null,
3028
+ publishedAt: now,
3029
+ isCurrent: true,
3030
+ reConsentDeadline: null,
3031
+ createdAt: now
3032
+ });
3033
+ }
3034
+ persistIfNeeded();
3035
+ },
3036
+ async reset() {
3037
+ store.clear();
3038
+ if (schema) {
3039
+ seedSchema(store, brandappId, schema);
3040
+ }
3041
+ persistIfNeeded();
3042
+ },
3043
+ async snapshot(path) {
3044
+ await mkdir(dirname(path), { recursive: true });
3045
+ await writeFile(path, store.toJSON(), "utf-8");
3046
+ },
3047
+ async restore(path) {
3048
+ const json = await readFile(path, "utf-8");
3049
+ store.fromJSON(json);
3050
+ persistIfNeeded();
3051
+ },
3052
+ async close() {
3053
+ if (persistTimer) clearTimeout(persistTimer);
3054
+ if (dataPath) {
3055
+ try {
3056
+ await mkdir(dirname(dataPath), { recursive: true });
3057
+ await writeFile(dataPath, store.toJSON(), "utf-8");
3058
+ } catch {
3059
+ }
3060
+ }
3061
+ await new Promise((resolve, reject) => {
3062
+ server.close((err) => err ? reject(err) : resolve());
3063
+ });
3064
+ }
3065
+ };
3066
+ return devServer;
3067
+ }
3068
+
3069
+ export { InMemoryStore, createDevServer, markdownToEditorSpec, markdownToEditorSpecMany };
3070
+ //# sourceMappingURL=index.js.map
3071
+ //# sourceMappingURL=index.js.map