monorise 2.0.0-dev.1 → 2.0.0-dev.2

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.
@@ -180,11 +180,13 @@ var createRouteGuards = (entityConfig) => {
180
180
  `adjust on these fields of '${entityType}'`
181
181
  );
182
182
  const checkSearch = (key, entityType) => {
183
- var _a, _b;
183
+ var _a;
184
+ const config = entityConfig[entityType];
185
+ const fields = (config == null ? void 0 : config.search) ? config.search.fields.map(({ field }) => field) : (_a = config == null ? void 0 : config.searchableFields) != null ? _a : [];
184
186
  return checkFields(
185
187
  key,
186
188
  key.access.entity(entityType).read,
187
- ((_b = (_a = entityConfig[entityType]) == null ? void 0 : _a.searchableFields) != null ? _b : []).map(String),
189
+ fields.map(String),
188
190
  `search on '${entityType}', which matches these fields it cannot read`
189
191
  );
190
192
  };
@@ -1454,12 +1456,10 @@ var EntityRepository = class extends Repository {
1454
1456
  const filteredItems = [];
1455
1457
  const { searchableFields } = this.EntityConfig[entityType];
1456
1458
  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(" ");
1459
+ const searchTerm = (searchableFields != null ? searchableFields : []).map((field) => {
1460
+ const value = item.data[field];
1461
+ return (Array.isArray(value) ? value : [value]).filter((v) => typeof v === "string" || typeof v === "number").map((v) => String(v).toLowerCase()).join(" ");
1462
+ }).join(" ");
1463
1463
  const isMatched = queryRegex.test(searchTerm);
1464
1464
  if (isMatched) {
1465
1465
  filteredItems.push(item);
@@ -1491,6 +1491,14 @@ var PROJECTION_EXPRESSION = {
1491
1491
  MUTUAL_DATA_ONLY: "byEntityType, byEntityId, entityType, entityId, mutualId, mutualData"
1492
1492
  };
1493
1493
 
1494
+ // helpers/debug.ts
1495
+ var OFF = /* @__PURE__ */ new Set(["", "0", "false", "off", "no"]);
1496
+ var debugLog = (...args) => {
1497
+ var _a;
1498
+ const flag = (_a = process.env.MONORISE_DEBUG) == null ? void 0 : _a.trim().toLowerCase();
1499
+ if (flag !== void 0 && !OFF.has(flag)) console.log(...args);
1500
+ };
1501
+
1494
1502
  // data/Mutual.ts
1495
1503
  var Mutual = class _Mutual {
1496
1504
  constructor(byEntityType, byEntityId, byData, entityType, entityId, data, mutualData, mutualId, _createdAt, _updatedAt, _mutualUpdatedAt, _expiresAt) {
@@ -1670,7 +1678,7 @@ var MutualRepository = class extends Repository {
1670
1678
  getMutual(byEntityType, byEntityId, entityType, entityId, opts) {
1671
1679
  return __async(this, null, function* () {
1672
1680
  var _a, _b, _c, _d, _e, _f;
1673
- console.log("[MONORISE_DEBUG] getMutual start:", {
1681
+ debugLog("[MONORISE_DEBUG] getMutual start:", {
1674
1682
  byEntityType,
1675
1683
  byEntityId,
1676
1684
  entityType,
@@ -1686,7 +1694,7 @@ var MutualRepository = class extends Repository {
1686
1694
  {},
1687
1695
  {}
1688
1696
  );
1689
- console.log("[MONORISE_DEBUG] getMutual querying:", {
1697
+ debugLog("[MONORISE_DEBUG] getMutual querying:", {
1690
1698
  byFullEntityId: mutual.byFullEntityId,
1691
1699
  fullEntityId: mutual.fullEntityId,
1692
1700
  tableName: this.TABLE_NAME
@@ -1707,7 +1715,7 @@ var MutualRepository = class extends Repository {
1707
1715
  },
1708
1716
  Limit: 1
1709
1717
  });
1710
- console.log("[MONORISE_DEBUG] getMutual query result:", {
1718
+ debugLog("[MONORISE_DEBUG] getMutual query result:", {
1711
1719
  hasItems: !!((_a = resp.Items) == null ? void 0 : _a.length),
1712
1720
  itemCount: (_c = (_b = resp.Items) == null ? void 0 : _b.length) != null ? _c : 0,
1713
1721
  hasLastEvaluatedKey: !!resp.LastEvaluatedKey
@@ -1722,12 +1730,12 @@ var MutualRepository = class extends Repository {
1722
1730
  });
1723
1731
  mutualMetadata = Mutual.fromItem(respMetadataMutual.Item);
1724
1732
  }
1725
- console.log("[MONORISE_DEBUG] getMutual fromItem:", {
1733
+ debugLog("[MONORISE_DEBUG] getMutual fromItem:", {
1726
1734
  hasMutualMetadata: !!mutualMetadata,
1727
1735
  hasFirstItem: !!((_e = resp.Items) == null ? void 0 : _e[0])
1728
1736
  });
1729
1737
  const result = mutualMetadata || Mutual.fromItem((_f = resp.Items) == null ? void 0 : _f[0]);
1730
- console.log("[MONORISE_DEBUG] getMutual complete:", {
1738
+ debugLog("[MONORISE_DEBUG] getMutual complete:", {
1731
1739
  mutualId: result.mutualId,
1732
1740
  byEntityType: result.byEntityType,
1733
1741
  entityType: result.entityType
@@ -1738,7 +1746,7 @@ var MutualRepository = class extends Repository {
1738
1746
  checkMutualExist(byEntityType, byEntityId, entityType, entityId) {
1739
1747
  return __async(this, null, function* () {
1740
1748
  var _a, _b;
1741
- console.log("[MONORISE_DEBUG] checkMutualExist:", {
1749
+ debugLog("[MONORISE_DEBUG] checkMutualExist:", {
1742
1750
  byEntityType,
1743
1751
  byEntityId,
1744
1752
  entityType,
@@ -1758,7 +1766,7 @@ var MutualRepository = class extends Repository {
1758
1766
  Key: mutual.subKeys(),
1759
1767
  ProjectionExpression: "PK, SK, expiresAt"
1760
1768
  });
1761
- console.log("[MONORISE_DEBUG] checkMutualExist result:", {
1769
+ debugLog("[MONORISE_DEBUG] checkMutualExist result:", {
1762
1770
  hasItem: !!resp.Item,
1763
1771
  hasExpiresAt: !!((_a = resp.Item) == null ? void 0 : _a.expiresAt)
1764
1772
  });
@@ -1772,7 +1780,7 @@ var MutualRepository = class extends Repository {
1772
1780
  });
1773
1781
  }
1774
1782
  createMutualTransactItems(mutual, opts) {
1775
- console.log("[MONORISE_DEBUG] createMutualTransactItems:", {
1783
+ debugLog("[MONORISE_DEBUG] createMutualTransactItems:", {
1776
1784
  mutualId: mutual.mutualId,
1777
1785
  byEntityType: mutual.byEntityType,
1778
1786
  byEntityId: mutual.byEntityId,
@@ -1860,7 +1868,7 @@ var MutualRepository = class extends Repository {
1860
1868
  */
1861
1869
  prepareUpdateMutual(byEntityType, byEntityId, entityType, entityId, toUpdate, opts) {
1862
1870
  return __async(this, null, function* () {
1863
- console.log("[MONORISE_DEBUG] updateMutual fetching mutual...");
1871
+ debugLog("[MONORISE_DEBUG] updateMutual fetching mutual...");
1864
1872
  const mutual = yield this.getMutual(
1865
1873
  byEntityType,
1866
1874
  byEntityId,
@@ -1868,7 +1876,7 @@ var MutualRepository = class extends Repository {
1868
1876
  entityId,
1869
1877
  { ProjectionExpression: PROJECTION_EXPRESSION.NO_DATA }
1870
1878
  );
1871
- console.log("[MONORISE_DEBUG] updateMutual mutual found:", {
1879
+ debugLog("[MONORISE_DEBUG] updateMutual mutual found:", {
1872
1880
  mutualId: mutual.mutualId,
1873
1881
  mainPk: mutual.mainPk,
1874
1882
  byFullEntityId: mutual.byFullEntityId,
@@ -1881,7 +1889,7 @@ var MutualRepository = class extends Repository {
1881
1889
  }, toUpdate),
1882
1890
  { maxLevel: opts == null ? void 0 : opts.maxObjectUpdateLevel }
1883
1891
  );
1884
- console.log("[MONORISE_DEBUG] updateMutual update expression:", {
1892
+ debugLog("[MONORISE_DEBUG] updateMutual update expression:", {
1885
1893
  UpdateExpression: toUpdateExpressions.UpdateExpression,
1886
1894
  ExpressionAttributeNames: toUpdateExpressions.ExpressionAttributeNames,
1887
1895
  hasExpressionAttributeValues: !!toUpdateExpressions.ExpressionAttributeValues
@@ -1918,7 +1926,7 @@ var MutualRepository = class extends Repository {
1918
1926
  }, updateExpression)
1919
1927
  }
1920
1928
  ];
1921
- console.log("[MONORISE_DEBUG] updateMutual transact items prepared:", {
1929
+ debugLog("[MONORISE_DEBUG] updateMutual transact items prepared:", {
1922
1930
  itemCount: TransactItems.length,
1923
1931
  tableName: this.TABLE_NAME
1924
1932
  });
@@ -1928,7 +1936,7 @@ var MutualRepository = class extends Repository {
1928
1936
  updateMutual(byEntityType, byEntityId, entityType, entityId, toUpdate, opts) {
1929
1937
  return __async(this, null, function* () {
1930
1938
  var _a, _b;
1931
- console.log("[MONORISE_DEBUG] updateMutual repository start:", {
1939
+ debugLog("[MONORISE_DEBUG] updateMutual repository start:", {
1932
1940
  byEntityType,
1933
1941
  byEntityId,
1934
1942
  entityType,
@@ -1948,24 +1956,24 @@ var MutualRepository = class extends Repository {
1948
1956
  opts
1949
1957
  );
1950
1958
  errorContext.TransactItems = TransactItems;
1951
- console.log("[MONORISE_DEBUG] updateMutual executing transaction...");
1959
+ debugLog("[MONORISE_DEBUG] updateMutual executing transaction...");
1952
1960
  yield this.ddbUtils.executeTransactWrite({ TransactItems });
1953
- console.log("[MONORISE_DEBUG] updateMutual transaction succeeded");
1961
+ debugLog("[MONORISE_DEBUG] updateMutual transaction succeeded");
1954
1962
  if (!returnUpdatedValue) {
1955
- console.log("[MONORISE_DEBUG] updateMutual returning (no value)");
1963
+ debugLog("[MONORISE_DEBUG] updateMutual returning (no value)");
1956
1964
  return;
1957
1965
  }
1958
- console.log("[MONORISE_DEBUG] updateMutual fetching updated mutual...");
1966
+ debugLog("[MONORISE_DEBUG] updateMutual fetching updated mutual...");
1959
1967
  const updatedMutual = yield this.getMutual(
1960
1968
  byEntityType,
1961
1969
  byEntityId,
1962
1970
  entityType,
1963
1971
  entityId
1964
1972
  );
1965
- console.log("[MONORISE_DEBUG] updateMutual repository complete");
1973
+ debugLog("[MONORISE_DEBUG] updateMutual repository complete");
1966
1974
  return updatedMutual;
1967
1975
  } catch (err) {
1968
- console.error("[MONORISE_DEBUG] updateMutual repository error:", {
1976
+ debugLog("[MONORISE_DEBUG] updateMutual repository error:", {
1969
1977
  errorName: (_b = err == null ? void 0 : err.constructor) == null ? void 0 : _b.name,
1970
1978
  errorMessage: err == null ? void 0 : err.message,
1971
1979
  errorCode: err == null ? void 0 : err.code,
@@ -2169,6 +2177,295 @@ var MutualRepository = class extends Repository {
2169
2177
  }
2170
2178
  };
2171
2179
 
2180
+ // data/Search.ts
2181
+ import {
2182
+ ConditionalCheckFailedException as ConditionalCheckFailedException2
2183
+ } from "@aws-sdk/client-dynamodb";
2184
+ import {
2185
+ indexedWords,
2186
+ matchesSearch,
2187
+ planSearch,
2188
+ resolveSearchConfig,
2189
+ searchConfigHash
2190
+ } from "../base/index.js";
2191
+ var INDEX_STATE_PK = "#SEARCH#";
2192
+ var BATCH_WRITE_LIMIT = 25;
2193
+ var SearchRepository = class {
2194
+ constructor(EntityConfig, TABLE_NAME, dynamodbClient, entityRepository, searchDefaults) {
2195
+ this.EntityConfig = EntityConfig;
2196
+ this.TABLE_NAME = TABLE_NAME;
2197
+ this.dynamodbClient = dynamodbClient;
2198
+ this.entityRepository = entityRepository;
2199
+ this.searchDefaults = searchDefaults;
2200
+ // Entity types whose index matched the config, once seen. The config is
2201
+ // fixed for the life of a Lambda instance, so this never goes stale.
2202
+ this.readyTypes = /* @__PURE__ */ new Set();
2203
+ }
2204
+ /** The resolved `search` config, or undefined if the type isn't indexed. */
2205
+ searchConfig(entityType) {
2206
+ var _a;
2207
+ const search = (_a = this.EntityConfig[entityType]) == null ? void 0 : _a.search;
2208
+ return search ? resolveSearchConfig(search, this.searchDefaults) : void 0;
2209
+ }
2210
+ indexedEntityTypes() {
2211
+ return Object.keys(this.EntityConfig).filter(
2212
+ (entityType) => {
2213
+ var _a;
2214
+ return (_a = this.EntityConfig[entityType]) == null ? void 0 : _a.search;
2215
+ }
2216
+ );
2217
+ }
2218
+ rowKeys(entityType, entityId, word) {
2219
+ return {
2220
+ PK: { S: `SEARCH#${entityType}` },
2221
+ SK: { S: `${word}#${entityId}` }
2222
+ };
2223
+ }
2224
+ searchRow(entity, word) {
2225
+ return __spreadProps(__spreadValues(__spreadValues({}, entity.toItem()), this.rowKeys(entity.entityType, entity.entityId, word)), {
2226
+ R1PK: entity.keys().PK,
2227
+ R1SK: { S: `SEARCH#${word}` }
2228
+ });
2229
+ }
2230
+ /** Puts a row for each word in `add` and deletes the rows in `remove`. */
2231
+ writeRows(entity, add, remove) {
2232
+ return __async(this, null, function* () {
2233
+ var _a, _b;
2234
+ const entityId = entity.entityId;
2235
+ const requests = [
2236
+ ...add.map((word) => ({
2237
+ PutRequest: { Item: this.searchRow(entity, word) }
2238
+ })),
2239
+ ...remove.map((word) => ({
2240
+ DeleteRequest: {
2241
+ Key: this.rowKeys(entity.entityType, entityId, word)
2242
+ }
2243
+ }))
2244
+ ];
2245
+ for (let i = 0; i < requests.length; i += BATCH_WRITE_LIMIT) {
2246
+ let batch = requests.slice(i, i + BATCH_WRITE_LIMIT);
2247
+ for (let attempt = 0; batch.length; attempt++) {
2248
+ if (attempt > 0) {
2249
+ yield new Promise(
2250
+ (resolve) => setTimeout(resolve, Math.min(1e3, 50 * 2 ** attempt))
2251
+ );
2252
+ }
2253
+ const resp = yield this.dynamodbClient.batchWriteItem({
2254
+ RequestItems: { [this.TABLE_NAME]: batch }
2255
+ });
2256
+ batch = (_b = (_a = resp.UnprocessedItems) == null ? void 0 : _a[this.TABLE_NAME]) != null ? _b : [];
2257
+ if (batch.length && attempt === 8) {
2258
+ throw new Error(
2259
+ `Search index: ${batch.length} writes still unprocessed for ${entity.entityType}#${entityId}`
2260
+ );
2261
+ }
2262
+ }
2263
+ }
2264
+ });
2265
+ }
2266
+ /** The words an entity currently has rows for, read from the GSI. */
2267
+ existingWords(entityType, entityId) {
2268
+ return __async(this, null, function* () {
2269
+ var _a, _b;
2270
+ const words = [];
2271
+ let lastKey;
2272
+ do {
2273
+ const resp = yield this.dynamodbClient.query({
2274
+ TableName: this.TABLE_NAME,
2275
+ IndexName: ENTITY_REPLICATION_INDEX,
2276
+ KeyConditionExpression: "#R1PK = :R1PK and begins_with(#R1SK, :R1SK)",
2277
+ ExpressionAttributeNames: { "#R1PK": "R1PK", "#R1SK": "R1SK" },
2278
+ ExpressionAttributeValues: {
2279
+ ":R1PK": { S: `${entityType}#${entityId}` },
2280
+ ":R1SK": { S: "SEARCH#" }
2281
+ },
2282
+ ExclusiveStartKey: lastKey
2283
+ });
2284
+ for (const item of (_a = resp.Items) != null ? _a : []) {
2285
+ const r1sk = (_b = item.R1SK) == null ? void 0 : _b.S;
2286
+ if (r1sk) words.push(r1sk.slice("SEARCH#".length));
2287
+ }
2288
+ lastKey = resp.LastEvaluatedKey;
2289
+ } while (lastKey);
2290
+ return words;
2291
+ });
2292
+ }
2293
+ getIndexState(entityType) {
2294
+ return __async(this, null, function* () {
2295
+ var _a, _b;
2296
+ const resp = yield this.dynamodbClient.getItem({
2297
+ TableName: this.TABLE_NAME,
2298
+ Key: { PK: { S: INDEX_STATE_PK }, SK: { S: `${entityType}` } }
2299
+ });
2300
+ if (!resp.Item) return void 0;
2301
+ return {
2302
+ state: (_a = resp.Item.state) == null ? void 0 : _a.S,
2303
+ configHash: (_b = resp.Item.configHash) == null ? void 0 : _b.S
2304
+ };
2305
+ });
2306
+ }
2307
+ markIndexBuilding(entityType, configHash) {
2308
+ return __async(this, null, function* () {
2309
+ yield this.dynamodbClient.putItem({
2310
+ TableName: this.TABLE_NAME,
2311
+ Item: {
2312
+ PK: { S: INDEX_STATE_PK },
2313
+ SK: { S: `${entityType}` },
2314
+ state: { S: "building" },
2315
+ configHash: { S: configHash },
2316
+ updatedAt: { S: (/* @__PURE__ */ new Date()).toISOString() }
2317
+ }
2318
+ });
2319
+ });
2320
+ }
2321
+ /**
2322
+ * Marks the index ready, unless a newer reindex has taken over since: its
2323
+ * config hash replaces this one when it starts.
2324
+ */
2325
+ markIndexReady(entityType, configHash) {
2326
+ return __async(this, null, function* () {
2327
+ try {
2328
+ yield this.dynamodbClient.updateItem({
2329
+ TableName: this.TABLE_NAME,
2330
+ Key: { PK: { S: INDEX_STATE_PK }, SK: { S: `${entityType}` } },
2331
+ UpdateExpression: "SET #state = :ready, #updatedAt = :now",
2332
+ ConditionExpression: "#configHash = :configHash",
2333
+ ExpressionAttributeNames: {
2334
+ "#state": "state",
2335
+ "#updatedAt": "updatedAt",
2336
+ "#configHash": "configHash"
2337
+ },
2338
+ ExpressionAttributeValues: {
2339
+ ":ready": { S: "ready" },
2340
+ ":now": { S: (/* @__PURE__ */ new Date()).toISOString() },
2341
+ ":configHash": { S: configHash }
2342
+ }
2343
+ });
2344
+ return true;
2345
+ } catch (err) {
2346
+ if (err instanceof ConditionalCheckFailedException2) return false;
2347
+ throw err;
2348
+ }
2349
+ });
2350
+ }
2351
+ /** Whether the index was fully built for the current config. */
2352
+ isIndexReady(entityType, config) {
2353
+ return __async(this, null, function* () {
2354
+ if (this.readyTypes.has(`${entityType}`)) return true;
2355
+ const state = yield this.getIndexState(entityType);
2356
+ const ready = (state == null ? void 0 : state.state) === "ready" && state.configHash === searchConfigHash(config);
2357
+ if (ready) this.readyTypes.add(`${entityType}`);
2358
+ return ready;
2359
+ });
2360
+ }
2361
+ /** Deletes the marker, so the next reindex rebuilds the type in full. */
2362
+ clearIndexState(entityType) {
2363
+ return __async(this, null, function* () {
2364
+ yield this.dynamodbClient.deleteItem({
2365
+ TableName: this.TABLE_NAME,
2366
+ Key: { PK: { S: INDEX_STATE_PK }, SK: { S: `${entityType}` } }
2367
+ });
2368
+ });
2369
+ }
2370
+ /**
2371
+ * Brings one entity's rows in line with its current data and config. It
2372
+ * runs alongside the stream, which may write a newer version of the same
2373
+ * rows, so each write only goes through over an older copy.
2374
+ */
2375
+ reindexEntity(entityType, entityId, config) {
2376
+ return __async(this, null, function* () {
2377
+ const resp = yield this.dynamodbClient.getItem({
2378
+ TableName: this.TABLE_NAME,
2379
+ Key: new Entity(entityType, entityId).keys(),
2380
+ ConsistentRead: true
2381
+ });
2382
+ if (!resp.Item) return;
2383
+ const entity = Entity.fromItem(resp.Item);
2384
+ const existing = yield this.existingWords(entityType, entityId);
2385
+ const words = indexedWords(entity.data, config);
2386
+ const notNewer = {
2387
+ ExpressionAttributeNames: { "#updatedAt": "updatedAt" },
2388
+ ExpressionAttributeValues: {
2389
+ ":updatedAt": { S: entity.updatedAt }
2390
+ }
2391
+ };
2392
+ const ignoreNewer = (err) => {
2393
+ if (!(err instanceof ConditionalCheckFailedException2)) throw err;
2394
+ };
2395
+ yield Promise.all([
2396
+ ...words.filter((word) => !existing.includes(word)).map(
2397
+ (word) => this.dynamodbClient.putItem(__spreadValues({
2398
+ TableName: this.TABLE_NAME,
2399
+ Item: this.searchRow(entity, word),
2400
+ ConditionExpression: "attribute_not_exists(PK) OR #updatedAt < :updatedAt"
2401
+ }, notNewer)).catch(ignoreNewer)
2402
+ ),
2403
+ ...existing.filter((word) => !words.includes(word)).map(
2404
+ (word) => this.dynamodbClient.deleteItem(__spreadValues({
2405
+ TableName: this.TABLE_NAME,
2406
+ Key: this.rowKeys(entityType, entityId, word),
2407
+ ConditionExpression: "#updatedAt <= :updatedAt"
2408
+ }, notNewer)).catch(ignoreNewer)
2409
+ )
2410
+ ]);
2411
+ });
2412
+ }
2413
+ lookUp(entityType, anchor) {
2414
+ return __async(this, null, function* () {
2415
+ var _a;
2416
+ const items = [];
2417
+ let lastKey;
2418
+ do {
2419
+ const resp = yield this.dynamodbClient.query({
2420
+ TableName: this.TABLE_NAME,
2421
+ KeyConditionExpression: "#PK = :PK and begins_with(#SK, :SK)",
2422
+ ExpressionAttributeNames: { "#PK": "PK", "#SK": "SK" },
2423
+ ExpressionAttributeValues: {
2424
+ ":PK": { S: `SEARCH#${entityType}` },
2425
+ ":SK": { S: anchor }
2426
+ },
2427
+ ExclusiveStartKey: lastKey
2428
+ });
2429
+ items.push(...(_a = resp.Items) != null ? _a : []);
2430
+ lastKey = resp.LastEvaluatedKey;
2431
+ } while (lastKey);
2432
+ return items.map(Entity.fromItem);
2433
+ });
2434
+ }
2435
+ /**
2436
+ * Every entity matching `query`, newest first. Reads the rows of the
2437
+ * query's longest word, or scans every entity while the index is still
2438
+ * being built for the current config. Both give the same matches.
2439
+ *
2440
+ * There's no `totalCount`: counting every entity of the type would take
2441
+ * the scan the index avoids. `filteredCount` is the number of matches.
2442
+ */
2443
+ searchEntities(entityType, query) {
2444
+ return __async(this, null, function* () {
2445
+ const config = this.searchConfig(entityType);
2446
+ const plan = config && planSearch(query, config.ignoreWords);
2447
+ if (!config || !(plan == null ? void 0 : plan.anchor)) {
2448
+ return { items: [], filteredCount: 0 };
2449
+ }
2450
+ const candidates = (yield this.isIndexReady(entityType, config)) ? yield this.lookUp(entityType, plan.anchor) : (yield this.entityRepository.listEntities({ entityType })).items;
2451
+ const seen = /* @__PURE__ */ new Set();
2452
+ const items = [];
2453
+ for (const entity of candidates) {
2454
+ const entityId = entity.entityId;
2455
+ if (seen.has(entityId)) continue;
2456
+ seen.add(entityId);
2457
+ if (matchesSearch(entity.data, plan, config)) {
2458
+ items.push(entity);
2459
+ }
2460
+ }
2461
+ items.sort(
2462
+ (a, b) => a.entityId < b.entityId ? 1 : -1
2463
+ );
2464
+ return { items, filteredCount: items.length };
2465
+ });
2466
+ }
2467
+ };
2468
+
2172
2469
  // data/Tag.ts
2173
2470
  import { marshall as marshall4, unmarshall as unmarshall3 } from "@aws-sdk/util-dynamodb";
2174
2471
  var TaggedEntity = class _TaggedEntity extends Entity {
@@ -8077,7 +8374,7 @@ var MutualService = class {
8077
8374
  options
8078
8375
  }
8079
8376
  };
8080
- console.log("[MONORISE_DEBUG] createMutual service start:", {
8377
+ debugLog("[MONORISE_DEBUG] createMutual service start:", {
8081
8378
  byEntityType,
8082
8379
  byEntityId,
8083
8380
  entityType,
@@ -8087,28 +8384,28 @@ var MutualService = class {
8087
8384
  });
8088
8385
  const mutualDataSchema = this.getMutualDataSchema(byEntityType, entityType);
8089
8386
  const schema = (_c = asEntityStorageSchema != null ? asEntityStorageSchema : mutualDataSchema) != null ? _c : external_exports.record(external_exports.string(), external_exports.any());
8090
- console.log("[MONORISE_DEBUG] createMutual schema resolved");
8387
+ debugLog("[MONORISE_DEBUG] createMutual schema resolved");
8091
8388
  const parsedMutualPayload = schema.parse(mutualPayload);
8092
- console.log("[MONORISE_DEBUG] createMutual payload parsed:", parsedMutualPayload);
8093
- console.log("[MONORISE_DEBUG] createMutual fetching entities...");
8389
+ debugLog("[MONORISE_DEBUG] createMutual payload parsed:", parsedMutualPayload);
8390
+ debugLog("[MONORISE_DEBUG] createMutual fetching entities...");
8094
8391
  const [{ data: byEntityData }, { data: entityData }] = yield Promise.all([
8095
8392
  this.entityRepository.getEntity(byEntityType, byEntityId),
8096
8393
  this.entityRepository.getEntity(entityType, entityId)
8097
8394
  ]);
8098
- console.log("[MONORISE_DEBUG] createMutual entities fetched:", {
8395
+ debugLog("[MONORISE_DEBUG] createMutual entities fetched:", {
8099
8396
  hasByEntityData: !!byEntityData,
8100
8397
  hasEntityData: !!entityData
8101
8398
  });
8102
8399
  errorContext.byEntityData = byEntityData;
8103
8400
  errorContext.entityData = entityData;
8104
- console.log("[MONORISE_DEBUG] createMutual checking mutual exist...");
8401
+ debugLog("[MONORISE_DEBUG] createMutual checking mutual exist...");
8105
8402
  yield this.mutualRepository.checkMutualExist(
8106
8403
  byEntityType,
8107
8404
  byEntityId,
8108
8405
  entityType,
8109
8406
  entityId
8110
8407
  );
8111
- console.log("[MONORISE_DEBUG] createMutual mutual does not exist (ok)");
8408
+ debugLog("[MONORISE_DEBUG] createMutual mutual does not exist (ok)");
8112
8409
  const currentDatetime = createAndUpdateDatetime || /* @__PURE__ */ new Date();
8113
8410
  const mutual = new Mutual(
8114
8411
  byEntityType,
@@ -8123,7 +8420,7 @@ var MutualService = class {
8123
8420
  currentDatetime,
8124
8421
  currentDatetime
8125
8422
  );
8126
- console.log("[MONORISE_DEBUG] createMutual mutual object created:", {
8423
+ debugLog("[MONORISE_DEBUG] createMutual mutual object created:", {
8127
8424
  mutualId: mutual.mutualId
8128
8425
  });
8129
8426
  const mutualTransactions = skipMutualCreation ? [] : this.mutualRepository.createMutualTransactItems(mutual, {
@@ -8160,13 +8457,13 @@ var MutualService = class {
8160
8457
  mutualPayload
8161
8458
  } = params;
8162
8459
  const { mutual, entity, transactItems, parsedMutualPayload } = yield this.prepareCreateMutual(params);
8163
- console.log("[MONORISE_DEBUG] createMutual executing transaction:", {
8460
+ debugLog("[MONORISE_DEBUG] createMutual executing transaction:", {
8164
8461
  transactItemCount: transactItems.length
8165
8462
  });
8166
8463
  yield this.ddbUtils.executeTransactWrite({
8167
8464
  TransactItems: transactItems
8168
8465
  });
8169
- console.log("[MONORISE_DEBUG] createMutual transaction succeeded");
8466
+ debugLog("[MONORISE_DEBUG] createMutual transaction succeeded");
8170
8467
  if (entity) {
8171
8468
  yield this.entityServiceLifeCycle.afterCreateEntityHook(
8172
8469
  entity,
@@ -8188,7 +8485,7 @@ var MutualService = class {
8188
8485
  })
8189
8486
  ];
8190
8487
  yield Promise.all(eventPromises);
8191
- console.log("[MONORISE_DEBUG] createMutual service complete");
8488
+ debugLog("[MONORISE_DEBUG] createMutual service complete");
8192
8489
  return { mutual, eventPayload };
8193
8490
  });
8194
8491
  /**
@@ -8255,7 +8552,7 @@ var MutualService = class {
8255
8552
  mutualPayload,
8256
8553
  options
8257
8554
  }) {
8258
- console.log("[MONORISE_DEBUG] updateMutual service start:", {
8555
+ debugLog("[MONORISE_DEBUG] updateMutual service start:", {
8259
8556
  byEntityType,
8260
8557
  byEntityId,
8261
8558
  entityType,
@@ -8264,10 +8561,10 @@ var MutualService = class {
8264
8561
  options
8265
8562
  });
8266
8563
  const schema = this.getMutualUpdateSchema(byEntityType, entityType);
8267
- console.log("[MONORISE_DEBUG] updateMutual schema resolved");
8564
+ debugLog("[MONORISE_DEBUG] updateMutual schema resolved");
8268
8565
  const parsedMutualPayload = schema.parse(mutualPayload);
8269
- console.log("[MONORISE_DEBUG] updateMutual payload parsed:", parsedMutualPayload);
8270
- console.log("[MONORISE_DEBUG] updateMutual calling repository...");
8566
+ debugLog("[MONORISE_DEBUG] updateMutual payload parsed:", parsedMutualPayload);
8567
+ debugLog("[MONORISE_DEBUG] updateMutual calling repository...");
8271
8568
  const mutual = yield this.mutualRepository.updateMutual(
8272
8569
  byEntityType,
8273
8570
  byEntityId,
@@ -8276,7 +8573,7 @@ var MutualService = class {
8276
8573
  { mutualData: parsedMutualPayload },
8277
8574
  options
8278
8575
  );
8279
- console.log("[MONORISE_DEBUG] updateMutual repository result:", {
8576
+ debugLog("[MONORISE_DEBUG] updateMutual repository result:", {
8280
8577
  hasMutual: !!mutual,
8281
8578
  mutualId: mutual == null ? void 0 : mutual.mutualId
8282
8579
  });
@@ -8290,7 +8587,7 @@ var MutualService = class {
8290
8587
  parsedMutualPayload
8291
8588
  }
8292
8589
  });
8293
- console.log("[MONORISE_DEBUG] updateMutual service complete");
8590
+ debugLog("[MONORISE_DEBUG] updateMutual service complete");
8294
8591
  return mutual;
8295
8592
  });
8296
8593
  /**
@@ -8849,8 +9146,148 @@ var handler8 = (container) => (ev) => __async(null, null, function* () {
8849
9146
  });
8850
9147
 
8851
9148
  // processors/replication-processor.ts
8852
- import { ConditionalCheckFailedException as ConditionalCheckFailedException2 } from "@aws-sdk/client-dynamodb";
8853
- var handler9 = (container) => (event) => __async(null, null, function* () {
9149
+ import { ConditionalCheckFailedException as ConditionalCheckFailedException3 } from "@aws-sdk/client-dynamodb";
9150
+
9151
+ // processors/search-index-processor.ts
9152
+ import { InvokeCommand as InvokeCommand2, LambdaClient as LambdaClient2 } from "@aws-sdk/client-lambda";
9153
+ import { unmarshall as unmarshall6 } from "@aws-sdk/util-dynamodb";
9154
+ import {
9155
+ indexedWords as indexedWords2,
9156
+ searchConfigHash as searchConfigHash2
9157
+ } from "../base/index.js";
9158
+ function syncSearchIndex(container, record) {
9159
+ return __async(this, null, function* () {
9160
+ var _a, _b, _c, _d, _e, _f;
9161
+ if (record.eventName !== "INSERT" && record.eventName !== "MODIFY") return;
9162
+ const newImage = (_a = record.dynamodb) == null ? void 0 : _a.NewImage;
9163
+ 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#"))) {
9164
+ return;
9165
+ }
9166
+ const entity = Entity.fromItem(newImage);
9167
+ const config = container.searchRepository.searchConfig(entity.entityType);
9168
+ if (!config) return;
9169
+ const oldImage = (_f = record.dynamodb) == null ? void 0 : _f.OldImage;
9170
+ const previous = oldImage ? indexedWords2(unmarshall6(oldImage).data, config) : [];
9171
+ const words = indexedWords2(entity.data, config);
9172
+ yield container.searchRepository.writeRows(
9173
+ entity,
9174
+ words.filter((word) => !previous.includes(word)),
9175
+ previous.filter((word) => !words.includes(word))
9176
+ );
9177
+ });
9178
+ }
9179
+ var HANDOVER_MS = 2 * 60 * 1e3;
9180
+ var PAGE_SIZE = 100;
9181
+ var CONCURRENCY = 25;
9182
+ var MAX_FAILURES = 3;
9183
+ var RETRY_WAIT_MS = 5e3;
9184
+ var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9185
+ var lambdaClient;
9186
+ var invokeSelf = (event) => __async(null, null, function* () {
9187
+ lambdaClient != null ? lambdaClient : lambdaClient = new LambdaClient2();
9188
+ yield lambdaClient.send(
9189
+ new InvokeCommand2({
9190
+ FunctionName: process.env.AWS_LAMBDA_FUNCTION_NAME,
9191
+ InvocationType: "Event",
9192
+ Payload: Buffer.from(JSON.stringify(event))
9193
+ })
9194
+ );
9195
+ });
9196
+ var handler9 = (container, invoke = invokeSelf, pause = wait) => (event, context) => __async(null, null, function* () {
9197
+ var _a;
9198
+ const { searchRepository, entityRepository } = container;
9199
+ if (event.action === "start") {
9200
+ const indexed = searchRepository.indexedEntityTypes();
9201
+ const entityTypes = Object.keys(
9202
+ container.config.EntityConfig
9203
+ );
9204
+ for (const entityType2 of entityTypes) {
9205
+ if (!indexed.includes(entityType2)) {
9206
+ yield searchRepository.clearIndexState(entityType2);
9207
+ }
9208
+ }
9209
+ for (const entityType2 of indexed) {
9210
+ const config2 = searchRepository.searchConfig(entityType2);
9211
+ if (!config2) continue;
9212
+ const configHash2 = searchConfigHash2(config2);
9213
+ const state = yield searchRepository.getIndexState(entityType2);
9214
+ if (!event.force && (state == null ? void 0 : state.state) === "ready" && state.configHash === configHash2) {
9215
+ continue;
9216
+ }
9217
+ yield searchRepository.markIndexBuilding(entityType2, configHash2);
9218
+ yield invoke({ action: "reindex", entityType: entityType2, configHash: configHash2 });
9219
+ }
9220
+ return;
9221
+ }
9222
+ const { entityType, configHash } = event;
9223
+ const config = searchRepository.searchConfig(entityType);
9224
+ if (!config || searchConfigHash2(config) !== configHash) {
9225
+ console.log("[SEARCH_REINDEX] superseded, stopping", { entityType });
9226
+ return;
9227
+ }
9228
+ let lastKey = event.lastKey;
9229
+ let failures = (_a = event.failures) != null ? _a : 0;
9230
+ do {
9231
+ try {
9232
+ const page = yield entityRepository.listEntities({
9233
+ entityType,
9234
+ limit: PAGE_SIZE,
9235
+ options: { lastKey }
9236
+ });
9237
+ for (let i = 0; i < page.items.length; i += CONCURRENCY) {
9238
+ yield Promise.all(
9239
+ page.items.slice(i, i + CONCURRENCY).map(
9240
+ (entity) => searchRepository.reindexEntity(
9241
+ entityType,
9242
+ entity.entityId,
9243
+ config
9244
+ )
9245
+ )
9246
+ );
9247
+ }
9248
+ lastKey = page.lastKey;
9249
+ failures = 0;
9250
+ } catch (err) {
9251
+ failures++;
9252
+ if (failures >= MAX_FAILURES) {
9253
+ console.error(
9254
+ "[SEARCH_REINDEX] giving up: search scans until rebuilt",
9255
+ {
9256
+ entityType,
9257
+ lastKey,
9258
+ failures,
9259
+ err
9260
+ }
9261
+ );
9262
+ throw err;
9263
+ }
9264
+ console.warn("[SEARCH_REINDEX] page failed, retrying", {
9265
+ entityType,
9266
+ lastKey,
9267
+ failures,
9268
+ err
9269
+ });
9270
+ yield pause(RETRY_WAIT_MS * 2 ** (failures - 1));
9271
+ yield invoke({
9272
+ action: "reindex",
9273
+ entityType,
9274
+ configHash,
9275
+ lastKey,
9276
+ failures
9277
+ });
9278
+ return;
9279
+ }
9280
+ if (lastKey && context && context.getRemainingTimeInMillis() < HANDOVER_MS) {
9281
+ yield invoke({ action: "reindex", entityType, configHash, lastKey });
9282
+ return;
9283
+ }
9284
+ } while (lastKey);
9285
+ const ready = yield searchRepository.markIndexReady(entityType, configHash);
9286
+ console.log("[SEARCH_REINDEX] done", { entityType, ready });
9287
+ });
9288
+
9289
+ // processors/replication-processor.ts
9290
+ var handler10 = (container) => (event) => __async(null, null, function* () {
8854
9291
  var _a, _b, _c, _d, _e, _f, _g;
8855
9292
  const TableName = process.env.DDB_TABLE || container.coreTable;
8856
9293
  const batchItemFailures = [];
@@ -8859,6 +9296,7 @@ var handler9 = (container) => (event) => __async(null, null, function* () {
8859
9296
  const errorContext = {};
8860
9297
  errorContext.record = record;
8861
9298
  try {
9299
+ yield syncSearchIndex(container, record);
8862
9300
  if (record.eventName === "MODIFY") {
8863
9301
  const modifiedItem = (_a = record.dynamodb) == null ? void 0 : _a.NewImage;
8864
9302
  if (!modifiedItem) {
@@ -8949,7 +9387,7 @@ var handler9 = (container) => (event) => __async(null, null, function* () {
8949
9387
  const results = yield Promise.allSettled(updatePromises);
8950
9388
  errorContext.results = results;
8951
9389
  if (results.some(
8952
- (result) => result.status === "rejected" && !(result.reason instanceof ConditionalCheckFailedException2)
9390
+ (result) => result.status === "rejected" && !(result.reason instanceof ConditionalCheckFailedException3)
8953
9391
  )) {
8954
9392
  throw new StandardError(
8955
9393
  StandardErrorCode.REPLICATION_ERROR,
@@ -9020,7 +9458,7 @@ var handler9 = (container) => (event) => __async(null, null, function* () {
9020
9458
  );
9021
9459
  errorContext.deleteResults = deleteResults;
9022
9460
  if (deleteResults.some(
9023
- (result) => result.status === "rejected" && !(result.reason instanceof ConditionalCheckFailedException2)
9461
+ (result) => result.status === "rejected" && !(result.reason instanceof ConditionalCheckFailedException3)
9024
9462
  )) {
9025
9463
  throw new StandardError(
9026
9464
  StandardErrorCode.REPLICATION_ERROR,
@@ -9114,7 +9552,7 @@ function batchUpdateTags(_0) {
9114
9552
  yield Promise.all(addPromises);
9115
9553
  });
9116
9554
  }
9117
- var handler10 = (container) => (ev) => __async(null, null, function* () {
9555
+ var handler11 = (container) => (ev) => __async(null, null, function* () {
9118
9556
  var _a;
9119
9557
  const batchItemFailures = [];
9120
9558
  for (const record of ev.Records) {
@@ -9179,7 +9617,7 @@ import {
9179
9617
  ApiGatewayManagementApiClient,
9180
9618
  PostToConnectionCommand
9181
9619
  } from "@aws-sdk/client-apigatewaymanagementapi";
9182
- import { unmarshall as unmarshall6 } from "@aws-sdk/util-dynamodb";
9620
+ import { unmarshall as unmarshall7 } from "@aws-sdk/util-dynamodb";
9183
9621
  import { ulid as ulid5 } from "ulid";
9184
9622
  var SUB_ENTITY_TYPE = "SUB#ENTITY#";
9185
9623
  var SUB_MUTUAL_TYPE = "SUB#MUTUAL#";
@@ -9481,7 +9919,7 @@ var broadcast = (container) => (event) => __async(null, null, function* () {
9481
9919
  byEntityId,
9482
9920
  mutualEntityType,
9483
9921
  entityId: skParts[1],
9484
- data: isRemove ? void 0 : unmarshall6(image)
9922
+ data: isRemove ? void 0 : unmarshall7(image)
9485
9923
  }
9486
9924
  };
9487
9925
  yield broadcastToSubscribers(
@@ -9505,7 +9943,7 @@ var broadcast = (container) => (event) => __async(null, null, function* () {
9505
9943
  payload: {
9506
9944
  entityType,
9507
9945
  entityId,
9508
- data: isRemove ? void 0 : unmarshall6(image)
9946
+ data: isRemove ? void 0 : unmarshall7(image)
9509
9947
  }
9510
9948
  };
9511
9949
  yield broadcastToSubscribers(
@@ -9531,7 +9969,7 @@ var broadcast = (container) => (event) => __async(null, null, function* () {
9531
9969
  byEntityId: entityId,
9532
9970
  mutualEntityType: sk.split("#")[0],
9533
9971
  entityId: sk.split("#")[1],
9534
- data: isRemove ? void 0 : unmarshall6(image)
9972
+ data: isRemove ? void 0 : unmarshall7(image)
9535
9973
  }
9536
9974
  } : {
9537
9975
  type: isInsert ? "entity.created" : isModify ? "entity.updated" : "entity.deleted",
@@ -9539,7 +9977,7 @@ var broadcast = (container) => (event) => __async(null, null, function* () {
9539
9977
  payload: {
9540
9978
  entityType,
9541
9979
  entityId,
9542
- data: isRemove ? void 0 : unmarshall6(image)
9980
+ data: isRemove ? void 0 : unmarshall7(image)
9543
9981
  }
9544
9982
  }
9545
9983
  );
@@ -9749,10 +10187,8 @@ var CreateEntityController = class {
9749
10187
  }
9750
10188
  console.log("===create-entity error:", {
9751
10189
  err,
9752
- errorContext: JSON.stringify({
9753
- body,
9754
- headers: c.req.header()
9755
- })
10190
+ // Not the headers: they include the caller's x-api-key.
10191
+ errorContext: JSON.stringify({ body })
9756
10192
  });
9757
10193
  throw err;
9758
10194
  }
@@ -9853,8 +10289,9 @@ var querySchema = external_exports.object({
9853
10289
  end: external_exports.string().optional()
9854
10290
  });
9855
10291
  var ListEntitiesController = class {
9856
- constructor(entityRepository) {
10292
+ constructor(entityRepository, searchRepository) {
9857
10293
  this.entityRepository = entityRepository;
10294
+ this.searchRepository = searchRepository;
9858
10295
  this.controller = createMiddleware9((c) => __async(this, null, function* () {
9859
10296
  const errorContext = {};
9860
10297
  try {
@@ -9865,10 +10302,7 @@ var ListEntitiesController = class {
9865
10302
  const { entityType } = params;
9866
10303
  const { lastKey, query, limit, start, end } = querySchema.parse(queries2);
9867
10304
  if (query) {
9868
- const results2 = yield this.entityRepository.queryEntities(
9869
- entityType,
9870
- query
9871
- );
10305
+ const results2 = this.searchRepository.searchConfig(entityType) ? yield this.searchRepository.searchEntities(entityType, query) : yield this.entityRepository.queryEntities(entityType, query);
9872
10306
  return c.json({
9873
10307
  data: results2.items.map((item) => item.toJSON()),
9874
10308
  totalCount: results2.totalCount,
@@ -11671,6 +12105,16 @@ var DependencyContainer = class {
11671
12105
  this.config.EmailAuthEnabledEntities
11672
12106
  );
11673
12107
  }
12108
+ get searchRepository() {
12109
+ return this.createCachedInstance(
12110
+ SearchRepository,
12111
+ this.config.EntityConfig,
12112
+ this.coreTable,
12113
+ this.dynamodbClient,
12114
+ this.entityRepository,
12115
+ this.config.SearchDefaults
12116
+ );
12117
+ }
11674
12118
  get mutualRepository() {
11675
12119
  return this.createCachedInstance(
11676
12120
  MutualRepository,
@@ -11737,7 +12181,8 @@ var DependencyContainer = class {
11737
12181
  get listEntitiesController() {
11738
12182
  return this.createCachedInstance(
11739
12183
  ListEntitiesController,
11740
- this.entityRepository
12184
+ this.entityRepository,
12185
+ this.searchRepository
11741
12186
  );
11742
12187
  }
11743
12188
  get createEntityController() {
@@ -11896,12 +12341,13 @@ var CoreFactory = class {
11896
12341
  this.dependencyContainer = dependencyContainer;
11897
12342
  this.setupCommonRoutes = setupCommonRoutes(dependencyContainer);
11898
12343
  this.mutualProcessor = handler7(dependencyContainer);
11899
- this.replicationProcessor = handler9(dependencyContainer);
12344
+ this.replicationProcessor = handler10(dependencyContainer);
12345
+ this.searchReindexProcessor = handler9(dependencyContainer);
11900
12346
  this.createEntityProcessor = handler(dependencyContainer);
11901
12347
  this.analyticsProcessor = handler2(this.config.EntityConfig);
11902
12348
  this.analyticsBackfillProcessor = handler3(this.config.EntityConfig);
11903
12349
  this.prejoinProcessor = handler8(dependencyContainer);
11904
- this.tagProcessor = handler10(dependencyContainer);
12350
+ this.tagProcessor = handler11(dependencyContainer);
11905
12351
  this.appHandler = appHandler(dependencyContainer);
11906
12352
  this.wsConnect = connect(dependencyContainer);
11907
12353
  this.wsDisconnect = disconnect(dependencyContainer);
@@ -11919,6 +12365,7 @@ export {
11919
12365
  MutualRepository,
11920
12366
  MutualService,
11921
12367
  PROJECTION_EXPRESSION,
12368
+ SearchRepository,
11922
12369
  StandardError,
11923
12370
  StandardErrorCode,
11924
12371
  TagRepository,
@@ -11935,11 +12382,12 @@ export {
11935
12382
  index_default as default,
11936
12383
  handler7 as mutualProcessor,
11937
12384
  handler8 as prejoinProcessor,
11938
- handler9 as replicationProcessor,
12385
+ handler10 as replicationProcessor,
11939
12386
  requires,
12387
+ handler9 as searchReindexProcessor,
11940
12388
  setupCommonRoutes,
11941
12389
  startBackfill as startAnalyticsBackfill,
11942
- handler10 as tagProcessor,
12390
+ handler11 as tagProcessor,
11943
12391
  transactional,
11944
12392
  broadcast as wsBroadcast,
11945
12393
  connect as wsConnect,