monorise 1.15.0-dev.0 → 1.15.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.
@@ -14,403 +14,13 @@ import {
14
14
  // controllers/setupRoutes.ts
15
15
  import { Hono } from "hono";
16
16
 
17
- // middlewares/authorize.ts
17
+ // middlewares/entity-type-check.ts
18
18
  import { createMiddleware } from "hono/factory";
19
19
  import httpStatus from "http-status";
20
- var ENTITY_ROUTE_ACTIONS = {
21
- read: ["read"],
22
- list: ["read", "list"],
23
- unique: ["read"],
24
- tag: ["read", "list"],
25
- create: ["create"],
26
- update: ["update"],
27
- // Upsert creates or updates depending on whether the entity exists, and
28
- // checking which before the write would race, so it needs both.
29
- upsert: ["create", "update"],
30
- adjust: ["update"],
31
- delete: ["delete"]
32
- };
33
- var ROUTE_GUARD = /* @__PURE__ */ Symbol.for("monorise.routeGuard");
34
- var ROUTE_PERMISSION = /* @__PURE__ */ Symbol.for("monorise.routePermission");
35
- var NOT_DATA = /* @__PURE__ */ new Set(["$condition", "$where"]);
36
- var routeGuard = (requirement, middleware) => Object.defineProperty(middleware, ROUTE_GUARD, { value: requirement });
37
- var forbidden = (c, message, details) => {
38
- c.status(httpStatus.FORBIDDEN);
39
- return c.json(__spreadValues({ code: "FORBIDDEN", message }, details));
40
- };
41
- var deny = (c, denial, details) => {
42
- if (denial.status === 403 && denial.fields) {
43
- c.status(httpStatus.FORBIDDEN);
44
- return c.json(__spreadValues({
45
- code: "FORBIDDEN_FIELDS",
46
- message: denial.message,
47
- fields: denial.fields
48
- }, details));
49
- }
50
- if (denial.status === 403) return forbidden(c, denial.message, details);
51
- c.status(httpStatus.NOT_FOUND);
52
- return c.json(__spreadValues({ code: "NOT_FOUND" }, details));
53
- };
54
- var allowsEntityAction = (access, action) => action === "delete" || action === "list" ? access[action] : access[action] !== null;
55
- var restrictedKey = (c) => {
56
- const key = c.get("apiKey");
57
- return key && !key.access.full ? key : void 0;
58
- };
59
- var jsonBody = (c) => __async(null, null, function* () {
60
- try {
61
- return yield c.req.json();
62
- } catch (e) {
63
- return void 0;
64
- }
65
- });
66
- var createRouteGuards = (entityConfig) => {
67
- const checkEntity = (key, entityType, action) => {
68
- const access = key.access.entity(entityType);
69
- if (!access.visible) return { status: 404 };
70
- if (allowsEntityAction(access, action)) return null;
71
- return {
72
- status: 403,
73
- message: `API key policy '${key.policy}' does not allow ${action} on '${entityType}'`
74
- };
75
- };
76
- const asEntityType = (byEntityType, entityType) => {
77
- var _a;
78
- const declared = (from, to) => {
79
- var _a2, _b, _c, _d, _e, _f;
80
- return (_f = (_e = (_d = Object.values((_c = (_b = (_a2 = entityConfig[from]) == null ? void 0 : _a2.mutual) == null ? void 0 : _b.mutualFields) != null ? _c : {}).find(
81
- (field) => field.entityType === to && field.mutual
82
- )) == null ? void 0 : _d.mutual) == null ? void 0 : _e.asEntity) == null ? void 0 : _f.name;
83
- };
84
- return (_a = declared(byEntityType, entityType)) != null ? _a : declared(entityType, byEntityType);
85
- };
86
- const checkDirection = (key, byEntityType, entityType, action, requestedAsEntity) => {
87
- const access = key.access.mutual(byEntityType, entityType);
88
- if (!access) return { status: 404 };
89
- const granted = action === "delete" ? access.delete : access[action] !== null;
90
- if (!granted) {
91
- return {
92
- status: 403,
93
- message: `API key policy '${key.policy}' does not allow ${action} on ${byEntityType}\u2192${entityType}`
94
- };
95
- }
96
- const asEntity = action === "create" ? requestedAsEntity || asEntityType(byEntityType, entityType) : void 0;
97
- if (asEntity && !key.access.entity(asEntity).create) {
98
- return {
99
- status: 403,
100
- message: `API key policy '${key.policy}' does not allow create on '${asEntity}', which ${byEntityType}\u2192${entityType} creates`
101
- };
102
- }
103
- return null;
104
- };
105
- const quoted = (fields) => fields.map((field) => `'${field}'`).join(", ");
106
- const checkFields = (key, granted, fields, what) => {
107
- const disallowed = granted === "*" ? [] : fields.filter((field) => !(granted == null ? void 0 : granted.has(field)));
108
- if (!disallowed.length) return null;
109
- return {
110
- status: 403,
111
- message: `API key policy '${key.policy}' does not allow ${what}: ${quoted(disallowed)}`,
112
- fields: disallowed
113
- };
114
- };
115
- const relationshipFieldNames = (entityType) => {
116
- var _a, _b, _c;
117
- return new Set(Object.keys((_c = (_b = (_a = entityConfig[entityType]) == null ? void 0 : _a.mutual) == null ? void 0 : _b.mutualFields) != null ? _c : {}));
118
- };
119
- const dataFields = (entityType, payload) => {
120
- if (typeof payload !== "object" || payload === null) return [];
121
- const relationships = relationshipFieldNames(entityType);
122
- return Object.keys(payload).filter(
123
- (field) => !NOT_DATA.has(field) && !relationships.has(field)
124
- );
125
- };
126
- const createFields = (entityType, payload, choosesEntityId) => {
127
- const fields = dataFields(entityType, payload).map(
128
- (field) => field === "entityId" ? "$entityId" : field === "createdAt" ? "$createdAt" : field
129
- );
130
- if (choosesEntityId && !fields.includes("$entityId")) {
131
- fields.push("$entityId");
132
- }
133
- return fields;
134
- };
135
- const checkRelationshipFields = (key, entityType, payload, write) => {
136
- var _a, _b, _c;
137
- if (typeof payload !== "object" || payload === null) return null;
138
- const relationshipFields = (_b = (_a = entityConfig[entityType]) == null ? void 0 : _a.mutual) == null ? void 0 : _b.mutualFields;
139
- if (!relationshipFields) return null;
140
- const actions = write === "create" ? ["create"] : ["create", "delete"];
141
- for (const field of Object.keys(payload)) {
142
- const target = (_c = relationshipFields[field]) == null ? void 0 : _c.entityType;
143
- if (!target) continue;
144
- for (const action of actions) {
145
- const denial = checkDirection(key, entityType, target, action);
146
- if (denial) return denial;
147
- }
148
- }
149
- return null;
150
- };
151
- const checkCreate = (key, entityType, payload, choosesEntityId) => {
152
- var _a;
153
- return (_a = checkRelationshipFields(key, entityType, payload, "create")) != null ? _a : checkFields(
154
- key,
155
- key.access.entity(entityType).create,
156
- createFields(entityType, payload, choosesEntityId),
157
- `create on these fields of '${entityType}'`
158
- );
159
- };
160
- const checkUpdate = (key, entityType, payload) => {
161
- var _a, _b;
162
- const access = key.access.entity(entityType);
163
- const where = payload == null ? void 0 : payload.$where;
164
- return (_b = (_a = checkRelationshipFields(key, entityType, payload, "update")) != null ? _a : checkFields(
165
- key,
166
- access.update,
167
- dataFields(entityType, payload),
168
- `update on these fields of '${entityType}'`
169
- )) != null ? _b : typeof where === "object" && where !== null ? checkFields(
170
- key,
171
- access.read,
172
- Object.keys(where),
173
- `$where on these fields of '${entityType}', which it cannot read`
174
- ) : null;
175
- };
176
- const checkAdjust = (key, entityType, adjustments) => checkFields(
177
- key,
178
- key.access.entity(entityType).update,
179
- dataFields(entityType, adjustments),
180
- `adjust on these fields of '${entityType}'`
181
- );
182
- const checkSearch = (key, entityType) => {
183
- var _a, _b;
184
- return checkFields(
185
- key,
186
- key.access.entity(entityType).read,
187
- ((_b = (_a = entityConfig[entityType]) == null ? void 0 : _a.searchableFields) != null ? _b : []).map(String),
188
- `search on '${entityType}', which matches these fields it cannot read`
189
- );
190
- };
191
- const checkUniqueLookup = (key, entityType, field) => checkFields(
192
- key,
193
- key.access.entity(entityType).read,
194
- [field],
195
- `a lookup on '${entityType}' by a field it cannot read`
196
- );
197
- const checkTag = (key, entityType, tagName) => {
198
- const { tags } = key.access.entity(entityType);
199
- if (tags === "*" || (tags == null ? void 0 : tags.has(tagName))) return null;
200
- return {
201
- status: 403,
202
- message: `API key policy '${key.policy}' does not allow reading tag '${tagName}' of '${entityType}'`
203
- };
204
- };
205
- const entity = (route) => routeGuard(
206
- `entity:${route}`,
207
- createMiddleware((c, next) => __async(null, null, function* () {
208
- var _a, _b, _c, _d;
209
- const key = restrictedKey(c);
210
- if (key) {
211
- const entityType = (_a = c.req.param("entityType")) != null ? _a : "";
212
- for (const action of ENTITY_ROUTE_ACTIONS[route]) {
213
- const denial2 = checkEntity(key, entityType, action);
214
- if (denial2) return deny(c, denial2);
215
- }
216
- let denial = null;
217
- if (route === "list" && c.req.query("query")) {
218
- denial = checkSearch(key, entityType);
219
- } else if (route === "unique") {
220
- denial = checkUniqueLookup(
221
- key,
222
- entityType,
223
- (_b = c.req.param("uniqueField")) != null ? _b : ""
224
- );
225
- } else if (route === "tag") {
226
- denial = checkTag(key, entityType, (_c = c.req.param("tagName")) != null ? _c : "");
227
- } else if (route === "create") {
228
- denial = checkCreate(key, entityType, yield jsonBody(c), false);
229
- } else if (route === "update") {
230
- denial = checkUpdate(key, entityType, yield jsonBody(c));
231
- } else if (route === "upsert") {
232
- const body = yield jsonBody(c);
233
- denial = (_d = checkCreate(key, entityType, body, true)) != null ? _d : checkUpdate(key, entityType, body);
234
- } else if (route === "adjust") {
235
- denial = checkAdjust(key, entityType, yield jsonBody(c));
236
- }
237
- if (denial) return deny(c, denial);
238
- }
239
- yield next();
240
- }))
241
- );
242
- const checkMutualData = (key, byEntityType, entityType, action, payload) => {
243
- var _a, _b;
244
- return typeof payload === "object" && payload !== null ? checkFields(
245
- key,
246
- (_b = (_a = key.access.mutual(byEntityType, entityType)) == null ? void 0 : _a[action]) != null ? _b : null,
247
- Object.keys(payload),
248
- `${action} on these mutualData fields of ${byEntityType}\u2192${entityType}`
249
- ) : null;
250
- };
251
- const mutual = (action) => routeGuard(
252
- `mutual:${action}`,
253
- createMiddleware((c, next) => __async(null, null, function* () {
254
- var _a, _b;
255
- const key = restrictedKey(c);
256
- if (key) {
257
- const byEntityType = (_a = c.req.param("byEntityType")) != null ? _a : "";
258
- const entityType = (_b = c.req.param("entityType")) != null ? _b : "";
259
- const chain = c.req.query("chainEntityQuery");
260
- const path = action === "read" && chain ? [byEntityType, ...chain.split(","), entityType] : [byEntityType, entityType];
261
- const requestedAsEntity = action === "create" ? c.req.query("asEntity") : void 0;
262
- for (let hop = 1; hop < path.length; hop++) {
263
- const denial = checkDirection(
264
- key,
265
- path[hop - 1],
266
- path[hop],
267
- action,
268
- requestedAsEntity
269
- );
270
- if (denial) return deny(c, denial);
271
- }
272
- if (action === "create" || action === "update") {
273
- const denial = checkMutualData(
274
- key,
275
- byEntityType,
276
- entityType,
277
- action,
278
- yield jsonBody(c)
279
- );
280
- if (denial) return deny(c, denial);
281
- }
282
- }
283
- yield next();
284
- }))
285
- );
286
- const checkOperation = (key, operation) => {
287
- var _a, _b, _c, _d, _e;
288
- switch (operation == null ? void 0 : operation.operation) {
289
- case "createEntity":
290
- return (_a = checkEntity(key, operation.entityType, "create")) != null ? _a : checkCreate(
291
- key,
292
- operation.entityType,
293
- operation.payload,
294
- Boolean(operation.entityId)
295
- );
296
- case "updateEntity":
297
- return (_b = checkEntity(key, operation.entityType, "update")) != null ? _b : checkUpdate(key, operation.entityType, operation.payload);
298
- case "adjustEntity":
299
- return (_c = checkEntity(key, operation.entityType, "update")) != null ? _c : checkAdjust(key, operation.entityType, operation.adjustments);
300
- case "deleteEntity":
301
- return checkEntity(key, operation.entityType, "delete");
302
- case "createMutual":
303
- return (_d = checkDirection(
304
- key,
305
- operation.byEntityType,
306
- operation.entityType,
307
- "create"
308
- )) != null ? _d : checkMutualData(
309
- key,
310
- operation.byEntityType,
311
- operation.entityType,
312
- "create",
313
- operation.payload
314
- );
315
- case "updateMutual":
316
- return (_e = checkDirection(
317
- key,
318
- operation.byEntityType,
319
- operation.entityType,
320
- "update"
321
- )) != null ? _e : checkMutualData(
322
- key,
323
- operation.byEntityType,
324
- operation.entityType,
325
- "update",
326
- operation.payload
327
- );
328
- case "deleteMutual":
329
- return checkDirection(
330
- key,
331
- operation.byEntityType,
332
- operation.entityType,
333
- "delete"
334
- );
335
- default:
336
- return null;
337
- }
338
- };
339
- const transaction = () => routeGuard(
340
- "transaction",
341
- createMiddleware((c, next) => __async(null, null, function* () {
342
- var _a;
343
- const key = restrictedKey(c);
344
- if (!key) return next();
345
- const operations = (_a = yield jsonBody(c)) == null ? void 0 : _a.operations;
346
- if (!Array.isArray(operations)) return next();
347
- for (const [operationIndex, operation] of operations.entries()) {
348
- const denial = checkOperation(key, operation);
349
- if (denial) return deny(c, denial, { operationIndex });
350
- }
351
- yield next();
352
- }))
353
- );
354
- return { entity, mutual, transaction };
355
- };
356
- var requireFullPolicy = () => routeGuard(
357
- "full",
358
- createMiddleware((c, next) => __async(null, null, function* () {
359
- const key = restrictedKey(c);
360
- if (key) {
361
- return forbidden(
362
- c,
363
- `API key policy '${key.policy}' cannot call this route; only 'full' can`
364
- );
365
- }
366
- yield next();
367
- }))
368
- );
369
- var requires = (permission) => Object.defineProperty(
370
- createMiddleware((c, next) => __async(null, null, function* () {
371
- const key = restrictedKey(c);
372
- if (key && !key.has(permission)) {
373
- return forbidden(
374
- c,
375
- `API key policy '${key.policy}' does not grant '${permission}'`
376
- );
377
- }
378
- yield next();
379
- })),
380
- ROUTE_PERMISSION,
381
- { value: permission }
382
- );
383
- var customRouteGate = () => createMiddleware((c, next) => __async(null, null, function* () {
384
- const key = restrictedKey(c);
385
- if (key) {
386
- const permissions = c.req.matchedRoutes.flatMap((route) => {
387
- const permission = route.handler[ROUTE_PERMISSION];
388
- return typeof permission === "string" ? [permission] : [];
389
- });
390
- if (!permissions.length) {
391
- return forbidden(
392
- c,
393
- "This route declares no permission with requires(), so only 'full' keys can call it"
394
- );
395
- }
396
- const missing = permissions.find((permission) => !key.has(permission));
397
- if (missing !== void 0) {
398
- return forbidden(
399
- c,
400
- `API key policy '${key.policy}' does not grant '${missing}'`
401
- );
402
- }
403
- }
404
- yield next();
405
- }));
406
-
407
- // middlewares/entity-type-check.ts
408
- import { createMiddleware as createMiddleware2 } from "hono/factory";
409
- import httpStatus2 from "http-status";
410
- var entityTypeCheck = (container) => createMiddleware2((c, next) => __async(null, null, function* () {
20
+ var entityTypeCheck = (container) => createMiddleware((c, next) => __async(null, null, function* () {
411
21
  const { entityType } = c.req.param();
412
22
  if (!container.config.AllowedEntityTypes.includes(entityType)) {
413
- c.status(httpStatus2.NOT_FOUND);
23
+ c.status(httpStatus.NOT_FOUND);
414
24
  return c.json({
415
25
  code: "NOT_FOUND"
416
26
  });
@@ -418,65 +28,13 @@ var entityTypeCheck = (container) => createMiddleware2((c, next) => __async(null
418
28
  yield next();
419
29
  }));
420
30
 
421
- // middlewares/mask.ts
422
- import { createMiddleware as createMiddleware3 } from "hono/factory";
423
- var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
424
- var maskFields = (data, granted) => granted === "*" ? data : Object.fromEntries(
425
- Object.entries(data).filter(([field]) => granted == null ? void 0 : granted.has(field))
426
- );
427
- var maskRecord = (record, access) => {
428
- var _a, _b;
429
- const entityType = record.entityType;
430
- const masked = __spreadValues({}, record);
431
- if (isPlainObject(record.data)) {
432
- masked.data = maskFields(record.data, access.entity(entityType).read);
433
- }
434
- if (typeof record.byEntityType === "string" && isPlainObject(record.mutualData)) {
435
- masked.mutualData = maskFields(
436
- record.mutualData,
437
- (_b = (_a = access.mutual(record.byEntityType, entityType)) == null ? void 0 : _a.read) != null ? _b : null
438
- );
439
- }
440
- return masked;
441
- };
442
- var maskResponseBody = (body, access) => {
443
- if (Array.isArray(body))
444
- return body.map((item) => maskResponseBody(item, access));
445
- if (!isPlainObject(body)) return body;
446
- if (typeof body.entityType === "string" && ("data" in body || "mutualData" in body)) {
447
- return maskRecord(body, access);
448
- }
449
- return Object.fromEntries(
450
- Object.entries(body).map(([key, value]) => [
451
- key,
452
- maskResponseBody(value, access)
453
- ])
454
- );
455
- };
456
- var maskResponses = () => createMiddleware3((c, next) => __async(null, null, function* () {
457
- var _a;
458
- yield next();
459
- const key = c.get("apiKey");
460
- if (!key || key.access.full || !c.res.ok) return;
461
- if (!((_a = c.res.headers.get("content-type")) == null ? void 0 : _a.includes("application/json"))) {
462
- return;
463
- }
464
- const body = yield c.res.json();
465
- const headers = new Headers(c.res.headers);
466
- headers.delete("content-length");
467
- c.res = new Response(JSON.stringify(maskResponseBody(body, key.access)), {
468
- status: c.res.status,
469
- headers
470
- });
471
- }));
472
-
473
31
  // middlewares/mutual-type-check.ts
474
- import { createMiddleware as createMiddleware4 } from "hono/factory";
475
- import httpStatus3 from "http-status";
476
- var mutualTypeCheck = (container) => createMiddleware4((c, next) => __async(null, null, function* () {
32
+ import { createMiddleware as createMiddleware2 } from "hono/factory";
33
+ import httpStatus2 from "http-status";
34
+ var mutualTypeCheck = (container) => createMiddleware2((c, next) => __async(null, null, function* () {
477
35
  const { entityType, byEntityType } = c.req.param();
478
36
  if (!container.config.AllowedEntityTypes.includes(entityType) || !container.config.AllowedEntityTypes.includes(byEntityType)) {
479
- c.status(httpStatus3.NOT_FOUND);
37
+ c.status(httpStatus2.NOT_FOUND);
480
38
  return c.json({
481
39
  code: "NOT_FOUND"
482
40
  });
@@ -487,91 +45,61 @@ var mutualTypeCheck = (container) => createMiddleware4((c, next) => __async(null
487
45
  // controllers/setupRoutes.ts
488
46
  var setupCommonRoutes = (container) => {
489
47
  const app = new Hono();
490
- const guard = createRouteGuards(container.config.EntityConfig);
491
- app.use("*", maskResponses());
492
48
  app.use(
493
49
  "/mutual/:byEntityType/:byEntityId/:entityType",
494
50
  mutualTypeCheck(container)
495
51
  );
496
52
  app.get(
497
53
  "/mutual/:byEntityType/:byEntityId/:entityType",
498
- guard.mutual("read"),
499
54
  container.listEntitiesByEntityController.controller
500
55
  );
501
56
  app.post(
502
57
  "/mutual/:byEntityType/:byEntityId/:entityType/:entityId",
503
- guard.mutual("create"),
504
58
  container.createMutualController.controller
505
59
  );
506
60
  app.get(
507
61
  "/mutual/:byEntityType/:byEntityId/:entityType/:entityId",
508
- guard.mutual("read"),
509
62
  container.getMutualController.controller
510
63
  );
511
64
  app.patch(
512
65
  "/mutual/:byEntityType/:byEntityId/:entityType/:entityId",
513
- guard.mutual("update"),
514
66
  container.updateMutualController.controller
515
67
  );
516
68
  app.delete(
517
69
  "/mutual/:byEntityType/:byEntityId/:entityType/:entityId",
518
- guard.mutual("delete"),
519
70
  container.deleteMutualController.controller
520
71
  );
521
72
  app.use("/entity/:entityType", entityTypeCheck(container));
522
- app.get(
523
- "/entity/:entityType",
524
- guard.entity("list"),
525
- container.listEntitiesController.controller
526
- );
527
- app.post(
528
- "/entity/:entityType",
529
- guard.entity("create"),
530
- container.createEntityController.controller
531
- );
73
+ app.get("/entity/:entityType", container.listEntitiesController.controller);
74
+ app.post("/entity/:entityType", container.createEntityController.controller);
532
75
  app.get(
533
76
  "/entity/:entityType/unique/:uniqueField/:uniqueFieldValue",
534
- guard.entity("unique"),
535
77
  container.getEntityByUniqueFieldController.controller
536
78
  );
537
79
  app.post(
538
80
  "/entity/:entityType/:entityId/adjust",
539
- guard.entity("adjust"),
540
81
  container.adjustEntityController.controller
541
82
  );
542
83
  app.get(
543
84
  "/entity/:entityType/:entityId",
544
- guard.entity("read"),
545
85
  container.getEntityController.controller
546
86
  );
547
87
  app.put(
548
88
  "/entity/:entityType/:entityId",
549
- guard.entity("upsert"),
550
89
  container.upsertEntityController.controller
551
90
  );
552
91
  app.patch(
553
92
  "/entity/:entityType/:entityId",
554
- guard.entity("update"),
555
93
  container.updateEntityController.controller
556
94
  );
557
95
  app.delete(
558
96
  "/entity/:entityType/:entityId",
559
- guard.entity("delete"),
560
97
  container.deleteEntityController.controller
561
98
  );
562
- app.get(
563
- "/tag/:entityType/:tagName",
564
- guard.entity("tag"),
565
- container.listTagsController.controller
566
- );
567
- app.post(
568
- "/transaction",
569
- guard.transaction(),
570
- container.executeTransactionController.controller
571
- );
99
+ app.get("/tag/:entityType/:tagName", container.listTagsController.controller);
100
+ app.post("/transaction", container.executeTransactionController.controller);
572
101
  app.post(
573
102
  "/ws/ticket/:entityType/:entityId",
574
- requireFullPolicy(),
575
103
  container.createTicketController.controller
576
104
  );
577
105
  return app;
@@ -995,10 +523,7 @@ var EntityRepository = class extends Repository {
995
523
  var _a;
996
524
  const resp = yield this.dynamodbClient.query({
997
525
  TableName: this.TABLE_NAME,
998
- // Exact match: a unique item's SK is the bare entity type, so a prefix
999
- // match would also return another type whose name starts with this one
1000
- // (e.g. 'user' matching 'user-profile').
1001
- KeyConditionExpression: "#PK = :PK and #SK = :SK",
526
+ KeyConditionExpression: "#PK = :PK and begins_with(#SK, :SK)",
1002
527
  ExpressionAttributeNames: {
1003
528
  "#PK": "PK",
1004
529
  "#SK": "SK"
@@ -1016,8 +541,7 @@ var EntityRepository = class extends Repository {
1016
541
  var _a;
1017
542
  const resp = yield this.dynamodbClient.query({
1018
543
  TableName: this.TABLE_NAME,
1019
- // Exact match, as in getEntityByUniqueField.
1020
- KeyConditionExpression: "#PK = :PK and #SK = :SK",
544
+ KeyConditionExpression: "#PK = :PK and begins_with(#SK, :SK)",
1021
545
  ExpressionAttributeNames: {
1022
546
  "#PK": "PK",
1023
547
  "#SK": "SK"
@@ -1454,12 +978,10 @@ var EntityRepository = class extends Repository {
1454
978
  const filteredItems = [];
1455
979
  const { searchableFields } = this.EntityConfig[entityType];
1456
980
  for (const item of results.items) {
1457
- const searchTerm = (searchableFields != null ? searchableFields : []).map(
1458
- (field) => {
1459
- var _a;
1460
- return (_a = item.data[field]) == null ? void 0 : _a.toLowerCase();
1461
- }
1462
- ).join(" ");
981
+ const searchTerm = (searchableFields != null ? searchableFields : []).map((field) => {
982
+ const value = item.data[field];
983
+ return (Array.isArray(value) ? value : [value]).filter((v) => typeof v === "string" || typeof v === "number").map((v) => String(v).toLowerCase()).join(" ");
984
+ }).join(" ");
1463
985
  const isMatched = queryRegex.test(searchTerm);
1464
986
  if (isMatched) {
1465
987
  filteredItems.push(item);
@@ -1491,6 +1013,14 @@ var PROJECTION_EXPRESSION = {
1491
1013
  MUTUAL_DATA_ONLY: "byEntityType, byEntityId, entityType, entityId, mutualId, mutualData"
1492
1014
  };
1493
1015
 
1016
+ // helpers/debug.ts
1017
+ var OFF = /* @__PURE__ */ new Set(["", "0", "false", "off", "no"]);
1018
+ var debugLog = (...args) => {
1019
+ var _a;
1020
+ const flag = (_a = process.env.MONORISE_DEBUG) == null ? void 0 : _a.trim().toLowerCase();
1021
+ if (flag !== void 0 && !OFF.has(flag)) console.log(...args);
1022
+ };
1023
+
1494
1024
  // data/Mutual.ts
1495
1025
  var Mutual = class _Mutual {
1496
1026
  constructor(byEntityType, byEntityId, byData, entityType, entityId, data, mutualData, mutualId, _createdAt, _updatedAt, _mutualUpdatedAt, _expiresAt) {
@@ -1670,7 +1200,7 @@ var MutualRepository = class extends Repository {
1670
1200
  getMutual(byEntityType, byEntityId, entityType, entityId, opts) {
1671
1201
  return __async(this, null, function* () {
1672
1202
  var _a, _b, _c, _d, _e, _f;
1673
- console.log("[MONORISE_DEBUG] getMutual start:", {
1203
+ debugLog("[MONORISE_DEBUG] getMutual start:", {
1674
1204
  byEntityType,
1675
1205
  byEntityId,
1676
1206
  entityType,
@@ -1686,7 +1216,7 @@ var MutualRepository = class extends Repository {
1686
1216
  {},
1687
1217
  {}
1688
1218
  );
1689
- console.log("[MONORISE_DEBUG] getMutual querying:", {
1219
+ debugLog("[MONORISE_DEBUG] getMutual querying:", {
1690
1220
  byFullEntityId: mutual.byFullEntityId,
1691
1221
  fullEntityId: mutual.fullEntityId,
1692
1222
  tableName: this.TABLE_NAME
@@ -1707,7 +1237,7 @@ var MutualRepository = class extends Repository {
1707
1237
  },
1708
1238
  Limit: 1
1709
1239
  });
1710
- console.log("[MONORISE_DEBUG] getMutual query result:", {
1240
+ debugLog("[MONORISE_DEBUG] getMutual query result:", {
1711
1241
  hasItems: !!((_a = resp.Items) == null ? void 0 : _a.length),
1712
1242
  itemCount: (_c = (_b = resp.Items) == null ? void 0 : _b.length) != null ? _c : 0,
1713
1243
  hasLastEvaluatedKey: !!resp.LastEvaluatedKey
@@ -1722,12 +1252,12 @@ var MutualRepository = class extends Repository {
1722
1252
  });
1723
1253
  mutualMetadata = Mutual.fromItem(respMetadataMutual.Item);
1724
1254
  }
1725
- console.log("[MONORISE_DEBUG] getMutual fromItem:", {
1255
+ debugLog("[MONORISE_DEBUG] getMutual fromItem:", {
1726
1256
  hasMutualMetadata: !!mutualMetadata,
1727
1257
  hasFirstItem: !!((_e = resp.Items) == null ? void 0 : _e[0])
1728
1258
  });
1729
1259
  const result = mutualMetadata || Mutual.fromItem((_f = resp.Items) == null ? void 0 : _f[0]);
1730
- console.log("[MONORISE_DEBUG] getMutual complete:", {
1260
+ debugLog("[MONORISE_DEBUG] getMutual complete:", {
1731
1261
  mutualId: result.mutualId,
1732
1262
  byEntityType: result.byEntityType,
1733
1263
  entityType: result.entityType
@@ -1738,7 +1268,7 @@ var MutualRepository = class extends Repository {
1738
1268
  checkMutualExist(byEntityType, byEntityId, entityType, entityId) {
1739
1269
  return __async(this, null, function* () {
1740
1270
  var _a, _b;
1741
- console.log("[MONORISE_DEBUG] checkMutualExist:", {
1271
+ debugLog("[MONORISE_DEBUG] checkMutualExist:", {
1742
1272
  byEntityType,
1743
1273
  byEntityId,
1744
1274
  entityType,
@@ -1758,7 +1288,7 @@ var MutualRepository = class extends Repository {
1758
1288
  Key: mutual.subKeys(),
1759
1289
  ProjectionExpression: "PK, SK, expiresAt"
1760
1290
  });
1761
- console.log("[MONORISE_DEBUG] checkMutualExist result:", {
1291
+ debugLog("[MONORISE_DEBUG] checkMutualExist result:", {
1762
1292
  hasItem: !!resp.Item,
1763
1293
  hasExpiresAt: !!((_a = resp.Item) == null ? void 0 : _a.expiresAt)
1764
1294
  });
@@ -1772,7 +1302,7 @@ var MutualRepository = class extends Repository {
1772
1302
  });
1773
1303
  }
1774
1304
  createMutualTransactItems(mutual, opts) {
1775
- console.log("[MONORISE_DEBUG] createMutualTransactItems:", {
1305
+ debugLog("[MONORISE_DEBUG] createMutualTransactItems:", {
1776
1306
  mutualId: mutual.mutualId,
1777
1307
  byEntityType: mutual.byEntityType,
1778
1308
  byEntityId: mutual.byEntityId,
@@ -1860,7 +1390,7 @@ var MutualRepository = class extends Repository {
1860
1390
  */
1861
1391
  prepareUpdateMutual(byEntityType, byEntityId, entityType, entityId, toUpdate, opts) {
1862
1392
  return __async(this, null, function* () {
1863
- console.log("[MONORISE_DEBUG] updateMutual fetching mutual...");
1393
+ debugLog("[MONORISE_DEBUG] updateMutual fetching mutual...");
1864
1394
  const mutual = yield this.getMutual(
1865
1395
  byEntityType,
1866
1396
  byEntityId,
@@ -1868,7 +1398,7 @@ var MutualRepository = class extends Repository {
1868
1398
  entityId,
1869
1399
  { ProjectionExpression: PROJECTION_EXPRESSION.NO_DATA }
1870
1400
  );
1871
- console.log("[MONORISE_DEBUG] updateMutual mutual found:", {
1401
+ debugLog("[MONORISE_DEBUG] updateMutual mutual found:", {
1872
1402
  mutualId: mutual.mutualId,
1873
1403
  mainPk: mutual.mainPk,
1874
1404
  byFullEntityId: mutual.byFullEntityId,
@@ -1881,7 +1411,7 @@ var MutualRepository = class extends Repository {
1881
1411
  }, toUpdate),
1882
1412
  { maxLevel: opts == null ? void 0 : opts.maxObjectUpdateLevel }
1883
1413
  );
1884
- console.log("[MONORISE_DEBUG] updateMutual update expression:", {
1414
+ debugLog("[MONORISE_DEBUG] updateMutual update expression:", {
1885
1415
  UpdateExpression: toUpdateExpressions.UpdateExpression,
1886
1416
  ExpressionAttributeNames: toUpdateExpressions.ExpressionAttributeNames,
1887
1417
  hasExpressionAttributeValues: !!toUpdateExpressions.ExpressionAttributeValues
@@ -1918,7 +1448,7 @@ var MutualRepository = class extends Repository {
1918
1448
  }, updateExpression)
1919
1449
  }
1920
1450
  ];
1921
- console.log("[MONORISE_DEBUG] updateMutual transact items prepared:", {
1451
+ debugLog("[MONORISE_DEBUG] updateMutual transact items prepared:", {
1922
1452
  itemCount: TransactItems.length,
1923
1453
  tableName: this.TABLE_NAME
1924
1454
  });
@@ -1928,7 +1458,7 @@ var MutualRepository = class extends Repository {
1928
1458
  updateMutual(byEntityType, byEntityId, entityType, entityId, toUpdate, opts) {
1929
1459
  return __async(this, null, function* () {
1930
1460
  var _a, _b;
1931
- console.log("[MONORISE_DEBUG] updateMutual repository start:", {
1461
+ debugLog("[MONORISE_DEBUG] updateMutual repository start:", {
1932
1462
  byEntityType,
1933
1463
  byEntityId,
1934
1464
  entityType,
@@ -1948,24 +1478,24 @@ var MutualRepository = class extends Repository {
1948
1478
  opts
1949
1479
  );
1950
1480
  errorContext.TransactItems = TransactItems;
1951
- console.log("[MONORISE_DEBUG] updateMutual executing transaction...");
1481
+ debugLog("[MONORISE_DEBUG] updateMutual executing transaction...");
1952
1482
  yield this.ddbUtils.executeTransactWrite({ TransactItems });
1953
- console.log("[MONORISE_DEBUG] updateMutual transaction succeeded");
1483
+ debugLog("[MONORISE_DEBUG] updateMutual transaction succeeded");
1954
1484
  if (!returnUpdatedValue) {
1955
- console.log("[MONORISE_DEBUG] updateMutual returning (no value)");
1485
+ debugLog("[MONORISE_DEBUG] updateMutual returning (no value)");
1956
1486
  return;
1957
1487
  }
1958
- console.log("[MONORISE_DEBUG] updateMutual fetching updated mutual...");
1488
+ debugLog("[MONORISE_DEBUG] updateMutual fetching updated mutual...");
1959
1489
  const updatedMutual = yield this.getMutual(
1960
1490
  byEntityType,
1961
1491
  byEntityId,
1962
1492
  entityType,
1963
1493
  entityId
1964
1494
  );
1965
- console.log("[MONORISE_DEBUG] updateMutual repository complete");
1495
+ debugLog("[MONORISE_DEBUG] updateMutual repository complete");
1966
1496
  return updatedMutual;
1967
1497
  } catch (err) {
1968
- console.error("[MONORISE_DEBUG] updateMutual repository error:", {
1498
+ debugLog("[MONORISE_DEBUG] updateMutual repository error:", {
1969
1499
  errorName: (_b = err == null ? void 0 : err.constructor) == null ? void 0 : _b.name,
1970
1500
  errorMessage: err == null ? void 0 : err.message,
1971
1501
  errorCode: err == null ? void 0 : err.code,
@@ -2169,6 +1699,295 @@ var MutualRepository = class extends Repository {
2169
1699
  }
2170
1700
  };
2171
1701
 
1702
+ // data/Search.ts
1703
+ import {
1704
+ ConditionalCheckFailedException as ConditionalCheckFailedException2
1705
+ } from "@aws-sdk/client-dynamodb";
1706
+ import {
1707
+ indexedWords,
1708
+ matchesSearch,
1709
+ planSearch,
1710
+ resolveSearchConfig,
1711
+ searchConfigHash
1712
+ } from "../base/index.js";
1713
+ var INDEX_STATE_PK = "#SEARCH#";
1714
+ var BATCH_WRITE_LIMIT = 25;
1715
+ var SearchRepository = class {
1716
+ constructor(EntityConfig, TABLE_NAME, dynamodbClient, entityRepository, searchDefaults) {
1717
+ this.EntityConfig = EntityConfig;
1718
+ this.TABLE_NAME = TABLE_NAME;
1719
+ this.dynamodbClient = dynamodbClient;
1720
+ this.entityRepository = entityRepository;
1721
+ this.searchDefaults = searchDefaults;
1722
+ // Entity types whose index matched the config, once seen. The config is
1723
+ // fixed for the life of a Lambda instance, so this never goes stale.
1724
+ this.readyTypes = /* @__PURE__ */ new Set();
1725
+ }
1726
+ /** The resolved `search` config, or undefined if the type isn't indexed. */
1727
+ searchConfig(entityType) {
1728
+ var _a;
1729
+ const search = (_a = this.EntityConfig[entityType]) == null ? void 0 : _a.search;
1730
+ return search ? resolveSearchConfig(search, this.searchDefaults) : void 0;
1731
+ }
1732
+ indexedEntityTypes() {
1733
+ return Object.keys(this.EntityConfig).filter(
1734
+ (entityType) => {
1735
+ var _a;
1736
+ return (_a = this.EntityConfig[entityType]) == null ? void 0 : _a.search;
1737
+ }
1738
+ );
1739
+ }
1740
+ rowKeys(entityType, entityId, word) {
1741
+ return {
1742
+ PK: { S: `SEARCH#${entityType}` },
1743
+ SK: { S: `${word}#${entityId}` }
1744
+ };
1745
+ }
1746
+ searchRow(entity, word) {
1747
+ return __spreadProps(__spreadValues(__spreadValues({}, entity.toItem()), this.rowKeys(entity.entityType, entity.entityId, word)), {
1748
+ R1PK: entity.keys().PK,
1749
+ R1SK: { S: `SEARCH#${word}` }
1750
+ });
1751
+ }
1752
+ /** Puts a row for each word in `add` and deletes the rows in `remove`. */
1753
+ writeRows(entity, add, remove) {
1754
+ return __async(this, null, function* () {
1755
+ var _a, _b;
1756
+ const entityId = entity.entityId;
1757
+ const requests = [
1758
+ ...add.map((word) => ({
1759
+ PutRequest: { Item: this.searchRow(entity, word) }
1760
+ })),
1761
+ ...remove.map((word) => ({
1762
+ DeleteRequest: {
1763
+ Key: this.rowKeys(entity.entityType, entityId, word)
1764
+ }
1765
+ }))
1766
+ ];
1767
+ for (let i = 0; i < requests.length; i += BATCH_WRITE_LIMIT) {
1768
+ let batch = requests.slice(i, i + BATCH_WRITE_LIMIT);
1769
+ for (let attempt = 0; batch.length; attempt++) {
1770
+ if (attempt > 0) {
1771
+ yield new Promise(
1772
+ (resolve) => setTimeout(resolve, Math.min(1e3, 50 * 2 ** attempt))
1773
+ );
1774
+ }
1775
+ const resp = yield this.dynamodbClient.batchWriteItem({
1776
+ RequestItems: { [this.TABLE_NAME]: batch }
1777
+ });
1778
+ batch = (_b = (_a = resp.UnprocessedItems) == null ? void 0 : _a[this.TABLE_NAME]) != null ? _b : [];
1779
+ if (batch.length && attempt === 8) {
1780
+ throw new Error(
1781
+ `Search index: ${batch.length} writes still unprocessed for ${entity.entityType}#${entityId}`
1782
+ );
1783
+ }
1784
+ }
1785
+ }
1786
+ });
1787
+ }
1788
+ /** The words an entity currently has rows for, read from the GSI. */
1789
+ existingWords(entityType, entityId) {
1790
+ return __async(this, null, function* () {
1791
+ var _a, _b;
1792
+ const words = [];
1793
+ let lastKey;
1794
+ do {
1795
+ const resp = yield this.dynamodbClient.query({
1796
+ TableName: this.TABLE_NAME,
1797
+ IndexName: ENTITY_REPLICATION_INDEX,
1798
+ KeyConditionExpression: "#R1PK = :R1PK and begins_with(#R1SK, :R1SK)",
1799
+ ExpressionAttributeNames: { "#R1PK": "R1PK", "#R1SK": "R1SK" },
1800
+ ExpressionAttributeValues: {
1801
+ ":R1PK": { S: `${entityType}#${entityId}` },
1802
+ ":R1SK": { S: "SEARCH#" }
1803
+ },
1804
+ ExclusiveStartKey: lastKey
1805
+ });
1806
+ for (const item of (_a = resp.Items) != null ? _a : []) {
1807
+ const r1sk = (_b = item.R1SK) == null ? void 0 : _b.S;
1808
+ if (r1sk) words.push(r1sk.slice("SEARCH#".length));
1809
+ }
1810
+ lastKey = resp.LastEvaluatedKey;
1811
+ } while (lastKey);
1812
+ return words;
1813
+ });
1814
+ }
1815
+ getIndexState(entityType) {
1816
+ return __async(this, null, function* () {
1817
+ var _a, _b;
1818
+ const resp = yield this.dynamodbClient.getItem({
1819
+ TableName: this.TABLE_NAME,
1820
+ Key: { PK: { S: INDEX_STATE_PK }, SK: { S: `${entityType}` } }
1821
+ });
1822
+ if (!resp.Item) return void 0;
1823
+ return {
1824
+ state: (_a = resp.Item.state) == null ? void 0 : _a.S,
1825
+ configHash: (_b = resp.Item.configHash) == null ? void 0 : _b.S
1826
+ };
1827
+ });
1828
+ }
1829
+ markIndexBuilding(entityType, configHash) {
1830
+ return __async(this, null, function* () {
1831
+ yield this.dynamodbClient.putItem({
1832
+ TableName: this.TABLE_NAME,
1833
+ Item: {
1834
+ PK: { S: INDEX_STATE_PK },
1835
+ SK: { S: `${entityType}` },
1836
+ state: { S: "building" },
1837
+ configHash: { S: configHash },
1838
+ updatedAt: { S: (/* @__PURE__ */ new Date()).toISOString() }
1839
+ }
1840
+ });
1841
+ });
1842
+ }
1843
+ /**
1844
+ * Marks the index ready, unless a newer reindex has taken over since: its
1845
+ * config hash replaces this one when it starts.
1846
+ */
1847
+ markIndexReady(entityType, configHash) {
1848
+ return __async(this, null, function* () {
1849
+ try {
1850
+ yield this.dynamodbClient.updateItem({
1851
+ TableName: this.TABLE_NAME,
1852
+ Key: { PK: { S: INDEX_STATE_PK }, SK: { S: `${entityType}` } },
1853
+ UpdateExpression: "SET #state = :ready, #updatedAt = :now",
1854
+ ConditionExpression: "#configHash = :configHash",
1855
+ ExpressionAttributeNames: {
1856
+ "#state": "state",
1857
+ "#updatedAt": "updatedAt",
1858
+ "#configHash": "configHash"
1859
+ },
1860
+ ExpressionAttributeValues: {
1861
+ ":ready": { S: "ready" },
1862
+ ":now": { S: (/* @__PURE__ */ new Date()).toISOString() },
1863
+ ":configHash": { S: configHash }
1864
+ }
1865
+ });
1866
+ return true;
1867
+ } catch (err) {
1868
+ if (err instanceof ConditionalCheckFailedException2) return false;
1869
+ throw err;
1870
+ }
1871
+ });
1872
+ }
1873
+ /** Whether the index was fully built for the current config. */
1874
+ isIndexReady(entityType, config) {
1875
+ return __async(this, null, function* () {
1876
+ if (this.readyTypes.has(`${entityType}`)) return true;
1877
+ const state = yield this.getIndexState(entityType);
1878
+ const ready = (state == null ? void 0 : state.state) === "ready" && state.configHash === searchConfigHash(config);
1879
+ if (ready) this.readyTypes.add(`${entityType}`);
1880
+ return ready;
1881
+ });
1882
+ }
1883
+ /** Deletes the marker, so the next reindex rebuilds the type in full. */
1884
+ clearIndexState(entityType) {
1885
+ return __async(this, null, function* () {
1886
+ yield this.dynamodbClient.deleteItem({
1887
+ TableName: this.TABLE_NAME,
1888
+ Key: { PK: { S: INDEX_STATE_PK }, SK: { S: `${entityType}` } }
1889
+ });
1890
+ });
1891
+ }
1892
+ /**
1893
+ * Brings one entity's rows in line with its current data and config. It
1894
+ * runs alongside the stream, which may write a newer version of the same
1895
+ * rows, so each write only goes through over an older copy.
1896
+ */
1897
+ reindexEntity(entityType, entityId, config) {
1898
+ return __async(this, null, function* () {
1899
+ const resp = yield this.dynamodbClient.getItem({
1900
+ TableName: this.TABLE_NAME,
1901
+ Key: new Entity(entityType, entityId).keys(),
1902
+ ConsistentRead: true
1903
+ });
1904
+ if (!resp.Item) return;
1905
+ const entity = Entity.fromItem(resp.Item);
1906
+ const existing = yield this.existingWords(entityType, entityId);
1907
+ const words = indexedWords(entity.data, config);
1908
+ const notNewer = {
1909
+ ExpressionAttributeNames: { "#updatedAt": "updatedAt" },
1910
+ ExpressionAttributeValues: {
1911
+ ":updatedAt": { S: entity.updatedAt }
1912
+ }
1913
+ };
1914
+ const ignoreNewer = (err) => {
1915
+ if (!(err instanceof ConditionalCheckFailedException2)) throw err;
1916
+ };
1917
+ yield Promise.all([
1918
+ ...words.filter((word) => !existing.includes(word)).map(
1919
+ (word) => this.dynamodbClient.putItem(__spreadValues({
1920
+ TableName: this.TABLE_NAME,
1921
+ Item: this.searchRow(entity, word),
1922
+ ConditionExpression: "attribute_not_exists(PK) OR #updatedAt < :updatedAt"
1923
+ }, notNewer)).catch(ignoreNewer)
1924
+ ),
1925
+ ...existing.filter((word) => !words.includes(word)).map(
1926
+ (word) => this.dynamodbClient.deleteItem(__spreadValues({
1927
+ TableName: this.TABLE_NAME,
1928
+ Key: this.rowKeys(entityType, entityId, word),
1929
+ ConditionExpression: "#updatedAt <= :updatedAt"
1930
+ }, notNewer)).catch(ignoreNewer)
1931
+ )
1932
+ ]);
1933
+ });
1934
+ }
1935
+ lookUp(entityType, anchor) {
1936
+ return __async(this, null, function* () {
1937
+ var _a;
1938
+ const items = [];
1939
+ let lastKey;
1940
+ do {
1941
+ const resp = yield this.dynamodbClient.query({
1942
+ TableName: this.TABLE_NAME,
1943
+ KeyConditionExpression: "#PK = :PK and begins_with(#SK, :SK)",
1944
+ ExpressionAttributeNames: { "#PK": "PK", "#SK": "SK" },
1945
+ ExpressionAttributeValues: {
1946
+ ":PK": { S: `SEARCH#${entityType}` },
1947
+ ":SK": { S: anchor }
1948
+ },
1949
+ ExclusiveStartKey: lastKey
1950
+ });
1951
+ items.push(...(_a = resp.Items) != null ? _a : []);
1952
+ lastKey = resp.LastEvaluatedKey;
1953
+ } while (lastKey);
1954
+ return items.map(Entity.fromItem);
1955
+ });
1956
+ }
1957
+ /**
1958
+ * Every entity matching `query`, newest first. Reads the rows of the
1959
+ * query's longest word, or scans every entity while the index is still
1960
+ * being built for the current config. Both give the same matches.
1961
+ *
1962
+ * There's no `totalCount`: counting every entity of the type would take
1963
+ * the scan the index avoids. `filteredCount` is the number of matches.
1964
+ */
1965
+ searchEntities(entityType, query) {
1966
+ return __async(this, null, function* () {
1967
+ const config = this.searchConfig(entityType);
1968
+ const plan = config && planSearch(query, config.ignoreWords);
1969
+ if (!config || !(plan == null ? void 0 : plan.anchor)) {
1970
+ return { items: [], filteredCount: 0 };
1971
+ }
1972
+ const candidates = (yield this.isIndexReady(entityType, config)) ? yield this.lookUp(entityType, plan.anchor) : (yield this.entityRepository.listEntities({ entityType })).items;
1973
+ const seen = /* @__PURE__ */ new Set();
1974
+ const items = [];
1975
+ for (const entity of candidates) {
1976
+ const entityId = entity.entityId;
1977
+ if (seen.has(entityId)) continue;
1978
+ seen.add(entityId);
1979
+ if (matchesSearch(entity.data, plan, config)) {
1980
+ items.push(entity);
1981
+ }
1982
+ }
1983
+ items.sort(
1984
+ (a, b) => a.entityId < b.entityId ? 1 : -1
1985
+ );
1986
+ return { items, filteredCount: items.length };
1987
+ });
1988
+ }
1989
+ };
1990
+
2172
1991
  // data/Tag.ts
2173
1992
  import { marshall as marshall4, unmarshall as unmarshall3 } from "@aws-sdk/util-dynamodb";
2174
1993
  var TaggedEntity = class _TaggedEntity extends Entity {
@@ -2774,155 +2593,25 @@ import { cors } from "hono/cors";
2774
2593
  import { secureHeaders } from "hono/secure-headers";
2775
2594
 
2776
2595
  // middlewares/api-key-auth.ts
2777
- import { createHash } from "crypto";
2778
- import {
2779
- FULL_API_KEY_POLICY,
2780
- compileApiKeyPolicy,
2781
- validateApiKeyPolicies
2782
- } from "../base/index.js";
2783
2596
  import { createFactory } from "hono/factory";
2784
- import httpStatus4 from "http-status";
2785
-
2786
- // helpers/request-context.ts
2787
- import { AsyncLocalStorage } from "async_hooks";
2788
- var storage = new AsyncLocalStorage();
2789
- var runWithApiKey = (apiKey, fn) => storage.run(apiKey, fn);
2790
- var currentApiKey = () => storage.getStore();
2791
-
2792
- // middlewares/api-key-auth.ts
2793
- var SHA256_PREFIX = "sha256:";
2794
- var createPrincipal = (policy, access) => ({
2795
- policy,
2796
- access,
2797
- can: (action, entityType, fields) => {
2798
- const entity = access.entity(entityType);
2799
- if (action === "delete") return entity.delete;
2800
- if (action === "list" && !entity.list) return false;
2801
- const granted = entity[action === "list" ? "read" : action];
2802
- if (granted === null) return false;
2803
- return !fields || granted === "*" || fields.every((f) => granted.has(f));
2804
- },
2805
- has: (permission) => access.allowsRoute(permission),
2806
- mask: (entityType, entity) => {
2807
- const record = typeof entity.toJSON === "function" ? entity.toJSON() : entity;
2808
- return maskRecord(__spreadProps(__spreadValues({}, record), { entityType }), access);
2809
- }
2810
- });
2811
- var fingerprintApiKey = (key) => createHash("sha256").update(key).digest("hex");
2812
- var SHA256_DIGEST = /^[0-9a-f]{64}$/i;
2813
- var toFingerprint = (entry, where) => {
2814
- if (!entry.startsWith(SHA256_PREFIX)) return fingerprintApiKey(entry);
2815
- const digest = entry.slice(SHA256_PREFIX.length);
2816
- if (!SHA256_DIGEST.test(digest)) {
2817
- console.error(
2818
- `[monorise] API_KEYS: a '${SHA256_PREFIX}' entry in ${where} isn't a 64-character hex SHA-256 digest and will be rejected`
2819
- );
2820
- return void 0;
2821
- }
2822
- return digest.toLowerCase();
2823
- };
2824
- var assertKeyList = (value, where) => {
2825
- if (!Array.isArray(value) || !value.every((key) => typeof key === "string" && key.length > 0)) {
2826
- throw new Error(
2827
- `[monorise] API_KEYS: ${where} must be an array of non-empty strings`
2828
- );
2829
- }
2830
- return value;
2831
- };
2832
- var parseApiKeys = (raw, definedPolicies = [FULL_API_KEY_POLICY]) => {
2833
- var _a;
2834
- const fingerprints = /* @__PURE__ */ new Map();
2835
- if (!raw) return fingerprints;
2836
- const parsed = JSON.parse(raw);
2837
- if (Array.isArray(parsed)) {
2838
- for (const key of assertKeyList(parsed, "the array form")) {
2839
- const fingerprint = toFingerprint(key, "the array form");
2840
- if (fingerprint) fingerprints.set(fingerprint, FULL_API_KEY_POLICY);
2841
- }
2842
- return fingerprints;
2843
- }
2844
- if (typeof parsed !== "object" || parsed === null) {
2845
- throw new Error(
2846
- "[monorise] API_KEYS must be a JSON array of keys or an object mapping policy names to keys"
2847
- );
2848
- }
2849
- const policiesByFingerprint = /* @__PURE__ */ new Map();
2850
- for (const [policy, keys] of Object.entries(parsed)) {
2851
- const keyList = assertKeyList(keys, `policy '${policy}'`);
2852
- if (!definedPolicies.includes(policy)) {
2853
- console.error(
2854
- `[monorise] API_KEYS: policy '${policy}' is not defined; its ${keyList.length} key(s) will be rejected`
2855
- );
2856
- }
2857
- for (const key of keyList) {
2858
- const fingerprint = toFingerprint(key, `policy '${policy}'`);
2859
- if (!fingerprint) continue;
2860
- const policies = (_a = policiesByFingerprint.get(fingerprint)) != null ? _a : /* @__PURE__ */ new Set();
2861
- policies.add(policy);
2862
- policiesByFingerprint.set(fingerprint, policies);
2863
- }
2864
- }
2865
- for (const [fingerprint, policies] of policiesByFingerprint) {
2866
- if (policies.size > 1) {
2867
- console.error(
2868
- `[monorise] API_KEYS: key ${fingerprint.slice(0, 12)}\u2026 is listed under more than one policy (${[...policies].join(", ")}) and will be rejected`
2869
- );
2870
- continue;
2871
- }
2872
- const [policy] = policies;
2873
- if (definedPolicies.includes(policy)) fingerprints.set(fingerprint, policy);
2874
- }
2875
- return fingerprints;
2876
- };
2597
+ import httpStatus3 from "http-status";
2877
2598
  var factory = createFactory();
2878
- var createApiKeyAuth = (fingerprints, policies = {}) => {
2879
- const principals = /* @__PURE__ */ new Map();
2880
- const principalFor = (name) => {
2881
- let principal = principals.get(name);
2882
- if (!principal) {
2883
- principal = createPrincipal(
2884
- name,
2885
- compileApiKeyPolicy(name, policies[name])
2886
- );
2887
- principals.set(name, principal);
2888
- }
2889
- return principal;
2890
- };
2891
- return factory.createMiddleware((c, next) => __async(null, null, function* () {
2892
- const xApiKey = c.req.header("x-api-key");
2893
- const fingerprint = xApiKey ? fingerprintApiKey(xApiKey) : void 0;
2894
- const policy = fingerprint ? fingerprints.get(fingerprint) : void 0;
2895
- if (!fingerprint || !policy) {
2896
- c.status(httpStatus4.UNAUTHORIZED);
2897
- return c.json({
2898
- status: httpStatus4.UNAUTHORIZED,
2899
- message: httpStatus4["401_MESSAGE"]
2900
- });
2901
- }
2902
- c.set("apiKey", __spreadProps(__spreadValues({}, principalFor(policy)), { fingerprint }));
2903
- return yield runWithApiKey({ policy, fingerprint }, () => next());
2904
- }));
2905
- };
2906
- var apiKeyAuth = ({
2907
- policies = {},
2908
- entityConfig,
2909
- apiKeys: apiKeys2 = process.env.API_KEYS
2910
- }) => {
2911
- const errors = validateApiKeyPolicies(policies, entityConfig);
2912
- if (errors.length) {
2913
- console.error(
2914
- `[monorise] Invalid API key policies; every key under them will be rejected:
2915
- - ${errors.join("\n - ")}`
2916
- );
2599
+ var API_KEYS = process.env.API_KEYS ? JSON.parse(process.env.API_KEYS) : [];
2600
+ var apiKeyAuth = factory.createMiddleware((c, next) => __async(null, null, function* () {
2601
+ const xApiKey = c.req.header("x-api-key");
2602
+ if (c.req.url.match(/^\/core\/public\//)) {
2603
+ return yield next();
2604
+ }
2605
+ if (!xApiKey || Array.isArray(xApiKey) || !API_KEYS.includes(xApiKey)) {
2606
+ c.status(httpStatus3.UNAUTHORIZED);
2607
+ return c.json({
2608
+ status: httpStatus3.UNAUTHORIZED,
2609
+ message: httpStatus3["401_MESSAGE"]
2610
+ });
2917
2611
  }
2918
- return createApiKeyAuth(
2919
- parseApiKeys(
2920
- apiKeys2,
2921
- errors.length ? [FULL_API_KEY_POLICY] : [FULL_API_KEY_POLICY, ...Object.keys(policies)]
2922
- ),
2923
- policies
2924
- );
2925
- };
2612
+ return yield next();
2613
+ }));
2614
+ var api_key_auth_default = apiKeyAuth;
2926
2615
 
2927
2616
  // middlewares/general-error-handler.ts
2928
2617
  import { createFactory as createFactory2 } from "hono/factory";
@@ -3027,11 +2716,10 @@ function publishEvent(_0) {
3027
2716
  payload,
3028
2717
  event
3029
2718
  }) {
3030
- const apiKey = currentApiKey();
3031
2719
  const params = {
3032
2720
  Entries: [
3033
2721
  __spreadProps(__spreadValues({}, event), {
3034
- Detail: JSON.stringify(apiKey ? __spreadProps(__spreadValues({}, payload), { apiKey }) : payload),
2722
+ Detail: JSON.stringify(payload),
3035
2723
  EventBusName: CORE_EVENT_BUS
3036
2724
  })
3037
2725
  ]
@@ -3080,7 +2768,7 @@ var getDependencies = () => {
3080
2768
  // middlewares/general-error-handler.ts
3081
2769
  var factory2 = createFactory2();
3082
2770
  var generalErrorHandler = (dependencies = getDependencies()) => factory2.createMiddleware((c) => __async(null, null, function* () {
3083
- var _a, _b, _c, _d, _e;
2771
+ var _a, _b, _c, _d;
3084
2772
  if (c.error) {
3085
2773
  const { nanoid: nanoid2, publishErrorEvent: publishErrorEvent2 } = dependencies;
3086
2774
  const errorId = nanoid2();
@@ -3098,15 +2786,14 @@ var generalErrorHandler = (dependencies = getDependencies()) => factory2.createM
3098
2786
  errorId,
3099
2787
  method: c.req.method,
3100
2788
  path: c.req.path,
3101
- apiKeyPolicy: (_a = c.get("apiKey")) == null ? void 0 : _a.policy,
3102
2789
  errorName: error == null ? void 0 : error.name,
3103
2790
  errorMessage: error == null ? void 0 : error.message,
3104
2791
  errorCode: error == null ? void 0 : error.code,
3105
2792
  errorStack: error == null ? void 0 : error.stack,
3106
- errorConstructor: (_b = error == null ? void 0 : error.constructor) == null ? void 0 : _b.name,
2793
+ errorConstructor: (_a = error == null ? void 0 : error.constructor) == null ? void 0 : _a.name,
3107
2794
  hasLastError: !!(error == null ? void 0 : error.lastError),
3108
- lastErrorName: (_d = (_c = error == null ? void 0 : error.lastError) == null ? void 0 : _c.constructor) == null ? void 0 : _d.name,
3109
- lastErrorMessage: (_e = error == null ? void 0 : error.lastError) == null ? void 0 : _e.message,
2795
+ lastErrorName: (_c = (_b = error == null ? void 0 : error.lastError) == null ? void 0 : _b.constructor) == null ? void 0 : _c.name,
2796
+ lastErrorMessage: (_d = error == null ? void 0 : error.lastError) == null ? void 0 : _d.message,
3110
2797
  context: error == null ? void 0 : error.context
3111
2798
  });
3112
2799
  c.status(500);
@@ -3132,14 +2819,8 @@ var appHandler = (container) => ({ routes }) => {
3132
2819
  origin: process.env.ALLOWED_ORIGIN ? JSON.parse(process.env.ALLOWED_ORIGIN) : []
3133
2820
  })
3134
2821
  );
3135
- app.use(
3136
- apiKeyAuth({
3137
- policies: container.config.ApiKeyPolicies,
3138
- entityConfig: container.config.EntityConfig
3139
- })
3140
- );
2822
+ app.use(api_key_auth_default);
3141
2823
  if (routes) {
3142
- app.use("/app/*", customRouteGate());
3143
2824
  if (typeof routes !== "function") {
3144
2825
  app.route("/app", routes);
3145
2826
  } else {
@@ -3160,10 +2841,10 @@ import {
3160
2841
  StopQueryExecutionCommand
3161
2842
  } from "@aws-sdk/client-athena";
3162
2843
  import { DynamoDBClient, GetItemCommand, PutItemCommand } from "@aws-sdk/client-dynamodb";
3163
- import { createHash as createHash2 } from "crypto";
2844
+ import { createHash } from "crypto";
3164
2845
  import { handle as handle2 } from "hono/aws-lambda";
3165
2846
  import { Hono as Hono3 } from "hono";
3166
- import httpStatus5 from "http-status";
2847
+ import httpStatus4 from "http-status";
3167
2848
  var athena = new AthenaClient();
3168
2849
  var dynamo = new DynamoDBClient();
3169
2850
  function required(name) {
@@ -3192,7 +2873,7 @@ function apiKeys() {
3192
2873
  return process.env.ANALYTICS_API_KEYS ? JSON.parse(process.env.ANALYTICS_API_KEYS) : [];
3193
2874
  }
3194
2875
  function keyFingerprint(key) {
3195
- return createHash2("sha256").update(key).digest("hex");
2876
+ return createHash("sha256").update(key).digest("hex");
3196
2877
  }
3197
2878
  function ownedExecution(id, key) {
3198
2879
  return __async(this, null, function* () {
@@ -3210,7 +2891,7 @@ var analyticsQueryHandler = () => {
3210
2891
  app.use("*", (c, next) => __async(null, null, function* () {
3211
2892
  const key = c.req.header("x-api-key");
3212
2893
  if (!key || !apiKeys().includes(key)) {
3213
- return c.json({ status: httpStatus5.UNAUTHORIZED, message: httpStatus5["401_MESSAGE"] }, httpStatus5.UNAUTHORIZED);
2894
+ return c.json({ status: httpStatus4.UNAUTHORIZED, message: httpStatus4["401_MESSAGE"] }, httpStatus4.UNAUTHORIZED);
3214
2895
  }
3215
2896
  return next();
3216
2897
  }));
@@ -3223,11 +2904,11 @@ var analyticsQueryHandler = () => {
3223
2904
  app.post("/queries/:name/executions", (c) => __async(null, null, function* () {
3224
2905
  var _a, _b;
3225
2906
  const query = queries()[c.req.param("name")];
3226
- if (!query) return c.json({ message: "Unknown analytics query." }, httpStatus5.NOT_FOUND);
2907
+ if (!query) return c.json({ message: "Unknown analytics query." }, httpStatus4.NOT_FOUND);
3227
2908
  const body = yield c.req.json().catch(() => ({}));
3228
2909
  const declared = (_a = query.parameters) != null ? _a : {};
3229
2910
  if (Object.keys(body).some((name) => !(name in declared))) {
3230
- return c.json({ message: "Unexpected query parameter." }, httpStatus5.BAD_REQUEST);
2911
+ return c.json({ message: "Unexpected query parameter." }, httpStatus4.BAD_REQUEST);
3231
2912
  }
3232
2913
  try {
3233
2914
  const parameters = Object.entries(declared).map(([name, definition]) => {
@@ -3253,10 +2934,10 @@ var analyticsQueryHandler = () => {
3253
2934
  expiresAt: { N: String(Math.floor(Date.now() / 1e3) + 86400) }
3254
2935
  }
3255
2936
  }));
3256
- return c.json({ queryExecutionId: started.QueryExecutionId, state: "QUEUED" }, httpStatus5.ACCEPTED);
2937
+ return c.json({ queryExecutionId: started.QueryExecutionId, state: "QUEUED" }, httpStatus4.ACCEPTED);
3257
2938
  } catch (error) {
3258
2939
  if (error instanceof Error && error.message.startsWith("Invalid or missing parameter:")) {
3259
- return c.json({ message: error.message }, httpStatus5.BAD_REQUEST);
2940
+ return c.json({ message: error.message }, httpStatus4.BAD_REQUEST);
3260
2941
  }
3261
2942
  throw error;
3262
2943
  }
@@ -3264,7 +2945,7 @@ var analyticsQueryHandler = () => {
3264
2945
  app.get("/executions/:id", (c) => __async(null, null, function* () {
3265
2946
  var _a, _b, _c, _d, _e, _f;
3266
2947
  const id = c.req.param("id");
3267
- if (!(yield ownedExecution(id, (_a = c.req.header("x-api-key")) != null ? _a : ""))) return c.json({ message: "Unknown analytics execution." }, httpStatus5.NOT_FOUND);
2948
+ if (!(yield ownedExecution(id, (_a = c.req.header("x-api-key")) != null ? _a : ""))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
3268
2949
  const execution = yield athena.send(new GetQueryExecutionCommand({ QueryExecutionId: id }));
3269
2950
  const status = (_b = execution.QueryExecution) == null ? void 0 : _b.Status;
3270
2951
  return c.json({
@@ -3278,7 +2959,7 @@ var analyticsQueryHandler = () => {
3278
2959
  app.get("/executions/:id/results", (c) => __async(null, null, function* () {
3279
2960
  var _a, _b, _c, _d, _e, _f, _g;
3280
2961
  const id = c.req.param("id");
3281
- if (!(yield ownedExecution(id, (_a = c.req.header("x-api-key")) != null ? _a : ""))) return c.json({ message: "Unknown analytics execution." }, httpStatus5.NOT_FOUND);
2962
+ if (!(yield ownedExecution(id, (_a = c.req.header("x-api-key")) != null ? _a : ""))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
3282
2963
  const requested = Number((_b = c.req.query("maxResults")) != null ? _b : 100);
3283
2964
  const maxResults = Number.isFinite(requested) ? Math.min(Math.max(requested, 1), 1e3) : 100;
3284
2965
  const nextToken = c.req.query("nextToken");
@@ -3304,9 +2985,9 @@ var analyticsQueryHandler = () => {
3304
2985
  app.post("/executions/:id/cancel", (c) => __async(null, null, function* () {
3305
2986
  var _a;
3306
2987
  const id = c.req.param("id");
3307
- if (!(yield ownedExecution(id, (_a = c.req.header("x-api-key")) != null ? _a : ""))) return c.json({ message: "Unknown analytics execution." }, httpStatus5.NOT_FOUND);
2988
+ if (!(yield ownedExecution(id, (_a = c.req.header("x-api-key")) != null ? _a : ""))) return c.json({ message: "Unknown analytics execution." }, httpStatus4.NOT_FOUND);
3308
2989
  yield athena.send(new StopQueryExecutionCommand({ QueryExecutionId: id }));
3309
- return c.body(null, httpStatus5.NO_CONTENT);
2990
+ return c.body(null, httpStatus4.NO_CONTENT);
3310
2991
  }));
3311
2992
  return handle2(app);
3312
2993
  };
@@ -8069,7 +7750,7 @@ var MutualService = class {
8069
7750
  options
8070
7751
  }
8071
7752
  };
8072
- console.log("[MONORISE_DEBUG] createMutual service start:", {
7753
+ debugLog("[MONORISE_DEBUG] createMutual service start:", {
8073
7754
  byEntityType,
8074
7755
  byEntityId,
8075
7756
  entityType,
@@ -8079,28 +7760,28 @@ var MutualService = class {
8079
7760
  });
8080
7761
  const mutualDataSchema = this.getMutualDataSchema(byEntityType, entityType);
8081
7762
  const schema = (_c = asEntityStorageSchema != null ? asEntityStorageSchema : mutualDataSchema) != null ? _c : external_exports.record(external_exports.string(), external_exports.any());
8082
- console.log("[MONORISE_DEBUG] createMutual schema resolved");
7763
+ debugLog("[MONORISE_DEBUG] createMutual schema resolved");
8083
7764
  const parsedMutualPayload = schema.parse(mutualPayload);
8084
- console.log("[MONORISE_DEBUG] createMutual payload parsed:", parsedMutualPayload);
8085
- console.log("[MONORISE_DEBUG] createMutual fetching entities...");
7765
+ debugLog("[MONORISE_DEBUG] createMutual payload parsed:", parsedMutualPayload);
7766
+ debugLog("[MONORISE_DEBUG] createMutual fetching entities...");
8086
7767
  const [{ data: byEntityData }, { data: entityData }] = yield Promise.all([
8087
7768
  this.entityRepository.getEntity(byEntityType, byEntityId),
8088
7769
  this.entityRepository.getEntity(entityType, entityId)
8089
7770
  ]);
8090
- console.log("[MONORISE_DEBUG] createMutual entities fetched:", {
7771
+ debugLog("[MONORISE_DEBUG] createMutual entities fetched:", {
8091
7772
  hasByEntityData: !!byEntityData,
8092
7773
  hasEntityData: !!entityData
8093
7774
  });
8094
7775
  errorContext.byEntityData = byEntityData;
8095
7776
  errorContext.entityData = entityData;
8096
- console.log("[MONORISE_DEBUG] createMutual checking mutual exist...");
7777
+ debugLog("[MONORISE_DEBUG] createMutual checking mutual exist...");
8097
7778
  yield this.mutualRepository.checkMutualExist(
8098
7779
  byEntityType,
8099
7780
  byEntityId,
8100
7781
  entityType,
8101
7782
  entityId
8102
7783
  );
8103
- console.log("[MONORISE_DEBUG] createMutual mutual does not exist (ok)");
7784
+ debugLog("[MONORISE_DEBUG] createMutual mutual does not exist (ok)");
8104
7785
  const currentDatetime = createAndUpdateDatetime || /* @__PURE__ */ new Date();
8105
7786
  const mutual = new Mutual(
8106
7787
  byEntityType,
@@ -8115,7 +7796,7 @@ var MutualService = class {
8115
7796
  currentDatetime,
8116
7797
  currentDatetime
8117
7798
  );
8118
- console.log("[MONORISE_DEBUG] createMutual mutual object created:", {
7799
+ debugLog("[MONORISE_DEBUG] createMutual mutual object created:", {
8119
7800
  mutualId: mutual.mutualId
8120
7801
  });
8121
7802
  const mutualTransactions = skipMutualCreation ? [] : this.mutualRepository.createMutualTransactItems(mutual, {
@@ -8153,13 +7834,13 @@ var MutualService = class {
8153
7834
  accountId
8154
7835
  } = params;
8155
7836
  const { mutual, entity, transactItems, parsedMutualPayload } = yield this.prepareCreateMutual(params);
8156
- console.log("[MONORISE_DEBUG] createMutual executing transaction:", {
7837
+ debugLog("[MONORISE_DEBUG] createMutual executing transaction:", {
8157
7838
  transactItemCount: transactItems.length
8158
7839
  });
8159
7840
  yield this.ddbUtils.executeTransactWrite({
8160
7841
  TransactItems: transactItems
8161
7842
  });
8162
- console.log("[MONORISE_DEBUG] createMutual transaction succeeded");
7843
+ debugLog("[MONORISE_DEBUG] createMutual transaction succeeded");
8163
7844
  if (entity) {
8164
7845
  yield this.entityServiceLifeCycle.afterCreateEntityHook(
8165
7846
  entity,
@@ -8183,7 +7864,7 @@ var MutualService = class {
8183
7864
  })
8184
7865
  ];
8185
7866
  yield Promise.all(eventPromises);
8186
- console.log("[MONORISE_DEBUG] createMutual service complete");
7867
+ debugLog("[MONORISE_DEBUG] createMutual service complete");
8187
7868
  return { mutual, eventPayload };
8188
7869
  });
8189
7870
  /**
@@ -8251,7 +7932,7 @@ var MutualService = class {
8251
7932
  accountId,
8252
7933
  options
8253
7934
  }) {
8254
- console.log("[MONORISE_DEBUG] updateMutual service start:", {
7935
+ debugLog("[MONORISE_DEBUG] updateMutual service start:", {
8255
7936
  byEntityType,
8256
7937
  byEntityId,
8257
7938
  entityType,
@@ -8260,10 +7941,10 @@ var MutualService = class {
8260
7941
  options
8261
7942
  });
8262
7943
  const schema = this.getMutualUpdateSchema(byEntityType, entityType);
8263
- console.log("[MONORISE_DEBUG] updateMutual schema resolved");
7944
+ debugLog("[MONORISE_DEBUG] updateMutual schema resolved");
8264
7945
  const parsedMutualPayload = schema.parse(mutualPayload);
8265
- console.log("[MONORISE_DEBUG] updateMutual payload parsed:", parsedMutualPayload);
8266
- console.log("[MONORISE_DEBUG] updateMutual calling repository...");
7946
+ debugLog("[MONORISE_DEBUG] updateMutual payload parsed:", parsedMutualPayload);
7947
+ debugLog("[MONORISE_DEBUG] updateMutual calling repository...");
8267
7948
  const mutual = yield this.mutualRepository.updateMutual(
8268
7949
  byEntityType,
8269
7950
  byEntityId,
@@ -8272,7 +7953,7 @@ var MutualService = class {
8272
7953
  { mutualData: parsedMutualPayload },
8273
7954
  options
8274
7955
  );
8275
- console.log("[MONORISE_DEBUG] updateMutual repository result:", {
7956
+ debugLog("[MONORISE_DEBUG] updateMutual repository result:", {
8276
7957
  hasMutual: !!mutual,
8277
7958
  mutualId: mutual == null ? void 0 : mutual.mutualId
8278
7959
  });
@@ -8287,7 +7968,7 @@ var MutualService = class {
8287
7968
  updatedByAccountId: accountId
8288
7969
  }
8289
7970
  });
8290
- console.log("[MONORISE_DEBUG] updateMutual service complete");
7971
+ debugLog("[MONORISE_DEBUG] updateMutual service complete");
8291
7972
  return mutual;
8292
7973
  });
8293
7974
  /**
@@ -8848,8 +8529,148 @@ var handler8 = (container) => (ev) => __async(null, null, function* () {
8848
8529
  });
8849
8530
 
8850
8531
  // processors/replication-processor.ts
8851
- import { ConditionalCheckFailedException as ConditionalCheckFailedException2 } from "@aws-sdk/client-dynamodb";
8852
- var handler9 = (container) => (event) => __async(null, null, function* () {
8532
+ import { ConditionalCheckFailedException as ConditionalCheckFailedException3 } from "@aws-sdk/client-dynamodb";
8533
+
8534
+ // processors/search-index-processor.ts
8535
+ import { InvokeCommand as InvokeCommand2, LambdaClient as LambdaClient2 } from "@aws-sdk/client-lambda";
8536
+ import { unmarshall as unmarshall6 } from "@aws-sdk/util-dynamodb";
8537
+ import {
8538
+ indexedWords as indexedWords2,
8539
+ searchConfigHash as searchConfigHash2
8540
+ } from "../base/index.js";
8541
+ function syncSearchIndex(container, record) {
8542
+ return __async(this, null, function* () {
8543
+ var _a, _b, _c, _d, _e, _f;
8544
+ if (record.eventName !== "INSERT" && record.eventName !== "MODIFY") return;
8545
+ const newImage = (_a = record.dynamodb) == null ? void 0 : _a.NewImage;
8546
+ if (!((_c = (_b = newImage == null ? void 0 : newImage.SK) == null ? void 0 : _b.S) == null ? void 0 : _c.startsWith("#METADATA#")) || ((_e = (_d = newImage.PK) == null ? void 0 : _d.S) == null ? void 0 : _e.startsWith("MUTUAL#"))) {
8547
+ return;
8548
+ }
8549
+ const entity = Entity.fromItem(newImage);
8550
+ const config = container.searchRepository.searchConfig(entity.entityType);
8551
+ if (!config) return;
8552
+ const oldImage = (_f = record.dynamodb) == null ? void 0 : _f.OldImage;
8553
+ const previous = oldImage ? indexedWords2(unmarshall6(oldImage).data, config) : [];
8554
+ const words = indexedWords2(entity.data, config);
8555
+ yield container.searchRepository.writeRows(
8556
+ entity,
8557
+ words.filter((word) => !previous.includes(word)),
8558
+ previous.filter((word) => !words.includes(word))
8559
+ );
8560
+ });
8561
+ }
8562
+ var HANDOVER_MS = 2 * 60 * 1e3;
8563
+ var PAGE_SIZE = 100;
8564
+ var CONCURRENCY = 25;
8565
+ var MAX_FAILURES = 3;
8566
+ var RETRY_WAIT_MS = 5e3;
8567
+ var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
8568
+ var lambdaClient;
8569
+ var invokeSelf = (event) => __async(null, null, function* () {
8570
+ lambdaClient != null ? lambdaClient : lambdaClient = new LambdaClient2();
8571
+ yield lambdaClient.send(
8572
+ new InvokeCommand2({
8573
+ FunctionName: process.env.AWS_LAMBDA_FUNCTION_NAME,
8574
+ InvocationType: "Event",
8575
+ Payload: Buffer.from(JSON.stringify(event))
8576
+ })
8577
+ );
8578
+ });
8579
+ var handler9 = (container, invoke = invokeSelf, pause = wait) => (event, context) => __async(null, null, function* () {
8580
+ var _a;
8581
+ const { searchRepository, entityRepository } = container;
8582
+ if (event.action === "start") {
8583
+ const indexed = searchRepository.indexedEntityTypes();
8584
+ const entityTypes = Object.keys(
8585
+ container.config.EntityConfig
8586
+ );
8587
+ for (const entityType2 of entityTypes) {
8588
+ if (!indexed.includes(entityType2)) {
8589
+ yield searchRepository.clearIndexState(entityType2);
8590
+ }
8591
+ }
8592
+ for (const entityType2 of indexed) {
8593
+ const config2 = searchRepository.searchConfig(entityType2);
8594
+ if (!config2) continue;
8595
+ const configHash2 = searchConfigHash2(config2);
8596
+ const state = yield searchRepository.getIndexState(entityType2);
8597
+ if (!event.force && (state == null ? void 0 : state.state) === "ready" && state.configHash === configHash2) {
8598
+ continue;
8599
+ }
8600
+ yield searchRepository.markIndexBuilding(entityType2, configHash2);
8601
+ yield invoke({ action: "reindex", entityType: entityType2, configHash: configHash2 });
8602
+ }
8603
+ return;
8604
+ }
8605
+ const { entityType, configHash } = event;
8606
+ const config = searchRepository.searchConfig(entityType);
8607
+ if (!config || searchConfigHash2(config) !== configHash) {
8608
+ console.log("[SEARCH_REINDEX] superseded, stopping", { entityType });
8609
+ return;
8610
+ }
8611
+ let lastKey = event.lastKey;
8612
+ let failures = (_a = event.failures) != null ? _a : 0;
8613
+ do {
8614
+ try {
8615
+ const page = yield entityRepository.listEntities({
8616
+ entityType,
8617
+ limit: PAGE_SIZE,
8618
+ options: { lastKey }
8619
+ });
8620
+ for (let i = 0; i < page.items.length; i += CONCURRENCY) {
8621
+ yield Promise.all(
8622
+ page.items.slice(i, i + CONCURRENCY).map(
8623
+ (entity) => searchRepository.reindexEntity(
8624
+ entityType,
8625
+ entity.entityId,
8626
+ config
8627
+ )
8628
+ )
8629
+ );
8630
+ }
8631
+ lastKey = page.lastKey;
8632
+ failures = 0;
8633
+ } catch (err) {
8634
+ failures++;
8635
+ if (failures >= MAX_FAILURES) {
8636
+ console.error(
8637
+ "[SEARCH_REINDEX] giving up: search scans until rebuilt",
8638
+ {
8639
+ entityType,
8640
+ lastKey,
8641
+ failures,
8642
+ err
8643
+ }
8644
+ );
8645
+ throw err;
8646
+ }
8647
+ console.warn("[SEARCH_REINDEX] page failed, retrying", {
8648
+ entityType,
8649
+ lastKey,
8650
+ failures,
8651
+ err
8652
+ });
8653
+ yield pause(RETRY_WAIT_MS * 2 ** (failures - 1));
8654
+ yield invoke({
8655
+ action: "reindex",
8656
+ entityType,
8657
+ configHash,
8658
+ lastKey,
8659
+ failures
8660
+ });
8661
+ return;
8662
+ }
8663
+ if (lastKey && context && context.getRemainingTimeInMillis() < HANDOVER_MS) {
8664
+ yield invoke({ action: "reindex", entityType, configHash, lastKey });
8665
+ return;
8666
+ }
8667
+ } while (lastKey);
8668
+ const ready = yield searchRepository.markIndexReady(entityType, configHash);
8669
+ console.log("[SEARCH_REINDEX] done", { entityType, ready });
8670
+ });
8671
+
8672
+ // processors/replication-processor.ts
8673
+ var handler10 = (container) => (event) => __async(null, null, function* () {
8853
8674
  var _a, _b, _c, _d, _e, _f, _g;
8854
8675
  const TableName = process.env.DDB_TABLE || container.coreTable;
8855
8676
  const batchItemFailures = [];
@@ -8858,6 +8679,7 @@ var handler9 = (container) => (event) => __async(null, null, function* () {
8858
8679
  const errorContext = {};
8859
8680
  errorContext.record = record;
8860
8681
  try {
8682
+ yield syncSearchIndex(container, record);
8861
8683
  if (record.eventName === "MODIFY") {
8862
8684
  const modifiedItem = (_a = record.dynamodb) == null ? void 0 : _a.NewImage;
8863
8685
  if (!modifiedItem) {
@@ -8948,7 +8770,7 @@ var handler9 = (container) => (event) => __async(null, null, function* () {
8948
8770
  const results = yield Promise.allSettled(updatePromises);
8949
8771
  errorContext.results = results;
8950
8772
  if (results.some(
8951
- (result) => result.status === "rejected" && !(result.reason instanceof ConditionalCheckFailedException2)
8773
+ (result) => result.status === "rejected" && !(result.reason instanceof ConditionalCheckFailedException3)
8952
8774
  )) {
8953
8775
  throw new StandardError(
8954
8776
  StandardErrorCode.REPLICATION_ERROR,
@@ -9019,7 +8841,7 @@ var handler9 = (container) => (event) => __async(null, null, function* () {
9019
8841
  );
9020
8842
  errorContext.deleteResults = deleteResults;
9021
8843
  if (deleteResults.some(
9022
- (result) => result.status === "rejected" && !(result.reason instanceof ConditionalCheckFailedException2)
8844
+ (result) => result.status === "rejected" && !(result.reason instanceof ConditionalCheckFailedException3)
9023
8845
  )) {
9024
8846
  throw new StandardError(
9025
8847
  StandardErrorCode.REPLICATION_ERROR,
@@ -9113,7 +8935,7 @@ function batchUpdateTags(_0) {
9113
8935
  yield Promise.all(addPromises);
9114
8936
  });
9115
8937
  }
9116
- var handler10 = (container) => (ev) => __async(null, null, function* () {
8938
+ var handler11 = (container) => (ev) => __async(null, null, function* () {
9117
8939
  var _a;
9118
8940
  const batchItemFailures = [];
9119
8941
  for (const record of ev.Records) {
@@ -9178,7 +9000,7 @@ import {
9178
9000
  ApiGatewayManagementApiClient,
9179
9001
  PostToConnectionCommand
9180
9002
  } from "@aws-sdk/client-apigatewaymanagementapi";
9181
- import { unmarshall as unmarshall6 } from "@aws-sdk/util-dynamodb";
9003
+ import { unmarshall as unmarshall7 } from "@aws-sdk/util-dynamodb";
9182
9004
  import { ulid as ulid5 } from "ulid";
9183
9005
  var SUB_ENTITY_TYPE = "SUB#ENTITY#";
9184
9006
  var SUB_MUTUAL_TYPE = "SUB#MUTUAL#";
@@ -9480,7 +9302,7 @@ var broadcast = (container) => (event) => __async(null, null, function* () {
9480
9302
  byEntityId,
9481
9303
  mutualEntityType,
9482
9304
  entityId: skParts[1],
9483
- data: isRemove ? void 0 : unmarshall6(image)
9305
+ data: isRemove ? void 0 : unmarshall7(image)
9484
9306
  }
9485
9307
  };
9486
9308
  yield broadcastToSubscribers(
@@ -9504,7 +9326,7 @@ var broadcast = (container) => (event) => __async(null, null, function* () {
9504
9326
  payload: {
9505
9327
  entityType,
9506
9328
  entityId,
9507
- data: isRemove ? void 0 : unmarshall6(image)
9329
+ data: isRemove ? void 0 : unmarshall7(image)
9508
9330
  }
9509
9331
  };
9510
9332
  yield broadcastToSubscribers(
@@ -9530,7 +9352,7 @@ var broadcast = (container) => (event) => __async(null, null, function* () {
9530
9352
  byEntityId: entityId,
9531
9353
  mutualEntityType: sk.split("#")[0],
9532
9354
  entityId: sk.split("#")[1],
9533
- data: isRemove ? void 0 : unmarshall6(image)
9355
+ data: isRemove ? void 0 : unmarshall7(image)
9534
9356
  }
9535
9357
  } : {
9536
9358
  type: isInsert ? "entity.created" : isModify ? "entity.updated" : "entity.deleted",
@@ -9538,7 +9360,7 @@ var broadcast = (container) => (event) => __async(null, null, function* () {
9538
9360
  payload: {
9539
9361
  entityType,
9540
9362
  entityId,
9541
- data: isRemove ? void 0 : unmarshall6(image)
9363
+ data: isRemove ? void 0 : unmarshall7(image)
9542
9364
  }
9543
9365
  }
9544
9366
  );
@@ -9710,12 +9532,12 @@ var EventUtils = class {
9710
9532
  };
9711
9533
 
9712
9534
  // controllers/entity/create-entity.controller.ts
9713
- import { createMiddleware as createMiddleware5 } from "hono/factory";
9714
- import httpStatus6 from "http-status";
9535
+ import { createMiddleware as createMiddleware3 } from "hono/factory";
9536
+ import httpStatus5 from "http-status";
9715
9537
  var CreateEntityController = class {
9716
9538
  constructor(entityService) {
9717
9539
  this.entityService = entityService;
9718
- this.controller = createMiddleware5((c) => __async(this, null, function* () {
9540
+ this.controller = createMiddleware3((c) => __async(this, null, function* () {
9719
9541
  const accountId = c.req.header("account-id");
9720
9542
  const { entityType } = c.req.param();
9721
9543
  const body = yield c.req.json();
@@ -9729,11 +9551,11 @@ var CreateEntityController = class {
9729
9551
  createAndUpdateDatetime: body.createdAt
9730
9552
  }
9731
9553
  });
9732
- c.status(httpStatus6.OK);
9554
+ c.status(httpStatus5.OK);
9733
9555
  return c.json(entity);
9734
9556
  } catch (err) {
9735
9557
  if ((err == null ? void 0 : err.name) === "ZodError") {
9736
- c.status(httpStatus6.BAD_REQUEST);
9558
+ c.status(httpStatus5.BAD_REQUEST);
9737
9559
  return c.json({
9738
9560
  code: "API_VALIDATION_ERROR",
9739
9561
  message: "API validation failed",
@@ -9741,19 +9563,17 @@ var CreateEntityController = class {
9741
9563
  });
9742
9564
  }
9743
9565
  if (err instanceof StandardError && err.code === StandardErrorCode.EMAIL_EXISTS) {
9744
- c.status(httpStatus6.BAD_REQUEST);
9566
+ c.status(httpStatus5.BAD_REQUEST);
9745
9567
  return c.json(__spreadValues({}, err.toJSON()));
9746
9568
  }
9747
9569
  if (err instanceof StandardError && err.code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
9748
- c.status(httpStatus6.BAD_REQUEST);
9570
+ c.status(httpStatus5.BAD_REQUEST);
9749
9571
  return c.json(__spreadValues({}, err.toJSON()));
9750
9572
  }
9751
9573
  console.log("===create-entity error:", {
9752
9574
  err,
9753
- errorContext: JSON.stringify({
9754
- body,
9755
- headers: c.req.header()
9756
- })
9575
+ // Not the headers: they include the caller's x-api-key.
9576
+ errorContext: JSON.stringify({ body })
9757
9577
  });
9758
9578
  throw err;
9759
9579
  }
@@ -9762,12 +9582,12 @@ var CreateEntityController = class {
9762
9582
  };
9763
9583
 
9764
9584
  // controllers/entity/delete-entity.controller.ts
9765
- import { createMiddleware as createMiddleware6 } from "hono/factory";
9766
- import httpStatus7 from "http-status";
9585
+ import { createMiddleware as createMiddleware4 } from "hono/factory";
9586
+ import httpStatus6 from "http-status";
9767
9587
  var DeleteEntityController = class {
9768
9588
  constructor(entityService) {
9769
9589
  this.entityService = entityService;
9770
- this.controller = createMiddleware6((c) => __async(this, null, function* () {
9590
+ this.controller = createMiddleware4((c) => __async(this, null, function* () {
9771
9591
  const accountId = c.req.header("account-id");
9772
9592
  const { entityType, entityId } = c.req.param();
9773
9593
  try {
@@ -9779,7 +9599,7 @@ var DeleteEntityController = class {
9779
9599
  return c.json({ message: "entity deleted" });
9780
9600
  } catch (err) {
9781
9601
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_NOT_FOUND) {
9782
- c.status(httpStatus7.NOT_FOUND);
9602
+ c.status(httpStatus6.NOT_FOUND);
9783
9603
  return c.json(__spreadValues({}, err.toJSON()));
9784
9604
  }
9785
9605
  throw err;
@@ -9789,12 +9609,12 @@ var DeleteEntityController = class {
9789
9609
  };
9790
9610
 
9791
9611
  // controllers/entity/get-entity-by-unique-field-value.controller.ts
9792
- import { createMiddleware as createMiddleware7 } from "hono/factory";
9793
- import httpStatus8 from "http-status";
9612
+ import { createMiddleware as createMiddleware5 } from "hono/factory";
9613
+ import httpStatus7 from "http-status";
9794
9614
  var GetEntityByUniqueFieldValueController = class {
9795
9615
  constructor(entityRepository) {
9796
9616
  this.entityRepository = entityRepository;
9797
- this.controller = createMiddleware7((c) => __async(this, null, function* () {
9617
+ this.controller = createMiddleware5((c) => __async(this, null, function* () {
9798
9618
  const { entityType, uniqueField, uniqueFieldValue } = c.req.param();
9799
9619
  try {
9800
9620
  const entity = yield this.entityRepository.getEntityByUniqueField(
@@ -9805,7 +9625,7 @@ var GetEntityByUniqueFieldValueController = class {
9805
9625
  return c.json(entity);
9806
9626
  } catch (err) {
9807
9627
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
9808
- c.status(httpStatus8.NOT_FOUND);
9628
+ c.status(httpStatus7.NOT_FOUND);
9809
9629
  return c.json({
9810
9630
  code: "ENTITY_NOT_FOUND",
9811
9631
  message: "Entity not found"
@@ -9818,23 +9638,23 @@ var GetEntityByUniqueFieldValueController = class {
9818
9638
  };
9819
9639
 
9820
9640
  // controllers/entity/get-entity.controller.ts
9821
- import { createMiddleware as createMiddleware8 } from "hono/factory";
9822
- import httpStatus9 from "http-status";
9641
+ import { createMiddleware as createMiddleware6 } from "hono/factory";
9642
+ import httpStatus8 from "http-status";
9823
9643
  var GetEntityController = class {
9824
9644
  constructor(entityRepository) {
9825
9645
  this.entityRepository = entityRepository;
9826
- this.controller = createMiddleware8((c) => __async(this, null, function* () {
9646
+ this.controller = createMiddleware6((c) => __async(this, null, function* () {
9827
9647
  const { entityType, entityId } = c.req.param();
9828
9648
  try {
9829
9649
  const entity = yield this.entityRepository.getEntity(
9830
9650
  entityType,
9831
9651
  entityId
9832
9652
  );
9833
- c.status(httpStatus9.OK);
9653
+ c.status(httpStatus8.OK);
9834
9654
  return c.json(entity);
9835
9655
  } catch (err) {
9836
9656
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
9837
- c.status(httpStatus9.NOT_FOUND);
9657
+ c.status(httpStatus8.NOT_FOUND);
9838
9658
  return c.json({
9839
9659
  code: "ENTITY_NOT_FOUND",
9840
9660
  message: "Entity not found"
@@ -9847,7 +9667,7 @@ var GetEntityController = class {
9847
9667
  };
9848
9668
 
9849
9669
  // controllers/entity/list-entities.controller.ts
9850
- import { createMiddleware as createMiddleware9 } from "hono/factory";
9670
+ import { createMiddleware as createMiddleware7 } from "hono/factory";
9851
9671
  var querySchema = external_exports.object({
9852
9672
  limit: external_exports.string().optional(),
9853
9673
  lastKey: external_exports.string().optional(),
@@ -9856,9 +9676,10 @@ var querySchema = external_exports.object({
9856
9676
  end: external_exports.string().optional()
9857
9677
  });
9858
9678
  var ListEntitiesController = class {
9859
- constructor(entityRepository) {
9679
+ constructor(entityRepository, searchRepository) {
9860
9680
  this.entityRepository = entityRepository;
9861
- this.controller = createMiddleware9((c) => __async(this, null, function* () {
9681
+ this.searchRepository = searchRepository;
9682
+ this.controller = createMiddleware7((c) => __async(this, null, function* () {
9862
9683
  const errorContext = {};
9863
9684
  try {
9864
9685
  const accountId = c.req.header("account-id") || "";
@@ -9873,10 +9694,7 @@ var ListEntitiesController = class {
9873
9694
  const { entityType } = params;
9874
9695
  const { lastKey, query, limit, start, end } = querySchema.parse(queries2);
9875
9696
  if (query) {
9876
- const results2 = yield this.entityRepository.queryEntities(
9877
- entityType,
9878
- query
9879
- );
9697
+ const results2 = this.searchRepository.searchConfig(entityType) ? yield this.searchRepository.searchEntities(entityType, query) : yield this.entityRepository.queryEntities(entityType, query);
9880
9698
  return c.json({
9881
9699
  data: results2.items.map((item) => item.toJSON()),
9882
9700
  totalCount: results2.totalCount,
@@ -9906,19 +9724,19 @@ var ListEntitiesController = class {
9906
9724
  };
9907
9725
 
9908
9726
  // controllers/entity/update-entity.controller.ts
9909
- import { createMiddleware as createMiddleware10 } from "hono/factory";
9910
- import httpStatus10 from "http-status";
9727
+ import { createMiddleware as createMiddleware8 } from "hono/factory";
9728
+ import httpStatus9 from "http-status";
9911
9729
  var UpdateEntityController = class {
9912
9730
  constructor(entityService) {
9913
9731
  this.entityService = entityService;
9914
- this.controller = createMiddleware10((c) => __async(this, null, function* () {
9732
+ this.controller = createMiddleware8((c) => __async(this, null, function* () {
9915
9733
  const accountId = c.req.header("account-id");
9916
9734
  const { entityType, entityId } = c.req.param();
9917
9735
  const body = yield c.req.json();
9918
9736
  const _a = body, { $condition: condition, $where: where } = _a, entityPayload = __objRest(_a, ["$condition", "$where"]);
9919
9737
  if (condition !== void 0) {
9920
9738
  if (typeof condition !== "string" || condition.trim().length === 0) {
9921
- c.status(httpStatus10.BAD_REQUEST);
9739
+ c.status(httpStatus9.BAD_REQUEST);
9922
9740
  return c.json({
9923
9741
  code: "API_VALIDATION_ERROR",
9924
9742
  message: "$condition must be a non-empty string"
@@ -9940,11 +9758,11 @@ var UpdateEntityController = class {
9940
9758
  where
9941
9759
  });
9942
9760
  errorContext.entity = entity;
9943
- c.status(httpStatus10.OK);
9761
+ c.status(httpStatus9.OK);
9944
9762
  return c.json(entity);
9945
9763
  } catch (err) {
9946
9764
  if ((err == null ? void 0 : err.name) === "ZodError") {
9947
- c.status(httpStatus10.BAD_REQUEST);
9765
+ c.status(httpStatus9.BAD_REQUEST);
9948
9766
  return c.json({
9949
9767
  code: "API_VALIDATION_ERROR",
9950
9768
  message: "API validation failed",
@@ -9952,19 +9770,19 @@ var UpdateEntityController = class {
9952
9770
  });
9953
9771
  }
9954
9772
  if (err instanceof StandardError && (err.code === StandardErrorCode.ENTITY_NOT_FOUND || err.code === StandardErrorCode.ENTITY_IS_UNDEFINED)) {
9955
- c.status(httpStatus10.NOT_FOUND);
9773
+ c.status(httpStatus9.NOT_FOUND);
9956
9774
  return c.json(__spreadValues({}, err.toJSON()));
9957
9775
  }
9958
9776
  if (err instanceof StandardError && err.code === StandardErrorCode.INVALID_CONDITION) {
9959
- c.status(httpStatus10.BAD_REQUEST);
9777
+ c.status(httpStatus9.BAD_REQUEST);
9960
9778
  return c.json(__spreadValues({}, err.toJSON()));
9961
9779
  }
9962
9780
  if (err instanceof StandardError && err.code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
9963
- c.status(httpStatus10.BAD_REQUEST);
9781
+ c.status(httpStatus9.BAD_REQUEST);
9964
9782
  return c.json(__spreadValues({}, err.toJSON()));
9965
9783
  }
9966
9784
  if (err instanceof StandardError && err.code === StandardErrorCode.CONDITIONAL_CHECK_FAILED) {
9967
- c.status(httpStatus10.CONFLICT);
9785
+ c.status(httpStatus9.CONFLICT);
9968
9786
  return c.json(__spreadValues({}, err.toJSON()));
9969
9787
  }
9970
9788
  console.log(
@@ -9979,12 +9797,12 @@ var UpdateEntityController = class {
9979
9797
  };
9980
9798
 
9981
9799
  // controllers/entity/adjust-entity.controller.ts
9982
- import { createMiddleware as createMiddleware11 } from "hono/factory";
9983
- import httpStatus11 from "http-status";
9800
+ import { createMiddleware as createMiddleware9 } from "hono/factory";
9801
+ import httpStatus10 from "http-status";
9984
9802
  var AdjustEntityController = class {
9985
9803
  constructor(entityService) {
9986
9804
  this.entityService = entityService;
9987
- this.controller = createMiddleware11((c) => __async(this, null, function* () {
9805
+ this.controller = createMiddleware9((c) => __async(this, null, function* () {
9988
9806
  var _b;
9989
9807
  const accountId = c.req.header("account-id") || "";
9990
9808
  const { entityType, entityId } = c.req.param();
@@ -9992,7 +9810,7 @@ var AdjustEntityController = class {
9992
9810
  const _a = body, { $condition: condition } = _a, adjustments = __objRest(_a, ["$condition"]);
9993
9811
  if (condition !== void 0) {
9994
9812
  if (typeof condition !== "string" || condition.trim().length === 0) {
9995
- c.status(httpStatus11.BAD_REQUEST);
9813
+ c.status(httpStatus10.BAD_REQUEST);
9996
9814
  return c.json({
9997
9815
  code: "API_VALIDATION_ERROR",
9998
9816
  message: "$condition must be a non-empty string"
@@ -10001,7 +9819,7 @@ var AdjustEntityController = class {
10001
9819
  }
10002
9820
  for (const [key, value] of Object.entries(adjustments)) {
10003
9821
  if (typeof value !== "number") {
10004
- c.status(httpStatus11.BAD_REQUEST);
9822
+ c.status(httpStatus10.BAD_REQUEST);
10005
9823
  return c.json({
10006
9824
  code: "API_VALIDATION_ERROR",
10007
9825
  message: `Field "${key}" must be a number, got ${typeof value}`
@@ -10016,19 +9834,19 @@ var AdjustEntityController = class {
10016
9834
  accountId,
10017
9835
  condition
10018
9836
  });
10019
- c.status(httpStatus11.OK);
9837
+ c.status(httpStatus10.OK);
10020
9838
  return c.json(entity.toJSON());
10021
9839
  } catch (err) {
10022
9840
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
10023
- c.status(httpStatus11.NOT_FOUND);
9841
+ c.status(httpStatus10.NOT_FOUND);
10024
9842
  return c.json(__spreadValues({}, err.toJSON()));
10025
9843
  }
10026
9844
  if (err instanceof StandardError && err.code === StandardErrorCode.INVALID_CONDITION) {
10027
- c.status(httpStatus11.BAD_REQUEST);
9845
+ c.status(httpStatus10.BAD_REQUEST);
10028
9846
  return c.json(__spreadValues({}, err.toJSON()));
10029
9847
  }
10030
9848
  if ((err == null ? void 0 : err.name) === "ConditionalCheckFailedException" || ((_b = err == null ? void 0 : err.__type) == null ? void 0 : _b.includes("ConditionalCheckFailed"))) {
10031
- c.status(httpStatus11.CONFLICT);
9849
+ c.status(httpStatus10.CONFLICT);
10032
9850
  return c.json({
10033
9851
  code: "ADJUSTMENT_CONSTRAINT_VIOLATED",
10034
9852
  message: "Adjustment would violate entity constraints"
@@ -10042,14 +9860,14 @@ var AdjustEntityController = class {
10042
9860
  };
10043
9861
 
10044
9862
  // controllers/entity/upsert-entity.controller.ts
10045
- import { createMiddleware as createMiddleware12 } from "hono/factory";
10046
- import httpStatus12 from "http-status";
9863
+ import { createMiddleware as createMiddleware10 } from "hono/factory";
9864
+ import httpStatus11 from "http-status";
10047
9865
  var UpsertEntityController = class {
10048
9866
  constructor(EntityConfig, entityRepository, publishEvent2) {
10049
9867
  this.EntityConfig = EntityConfig;
10050
9868
  this.entityRepository = entityRepository;
10051
9869
  this.publishEvent = publishEvent2;
10052
- this.controller = createMiddleware12((c) => __async(this, null, function* () {
9870
+ this.controller = createMiddleware10((c) => __async(this, null, function* () {
10053
9871
  var _a;
10054
9872
  const accountId = c.req.header("account-id");
10055
9873
  const { entityType, entityId } = c.req.param();
@@ -10114,7 +9932,7 @@ var UpsertEntityController = class {
10114
9932
  return c.json(entity);
10115
9933
  } catch (err) {
10116
9934
  if (err instanceof ZodError) {
10117
- c.status(httpStatus12.BAD_REQUEST);
9935
+ c.status(httpStatus11.BAD_REQUEST);
10118
9936
  return c.json({
10119
9937
  code: "API_VALIDATION_ERROR",
10120
9938
  message: "API validation failed",
@@ -10122,7 +9940,7 @@ var UpsertEntityController = class {
10122
9940
  });
10123
9941
  }
10124
9942
  if (err instanceof StandardError && err.code === StandardErrorCode.EMAIL_EXISTS) {
10125
- c.status(httpStatus12.BAD_REQUEST);
9943
+ c.status(httpStatus11.BAD_REQUEST);
10126
9944
  return c.json(__spreadValues({}, err.toJSON()));
10127
9945
  }
10128
9946
  throw err;
@@ -10132,12 +9950,12 @@ var UpsertEntityController = class {
10132
9950
  };
10133
9951
 
10134
9952
  // controllers/mutual/create-mutual.controller.ts
10135
- import { createMiddleware as createMiddleware13 } from "hono/factory";
10136
- import httpStatus13 from "http-status";
9953
+ import { createMiddleware as createMiddleware11 } from "hono/factory";
9954
+ import httpStatus12 from "http-status";
10137
9955
  var CreateMutualController = class {
10138
9956
  constructor(mutualService) {
10139
9957
  this.mutualService = mutualService;
10140
- this.controller = createMiddleware13((c) => __async(this, null, function* () {
9958
+ this.controller = createMiddleware11((c) => __async(this, null, function* () {
10141
9959
  const accountId = c.req.header("account-id");
10142
9960
  const { byEntityType, byEntityId, entityType, entityId } = c.req.param();
10143
9961
  const asEntity = c.req.query("asEntity");
@@ -10157,7 +9975,7 @@ var CreateMutualController = class {
10157
9975
  return c.json(mutual);
10158
9976
  } catch (err) {
10159
9977
  if (err instanceof ZodError) {
10160
- c.status(httpStatus13.BAD_REQUEST);
9978
+ c.status(httpStatus12.BAD_REQUEST);
10161
9979
  return c.json({
10162
9980
  code: "API_VALIDATION_ERROR",
10163
9981
  message: "API validation failed",
@@ -10165,11 +9983,11 @@ var CreateMutualController = class {
10165
9983
  });
10166
9984
  }
10167
9985
  if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_EXISTS) {
10168
- c.status(httpStatus13.BAD_REQUEST);
9986
+ c.status(httpStatus12.BAD_REQUEST);
10169
9987
  return c.json(__spreadValues({}, err.toJSON()));
10170
9988
  }
10171
9989
  if (err instanceof StandardError && err.code === StandardErrorCode.ENTITY_IS_UNDEFINED) {
10172
- c.status(httpStatus13.BAD_REQUEST);
9990
+ c.status(httpStatus12.BAD_REQUEST);
10173
9991
  return c.json(__spreadValues({}, err.toJSON()));
10174
9992
  }
10175
9993
  throw err;
@@ -10179,12 +9997,12 @@ var CreateMutualController = class {
10179
9997
  };
10180
9998
 
10181
9999
  // controllers/mutual/delete-mutual.controller.ts
10182
- import { createMiddleware as createMiddleware14 } from "hono/factory";
10183
- import httpStatus14 from "http-status";
10000
+ import { createMiddleware as createMiddleware12 } from "hono/factory";
10001
+ import httpStatus13 from "http-status";
10184
10002
  var DeleteMutualController = class {
10185
10003
  constructor(mutualService) {
10186
10004
  this.mutualService = mutualService;
10187
- this.controller = createMiddleware14((c) => __async(this, null, function* () {
10005
+ this.controller = createMiddleware12((c) => __async(this, null, function* () {
10188
10006
  const accountId = c.req.header("account-id");
10189
10007
  const { byEntityType, byEntityId, entityType, entityId } = c.req.param();
10190
10008
  try {
@@ -10198,7 +10016,7 @@ var DeleteMutualController = class {
10198
10016
  return c.json(mutual);
10199
10017
  } catch (err) {
10200
10018
  if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_NOT_FOUND) {
10201
- c.status(httpStatus14.BAD_REQUEST);
10019
+ c.status(httpStatus13.BAD_REQUEST);
10202
10020
  return c.json(__spreadValues({}, err.toJSON()));
10203
10021
  }
10204
10022
  throw err;
@@ -10208,12 +10026,12 @@ var DeleteMutualController = class {
10208
10026
  };
10209
10027
 
10210
10028
  // controllers/mutual/get-mutual.controller.ts
10211
- import { createMiddleware as createMiddleware15 } from "hono/factory";
10212
- import httpStatus15 from "http-status";
10029
+ import { createMiddleware as createMiddleware13 } from "hono/factory";
10030
+ import httpStatus14 from "http-status";
10213
10031
  var GetMutualController = class {
10214
10032
  constructor(associateRepository) {
10215
10033
  this.associateRepository = associateRepository;
10216
- this.controller = createMiddleware15((c) => __async(this, null, function* () {
10034
+ this.controller = createMiddleware13((c) => __async(this, null, function* () {
10217
10035
  const { byEntityType, byEntityId, entityType, entityId } = c.req.param();
10218
10036
  try {
10219
10037
  const associate = yield this.associateRepository.getMutual(
@@ -10225,7 +10043,7 @@ var GetMutualController = class {
10225
10043
  return c.json(associate);
10226
10044
  } catch (err) {
10227
10045
  if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_IS_UNDEFINED) {
10228
- c.status(httpStatus15.NOT_FOUND);
10046
+ c.status(httpStatus14.NOT_FOUND);
10229
10047
  return c.json({
10230
10048
  code: "MUTUAL_NOT_FOUND",
10231
10049
  message: "Mutual not found"
@@ -10238,11 +10056,11 @@ var GetMutualController = class {
10238
10056
  };
10239
10057
 
10240
10058
  // controllers/mutual/list-entities-by-entity.controller.ts
10241
- import { createMiddleware as createMiddleware16 } from "hono/factory";
10059
+ import { createMiddleware as createMiddleware14 } from "hono/factory";
10242
10060
  var ListEntitiesByEntityController = class {
10243
10061
  constructor(associateRepository) {
10244
10062
  this.associateRepository = associateRepository;
10245
- this.controller = createMiddleware16((c) => __async(this, null, function* () {
10063
+ this.controller = createMiddleware14((c) => __async(this, null, function* () {
10246
10064
  const { byEntityType, byEntityId, entityType } = c.req.param();
10247
10065
  const querySchema3 = external_exports.object({
10248
10066
  chainEntityQuery: external_exports.string().optional(),
@@ -10300,12 +10118,12 @@ var ListEntitiesByEntityController = class {
10300
10118
  };
10301
10119
 
10302
10120
  // controllers/mutual/update-mutual.controller.ts
10303
- import { createMiddleware as createMiddleware17 } from "hono/factory";
10304
- import httpStatus16 from "http-status";
10121
+ import { createMiddleware as createMiddleware15 } from "hono/factory";
10122
+ import httpStatus15 from "http-status";
10305
10123
  var UpdateMutualController = class {
10306
10124
  constructor(mutualService) {
10307
10125
  this.mutualService = mutualService;
10308
- this.controller = createMiddleware17((c) => __async(this, null, function* () {
10126
+ this.controller = createMiddleware15((c) => __async(this, null, function* () {
10309
10127
  const accountId = c.req.header("account-id");
10310
10128
  const { byEntityType, byEntityId, entityType, entityId } = c.req.param();
10311
10129
  const body = yield c.req.json();
@@ -10324,7 +10142,7 @@ var UpdateMutualController = class {
10324
10142
  return c.json(mutual);
10325
10143
  } catch (err) {
10326
10144
  if (err instanceof ZodError) {
10327
- c.status(httpStatus16.BAD_REQUEST);
10145
+ c.status(httpStatus15.BAD_REQUEST);
10328
10146
  return c.json({
10329
10147
  code: "API_VALIDATION_ERROR",
10330
10148
  message: "API validation failed",
@@ -10332,7 +10150,7 @@ var UpdateMutualController = class {
10332
10150
  });
10333
10151
  }
10334
10152
  if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_NOT_FOUND) {
10335
- c.status(httpStatus16.BAD_REQUEST);
10153
+ c.status(httpStatus15.BAD_REQUEST);
10336
10154
  return c.json(__spreadValues({}, err.toJSON()));
10337
10155
  }
10338
10156
  throw err;
@@ -10773,7 +10591,7 @@ var EntityService = class {
10773
10591
  };
10774
10592
 
10775
10593
  // controllers/tag/list-tags.controller.ts
10776
- import { createMiddleware as createMiddleware18 } from "hono/factory";
10594
+ import { createMiddleware as createMiddleware16 } from "hono/factory";
10777
10595
  var querySchema2 = external_exports.object({
10778
10596
  group: external_exports.string().optional(),
10779
10597
  query: external_exports.string().optional(),
@@ -10785,7 +10603,7 @@ var querySchema2 = external_exports.object({
10785
10603
  var ListTagsController = class {
10786
10604
  constructor(tagRepository) {
10787
10605
  this.tagRepository = tagRepository;
10788
- this.controller = createMiddleware18((c) => __async(this, null, function* () {
10606
+ this.controller = createMiddleware16((c) => __async(this, null, function* () {
10789
10607
  const errorContext = {};
10790
10608
  try {
10791
10609
  errorContext.params = c.req.param();
@@ -10820,18 +10638,18 @@ var ListTagsController = class {
10820
10638
  };
10821
10639
 
10822
10640
  // controllers/transaction/execute-transaction.controller.ts
10823
- import { createMiddleware as createMiddleware19 } from "hono/factory";
10824
- import httpStatus17 from "http-status";
10641
+ import { createMiddleware as createMiddleware17 } from "hono/factory";
10642
+ import httpStatus16 from "http-status";
10825
10643
  var ExecuteTransactionController = class {
10826
10644
  constructor(transactionService) {
10827
10645
  this.transactionService = transactionService;
10828
10646
  // biome-ignore lint/suspicious/noExplicitAny: Hono createMiddleware requires consistent return types
10829
- this.controller = createMiddleware19((c) => __async(this, null, function* () {
10647
+ this.controller = createMiddleware17((c) => __async(this, null, function* () {
10830
10648
  const accountId = c.req.header("account-id") || "";
10831
10649
  try {
10832
10650
  const body = yield c.req.json();
10833
10651
  if (!body.operations || !Array.isArray(body.operations)) {
10834
- c.status(httpStatus17.BAD_REQUEST);
10652
+ c.status(httpStatus16.BAD_REQUEST);
10835
10653
  return c.json({
10836
10654
  code: "API_VALIDATION_ERROR",
10837
10655
  message: 'Request body must contain an "operations" array'
@@ -10841,11 +10659,11 @@ var ExecuteTransactionController = class {
10841
10659
  body.operations,
10842
10660
  accountId
10843
10661
  );
10844
- c.status(httpStatus17.OK);
10662
+ c.status(httpStatus16.OK);
10845
10663
  return c.json(result);
10846
10664
  } catch (err) {
10847
10665
  if ((err == null ? void 0 : err.name) === "ZodError") {
10848
- c.status(httpStatus17.BAD_REQUEST);
10666
+ c.status(httpStatus16.BAD_REQUEST);
10849
10667
  return c.json({
10850
10668
  code: "API_VALIDATION_ERROR",
10851
10669
  message: "Validation failed",
@@ -10853,7 +10671,7 @@ var ExecuteTransactionController = class {
10853
10671
  });
10854
10672
  }
10855
10673
  if (err instanceof SyntaxError) {
10856
- c.status(httpStatus17.BAD_REQUEST);
10674
+ c.status(httpStatus16.BAD_REQUEST);
10857
10675
  return c.json({
10858
10676
  code: "API_VALIDATION_ERROR",
10859
10677
  message: "Request body must be valid JSON"
@@ -10862,15 +10680,15 @@ var ExecuteTransactionController = class {
10862
10680
  if (err instanceof StandardError) {
10863
10681
  const code = err.code;
10864
10682
  if (code === StandardErrorCode.ENTITY_IS_UNDEFINED || code === StandardErrorCode.ENTITY_NOT_FOUND || code === StandardErrorCode.MUTUAL_NOT_FOUND) {
10865
- c.status(httpStatus17.NOT_FOUND);
10683
+ c.status(httpStatus16.NOT_FOUND);
10866
10684
  return c.json(__spreadValues({}, err.toJSON()));
10867
10685
  }
10868
10686
  if (code === StandardErrorCode.TRANSACTION_EMPTY || code === StandardErrorCode.TRANSACTION_ITEM_LIMIT_EXCEEDED || code === StandardErrorCode.TRANSACTION_UNIQUE_FIELD_UPDATE || code === StandardErrorCode.TRANSACTION_INVALID_OPERATION || code === StandardErrorCode.TRANSACTION_VALIDATION_ERROR || code === StandardErrorCode.INVALID_ENTITY_TYPE || code === StandardErrorCode.INVALID_CONDITION || code === StandardErrorCode.INVALID_UNIQUE_VALUE_TYPE) {
10869
- c.status(httpStatus17.BAD_REQUEST);
10687
+ c.status(httpStatus16.BAD_REQUEST);
10870
10688
  return c.json(__spreadValues({}, err.toJSON()));
10871
10689
  }
10872
10690
  if (code === StandardErrorCode.TRANSACTION_FAILED || code === StandardErrorCode.CONDITIONAL_CHECK_FAILED || code === StandardErrorCode.UNIQUE_VALUE_EXISTS || code === StandardErrorCode.MUTUAL_EXISTS) {
10873
- c.status(httpStatus17.CONFLICT);
10691
+ c.status(httpStatus16.CONFLICT);
10874
10692
  return c.json(__spreadValues({}, err.toJSON()));
10875
10693
  }
10876
10694
  }
@@ -10881,13 +10699,13 @@ var ExecuteTransactionController = class {
10881
10699
  };
10882
10700
 
10883
10701
  // controllers/ws/create-ticket.controller.ts
10884
- import { createMiddleware as createMiddleware20 } from "hono/factory";
10702
+ import { createMiddleware as createMiddleware18 } from "hono/factory";
10885
10703
  import { ulid as ulid6 } from "ulid";
10886
10704
  var TICKET_TTL_SECONDS = 30 * 60;
10887
10705
  var CreateTicketController = class {
10888
10706
  constructor(container) {
10889
10707
  this.container = container;
10890
- this.controller = createMiddleware20((c) => __async(this, null, function* () {
10708
+ this.controller = createMiddleware18((c) => __async(this, null, function* () {
10891
10709
  var _a, _b;
10892
10710
  const { entityType, entityId } = c.req.param();
10893
10711
  let feedTypes;
@@ -11711,6 +11529,16 @@ var DependencyContainer = class {
11711
11529
  this.config.EmailAuthEnabledEntities
11712
11530
  );
11713
11531
  }
11532
+ get searchRepository() {
11533
+ return this.createCachedInstance(
11534
+ SearchRepository,
11535
+ this.config.EntityConfig,
11536
+ this.coreTable,
11537
+ this.dynamodbClient,
11538
+ this.entityRepository,
11539
+ this.config.SearchDefaults
11540
+ );
11541
+ }
11714
11542
  get mutualRepository() {
11715
11543
  return this.createCachedInstance(
11716
11544
  MutualRepository,
@@ -11777,7 +11605,8 @@ var DependencyContainer = class {
11777
11605
  get listEntitiesController() {
11778
11606
  return this.createCachedInstance(
11779
11607
  ListEntitiesController,
11780
- this.entityRepository
11608
+ this.entityRepository,
11609
+ this.searchRepository
11781
11610
  );
11782
11611
  }
11783
11612
  get createEntityController() {
@@ -11936,12 +11765,13 @@ var CoreFactory = class {
11936
11765
  this.dependencyContainer = dependencyContainer;
11937
11766
  this.setupCommonRoutes = setupCommonRoutes(dependencyContainer);
11938
11767
  this.mutualProcessor = handler7(dependencyContainer);
11939
- this.replicationProcessor = handler9(dependencyContainer);
11768
+ this.replicationProcessor = handler10(dependencyContainer);
11769
+ this.searchReindexProcessor = handler9(dependencyContainer);
11940
11770
  this.createEntityProcessor = handler(dependencyContainer);
11941
11771
  this.analyticsProcessor = handler2(this.config.EntityConfig);
11942
11772
  this.analyticsBackfillProcessor = handler3(this.config.EntityConfig);
11943
11773
  this.prejoinProcessor = handler8(dependencyContainer);
11944
- this.tagProcessor = handler10(dependencyContainer);
11774
+ this.tagProcessor = handler11(dependencyContainer);
11945
11775
  this.appHandler = appHandler(dependencyContainer);
11946
11776
  this.wsConnect = connect(dependencyContainer);
11947
11777
  this.wsDisconnect = disconnect(dependencyContainer);
@@ -11959,6 +11789,7 @@ export {
11959
11789
  MutualRepository,
11960
11790
  MutualService,
11961
11791
  PROJECTION_EXPRESSION,
11792
+ SearchRepository,
11962
11793
  StandardError,
11963
11794
  StandardErrorCode,
11964
11795
  TagRepository,
@@ -11975,11 +11806,11 @@ export {
11975
11806
  index_default as default,
11976
11807
  handler7 as mutualProcessor,
11977
11808
  handler8 as prejoinProcessor,
11978
- handler9 as replicationProcessor,
11979
- requires,
11809
+ handler10 as replicationProcessor,
11810
+ handler9 as searchReindexProcessor,
11980
11811
  setupCommonRoutes,
11981
11812
  startBackfill as startAnalyticsBackfill,
11982
- handler10 as tagProcessor,
11813
+ handler11 as tagProcessor,
11983
11814
  transactional,
11984
11815
  broadcast as wsBroadcast,
11985
11816
  connect as wsConnect,