monorise 1.11.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/base/index.d.ts +4 -4
  2. package/dist/base/index.js.map +1 -1
  3. package/dist/cli/cli.js +6 -0
  4. package/dist/cli/cli.js.map +1 -1
  5. package/dist/core/chunk-W6HUNJ6S.js +79 -0
  6. package/dist/core/chunk-W6HUNJ6S.js.map +1 -0
  7. package/dist/core/index.d.ts +253 -24
  8. package/dist/core/index.js +1304 -182
  9. package/dist/core/index.js.map +1 -1
  10. package/dist/core/service.config-U77V7WIB.js +13 -0
  11. package/dist/core/service.config-U77V7WIB.js.map +1 -0
  12. package/dist/index.d.ts +15 -0
  13. package/dist/proxy/index.d.ts +35 -0
  14. package/dist/proxy/index.js +78 -0
  15. package/dist/proxy/index.js.map +1 -0
  16. package/dist/react/actions/core.action.d.ts.map +1 -1
  17. package/dist/react/actions/websocket.action.d.ts +71 -0
  18. package/dist/react/actions/websocket.action.d.ts.map +1 -0
  19. package/dist/react/chunk-CQQYJW4K.js +444 -0
  20. package/dist/react/chunk-CQQYJW4K.js.map +1 -0
  21. package/dist/react/helpers/transactional.d.ts +32 -1
  22. package/dist/react/helpers/transactional.d.ts.map +1 -1
  23. package/dist/react/index.d.ts +30 -2
  24. package/dist/react/index.d.ts.map +1 -1
  25. package/dist/react/index.js +714 -43
  26. package/dist/react/index.js.map +1 -1
  27. package/dist/react/websocket/WebSocketManager.d.ts +72 -0
  28. package/dist/react/websocket/WebSocketManager.d.ts.map +1 -0
  29. package/dist/react/websocket/index.d.ts +3 -0
  30. package/dist/react/websocket/index.d.ts.map +1 -0
  31. package/dist/react/websocket/optimistic.d.ts +51 -0
  32. package/dist/react/websocket/optimistic.d.ts.map +1 -0
  33. package/dist/react/websocket-34W2HQLH.js +9 -0
  34. package/dist/react/websocket-34W2HQLH.js.map +1 -0
  35. package/dist/sst/components/monorise-core.d.ts +10 -0
  36. package/dist/sst/components/monorise-core.d.ts.map +1 -1
  37. package/dist/sst/components/single-table.d.ts.map +1 -1
  38. package/dist/sst/index.js +86 -14
  39. package/dist/sst/index.js.map +1 -1
  40. package/package.json +11 -1
@@ -1,60 +1,15 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
8
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
- var __spreadValues = (a, b) => {
10
- for (var prop in b || (b = {}))
11
- if (__hasOwnProp.call(b, prop))
12
- __defNormalProp(a, prop, b[prop]);
13
- if (__getOwnPropSymbols)
14
- for (var prop of __getOwnPropSymbols(b)) {
15
- if (__propIsEnum.call(b, prop))
16
- __defNormalProp(a, prop, b[prop]);
17
- }
18
- return a;
19
- };
20
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
21
- var __objRest = (source, exclude) => {
22
- var target = {};
23
- for (var prop in source)
24
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
25
- target[prop] = source[prop];
26
- if (source != null && __getOwnPropSymbols)
27
- for (var prop of __getOwnPropSymbols(source)) {
28
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
29
- target[prop] = source[prop];
30
- }
31
- return target;
32
- };
33
- var __export = (target, all) => {
34
- for (var name in all)
35
- __defProp(target, name, { get: all[name], enumerable: true });
36
- };
37
- var __async = (__this, __arguments, generator) => {
38
- return new Promise((resolve, reject) => {
39
- var fulfilled = (value) => {
40
- try {
41
- step(generator.next(value));
42
- } catch (e) {
43
- reject(e);
44
- }
45
- };
46
- var rejected = (value) => {
47
- try {
48
- step(generator.throw(value));
49
- } catch (e) {
50
- reject(e);
51
- }
52
- };
53
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
54
- step((generator = generator.apply(__this, __arguments)).next());
55
- });
56
- };
57
- var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")]) ? it.call(obj) : (obj = obj[__knownSymbol("iterator")](), it = {}, method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((yes, no, done) => (arg = fn.call(obj, arg), done = arg.done, Promise.resolve(arg.value).then((value) => yes({ value, done }), no)))), method("next"), method("return"), it);
1
+ import {
2
+ CORE_EVENT_BUS,
3
+ CORE_TABLE,
4
+ ENTITY_REPLICATION_INDEX,
5
+ MUTUAL_REPLICATION_INDEX,
6
+ __async,
7
+ __export,
8
+ __forAwait,
9
+ __objRest,
10
+ __spreadProps,
11
+ __spreadValues
12
+ } from "./chunk-W6HUNJ6S.js";
58
13
 
59
14
  // controllers/setupRoutes.ts
60
15
  import { Hono } from "hono";
@@ -143,6 +98,10 @@ var setupCommonRoutes = (container) => {
143
98
  );
144
99
  app.get("/tag/:entityType/:tagName", container.listTagsController.controller);
145
100
  app.post("/transaction", container.executeTransactionController.controller);
101
+ app.post(
102
+ "/ws/ticket/:entityType/:entityId",
103
+ container.createTicketController.controller
104
+ );
146
105
  return app;
147
106
  };
148
107
 
@@ -1417,6 +1376,79 @@ var MutualRepository = class extends Repository {
1417
1376
  return mutual;
1418
1377
  });
1419
1378
  }
1379
+ /**
1380
+ * @description Resolves the live mutual and builds the TransactWriteItems that update its
1381
+ * `mutualData` on all three records, without writing them. `updateMutual` writes them on their
1382
+ * own; `TransactionService` folds them into a larger transaction. Throws `MUTUAL_IS_UNDEFINED`
1383
+ * when there is no live mutual for the pair.
1384
+ */
1385
+ prepareUpdateMutual(byEntityType, byEntityId, entityType, entityId, toUpdate, opts) {
1386
+ return __async(this, null, function* () {
1387
+ console.log("[MONORISE_DEBUG] updateMutual fetching mutual...");
1388
+ const mutual = yield this.getMutual(
1389
+ byEntityType,
1390
+ byEntityId,
1391
+ entityType,
1392
+ entityId,
1393
+ { ProjectionExpression: PROJECTION_EXPRESSION.NO_DATA }
1394
+ );
1395
+ console.log("[MONORISE_DEBUG] updateMutual mutual found:", {
1396
+ mutualId: mutual.mutualId,
1397
+ mainPk: mutual.mainPk,
1398
+ byFullEntityId: mutual.byFullEntityId,
1399
+ fullEntityId: mutual.fullEntityId
1400
+ });
1401
+ const currentDatetime = (/* @__PURE__ */ new Date()).toISOString();
1402
+ const toUpdateExpressions = this.toUpdate(
1403
+ __spreadValues({
1404
+ mutualUpdatedAt: currentDatetime
1405
+ }, toUpdate),
1406
+ { maxLevel: opts == null ? void 0 : opts.maxObjectUpdateLevel }
1407
+ );
1408
+ console.log("[MONORISE_DEBUG] updateMutual update expression:", {
1409
+ UpdateExpression: toUpdateExpressions.UpdateExpression,
1410
+ ExpressionAttributeNames: toUpdateExpressions.ExpressionAttributeNames,
1411
+ hasExpressionAttributeValues: !!toUpdateExpressions.ExpressionAttributeValues
1412
+ });
1413
+ const updateExpression = {
1414
+ ConditionExpression: (opts == null ? void 0 : opts.ConditionExpression) || "attribute_exists(PK)",
1415
+ UpdateExpression: toUpdateExpressions.UpdateExpression,
1416
+ ExpressionAttributeNames: __spreadValues(__spreadValues({}, toUpdateExpressions.ExpressionAttributeNames), opts == null ? void 0 : opts.ExpressionAttributeNames),
1417
+ ExpressionAttributeValues: __spreadValues(__spreadValues({}, toUpdateExpressions.ExpressionAttributeValues), opts == null ? void 0 : opts.ExpressionAttributeValues)
1418
+ };
1419
+ const TransactItems = [
1420
+ {
1421
+ Update: __spreadValues({
1422
+ TableName: this.TABLE_NAME,
1423
+ Key: mutual.mainKeys()
1424
+ }, updateExpression)
1425
+ },
1426
+ {
1427
+ Update: __spreadValues({
1428
+ TableName: this.TABLE_NAME,
1429
+ Key: {
1430
+ PK: { S: mutual.byFullEntityId },
1431
+ SK: { S: mutual.fullEntityId }
1432
+ }
1433
+ }, updateExpression)
1434
+ },
1435
+ {
1436
+ Update: __spreadValues({
1437
+ TableName: this.TABLE_NAME,
1438
+ Key: {
1439
+ PK: { S: mutual.fullEntityId },
1440
+ SK: { S: mutual.byFullEntityId }
1441
+ }
1442
+ }, updateExpression)
1443
+ }
1444
+ ];
1445
+ console.log("[MONORISE_DEBUG] updateMutual transact items prepared:", {
1446
+ itemCount: TransactItems.length,
1447
+ tableName: this.TABLE_NAME
1448
+ });
1449
+ return { mutual, TransactItems };
1450
+ });
1451
+ }
1420
1452
  updateMutual(byEntityType, byEntityId, entityType, entityId, toUpdate, opts) {
1421
1453
  return __async(this, null, function* () {
1422
1454
  var _a, _b;
@@ -1431,69 +1463,15 @@ var MutualRepository = class extends Repository {
1431
1463
  const returnUpdatedValue = (_a = opts == null ? void 0 : opts.returnUpdatedValue) != null ? _a : false;
1432
1464
  const errorContext = {};
1433
1465
  try {
1434
- console.log("[MONORISE_DEBUG] updateMutual fetching mutual...");
1435
- const mutual = yield this.getMutual(
1466
+ const { TransactItems } = yield this.prepareUpdateMutual(
1436
1467
  byEntityType,
1437
1468
  byEntityId,
1438
1469
  entityType,
1439
1470
  entityId,
1440
- { ProjectionExpression: PROJECTION_EXPRESSION.NO_DATA }
1441
- );
1442
- console.log("[MONORISE_DEBUG] updateMutual mutual found:", {
1443
- mutualId: mutual.mutualId,
1444
- mainPk: mutual.mainPk,
1445
- byFullEntityId: mutual.byFullEntityId,
1446
- fullEntityId: mutual.fullEntityId
1447
- });
1448
- const currentDatetime = (/* @__PURE__ */ new Date()).toISOString();
1449
- const toUpdateExpressions = this.toUpdate(
1450
- __spreadValues({
1451
- mutualUpdatedAt: currentDatetime
1452
- }, toUpdate),
1453
- { maxLevel: opts == null ? void 0 : opts.maxObjectUpdateLevel }
1471
+ toUpdate,
1472
+ opts
1454
1473
  );
1455
- console.log("[MONORISE_DEBUG] updateMutual update expression:", {
1456
- UpdateExpression: toUpdateExpressions.UpdateExpression,
1457
- ExpressionAttributeNames: toUpdateExpressions.ExpressionAttributeNames,
1458
- hasExpressionAttributeValues: !!toUpdateExpressions.ExpressionAttributeValues
1459
- });
1460
- const updateExpression = {
1461
- ConditionExpression: (opts == null ? void 0 : opts.ConditionExpression) || "attribute_exists(PK)",
1462
- UpdateExpression: toUpdateExpressions.UpdateExpression,
1463
- ExpressionAttributeNames: __spreadValues(__spreadValues({}, toUpdateExpressions.ExpressionAttributeNames), opts == null ? void 0 : opts.ExpressionAttributeNames),
1464
- ExpressionAttributeValues: __spreadValues(__spreadValues({}, toUpdateExpressions.ExpressionAttributeValues), opts == null ? void 0 : opts.ExpressionAttributeValues)
1465
- };
1466
- const TransactItems = [
1467
- {
1468
- Update: __spreadValues({
1469
- TableName: this.TABLE_NAME,
1470
- Key: mutual.mainKeys()
1471
- }, updateExpression)
1472
- },
1473
- {
1474
- Update: __spreadValues({
1475
- TableName: this.TABLE_NAME,
1476
- Key: {
1477
- PK: { S: mutual.byFullEntityId },
1478
- SK: { S: mutual.fullEntityId }
1479
- }
1480
- }, updateExpression)
1481
- },
1482
- {
1483
- Update: __spreadValues({
1484
- TableName: this.TABLE_NAME,
1485
- Key: {
1486
- PK: { S: mutual.fullEntityId },
1487
- SK: { S: mutual.byFullEntityId }
1488
- }
1489
- }, updateExpression)
1490
- }
1491
- ];
1492
1474
  errorContext.TransactItems = TransactItems;
1493
- console.log("[MONORISE_DEBUG] updateMutual transact items prepared:", {
1494
- itemCount: TransactItems.length,
1495
- tableName: this.TABLE_NAME
1496
- });
1497
1475
  console.log("[MONORISE_DEBUG] updateMutual executing transaction...");
1498
1476
  yield this.ddbUtils.executeTransactWrite({ TransactItems });
1499
1477
  console.log("[MONORISE_DEBUG] updateMutual transaction succeeded");
@@ -1531,6 +1509,64 @@ var MutualRepository = class extends Repository {
1531
1509
  }
1532
1510
  });
1533
1511
  }
1512
+ /**
1513
+ * @description Resolves the live mutual and builds the TransactWriteItems that soft-delete it
1514
+ * (all three records get a 10-minute `expiresAt`), without writing them. `deleteMutual` writes
1515
+ * them on their own; `TransactionService` folds them into a larger transaction. Throws
1516
+ * `MUTUAL_IS_UNDEFINED` when there is no live mutual for the pair.
1517
+ */
1518
+ prepareDeleteMutual(byEntityType, byEntityId, entityType, entityId, opts) {
1519
+ return __async(this, null, function* () {
1520
+ const mutual = yield this.getMutual(
1521
+ byEntityType,
1522
+ byEntityId,
1523
+ entityType,
1524
+ entityId,
1525
+ { ProjectionExpression: PROJECTION_EXPRESSION.NO_DATA }
1526
+ );
1527
+ const tenMinsLater = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3 + 10 * 60);
1528
+ const expressions = {
1529
+ UpdateExpression: "SET #expiresAt = :expiresAt, #mutualUpdatedAt = :mutualUpdatedAt, #updatedAt = :mutualUpdatedAt",
1530
+ ConditionExpression: (opts == null ? void 0 : opts.ConditionExpression) || "attribute_exists(PK) AND attribute_not_exists(#expiresAt)",
1531
+ ExpressionAttributeNames: __spreadValues({
1532
+ "#expiresAt": "expiresAt",
1533
+ "#mutualUpdatedAt": "mutualUpdatedAt",
1534
+ "#updatedAt": "updatedAt"
1535
+ }, opts == null ? void 0 : opts.ExpressionAttributeNames),
1536
+ ExpressionAttributeValues: __spreadValues({
1537
+ ":expiresAt": { N: String(tenMinsLater) },
1538
+ ":mutualUpdatedAt": { S: (/* @__PURE__ */ new Date()).toISOString() }
1539
+ }, opts == null ? void 0 : opts.ExpressionAttributeValues)
1540
+ };
1541
+ const TransactItems = [
1542
+ {
1543
+ Update: __spreadValues({
1544
+ TableName: this.TABLE_NAME,
1545
+ Key: mutual.mainKeys()
1546
+ }, expressions)
1547
+ },
1548
+ {
1549
+ Update: __spreadValues({
1550
+ TableName: this.TABLE_NAME,
1551
+ Key: {
1552
+ PK: { S: mutual.byFullEntityId },
1553
+ SK: { S: mutual.fullEntityId }
1554
+ }
1555
+ }, expressions)
1556
+ },
1557
+ {
1558
+ Update: __spreadValues({
1559
+ TableName: this.TABLE_NAME,
1560
+ Key: {
1561
+ PK: { S: mutual.fullEntityId },
1562
+ SK: { S: mutual.byFullEntityId }
1563
+ }
1564
+ }, expressions)
1565
+ }
1566
+ ];
1567
+ return { mutual, TransactItems };
1568
+ });
1569
+ }
1534
1570
  deleteMutual(byEntityType, byEntityId, entityType, entityId, opts) {
1535
1571
  return __async(this, null, function* () {
1536
1572
  var _a;
@@ -1541,53 +1577,13 @@ var MutualRepository = class extends Repository {
1541
1577
  entityId
1542
1578
  };
1543
1579
  try {
1544
- const mutual = yield this.getMutual(
1580
+ const { mutual, TransactItems } = yield this.prepareDeleteMutual(
1545
1581
  byEntityType,
1546
1582
  byEntityId,
1547
1583
  entityType,
1548
1584
  entityId,
1549
- { ProjectionExpression: PROJECTION_EXPRESSION.NO_DATA }
1585
+ opts
1550
1586
  );
1551
- const tenMinsLater = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3 + 10 * 60);
1552
- const expressions = {
1553
- UpdateExpression: "SET #expiresAt = :expiresAt, #mutualUpdatedAt = :mutualUpdatedAt, #updatedAt = :mutualUpdatedAt",
1554
- ConditionExpression: (opts == null ? void 0 : opts.ConditionExpression) || "attribute_exists(PK) AND attribute_not_exists(#expiresAt)",
1555
- ExpressionAttributeNames: __spreadValues({
1556
- "#expiresAt": "expiresAt",
1557
- "#mutualUpdatedAt": "mutualUpdatedAt",
1558
- "#updatedAt": "updatedAt"
1559
- }, opts == null ? void 0 : opts.ExpressionAttributeNames),
1560
- ExpressionAttributeValues: __spreadValues({
1561
- ":expiresAt": { N: String(tenMinsLater) },
1562
- ":mutualUpdatedAt": { S: (/* @__PURE__ */ new Date()).toISOString() }
1563
- }, opts == null ? void 0 : opts.ExpressionAttributeValues)
1564
- };
1565
- const TransactItems = [
1566
- {
1567
- Update: __spreadValues({
1568
- TableName: this.TABLE_NAME,
1569
- Key: mutual.mainKeys()
1570
- }, expressions)
1571
- },
1572
- {
1573
- Update: __spreadValues({
1574
- TableName: this.TABLE_NAME,
1575
- Key: {
1576
- PK: { S: mutual.byFullEntityId },
1577
- SK: { S: mutual.fullEntityId }
1578
- }
1579
- }, expressions)
1580
- },
1581
- {
1582
- Update: __spreadValues({
1583
- TableName: this.TABLE_NAME,
1584
- Key: {
1585
- PK: { S: mutual.fullEntityId },
1586
- SK: { S: mutual.byFullEntityId }
1587
- }
1588
- }, expressions)
1589
- }
1590
- ];
1591
1587
  errorContext.TransactItems = TransactItems;
1592
1588
  yield this.dynamodbClient.transactWriteItems({ TransactItems });
1593
1589
  return mutual;
@@ -2061,6 +2057,240 @@ var TagRepository = class extends Repository {
2061
2057
  }
2062
2058
  };
2063
2059
 
2060
+ // data/WebSocket.ts
2061
+ import {
2062
+ DeleteCommand,
2063
+ DynamoDBDocumentClient,
2064
+ PutCommand,
2065
+ QueryCommand
2066
+ } from "@aws-sdk/lib-dynamodb";
2067
+ var SUBSCRIPTION_TTL_SECONDS = 24 * 60 * 60;
2068
+ var WebSocketRepository = class extends Repository {
2069
+ constructor(tableName, dynamodbClient) {
2070
+ super();
2071
+ this.tableName = tableName;
2072
+ this.dynamodbClient = dynamodbClient;
2073
+ this.docClient = DynamoDBDocumentClient.from(dynamodbClient);
2074
+ }
2075
+ createConnection(connectionId, metadata, expiresAt) {
2076
+ return __async(this, null, function* () {
2077
+ yield this.docClient.send(
2078
+ new PutCommand({
2079
+ TableName: this.tableName,
2080
+ Item: __spreadProps(__spreadValues({
2081
+ PK: `CONN#${connectionId}`,
2082
+ SK: "#METADATA#",
2083
+ connectionId
2084
+ }, metadata), {
2085
+ expiresAt
2086
+ })
2087
+ })
2088
+ );
2089
+ });
2090
+ }
2091
+ getConnection(connectionId) {
2092
+ return __async(this, null, function* () {
2093
+ var _a;
2094
+ const result = yield this.docClient.send(
2095
+ new QueryCommand({
2096
+ TableName: this.tableName,
2097
+ KeyConditionExpression: "PK = :pk",
2098
+ ExpressionAttributeValues: {
2099
+ ":pk": `CONN#${connectionId}`
2100
+ }
2101
+ })
2102
+ );
2103
+ return (_a = result.Items) == null ? void 0 : _a[0];
2104
+ });
2105
+ }
2106
+ deleteConnection(connectionId) {
2107
+ return __async(this, null, function* () {
2108
+ yield this.docClient.send(
2109
+ new DeleteCommand({
2110
+ TableName: this.tableName,
2111
+ Key: {
2112
+ PK: `CONN#${connectionId}`,
2113
+ SK: "#METADATA#"
2114
+ }
2115
+ })
2116
+ );
2117
+ });
2118
+ }
2119
+ createSubscription(subKey, connectionId, data) {
2120
+ return __async(this, null, function* () {
2121
+ yield this.docClient.send(
2122
+ new PutCommand({
2123
+ TableName: this.tableName,
2124
+ Item: __spreadValues({
2125
+ PK: subKey,
2126
+ SK: `CONN#${connectionId}`,
2127
+ R1PK: `CONN#${connectionId}`,
2128
+ R1SK: subKey,
2129
+ connectionId,
2130
+ // Backstop only. $disconnect is what normally removes these, but it
2131
+ // is not guaranteed to run or to see every row, and without a TTL a
2132
+ // missed cleanup leaves the subscription forever. Comfortably longer
2133
+ // than API Gateway's own 2h max WebSocket connection lifetime, so it
2134
+ // never expires a live subscription.
2135
+ expiresAt: Math.floor(Date.now() / 1e3) + SUBSCRIPTION_TTL_SECONDS
2136
+ }, data)
2137
+ })
2138
+ );
2139
+ });
2140
+ }
2141
+ deleteSubscription(subKey, connectionId) {
2142
+ return __async(this, null, function* () {
2143
+ yield this.docClient.send(
2144
+ new DeleteCommand({
2145
+ TableName: this.tableName,
2146
+ Key: {
2147
+ PK: subKey,
2148
+ SK: `CONN#${connectionId}`
2149
+ }
2150
+ })
2151
+ );
2152
+ });
2153
+ }
2154
+ /**
2155
+ * Run a query to exhaustion.
2156
+ *
2157
+ * Every caller below fans a broadcast out to the rows it returns, so a
2158
+ * single-page query silently drops recipients past DynamoDB's 1MB limit --
2159
+ * and on `$disconnect`, silently leaves their subscription rows behind. The
2160
+ * `ConsistentRead` on these queries exists to avoid dropping recipients;
2161
+ * stopping at one page drops them the same way, just at a different
2162
+ * threshold.
2163
+ */
2164
+ queryAllPages(input) {
2165
+ return __async(this, null, function* () {
2166
+ const items = [];
2167
+ let lastKey;
2168
+ do {
2169
+ const result = yield this.docClient.send(
2170
+ new QueryCommand(__spreadProps(__spreadValues({}, input), { ExclusiveStartKey: lastKey }))
2171
+ );
2172
+ items.push(...result.Items || []);
2173
+ lastKey = result.LastEvaluatedKey;
2174
+ } while (lastKey);
2175
+ return items;
2176
+ });
2177
+ }
2178
+ querySubscriptionsByKey(subKey) {
2179
+ return __async(this, null, function* () {
2180
+ const items = yield this.queryAllPages({
2181
+ TableName: this.tableName,
2182
+ KeyConditionExpression: "PK = :pk",
2183
+ ExpressionAttributeValues: {
2184
+ ":pk": subKey
2185
+ },
2186
+ ConsistentRead: true
2187
+ });
2188
+ return items;
2189
+ });
2190
+ }
2191
+ querySubscriptionsByConnectionId(connectionId) {
2192
+ return __async(this, null, function* () {
2193
+ const { ENTITY_REPLICATION_INDEX: ENTITY_REPLICATION_INDEX2 } = yield import("./service.config-U77V7WIB.js");
2194
+ const items = yield this.queryAllPages({
2195
+ TableName: this.tableName,
2196
+ IndexName: ENTITY_REPLICATION_INDEX2,
2197
+ KeyConditionExpression: "R1PK = :r1pk",
2198
+ ExpressionAttributeValues: {
2199
+ ":r1pk": `CONN#${connectionId}`
2200
+ }
2201
+ });
2202
+ return items;
2203
+ });
2204
+ }
2205
+ createTicket(ticket, entityType, entityId, feedTypes, expiresAt) {
2206
+ return __async(this, null, function* () {
2207
+ yield this.docClient.send(
2208
+ new PutCommand({
2209
+ TableName: this.tableName,
2210
+ Item: {
2211
+ PK: `TICKET#${ticket}`,
2212
+ SK: "#METADATA#",
2213
+ entityType,
2214
+ entityId,
2215
+ feedTypes,
2216
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2217
+ expiresAt
2218
+ }
2219
+ })
2220
+ );
2221
+ });
2222
+ }
2223
+ consumeTicket(ticket) {
2224
+ return __async(this, null, function* () {
2225
+ try {
2226
+ const result = yield this.docClient.send(
2227
+ new DeleteCommand({
2228
+ TableName: this.tableName,
2229
+ Key: {
2230
+ PK: `TICKET#${ticket}`,
2231
+ SK: "#METADATA#"
2232
+ },
2233
+ ConditionExpression: "attribute_exists(PK)",
2234
+ ReturnValues: "ALL_OLD"
2235
+ })
2236
+ );
2237
+ const item = result.Attributes;
2238
+ if (!item) return null;
2239
+ const expiresAt = item.expiresAt;
2240
+ if (expiresAt && expiresAt < Math.floor(Date.now() / 1e3)) {
2241
+ return null;
2242
+ }
2243
+ return {
2244
+ entityType: item.entityType,
2245
+ entityId: item.entityId,
2246
+ feedTypes: item.feedTypes || []
2247
+ };
2248
+ } catch (error) {
2249
+ if (error instanceof Error && error.name === "ConditionalCheckFailedException") {
2250
+ return null;
2251
+ }
2252
+ throw error;
2253
+ }
2254
+ });
2255
+ }
2256
+ queryMutualConnections(byEntityType, byEntityId) {
2257
+ return __async(this, null, function* () {
2258
+ const items = yield this.queryAllPages({
2259
+ TableName: this.tableName,
2260
+ KeyConditionExpression: "PK = :pk",
2261
+ ExpressionAttributeValues: {
2262
+ ":pk": `${byEntityType}#${byEntityId}`
2263
+ },
2264
+ ProjectionExpression: "SK",
2265
+ ConsistentRead: true
2266
+ });
2267
+ const connections = [];
2268
+ for (const item of items) {
2269
+ const sk = item.SK;
2270
+ if (!sk || sk === "#METADATA#" || sk.startsWith("#")) continue;
2271
+ const parts = sk.split("#");
2272
+ if (parts.length >= 2) {
2273
+ connections.push({ entityType: parts[0], entityId: parts[1] });
2274
+ }
2275
+ }
2276
+ return connections;
2277
+ });
2278
+ }
2279
+ queryFeedSubscriptions(entityType, entityId) {
2280
+ return __async(this, null, function* () {
2281
+ const items = yield this.queryAllPages({
2282
+ TableName: this.tableName,
2283
+ KeyConditionExpression: "PK = :pk",
2284
+ ExpressionAttributeValues: {
2285
+ ":pk": `SUB#FEED#${entityType}#${entityId}`
2286
+ },
2287
+ ConsistentRead: true
2288
+ });
2289
+ return items;
2290
+ });
2291
+ }
2292
+ };
2293
+
2064
2294
  // handles/app.ts
2065
2295
  import { Hono as Hono2 } from "hono";
2066
2296
  import { handle } from "hono/aws-lambda";
@@ -2100,14 +2330,6 @@ import {
2100
2330
  PutEventsCommand
2101
2331
  } from "@aws-sdk/client-eventbridge";
2102
2332
 
2103
- // constants/table.ts
2104
- var ENTITY_REPLICATION_INDEX = "ENTITY_REPLICATION_INDEX";
2105
- var MUTUAL_REPLICATION_INDEX = "MUTUAL_REPLICATION_INDEX";
2106
-
2107
- // configs/service.config.ts
2108
- var CORE_TABLE = process.env.CORE_TABLE || "";
2109
- var CORE_EVENT_BUS = process.env.CORE_EVENT_BUS || "";
2110
-
2111
2333
  // types/event.ts
2112
2334
  var SOURCE = {
2113
2335
  CORE: "core-service",
@@ -7195,13 +7417,20 @@ var MutualService = class {
7195
7417
  this.publishEvent = publishEvent2;
7196
7418
  this.ddbUtils = ddbUtils;
7197
7419
  this.entityServiceLifeCycle = entityServiceLifeCycle;
7198
- this.createMutual = (_0) => __async(this, [_0], function* ({
7420
+ /**
7421
+ * @description Everything `createMutual` does before it writes: validates the payload, reads
7422
+ * both entities, checks no live mutual exists, and builds the TransactWriteItems (plus the
7423
+ * `asEntity` projection's items, when there is one). Nothing is written. `createMutual` commits
7424
+ * the items on their own; `TransactionService` folds them into a larger transaction. Either
7425
+ * caller then runs `afterCreateEntityHook` for `entity` (when set) and publishes MUTUAL_CREATED
7426
+ * once the write has committed.
7427
+ */
7428
+ this.prepareCreateMutual = (_0) => __async(this, [_0], function* ({
7199
7429
  byEntityType,
7200
7430
  byEntityId,
7201
7431
  entityType,
7202
7432
  entityId,
7203
7433
  mutualPayload,
7204
- accountId,
7205
7434
  options = {}
7206
7435
  }) {
7207
7436
  var _a, _b, _c;
@@ -7296,13 +7525,25 @@ var MutualService = class {
7296
7525
  })
7297
7526
  );
7298
7527
  }
7299
- const createTransactItems = [...mutualTransactions, ...entityTransactions];
7300
- errorContext.createTransactItems = createTransactItems;
7528
+ const transactItems = [...mutualTransactions, ...entityTransactions];
7529
+ errorContext.createTransactItems = transactItems;
7530
+ return { mutual, entity, transactItems, parsedMutualPayload };
7531
+ });
7532
+ this.createMutual = (params) => __async(this, null, function* () {
7533
+ const {
7534
+ byEntityType,
7535
+ byEntityId,
7536
+ entityType,
7537
+ entityId,
7538
+ mutualPayload,
7539
+ accountId
7540
+ } = params;
7541
+ const { mutual, entity, transactItems, parsedMutualPayload } = yield this.prepareCreateMutual(params);
7301
7542
  console.log("[MONORISE_DEBUG] createMutual executing transaction:", {
7302
- transactItemCount: createTransactItems.length
7543
+ transactItemCount: transactItems.length
7303
7544
  });
7304
7545
  yield this.ddbUtils.executeTransactWrite({
7305
- TransactItems: createTransactItems
7546
+ TransactItems: transactItems
7306
7547
  });
7307
7548
  console.log("[MONORISE_DEBUG] createMutual transaction succeeded");
7308
7549
  if (entity) {
@@ -7331,6 +7572,62 @@ var MutualService = class {
7331
7572
  console.log("[MONORISE_DEBUG] createMutual service complete");
7332
7573
  return { mutual, eventPayload };
7333
7574
  });
7575
+ /**
7576
+ * @description Reads the live mutual for a pair, with its stored `data` and `mutualData` —
7577
+ * the same read `updateMutual` returns with `returnUpdatedValue`. Throws `MUTUAL_IS_UNDEFINED`
7578
+ * when there is none.
7579
+ */
7580
+ this.getMutual = ({
7581
+ byEntityType,
7582
+ byEntityId,
7583
+ entityType,
7584
+ entityId
7585
+ }) => this.mutualRepository.getMutual(
7586
+ byEntityType,
7587
+ byEntityId,
7588
+ entityType,
7589
+ entityId
7590
+ );
7591
+ /**
7592
+ * @description Everything `updateMutual` does before it writes: validates the patch with the
7593
+ * same schema, resolves the live mutual and builds the TransactWriteItems. Nothing is written —
7594
+ * for `TransactionService`, which publishes the same MUTUAL_UPDATED event once its transaction
7595
+ * commits. Throws `MUTUAL_NOT_FOUND` when there is no live mutual for the pair.
7596
+ */
7597
+ this.prepareUpdateMutual = (_0) => __async(this, [_0], function* ({
7598
+ byEntityType,
7599
+ byEntityId,
7600
+ entityType,
7601
+ entityId,
7602
+ mutualPayload,
7603
+ options
7604
+ }) {
7605
+ const parsedMutualPayload = this.getMutualUpdateSchema(
7606
+ byEntityType,
7607
+ entityType
7608
+ ).parse(mutualPayload);
7609
+ try {
7610
+ const { mutual, TransactItems } = yield this.mutualRepository.prepareUpdateMutual(
7611
+ byEntityType,
7612
+ byEntityId,
7613
+ entityType,
7614
+ entityId,
7615
+ { mutualData: parsedMutualPayload },
7616
+ options
7617
+ );
7618
+ return { mutual, TransactItems, parsedMutualPayload };
7619
+ } catch (err) {
7620
+ if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_IS_UNDEFINED) {
7621
+ throw new StandardError(
7622
+ StandardErrorCode.MUTUAL_NOT_FOUND,
7623
+ "Mutual not found",
7624
+ err,
7625
+ { byEntityType, byEntityId, entityType, entityId }
7626
+ );
7627
+ }
7628
+ throw err;
7629
+ }
7630
+ });
7334
7631
  this.updateMutual = (_0) => __async(this, [_0], function* ({
7335
7632
  byEntityType,
7336
7633
  byEntityId,
@@ -7340,7 +7637,6 @@ var MutualService = class {
7340
7637
  accountId,
7341
7638
  options
7342
7639
  }) {
7343
- var _a, _b;
7344
7640
  console.log("[MONORISE_DEBUG] updateMutual service start:", {
7345
7641
  byEntityType,
7346
7642
  byEntityId,
@@ -7349,9 +7645,7 @@ var MutualService = class {
7349
7645
  mutualPayload,
7350
7646
  options
7351
7647
  });
7352
- const mutualFieldConfig = this.getMutualFieldConfig(byEntityType, entityType);
7353
- const asEntityStorageSchema = (mutualFieldConfig == null ? void 0 : mutualFieldConfig.asEntity) ? (_a = mutualFieldConfig.asEntity.createSchema) != null ? _a : mutualFieldConfig.asEntity.baseSchema : void 0;
7354
- const schema = (_b = asEntityStorageSchema != null ? asEntityStorageSchema : mutualFieldConfig == null ? void 0 : mutualFieldConfig.mutualDataSchema) != null ? _b : external_exports.record(external_exports.string(), external_exports.any());
7648
+ const schema = this.getMutualUpdateSchema(byEntityType, entityType);
7355
7649
  console.log("[MONORISE_DEBUG] updateMutual schema resolved");
7356
7650
  const parsedMutualPayload = schema.parse(mutualPayload);
7357
7651
  console.log("[MONORISE_DEBUG] updateMutual payload parsed:", parsedMutualPayload);
@@ -7382,6 +7676,36 @@ var MutualService = class {
7382
7676
  console.log("[MONORISE_DEBUG] updateMutual service complete");
7383
7677
  return mutual;
7384
7678
  });
7679
+ /**
7680
+ * @description Resolves the live mutual and builds the TransactWriteItems that delete it,
7681
+ * without writing — for `TransactionService`. Throws `MUTUAL_NOT_FOUND` (same as
7682
+ * `deleteMutual`) when there is no live mutual for the pair.
7683
+ */
7684
+ this.prepareDeleteMutual = (_0) => __async(this, [_0], function* ({
7685
+ byEntityType,
7686
+ byEntityId,
7687
+ entityType,
7688
+ entityId
7689
+ }) {
7690
+ try {
7691
+ return yield this.mutualRepository.prepareDeleteMutual(
7692
+ byEntityType,
7693
+ byEntityId,
7694
+ entityType,
7695
+ entityId
7696
+ );
7697
+ } catch (err) {
7698
+ if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_IS_UNDEFINED) {
7699
+ throw new StandardError(
7700
+ StandardErrorCode.MUTUAL_NOT_FOUND,
7701
+ "Mutual not found",
7702
+ err,
7703
+ { byEntityType, byEntityId, entityType, entityId }
7704
+ );
7705
+ }
7706
+ throw err;
7707
+ }
7708
+ });
7385
7709
  this.deleteMutual = (_0) => __async(this, [_0], function* ({
7386
7710
  byEntityType,
7387
7711
  byEntityId,
@@ -7442,6 +7766,19 @@ var MutualService = class {
7442
7766
  var _a;
7443
7767
  return (_a = this.getMutualFieldConfig(byEntityType, entityType)) == null ? void 0 : _a.mutualDataSchema;
7444
7768
  }
7769
+ // Same `asEntity`-aware narrowing as `createMutual` — an update to an `asEntity` mutual must
7770
+ // not re-introduce the target entity's own further `mutualFields` keys into stored
7771
+ // `mutualData` any more than the initial create does (see `createMutual`'s own comment).
7772
+ // Shared by `updateMutual` and `prepareUpdateMutual` so both validate a patch identically.
7773
+ getMutualUpdateSchema(byEntityType, entityType) {
7774
+ var _a, _b;
7775
+ const mutualFieldConfig = this.getMutualFieldConfig(
7776
+ byEntityType,
7777
+ entityType
7778
+ );
7779
+ const asEntityStorageSchema = (mutualFieldConfig == null ? void 0 : mutualFieldConfig.asEntity) ? (_a = mutualFieldConfig.asEntity.createSchema) != null ? _a : mutualFieldConfig.asEntity.baseSchema : void 0;
7780
+ return (_b = asEntityStorageSchema != null ? asEntityStorageSchema : mutualFieldConfig == null ? void 0 : mutualFieldConfig.mutualDataSchema) != null ? _b : external_exports.record(external_exports.string(), external_exports.any());
7781
+ }
7445
7782
  };
7446
7783
 
7447
7784
  // processors/mutual-processor.ts
@@ -8222,6 +8559,462 @@ var handler10 = (container) => (ev) => __async(null, null, function* () {
8222
8559
  return { batchItemFailures };
8223
8560
  });
8224
8561
 
8562
+ // processors/websocket-processor.ts
8563
+ import {
8564
+ ApiGatewayManagementApiClient,
8565
+ PostToConnectionCommand
8566
+ } from "@aws-sdk/client-apigatewaymanagementapi";
8567
+ import { unmarshall as unmarshall6 } from "@aws-sdk/util-dynamodb";
8568
+ import { ulid as ulid5 } from "ulid";
8569
+ var SUB_ENTITY_TYPE = "SUB#ENTITY#";
8570
+ var SUB_MUTUAL_TYPE = "SUB#MUTUAL#";
8571
+ var SUB_EPHEMERAL = "SUB#EPHEMERAL#";
8572
+ var SUB_FEED = "SUB#FEED#";
8573
+ var getWsEndpoint = () => process.env.WEBSOCKET_MANAGEMENT_ENDPOINT || "";
8574
+ var connect = (container) => (event) => __async(null, null, function* () {
8575
+ var _a, _b, _c, _d;
8576
+ const connectionId = event.requestContext.connectionId;
8577
+ if (!connectionId) {
8578
+ return { statusCode: 400, body: "Missing connection ID" };
8579
+ }
8580
+ const expiresAt = Math.floor(Date.now() / 1e3) + 2 * 60 * 60;
8581
+ const ticket = (_a = event.queryStringParameters) == null ? void 0 : _a.ticket;
8582
+ const token = ((_b = event.queryStringParameters) == null ? void 0 : _b.token) || ((_c = event.headers) == null ? void 0 : _c.authorization) || ((_d = event.headers) == null ? void 0 : _d.Authorization);
8583
+ if (!ticket && !token) {
8584
+ return { statusCode: 401, body: "Unauthorized" };
8585
+ }
8586
+ const wsRepo = container.websocketRepository;
8587
+ try {
8588
+ let entityType;
8589
+ let entityId;
8590
+ let feedTypes;
8591
+ if (ticket) {
8592
+ const ticketData = yield wsRepo.consumeTicket(ticket);
8593
+ if (!ticketData) {
8594
+ return { statusCode: 401, body: "Invalid or expired ticket" };
8595
+ }
8596
+ entityType = ticketData.entityType;
8597
+ entityId = ticketData.entityId;
8598
+ feedTypes = ticketData.feedTypes;
8599
+ } else {
8600
+ entityId = token;
8601
+ }
8602
+ yield wsRepo.createConnection(
8603
+ connectionId,
8604
+ __spreadProps(__spreadValues(__spreadValues({}, entityType && { entityType }), entityId && { entityId }), {
8605
+ connectedAt: (/* @__PURE__ */ new Date()).toISOString()
8606
+ }),
8607
+ expiresAt
8608
+ );
8609
+ if (entityType && entityId && feedTypes) {
8610
+ yield wsRepo.createSubscription(
8611
+ `${SUB_FEED}${entityType}#${entityId}`,
8612
+ connectionId,
8613
+ {
8614
+ subscriptionType: "feed",
8615
+ entityType,
8616
+ entityId,
8617
+ feedTypes,
8618
+ subscribedAt: (/* @__PURE__ */ new Date()).toISOString(),
8619
+ expiresAt
8620
+ }
8621
+ );
8622
+ }
8623
+ return { statusCode: 200, body: "Connected" };
8624
+ } catch (error) {
8625
+ console.error("Error in $connect:", error);
8626
+ return { statusCode: 500, body: "Failed to connect" };
8627
+ }
8628
+ });
8629
+ var disconnect = (container) => (event) => __async(null, null, function* () {
8630
+ const connectionId = event.requestContext.connectionId;
8631
+ if (!connectionId) {
8632
+ return { statusCode: 400, body: "Missing connection ID" };
8633
+ }
8634
+ const wsRepo = container.websocketRepository;
8635
+ try {
8636
+ const subscriptions = yield wsRepo.querySubscriptionsByConnectionId(connectionId);
8637
+ const deletePromises = [];
8638
+ for (const item of subscriptions) {
8639
+ if (item.PK && item.SK) {
8640
+ deletePromises.push(
8641
+ wsRepo.deleteSubscription(item.PK, item.connectionId).catch(
8642
+ (e) => console.warn("Failed to delete subscription on disconnect:", e)
8643
+ )
8644
+ );
8645
+ }
8646
+ }
8647
+ deletePromises.push(wsRepo.deleteConnection(connectionId));
8648
+ yield Promise.all(deletePromises);
8649
+ return { statusCode: 200, body: "Disconnected" };
8650
+ } catch (error) {
8651
+ console.error("Error cleaning up connection:", error);
8652
+ return { statusCode: 500, body: "Failed to disconnect" };
8653
+ }
8654
+ });
8655
+ var $default = (container) => (event) => __async(null, null, function* () {
8656
+ const connectionId = event.requestContext.connectionId;
8657
+ if (!connectionId || !event.body) {
8658
+ return { statusCode: 400, body: "Invalid message" };
8659
+ }
8660
+ let message;
8661
+ try {
8662
+ message = JSON.parse(event.body);
8663
+ } catch (e) {
8664
+ return { statusCode: 400, body: "Invalid JSON" };
8665
+ }
8666
+ const wsRepo = container.websocketRepository;
8667
+ const wsEndpoint = getWsEndpoint();
8668
+ const managementApi = new ApiGatewayManagementApiClient({
8669
+ endpoint: wsEndpoint
8670
+ });
8671
+ try {
8672
+ switch (message.action) {
8673
+ case "subscribe": {
8674
+ const {
8675
+ entityType,
8676
+ byEntityType,
8677
+ byEntityId,
8678
+ mutualEntityType,
8679
+ channel
8680
+ } = message.payload;
8681
+ if (entityType && !byEntityType) {
8682
+ yield wsRepo.createSubscription(
8683
+ `${SUB_ENTITY_TYPE}${entityType}`,
8684
+ connectionId,
8685
+ {
8686
+ subscriptionType: "entity-type",
8687
+ entityType,
8688
+ subscribedAt: (/* @__PURE__ */ new Date()).toISOString()
8689
+ }
8690
+ );
8691
+ } else if (byEntityType && byEntityId && mutualEntityType) {
8692
+ yield wsRepo.createSubscription(
8693
+ `${SUB_MUTUAL_TYPE}${byEntityType}#${byEntityId}#${mutualEntityType}`,
8694
+ connectionId,
8695
+ {
8696
+ subscriptionType: "mutual-type",
8697
+ byEntityType,
8698
+ byEntityId,
8699
+ entityType: mutualEntityType,
8700
+ subscribedAt: (/* @__PURE__ */ new Date()).toISOString()
8701
+ }
8702
+ );
8703
+ } else if (channel) {
8704
+ yield wsRepo.createSubscription(
8705
+ `${SUB_EPHEMERAL}${channel}`,
8706
+ connectionId,
8707
+ {
8708
+ subscriptionType: "ephemeral",
8709
+ channel,
8710
+ subscribedAt: (/* @__PURE__ */ new Date()).toISOString()
8711
+ }
8712
+ );
8713
+ } else {
8714
+ return { statusCode: 400, body: "Invalid subscription parameters" };
8715
+ }
8716
+ const ackMessage = {
8717
+ type: "ack",
8718
+ id: message.id,
8719
+ payload: { action: "subscribe", success: true }
8720
+ };
8721
+ yield managementApi.send(
8722
+ new PostToConnectionCommand({
8723
+ ConnectionId: connectionId,
8724
+ Data: JSON.stringify(ackMessage)
8725
+ })
8726
+ );
8727
+ return { statusCode: 200, body: "Subscribed" };
8728
+ }
8729
+ case "unsubscribe": {
8730
+ const {
8731
+ entityType,
8732
+ byEntityType,
8733
+ byEntityId,
8734
+ mutualEntityType,
8735
+ channel
8736
+ } = message.payload;
8737
+ if (entityType && !byEntityType) {
8738
+ yield wsRepo.deleteSubscription(
8739
+ `${SUB_ENTITY_TYPE}${entityType}`,
8740
+ connectionId
8741
+ );
8742
+ } else if (byEntityType && byEntityId && mutualEntityType) {
8743
+ yield wsRepo.deleteSubscription(
8744
+ `${SUB_MUTUAL_TYPE}${byEntityType}#${byEntityId}#${mutualEntityType}`,
8745
+ connectionId
8746
+ );
8747
+ } else if (channel) {
8748
+ yield wsRepo.deleteSubscription(
8749
+ `${SUB_EPHEMERAL}${channel}`,
8750
+ connectionId
8751
+ );
8752
+ }
8753
+ const ackMessage = {
8754
+ type: "ack",
8755
+ id: message.id,
8756
+ payload: { action: "unsubscribe", success: true }
8757
+ };
8758
+ yield managementApi.send(
8759
+ new PostToConnectionCommand({
8760
+ ConnectionId: connectionId,
8761
+ Data: JSON.stringify(ackMessage)
8762
+ })
8763
+ );
8764
+ return { statusCode: 200, body: "Unsubscribed" };
8765
+ }
8766
+ case "ping": {
8767
+ const pongMessage = {
8768
+ type: "pong",
8769
+ id: message.id,
8770
+ payload: { timestamp: Date.now() }
8771
+ };
8772
+ yield managementApi.send(
8773
+ new PostToConnectionCommand({
8774
+ ConnectionId: connectionId,
8775
+ Data: JSON.stringify(pongMessage)
8776
+ })
8777
+ );
8778
+ return { statusCode: 200, body: "Pong" };
8779
+ }
8780
+ case "ephemeral": {
8781
+ const { channel, data } = message.payload;
8782
+ if (!channel) {
8783
+ return { statusCode: 400, body: "Missing channel" };
8784
+ }
8785
+ const conn = yield wsRepo.getConnection(connectionId);
8786
+ const senderId = conn == null ? void 0 : conn.entityId;
8787
+ const subKey = `${SUB_EPHEMERAL}${channel}`;
8788
+ const ephemeralMessage = {
8789
+ type: "ephemeral",
8790
+ id: ulid5(),
8791
+ payload: { channel, data, senderId }
8792
+ };
8793
+ yield broadcastToSubscribers(
8794
+ managementApi,
8795
+ wsRepo,
8796
+ subKey,
8797
+ ephemeralMessage,
8798
+ connectionId
8799
+ // Exclude sender
8800
+ );
8801
+ return { statusCode: 200, body: "Broadcasted" };
8802
+ }
8803
+ default:
8804
+ return { statusCode: 400, body: "Unknown action" };
8805
+ }
8806
+ } catch (error) {
8807
+ console.error("Error handling message:", error);
8808
+ try {
8809
+ const errorMessage = {
8810
+ type: "error",
8811
+ id: message.id,
8812
+ payload: { message: "Internal server error" }
8813
+ };
8814
+ yield managementApi.send(
8815
+ new PostToConnectionCommand({
8816
+ ConnectionId: connectionId,
8817
+ Data: JSON.stringify(errorMessage)
8818
+ })
8819
+ );
8820
+ } catch (e) {
8821
+ }
8822
+ return { statusCode: 500, body: "Internal server error" };
8823
+ }
8824
+ });
8825
+ var broadcast = (container) => (event) => __async(null, null, function* () {
8826
+ var _a, _b, _c, _d;
8827
+ const wsRepo = container.websocketRepository;
8828
+ const wsEndpoint = getWsEndpoint();
8829
+ const managementApi = new ApiGatewayManagementApiClient({
8830
+ endpoint: wsEndpoint
8831
+ });
8832
+ for (const record of event.Records) {
8833
+ const isInsert = record.eventName === "INSERT";
8834
+ const isModify = record.eventName === "MODIFY";
8835
+ const isRemove = record.eventName === "REMOVE";
8836
+ if (!isInsert && !isModify && !isRemove) continue;
8837
+ const newImage = (_a = record.dynamodb) == null ? void 0 : _a.NewImage;
8838
+ const oldImage = (_b = record.dynamodb) == null ? void 0 : _b.OldImage;
8839
+ const image = newImage || oldImage;
8840
+ if (!image) continue;
8841
+ const pk = ((_c = image.PK) == null ? void 0 : _c.S) || "";
8842
+ const sk = ((_d = image.SK) == null ? void 0 : _d.S) || "";
8843
+ const pkParts = pk.split("#");
8844
+ if (pkParts.length < 2) continue;
8845
+ const entityType = pkParts[0];
8846
+ const entityId = pkParts[1];
8847
+ if (!(entityType in container.config.EntityConfig)) continue;
8848
+ const isMutual = !sk.startsWith("#METADATA#") && sk.includes("#");
8849
+ try {
8850
+ if (isMutual) {
8851
+ const skParts = sk.split("#");
8852
+ const mutualEntityType = skParts[0];
8853
+ const byEntityId = entityId;
8854
+ const subKey = `${SUB_MUTUAL_TYPE}${entityType}#${byEntityId}#${mutualEntityType}`;
8855
+ const subscribers = yield wsRepo.querySubscriptionsByKey(subKey);
8856
+ if (subscribers.length) {
8857
+ let eventType;
8858
+ if (isInsert) eventType = "mutual.created";
8859
+ else if (isModify) eventType = "mutual.updated";
8860
+ else eventType = "mutual.deleted";
8861
+ const message = {
8862
+ type: eventType,
8863
+ id: ulid5(),
8864
+ payload: {
8865
+ byEntityType: entityType,
8866
+ byEntityId,
8867
+ mutualEntityType,
8868
+ entityId: skParts[1],
8869
+ data: isRemove ? void 0 : unmarshall6(image)
8870
+ }
8871
+ };
8872
+ yield broadcastToSubscribers(
8873
+ managementApi,
8874
+ wsRepo,
8875
+ subKey,
8876
+ message
8877
+ );
8878
+ }
8879
+ } else {
8880
+ const subKey = `${SUB_ENTITY_TYPE}${entityType}`;
8881
+ const subscribers = yield wsRepo.querySubscriptionsByKey(subKey);
8882
+ if (subscribers.length) {
8883
+ let eventType;
8884
+ if (isInsert) eventType = "entity.created";
8885
+ else if (isModify) eventType = "entity.updated";
8886
+ else eventType = "entity.deleted";
8887
+ const message = {
8888
+ type: eventType,
8889
+ id: ulid5(),
8890
+ payload: {
8891
+ entityType,
8892
+ entityId,
8893
+ data: isRemove ? void 0 : unmarshall6(image)
8894
+ }
8895
+ };
8896
+ yield broadcastToSubscribers(
8897
+ managementApi,
8898
+ wsRepo,
8899
+ subKey,
8900
+ message
8901
+ );
8902
+ }
8903
+ }
8904
+ yield broadcastToFeedSubscribers(
8905
+ managementApi,
8906
+ wsRepo,
8907
+ entityType,
8908
+ entityId,
8909
+ isMutual ? sk.split("#")[0] : entityType,
8910
+ // the changed entity type
8911
+ isMutual ? {
8912
+ type: isInsert ? "mutual.created" : isModify ? "mutual.updated" : "mutual.deleted",
8913
+ id: ulid5(),
8914
+ payload: {
8915
+ byEntityType: entityType,
8916
+ byEntityId: entityId,
8917
+ mutualEntityType: sk.split("#")[0],
8918
+ entityId: sk.split("#")[1],
8919
+ data: isRemove ? void 0 : unmarshall6(image)
8920
+ }
8921
+ } : {
8922
+ type: isInsert ? "entity.created" : isModify ? "entity.updated" : "entity.deleted",
8923
+ id: ulid5(),
8924
+ payload: {
8925
+ entityType,
8926
+ entityId,
8927
+ data: isRemove ? void 0 : unmarshall6(image)
8928
+ }
8929
+ }
8930
+ );
8931
+ } catch (error) {
8932
+ console.error("Error broadcasting:", error);
8933
+ }
8934
+ }
8935
+ });
8936
+ function broadcastToSubscribers(managementApi, wsRepo, subKey, message, excludeConnectionId) {
8937
+ return __async(this, null, function* () {
8938
+ const subscribers = yield wsRepo.querySubscriptionsByKey(subKey);
8939
+ if (!subscribers.length) return;
8940
+ const messageData = JSON.stringify(message);
8941
+ const sends = subscribers.filter((subscriber) => {
8942
+ const id = subscriber.connectionId;
8943
+ return !excludeConnectionId || id !== excludeConnectionId;
8944
+ }).map((subscriber) => __async(null, null, function* () {
8945
+ var _a;
8946
+ try {
8947
+ yield managementApi.send(
8948
+ new PostToConnectionCommand({
8949
+ ConnectionId: subscriber.connectionId,
8950
+ Data: messageData
8951
+ })
8952
+ );
8953
+ } catch (error) {
8954
+ const isGone = (error == null ? void 0 : error.name) === "GoneException" || ((_a = error == null ? void 0 : error.$metadata) == null ? void 0 : _a.httpStatusCode) === 410;
8955
+ if (isGone) {
8956
+ yield wsRepo.deleteSubscription(subKey, subscriber.connectionId).catch(
8957
+ (e) => console.warn("Failed to clean up stale subscription:", e)
8958
+ );
8959
+ }
8960
+ }
8961
+ }));
8962
+ yield Promise.allSettled(sends);
8963
+ });
8964
+ }
8965
+ function broadcastToFeedSubscribers(managementApi, wsRepo, byEntityType, byEntityId, changedEntityType, message) {
8966
+ return __async(this, null, function* () {
8967
+ var _a;
8968
+ const connections = yield wsRepo.queryMutualConnections(
8969
+ byEntityType,
8970
+ byEntityId
8971
+ );
8972
+ const connectedEntities = new Set(
8973
+ connections.map((c) => `${c.entityType}:${c.entityId}`)
8974
+ );
8975
+ connectedEntities.add(`${byEntityType}:${byEntityId}`);
8976
+ const sentConnections = /* @__PURE__ */ new Set();
8977
+ const resolved = yield Promise.all(
8978
+ Array.from(connectedEntities).map((connEntity) => __async(null, null, function* () {
8979
+ const [entityType, entityId] = connEntity.split(":");
8980
+ return {
8981
+ entityType,
8982
+ entityId,
8983
+ feedSubs: yield wsRepo.queryFeedSubscriptions(entityType, entityId)
8984
+ };
8985
+ }))
8986
+ );
8987
+ for (const { entityType, entityId, feedSubs } of resolved) {
8988
+ if (!feedSubs.length) continue;
8989
+ for (const feedSub of feedSubs) {
8990
+ const feedTypes = feedSub.feedTypes;
8991
+ const connectionId = feedSub.connectionId;
8992
+ if (feedTypes && !feedTypes.includes(changedEntityType)) continue;
8993
+ if (sentConnections.has(connectionId)) continue;
8994
+ sentConnections.add(connectionId);
8995
+ try {
8996
+ yield managementApi.send(
8997
+ new PostToConnectionCommand({
8998
+ ConnectionId: connectionId,
8999
+ Data: JSON.stringify(message)
9000
+ })
9001
+ );
9002
+ } catch (error) {
9003
+ const isGone = (error == null ? void 0 : error.name) === "GoneException" || ((_a = error == null ? void 0 : error.$metadata) == null ? void 0 : _a.httpStatusCode) === 410;
9004
+ if (isGone) {
9005
+ yield wsRepo.deleteSubscription(
9006
+ `SUB#FEED#${entityType}#${entityId}`,
9007
+ connectionId
9008
+ ).catch(
9009
+ (e) => console.warn("Failed to clean up stale feed subscription:", e)
9010
+ );
9011
+ }
9012
+ }
9013
+ }
9014
+ }
9015
+ });
9016
+ }
9017
+
8225
9018
  // services/DependencyContainer.ts
8226
9019
  import { DynamoDB } from "@aws-sdk/client-dynamodb";
8227
9020
 
@@ -9454,7 +10247,7 @@ var ExecuteTransactionController = class {
9454
10247
  }
9455
10248
  if (err instanceof StandardError) {
9456
10249
  const code = err.code;
9457
- if (code === StandardErrorCode.ENTITY_IS_UNDEFINED || code === StandardErrorCode.ENTITY_NOT_FOUND) {
10250
+ if (code === StandardErrorCode.ENTITY_IS_UNDEFINED || code === StandardErrorCode.ENTITY_NOT_FOUND || code === StandardErrorCode.MUTUAL_NOT_FOUND) {
9458
10251
  c.status(httpStatus16.NOT_FOUND);
9459
10252
  return c.json(__spreadValues({}, err.toJSON()));
9460
10253
  }
@@ -9462,7 +10255,7 @@ var ExecuteTransactionController = class {
9462
10255
  c.status(httpStatus16.BAD_REQUEST);
9463
10256
  return c.json(__spreadValues({}, err.toJSON()));
9464
10257
  }
9465
- if (code === StandardErrorCode.TRANSACTION_FAILED || code === StandardErrorCode.CONDITIONAL_CHECK_FAILED || code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
10258
+ if (code === StandardErrorCode.TRANSACTION_FAILED || code === StandardErrorCode.CONDITIONAL_CHECK_FAILED || code === StandardErrorCode.UNIQUE_VALUE_EXISTS || code === StandardErrorCode.MUTUAL_EXISTS) {
9466
10259
  c.status(httpStatus16.CONFLICT);
9467
10260
  return c.json(__spreadValues({}, err.toJSON()));
9468
10261
  }
@@ -9473,6 +10266,72 @@ var ExecuteTransactionController = class {
9473
10266
  }
9474
10267
  };
9475
10268
 
10269
+ // controllers/ws/create-ticket.controller.ts
10270
+ import { createMiddleware as createMiddleware18 } from "hono/factory";
10271
+ import { ulid as ulid6 } from "ulid";
10272
+ var TICKET_TTL_SECONDS = 30 * 60;
10273
+ var CreateTicketController = class {
10274
+ constructor(container) {
10275
+ this.container = container;
10276
+ this.controller = createMiddleware18((c) => __async(this, null, function* () {
10277
+ var _a, _b;
10278
+ const { entityType, entityId } = c.req.param();
10279
+ let feedTypes;
10280
+ try {
10281
+ const body = yield c.req.json();
10282
+ feedTypes = body.feedTypes;
10283
+ } catch (e) {
10284
+ }
10285
+ if (!feedTypes || feedTypes.length === 0) {
10286
+ const allConfigs = this.container.config.EntityConfig;
10287
+ const adjacency = /* @__PURE__ */ new Map();
10288
+ const link = (from, to) => {
10289
+ var _a2;
10290
+ if (!adjacency.has(from)) adjacency.set(from, /* @__PURE__ */ new Set());
10291
+ (_a2 = adjacency.get(from)) == null ? void 0 : _a2.add(to);
10292
+ };
10293
+ for (const [type, config] of Object.entries(allConfigs)) {
10294
+ const fields = (_a = config == null ? void 0 : config.mutual) == null ? void 0 : _a.mutualFields;
10295
+ if (!fields) continue;
10296
+ for (const field of Object.values(fields)) {
10297
+ link(type, field.entityType);
10298
+ link(field.entityType, type);
10299
+ }
10300
+ }
10301
+ const visited = /* @__PURE__ */ new Set();
10302
+ const queue = [entityType];
10303
+ while (queue.length > 0) {
10304
+ const current = queue.shift();
10305
+ if (!current) continue;
10306
+ if (visited.has(current)) continue;
10307
+ visited.add(current);
10308
+ for (const neighbour of (_b = adjacency.get(current)) != null ? _b : []) {
10309
+ if (!visited.has(neighbour)) queue.push(neighbour);
10310
+ }
10311
+ }
10312
+ visited.delete(entityType);
10313
+ feedTypes = Array.from(visited);
10314
+ }
10315
+ const ticket = ulid6();
10316
+ const now = Math.floor(Date.now() / 1e3);
10317
+ const expiresAt = now + TICKET_TTL_SECONDS;
10318
+ yield this.container.websocketRepository.createTicket(
10319
+ ticket,
10320
+ entityType,
10321
+ entityId,
10322
+ feedTypes,
10323
+ expiresAt
10324
+ );
10325
+ const wsEndpoint = process.env.WEBSOCKET_URL || "";
10326
+ return c.json({
10327
+ ticket,
10328
+ wsUrl: wsEndpoint,
10329
+ expiresIn: TICKET_TTL_SECONDS
10330
+ });
10331
+ }));
10332
+ }
10333
+ };
10334
+
9476
10335
  // services/entity-service-lifecycle.ts
9477
10336
  var EntityServiceLifeCycle = class {
9478
10337
  constructor(EntityConfig, publishEvent2, eventUtils) {
@@ -9508,10 +10367,10 @@ var EntityServiceLifeCycle = class {
9508
10367
 
9509
10368
  // services/transaction.service.ts
9510
10369
  import { TransactionCanceledException as TransactionCanceledException5 } from "@aws-sdk/client-dynamodb";
9511
- import { ulid as ulid5 } from "ulid";
10370
+ import { ulid as ulid7 } from "ulid";
9512
10371
  var MAX_TRANSACTION_ITEMS = 100;
9513
10372
  var TransactionService = class {
9514
- constructor(EntityConfig, EmailAuthEnabledEntities, entityRepository, dynamodbClient, publishEvent2, entityServiceLifeCycle, eventUtils) {
10373
+ constructor(EntityConfig, EmailAuthEnabledEntities, entityRepository, dynamodbClient, publishEvent2, entityServiceLifeCycle, eventUtils, mutualService) {
9515
10374
  this.EntityConfig = EntityConfig;
9516
10375
  this.EmailAuthEnabledEntities = EmailAuthEnabledEntities;
9517
10376
  this.entityRepository = entityRepository;
@@ -9519,6 +10378,7 @@ var TransactionService = class {
9519
10378
  this.publishEvent = publishEvent2;
9520
10379
  this.entityServiceLifeCycle = entityServiceLifeCycle;
9521
10380
  this.eventUtils = eventUtils;
10381
+ this.mutualService = mutualService;
9522
10382
  this.executeTransaction = (operations, accountId) => __async(this, null, function* () {
9523
10383
  var _a;
9524
10384
  if (!operations || operations.length === 0) {
@@ -9533,9 +10393,11 @@ var TransactionService = class {
9533
10393
  const processed = yield Promise.all(
9534
10394
  operations.map((op) => this.processOperation(op, accountId))
9535
10395
  );
9536
- for (const { items, events, resultEntry } of processed) {
10396
+ const afterCommits = [];
10397
+ for (const { items, events, afterCommit, resultEntry } of processed) {
9537
10398
  allTransactItems.push(...items);
9538
10399
  pendingEvents.push(...events);
10400
+ if (afterCommit) afterCommits.push(afterCommit);
9539
10401
  resultEntries.push(resultEntry);
9540
10402
  }
9541
10403
  if (allTransactItems.length > MAX_TRANSACTION_ITEMS) {
@@ -9583,8 +10445,53 @@ var TransactionService = class {
9583
10445
  } catch (e) {
9584
10446
  }
9585
10447
  }
10448
+ if (entry.operation === "updateMutual" && this.mutualService) {
10449
+ try {
10450
+ const mutual = yield this.mutualService.getMutual({
10451
+ byEntityType: entry.byEntityType,
10452
+ byEntityId: entry.byEntityId,
10453
+ entityType: entry.entityType,
10454
+ entityId: entry.entityId
10455
+ });
10456
+ entry.mutualId = mutual.mutualId;
10457
+ entry.data = mutual.data;
10458
+ entry.mutualData = mutual.mutualData;
10459
+ entry.createdAt = mutual.createdAt;
10460
+ entry.updatedAt = mutual.updatedAt;
10461
+ entry.mutualUpdatedAt = mutual.mutualUpdatedAt;
10462
+ } catch (e) {
10463
+ }
10464
+ }
9586
10465
  }));
9587
10466
  yield Promise.all(readPromises);
10467
+ const committedEntityData = /* @__PURE__ */ new Map();
10468
+ for (const entry of resultEntries) {
10469
+ if ((entry.operation === "updateEntity" || entry.operation === "adjustEntity") && entry.data) {
10470
+ committedEntityData.set(
10471
+ `${entry.entityType}#${entry.entityId}`,
10472
+ entry.data
10473
+ );
10474
+ }
10475
+ }
10476
+ for (const entry of resultEntries) {
10477
+ if (entry.operation === "createMutual" || entry.operation === "updateMutual") {
10478
+ const fresh = committedEntityData.get(
10479
+ `${entry.entityType}#${entry.entityId}`
10480
+ );
10481
+ if (fresh) entry.data = fresh;
10482
+ }
10483
+ }
10484
+ const afterCommitResults = yield Promise.allSettled(
10485
+ afterCommits.map((run) => run())
10486
+ );
10487
+ for (const result of afterCommitResults) {
10488
+ if (result.status === "rejected") {
10489
+ console.error(
10490
+ "[monorise] Post-commit hook failed after transaction commit:",
10491
+ { reason: result.reason }
10492
+ );
10493
+ }
10494
+ }
9588
10495
  const eventResults = yield Promise.allSettled(
9589
10496
  pendingEvents.map((ev) => this.publishEvent(ev))
9590
10497
  );
@@ -9678,6 +10585,12 @@ var TransactionService = class {
9678
10585
  }
9679
10586
  };
9680
10587
  }
10588
+ case "createMutual":
10589
+ return this.processCreateMutual(op, accountId);
10590
+ case "updateMutual":
10591
+ return this.processUpdateMutual(op, accountId);
10592
+ case "deleteMutual":
10593
+ return this.processDeleteMutual(op, accountId);
9681
10594
  default:
9682
10595
  throw new StandardError(
9683
10596
  StandardErrorCode.TRANSACTION_INVALID_OPERATION,
@@ -9686,6 +10599,171 @@ var TransactionService = class {
9686
10599
  }
9687
10600
  });
9688
10601
  }
10602
+ // Same validation, reads and records as MutualService.createMutual — only
10603
+ // the write is deferred into this transaction. A mutual created here
10604
+ // publishes the same MUTUAL_CREATED event, and an asEntity mutual's
10605
+ // projection is written in the same transaction.
10606
+ processCreateMutual(op, accountId) {
10607
+ return __async(this, null, function* () {
10608
+ var _a, _b;
10609
+ this.assertMutualOperation(op);
10610
+ const mutualPayload = (_a = op.payload) != null ? _a : {};
10611
+ const { mutual, entity, transactItems, parsedMutualPayload } = yield this.requireMutualService(op).prepareCreateMutual({
10612
+ byEntityType: op.byEntityType,
10613
+ byEntityId: op.byEntityId,
10614
+ entityType: op.entityType,
10615
+ entityId: op.entityId,
10616
+ mutualPayload
10617
+ });
10618
+ return {
10619
+ items: transactItems,
10620
+ events: [
10621
+ {
10622
+ event: EVENT.CORE.MUTUAL_CREATED(op.byEntityType, op.entityType),
10623
+ payload: {
10624
+ byEntityType: op.byEntityType,
10625
+ byEntityId: op.byEntityId,
10626
+ entityType: op.entityType,
10627
+ entityId: op.entityId,
10628
+ parsedMutualPayload,
10629
+ accountId,
10630
+ publishedAt: (_b = mutual.createdAt) != null ? _b : (/* @__PURE__ */ new Date()).toISOString()
10631
+ }
10632
+ }
10633
+ ],
10634
+ afterCommit: entity ? () => this.entityServiceLifeCycle.afterCreateEntityHook(
10635
+ entity,
10636
+ mutualPayload,
10637
+ accountId
10638
+ ) : void 0,
10639
+ resultEntry: {
10640
+ operation: "createMutual",
10641
+ byEntityType: op.byEntityType,
10642
+ byEntityId: op.byEntityId,
10643
+ entityType: op.entityType,
10644
+ entityId: op.entityId,
10645
+ mutualId: mutual.mutualId,
10646
+ data: mutual.data,
10647
+ mutualData: mutual.mutualData,
10648
+ createdAt: mutual.createdAt,
10649
+ updatedAt: mutual.updatedAt,
10650
+ mutualUpdatedAt: mutual.mutualUpdatedAt
10651
+ }
10652
+ };
10653
+ });
10654
+ }
10655
+ // Same validation and records as MutualService.updateMutual, and the same
10656
+ // MUTUAL_UPDATED event. The stored values are read back after the commit
10657
+ // (Phase 4), as a standalone PATCH /mutual/... returns them.
10658
+ processUpdateMutual(op, accountId) {
10659
+ return __async(this, null, function* () {
10660
+ this.assertMutualOperation(op);
10661
+ if (!op.payload || typeof op.payload !== "object") {
10662
+ throw new StandardError(
10663
+ StandardErrorCode.TRANSACTION_INVALID_OPERATION,
10664
+ "'updateMutual' requires a payload object"
10665
+ );
10666
+ }
10667
+ const { mutual, TransactItems, parsedMutualPayload } = yield this.requireMutualService(op).prepareUpdateMutual({
10668
+ byEntityType: op.byEntityType,
10669
+ byEntityId: op.byEntityId,
10670
+ entityType: op.entityType,
10671
+ entityId: op.entityId,
10672
+ mutualPayload: op.payload
10673
+ });
10674
+ return {
10675
+ items: TransactItems,
10676
+ events: [
10677
+ {
10678
+ event: EVENT.CORE.MUTUAL_UPDATED(op.byEntityType, op.entityType),
10679
+ payload: {
10680
+ byEntityType: op.byEntityType,
10681
+ byEntityId: op.byEntityId,
10682
+ entityType: op.entityType,
10683
+ entityId: op.entityId,
10684
+ parsedMutualPayload,
10685
+ updatedByAccountId: accountId
10686
+ }
10687
+ }
10688
+ ],
10689
+ resultEntry: {
10690
+ operation: "updateMutual",
10691
+ byEntityType: op.byEntityType,
10692
+ byEntityId: op.byEntityId,
10693
+ entityType: op.entityType,
10694
+ entityId: op.entityId,
10695
+ mutualId: mutual.mutualId
10696
+ }
10697
+ };
10698
+ });
10699
+ }
10700
+ // Same soft delete as MutualService.deleteMutual, and the same event.
10701
+ processDeleteMutual(op, accountId) {
10702
+ return __async(this, null, function* () {
10703
+ this.assertMutualOperation(op);
10704
+ const { mutual, TransactItems } = yield this.requireMutualService(
10705
+ op
10706
+ ).prepareDeleteMutual({
10707
+ byEntityType: op.byEntityType,
10708
+ byEntityId: op.byEntityId,
10709
+ entityType: op.entityType,
10710
+ entityId: op.entityId
10711
+ });
10712
+ return {
10713
+ items: TransactItems,
10714
+ events: [
10715
+ {
10716
+ event: EVENT.CORE.MUTUAL_UPDATED(op.byEntityType, op.entityType),
10717
+ payload: {
10718
+ byEntityType: op.byEntityType,
10719
+ byEntityId: op.byEntityId,
10720
+ entityType: op.entityType,
10721
+ entityId: op.entityId,
10722
+ deletedByAccountId: accountId
10723
+ }
10724
+ }
10725
+ ],
10726
+ resultEntry: {
10727
+ operation: "deleteMutual",
10728
+ byEntityType: op.byEntityType,
10729
+ byEntityId: op.byEntityId,
10730
+ entityType: op.entityType,
10731
+ entityId: op.entityId,
10732
+ mutualId: mutual.mutualId
10733
+ }
10734
+ };
10735
+ });
10736
+ }
10737
+ assertMutualOperation(op) {
10738
+ for (const type of [op.byEntityType, op.entityType]) {
10739
+ if (!this.EntityConfig[type]) {
10740
+ throw new StandardError(
10741
+ StandardErrorCode.INVALID_ENTITY_TYPE,
10742
+ `Unknown entity type: '${type}'`
10743
+ );
10744
+ }
10745
+ }
10746
+ for (const [field, id] of [
10747
+ ["byEntityId", op.byEntityId],
10748
+ ["entityId", op.entityId]
10749
+ ]) {
10750
+ if (typeof id !== "string" || id.length === 0) {
10751
+ throw new StandardError(
10752
+ StandardErrorCode.TRANSACTION_INVALID_OPERATION,
10753
+ `'${op.operation}' requires a non-empty ${field}`
10754
+ );
10755
+ }
10756
+ }
10757
+ }
10758
+ requireMutualService(op) {
10759
+ if (!this.mutualService) {
10760
+ throw new StandardError(
10761
+ StandardErrorCode.TRANSACTION_INVALID_OPERATION,
10762
+ `'${op.operation}' needs a TransactionService constructed with a MutualService`
10763
+ );
10764
+ }
10765
+ return this.mutualService;
10766
+ }
9689
10767
  buildCreateItems(op) {
9690
10768
  return __async(this, null, function* () {
9691
10769
  const config = this.EntityConfig[op.entityType];
@@ -9711,7 +10789,7 @@ var TransactionService = class {
9711
10789
  const currentDatetime = /* @__PURE__ */ new Date();
9712
10790
  const entity = new Entity(
9713
10791
  op.entityType,
9714
- op.entityId || ulid5(),
10792
+ op.entityId || ulid7(),
9715
10793
  parsedPayload,
9716
10794
  currentDatetime,
9717
10795
  currentDatetime
@@ -10063,6 +11141,13 @@ var DependencyContainer = class {
10063
11141
  this.dynamodbClient
10064
11142
  );
10065
11143
  }
11144
+ get websocketRepository() {
11145
+ return this.createCachedInstance(
11146
+ WebSocketRepository,
11147
+ this.coreTable,
11148
+ this.dynamodbClient
11149
+ );
11150
+ }
10066
11151
  get getEntityController() {
10067
11152
  return this.createCachedInstance(
10068
11153
  GetEntityController,
@@ -10155,7 +11240,8 @@ var DependencyContainer = class {
10155
11240
  this.dynamodbClient,
10156
11241
  this.publishEvent,
10157
11242
  this.entityServiceLifeCycle,
10158
- this.eventUtils
11243
+ this.eventUtils,
11244
+ this.mutualService
10159
11245
  );
10160
11246
  }
10161
11247
  get executeTransactionController() {
@@ -10164,6 +11250,9 @@ var DependencyContainer = class {
10164
11250
  this.transactionService
10165
11251
  );
10166
11252
  }
11253
+ get createTicketController() {
11254
+ return this.createCachedInstance(CreateTicketController, this);
11255
+ }
10167
11256
  };
10168
11257
 
10169
11258
  // helpers/transactional.ts
@@ -10198,6 +11287,30 @@ var transactional = {
10198
11287
  operation: "deleteEntity",
10199
11288
  entityType,
10200
11289
  entityId
11290
+ }),
11291
+ // Same argument order as the client's standalone createMutual / editMutual
11292
+ // / deleteMutual.
11293
+ createMutual: (byEntityType, entityType, byEntityId, entityId, payload) => __spreadValues({
11294
+ operation: "createMutual",
11295
+ byEntityType,
11296
+ byEntityId,
11297
+ entityType,
11298
+ entityId
11299
+ }, payload && { payload }),
11300
+ updateMutual: (byEntityType, entityType, byEntityId, entityId, payload) => ({
11301
+ operation: "updateMutual",
11302
+ byEntityType,
11303
+ byEntityId,
11304
+ entityType,
11305
+ entityId,
11306
+ payload
11307
+ }),
11308
+ deleteMutual: (byEntityType, entityType, byEntityId, entityId) => ({
11309
+ operation: "deleteMutual",
11310
+ byEntityType,
11311
+ byEntityId,
11312
+ entityType,
11313
+ entityId
10201
11314
  })
10202
11315
  };
10203
11316
 
@@ -10216,6 +11329,10 @@ var CoreFactory = class {
10216
11329
  this.prejoinProcessor = handler8(dependencyContainer);
10217
11330
  this.tagProcessor = handler10(dependencyContainer);
10218
11331
  this.appHandler = appHandler(dependencyContainer);
11332
+ this.wsConnect = connect(dependencyContainer);
11333
+ this.wsDisconnect = disconnect(dependencyContainer);
11334
+ this.wsDefault = $default(dependencyContainer);
11335
+ this.wsBroadcast = broadcast(dependencyContainer);
10219
11336
  }
10220
11337
  };
10221
11338
  var index_default = CoreFactory;
@@ -10232,6 +11349,7 @@ export {
10232
11349
  StandardErrorCode,
10233
11350
  TagRepository,
10234
11351
  TransactionService,
11352
+ WebSocketRepository,
10235
11353
  handler3 as analyticsBackfillProcessor,
10236
11354
  handler4 as analyticsMaterializationProcessor,
10237
11355
  handler5 as analyticsModelProcessor,
@@ -10247,6 +11365,10 @@ export {
10247
11365
  setupCommonRoutes,
10248
11366
  startBackfill as startAnalyticsBackfill,
10249
11367
  handler10 as tagProcessor,
10250
- transactional
11368
+ transactional,
11369
+ broadcast as wsBroadcast,
11370
+ connect as wsConnect,
11371
+ $default as wsDefault,
11372
+ disconnect as wsDisconnect
10251
11373
  };
10252
11374
  //# sourceMappingURL=index.js.map