monorise 1.5.0 → 1.8.0-dev.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 (72) hide show
  1. package/dist/base/index.d.ts +5 -0
  2. package/dist/base/index.js.map +1 -1
  3. package/dist/cli/cli.js +157 -2
  4. package/dist/cli/cli.js.map +1 -1
  5. package/dist/core/index.d.ts +135 -5
  6. package/dist/core/index.js +1135 -16
  7. package/dist/core/index.js.map +1 -1
  8. package/dist/react/bowser-RUCNDTEX.js +2822 -0
  9. package/dist/react/bowser-RUCNDTEX.js.map +1 -0
  10. package/dist/react/chunk-2U2REJF4.js +138 -0
  11. package/dist/react/chunk-2U2REJF4.js.map +1 -0
  12. package/dist/react/chunk-5CPIG7AN.js +449 -0
  13. package/dist/react/chunk-5CPIG7AN.js.map +1 -0
  14. package/dist/react/chunk-7BSJSLIL.js +528 -0
  15. package/dist/react/chunk-7BSJSLIL.js.map +1 -0
  16. package/dist/react/chunk-7MNBSDJI.js +3362 -0
  17. package/dist/react/chunk-7MNBSDJI.js.map +1 -0
  18. package/dist/react/chunk-JXBFOCBM.js +2929 -0
  19. package/dist/react/chunk-JXBFOCBM.js.map +1 -0
  20. package/dist/react/chunk-MIXAYX55.js +147 -0
  21. package/dist/react/chunk-MIXAYX55.js.map +1 -0
  22. package/dist/react/chunk-Q26JGAFF.js +47 -0
  23. package/dist/react/chunk-Q26JGAFF.js.map +1 -0
  24. package/dist/react/chunk-QZSEUOCY.js +2298 -0
  25. package/dist/react/chunk-QZSEUOCY.js.map +1 -0
  26. package/dist/react/chunk-W6S3JWZV.js +1045 -0
  27. package/dist/react/chunk-W6S3JWZV.js.map +1 -0
  28. package/dist/react/chunk-WUOPYF3V.js +127 -0
  29. package/dist/react/chunk-WUOPYF3V.js.map +1 -0
  30. package/dist/react/chunk-Z45ECZFO.js +995 -0
  31. package/dist/react/chunk-Z45ECZFO.js.map +1 -0
  32. package/dist/react/dist-es-2P6AKQM3.js +325 -0
  33. package/dist/react/dist-es-2P6AKQM3.js.map +1 -0
  34. package/dist/react/dist-es-CEMZ6HT6.js +294 -0
  35. package/dist/react/dist-es-CEMZ6HT6.js.map +1 -0
  36. package/dist/react/dist-es-NZWWHEBR.js +89 -0
  37. package/dist/react/dist-es-NZWWHEBR.js.map +1 -0
  38. package/dist/react/dist-es-QVQ2CPIM.js +376 -0
  39. package/dist/react/dist-es-QVQ2CPIM.js.map +1 -0
  40. package/dist/react/dist-es-VBWII54H.js +70 -0
  41. package/dist/react/dist-es-VBWII54H.js.map +1 -0
  42. package/dist/react/dist-es-VXN7IC3J.js +23 -0
  43. package/dist/react/dist-es-VXN7IC3J.js.map +1 -0
  44. package/dist/react/dist-es-YKVDPOOB.js +221 -0
  45. package/dist/react/dist-es-YKVDPOOB.js.map +1 -0
  46. package/dist/react/dist-es-ZPOY2Z6R.js +178 -0
  47. package/dist/react/dist-es-ZPOY2Z6R.js.map +1 -0
  48. package/dist/react/event-streams-NBH35WQC.js +44 -0
  49. package/dist/react/event-streams-NBH35WQC.js.map +1 -0
  50. package/dist/react/index.d.ts +17 -0
  51. package/dist/react/index.d.ts.map +1 -1
  52. package/dist/react/index.js +25670 -368
  53. package/dist/react/index.js.map +1 -1
  54. package/dist/react/loadSso-2GPAQE3H.js +583 -0
  55. package/dist/react/loadSso-2GPAQE3H.js.map +1 -0
  56. package/dist/react/services/core.service.d.ts +8 -0
  57. package/dist/react/services/core.service.d.ts.map +1 -1
  58. package/dist/react/signin-HT4EDHQE.js +821 -0
  59. package/dist/react/signin-HT4EDHQE.js.map +1 -0
  60. package/dist/react/sso-oidc-WA3BK6FI.js +830 -0
  61. package/dist/react/sso-oidc-WA3BK6FI.js.map +1 -0
  62. package/dist/react/sts-V7PNNQ2L.js +1114 -0
  63. package/dist/react/sts-V7PNNQ2L.js.map +1 -0
  64. package/dist/sst/components/analytics.d.ts +52 -0
  65. package/dist/sst/components/analytics.d.ts.map +1 -0
  66. package/dist/sst/components/monorise-core.d.ts +5 -1
  67. package/dist/sst/components/monorise-core.d.ts.map +1 -1
  68. package/dist/sst/components/single-table.d.ts +3 -1
  69. package/dist/sst/components/single-table.d.ts.map +1 -1
  70. package/dist/sst/index.js +344 -7
  71. package/dist/sst/index.js.map +1 -1
  72. package/package.json +4 -1
@@ -4,6 +4,7 @@ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
4
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
6
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
7
8
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
9
  var __spreadValues = (a, b) => {
9
10
  for (var prop in b || (b = {}))
@@ -53,6 +54,7 @@ var __async = (__this, __arguments, generator) => {
53
54
  step((generator = generator.apply(__this, __arguments)).next());
54
55
  });
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);
56
58
 
57
59
  // controllers/setupRoutes.ts
58
60
  import { Hono } from "hono";
@@ -140,6 +142,7 @@ var setupCommonRoutes = (container) => {
140
142
  container.deleteEntityController.controller
141
143
  );
142
144
  app.get("/tag/:entityType/:tagName", container.listTagsController.controller);
145
+ app.post("/transaction", container.executeTransactionController.controller);
143
146
  return app;
144
147
  };
145
148
 
@@ -188,7 +191,12 @@ var StandardErrorCode = {
188
191
  REPLICATION_ERROR: "REPLICATION_ERROR",
189
192
  RETRYABLE_MUTUAL_LOCK_CONFLICT: "RETRYABLE_MUTUAL_LOCK_CONFLICT",
190
193
  TAG_IS_UNDEFINED: "TAG_IS_UNDEFINED",
194
+ TRANSACTION_EMPTY: "TRANSACTION_EMPTY",
191
195
  TRANSACTION_FAILED: "TRANSACTION_FAILED",
196
+ TRANSACTION_INVALID_OPERATION: "TRANSACTION_INVALID_OPERATION",
197
+ TRANSACTION_ITEM_LIMIT_EXCEEDED: "TRANSACTION_ITEM_LIMIT_EXCEEDED",
198
+ TRANSACTION_UNIQUE_FIELD_UPDATE: "TRANSACTION_UNIQUE_FIELD_UPDATE",
199
+ TRANSACTION_VALIDATION_ERROR: "TRANSACTION_VALIDATION_ERROR",
192
200
  UNIQUE_VALUE_EXISTS: "UNIQUE_VALUE_EXISTS"
193
201
  };
194
202
 
@@ -2343,12 +2351,544 @@ var handler = (container) => (ev) => __async(null, null, function* () {
2343
2351
  return { batchItemFailures };
2344
2352
  });
2345
2353
 
2354
+ // processors/analytics-processor.ts
2355
+ import {
2356
+ FirehoseClient,
2357
+ PutRecordBatchCommand
2358
+ } from "@aws-sdk/client-firehose";
2359
+ import { unmarshall as unmarshall4 } from "@aws-sdk/util-dynamodb";
2360
+ var firehose = new FirehoseClient();
2361
+ function encodeAnalyticsEvent(event) {
2362
+ return {
2363
+ event_id: event.eventId,
2364
+ idempotency_key: event.idempotencyKey,
2365
+ ordering_key: event.orderingKey,
2366
+ sequence_number: event.sequenceNumber,
2367
+ operation: event.operation,
2368
+ occurred_at: event.occurredAt,
2369
+ dataset: event.dataset,
2370
+ kind: event.kind,
2371
+ path: event.path,
2372
+ before: event.before ? JSON.stringify(event.before) : void 0,
2373
+ after: event.after ? JSON.stringify(event.after) : void 0
2374
+ };
2375
+ }
2376
+ function omitTopLevelFields(value, fields) {
2377
+ if (!value) return value;
2378
+ return Object.fromEntries(
2379
+ Object.entries(value).filter(([key]) => !fields.has(key))
2380
+ );
2381
+ }
2382
+ function sanitizeItem(item, omittedFields) {
2383
+ if (!item) return item;
2384
+ return __spreadProps(__spreadValues({}, item), {
2385
+ data: omitTopLevelFields(
2386
+ item.data,
2387
+ omittedFields
2388
+ ),
2389
+ mutualData: omitTopLevelFields(
2390
+ item.mutualData,
2391
+ omittedFields
2392
+ )
2393
+ });
2394
+ }
2395
+ function parseAnalyticsManifest() {
2396
+ const raw = process.env.ANALYTICS_MANIFEST;
2397
+ if (!raw) throw new Error("ANALYTICS_MANIFEST is required.");
2398
+ return JSON.parse(raw);
2399
+ }
2400
+ function datasetForRecord(record, manifest2, config) {
2401
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2402
+ const image = (_c = (_a = record.dynamodb) == null ? void 0 : _a.NewImage) != null ? _c : (_b = record.dynamodb) == null ? void 0 : _b.OldImage;
2403
+ if (!((_d = image == null ? void 0 : image.PK) == null ? void 0 : _d.S) || ((_e = image.SK) == null ? void 0 : _e.S) !== "#METADATA#") return void 0;
2404
+ if (!image.PK.S.startsWith("MUTUAL#")) {
2405
+ const entityType = (_f = image.entityType) == null ? void 0 : _f.S;
2406
+ const dataset = manifest2.datasets.find(
2407
+ (candidate) => candidate.kind === "entity" && candidate.name === entityType
2408
+ );
2409
+ return dataset && {
2410
+ name: dataset.name,
2411
+ kind: dataset.kind,
2412
+ granularity: dataset.partition.granularity
2413
+ };
2414
+ }
2415
+ const item = unmarshall4(image);
2416
+ const pair = [item.byEntityType, item.entityType].sort().join("::");
2417
+ for (const entityConfig of Object.values(config)) {
2418
+ for (const field of Object.values(
2419
+ (_h = (_g = entityConfig.mutual) == null ? void 0 : _g.mutualFields) != null ? _h : {}
2420
+ )) {
2421
+ const mutual = field.mutual;
2422
+ if (!(mutual == null ? void 0 : mutual.name)) continue;
2423
+ if ([entityConfig.name, field.entityType].sort().join("::") !== pair) continue;
2424
+ const dataset = manifest2.datasets.find(
2425
+ (candidate) => candidate.kind === "mutual" && candidate.name === mutual.name
2426
+ );
2427
+ return dataset && {
2428
+ name: dataset.name,
2429
+ kind: dataset.kind,
2430
+ granularity: dataset.partition.granularity
2431
+ };
2432
+ }
2433
+ }
2434
+ }
2435
+ var handler2 = (config) => (event) => __async(null, null, function* () {
2436
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
2437
+ const streamName = process.env.ANALYTICS_DELIVERY_STREAM;
2438
+ if (!streamName) throw new Error("ANALYTICS_DELIVERY_STREAM is required.");
2439
+ const manifest2 = parseAnalyticsManifest();
2440
+ const omittedFields = new Set(
2441
+ JSON.parse((_a = process.env.ANALYTICS_OMIT_FIELDS) != null ? _a : "[]")
2442
+ );
2443
+ const failures = [];
2444
+ const events = [];
2445
+ for (const record of event.Records) {
2446
+ try {
2447
+ const dataset = datasetForRecord(record, manifest2, config);
2448
+ if (!dataset || !record.eventName || !record.eventID) continue;
2449
+ const occurredAt = new Date(
2450
+ Number(
2451
+ (_c = (_b = record.dynamodb) == null ? void 0 : _b.ApproximateCreationDateTime) != null ? _c : Date.now() / 1e3
2452
+ ) * 1e3
2453
+ );
2454
+ const eventDate = occurredAt.toISOString().slice(0, 10);
2455
+ const eventHour = occurredAt.toISOString().slice(11, 13);
2456
+ const path = `${dataset.kind === "entity" ? "entities" : "mutuals"}/${dataset.name}/event_date=${eventDate}${dataset.granularity === "hour" ? `/event_hour=${eventHour}` : ""}`;
2457
+ events.push({
2458
+ record,
2459
+ event: {
2460
+ eventId: record.eventID,
2461
+ idempotencyKey: record.eventID,
2462
+ orderingKey: (_e = (_d = record.dynamodb) == null ? void 0 : _d.SequenceNumber) != null ? _e : record.eventID,
2463
+ sequenceNumber: (_f = record.dynamodb) == null ? void 0 : _f.SequenceNumber,
2464
+ operation: record.eventName,
2465
+ occurredAt: occurredAt.toISOString(),
2466
+ dataset: dataset.name,
2467
+ kind: dataset.kind,
2468
+ path,
2469
+ before: sanitizeItem(
2470
+ ((_g = record.dynamodb) == null ? void 0 : _g.OldImage) ? unmarshall4(record.dynamodb.OldImage) : void 0,
2471
+ omittedFields
2472
+ ),
2473
+ after: sanitizeItem(
2474
+ ((_h = record.dynamodb) == null ? void 0 : _h.NewImage) ? unmarshall4(record.dynamodb.NewImage) : void 0,
2475
+ omittedFields
2476
+ )
2477
+ }
2478
+ });
2479
+ } catch (error) {
2480
+ console.error("Unable to normalize analytics stream record", error);
2481
+ failures.push({ itemIdentifier: (_j = (_i = record.dynamodb) == null ? void 0 : _i.SequenceNumber) != null ? _j : "" });
2482
+ }
2483
+ }
2484
+ for (let index = 0; index < events.length; index += 500) {
2485
+ const batch = events.slice(index, index + 500);
2486
+ const result = yield firehose.send(
2487
+ new PutRecordBatchCommand({
2488
+ DeliveryStreamName: streamName,
2489
+ Records: batch.map(({ event: value }) => ({
2490
+ Data: Buffer.from(`${JSON.stringify(encodeAnalyticsEvent(value))}
2491
+ `)
2492
+ }))
2493
+ })
2494
+ );
2495
+ (_k = result.RequestResponses) == null ? void 0 : _k.forEach((response, responseIndex) => {
2496
+ var _a2, _b2, _c2;
2497
+ if (!response.ErrorCode) return;
2498
+ failures.push({
2499
+ itemIdentifier: (_c2 = (_b2 = (_a2 = batch[responseIndex]) == null ? void 0 : _a2.record.dynamodb) == null ? void 0 : _b2.SequenceNumber) != null ? _c2 : ""
2500
+ });
2501
+ });
2502
+ }
2503
+ return { batchItemFailures: failures };
2504
+ });
2505
+
2506
+ // processors/analytics-backfill-processor.ts
2507
+ import {
2508
+ DeleteItemCommand,
2509
+ DynamoDBClient,
2510
+ ExportTableToPointInTimeCommand,
2511
+ GetItemCommand,
2512
+ PutItemCommand,
2513
+ UpdateItemCommand
2514
+ } from "@aws-sdk/client-dynamodb";
2515
+ import { FirehoseClient as FirehoseClient2, PutRecordBatchCommand as PutRecordBatchCommand2 } from "@aws-sdk/client-firehose";
2516
+ import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";
2517
+ import { marshall as marshall5, unmarshall as unmarshall5 } from "@aws-sdk/util-dynamodb";
2518
+ import { gunzipSync } from "zlib";
2519
+ var dynamodb = new DynamoDBClient();
2520
+ var firehose2 = new FirehoseClient2();
2521
+ var s3 = new S3Client();
2522
+ var backfillMarker = { PK: "#ANALYTICS#", SK: "#BACKFILL#" };
2523
+ function required(name) {
2524
+ const value = process.env[name];
2525
+ if (!value) throw new Error(`${name} is required.`);
2526
+ return value;
2527
+ }
2528
+ function exportTimestamp() {
2529
+ const value = process.env.ANALYTICS_EXPORT_TIME;
2530
+ const timestamp = value ? new Date(value) : /* @__PURE__ */ new Date();
2531
+ if (Number.isNaN(timestamp.getTime())) {
2532
+ throw new Error("ANALYTICS_EXPORT_TIME must be an ISO-8601 timestamp.");
2533
+ }
2534
+ return timestamp;
2535
+ }
2536
+ function startBackfill(reconcile = false) {
2537
+ return __async(this, null, function* () {
2538
+ var _a, _b, _c;
2539
+ const timestamp = exportTimestamp();
2540
+ const tableName = required("ANALYTICS_BACKFILL_MARKER_TABLE");
2541
+ const marker = marshall5(__spreadProps(__spreadValues({}, backfillMarker), { exportTime: timestamp.toISOString(), state: "starting" }));
2542
+ let createdMarker = false;
2543
+ try {
2544
+ yield dynamodb.send(new PutItemCommand({ TableName: tableName, Item: marker, ConditionExpression: "attribute_not_exists(PK)" }));
2545
+ createdMarker = true;
2546
+ } catch (error) {
2547
+ if (error.name !== "ConditionalCheckFailedException") throw error;
2548
+ if (reconcile) {
2549
+ yield dynamodb.send(new UpdateItemCommand({
2550
+ TableName: tableName,
2551
+ Key: marshall5(backfillMarker),
2552
+ UpdateExpression: "SET exportTime = :exportTime, #state = :state REMOVE exportArn",
2553
+ ExpressionAttributeNames: { "#state": "state" },
2554
+ ExpressionAttributeValues: marshall5({ ":exportTime": timestamp.toISOString(), ":state": "starting" })
2555
+ }));
2556
+ } else {
2557
+ const existing = yield dynamodb.send(new GetItemCommand({ TableName: tableName, Key: marshall5(backfillMarker), ConsistentRead: true }));
2558
+ const value = existing.Item ? unmarshall5(existing.Item) : {};
2559
+ return { exportArn: value.exportArn, exportTime: value.exportTime, started: false };
2560
+ }
2561
+ }
2562
+ let result;
2563
+ try {
2564
+ result = yield dynamodb.send(new ExportTableToPointInTimeCommand({
2565
+ TableArn: required("ANALYTICS_TABLE_ARN"),
2566
+ S3Bucket: required("ANALYTICS_BACKFILL_BUCKET"),
2567
+ S3Prefix: (_a = process.env.ANALYTICS_BACKFILL_PREFIX) != null ? _a : "backfill",
2568
+ ExportTime: timestamp,
2569
+ ExportFormat: "DYNAMODB_JSON"
2570
+ }));
2571
+ } catch (error) {
2572
+ if (createdMarker) {
2573
+ yield dynamodb.send(new DeleteItemCommand({
2574
+ TableName: tableName,
2575
+ Key: marshall5(backfillMarker),
2576
+ ConditionExpression: "exportTime = :exportTime",
2577
+ ExpressionAttributeValues: marshall5({ ":exportTime": timestamp.toISOString() })
2578
+ }));
2579
+ } else {
2580
+ yield dynamodb.send(new UpdateItemCommand({
2581
+ TableName: tableName,
2582
+ Key: marshall5(backfillMarker),
2583
+ UpdateExpression: "SET #state = :state",
2584
+ ConditionExpression: "exportTime = :exportTime",
2585
+ ExpressionAttributeNames: { "#state": "state" },
2586
+ ExpressionAttributeValues: marshall5({ ":state": "failed", ":exportTime": timestamp.toISOString() })
2587
+ }));
2588
+ }
2589
+ throw error;
2590
+ }
2591
+ yield dynamodb.send(new UpdateItemCommand({
2592
+ TableName: tableName,
2593
+ Key: marshall5(backfillMarker),
2594
+ UpdateExpression: "SET #state = :state, exportArn = :exportArn",
2595
+ ConditionExpression: "exportTime = :exportTime",
2596
+ ExpressionAttributeNames: { "#state": "state" },
2597
+ ExpressionAttributeValues: marshall5({ ":state": "started", ":exportArn": (_b = result.ExportDescription) == null ? void 0 : _b.ExportArn, ":exportTime": timestamp.toISOString() }, { removeUndefinedValues: true })
2598
+ }));
2599
+ return { exportArn: (_c = result.ExportDescription) == null ? void 0 : _c.ExportArn, exportTime: timestamp.toISOString(), started: true };
2600
+ });
2601
+ }
2602
+ function backfillTimestamp() {
2603
+ return __async(this, null, function* () {
2604
+ const tableName = process.env.ANALYTICS_BACKFILL_MARKER_TABLE;
2605
+ if (!tableName) return exportTimestamp();
2606
+ const result = yield dynamodb.send(new GetItemCommand({ TableName: tableName, Key: marshall5(backfillMarker), ConsistentRead: true }));
2607
+ const value = result.Item ? unmarshall5(result.Item).exportTime : void 0;
2608
+ if (typeof value !== "string") throw new Error("Analytics backfill marker is missing its export timestamp.");
2609
+ const timestamp = new Date(value);
2610
+ if (Number.isNaN(timestamp.getTime())) throw new Error("Analytics backfill marker has an invalid export timestamp.");
2611
+ return timestamp;
2612
+ });
2613
+ }
2614
+ function streamToBuffer(stream) {
2615
+ return (() => __async(null, null, function* () {
2616
+ const chunks = [];
2617
+ try {
2618
+ for (var iter = __forAwait(stream), more, temp, error; more = !(temp = yield iter.next()).done; more = false) {
2619
+ const chunk = temp.value;
2620
+ chunks.push(chunk);
2621
+ }
2622
+ } catch (temp) {
2623
+ error = [temp];
2624
+ } finally {
2625
+ try {
2626
+ more && (temp = iter.return) && (yield temp.call(iter));
2627
+ } finally {
2628
+ if (error)
2629
+ throw error[0];
2630
+ }
2631
+ }
2632
+ return Buffer.concat(chunks);
2633
+ }))();
2634
+ }
2635
+ function snapshotEvent(item, config, occurredAt, omittedFields) {
2636
+ const attributes = marshall5(item, { removeUndefinedValues: true });
2637
+ const dataset = datasetForRecord({ dynamodb: { NewImage: attributes } }, parseAnalyticsManifest(), config);
2638
+ if (!dataset) return void 0;
2639
+ const after = sanitizeItem(item, omittedFields);
2640
+ const key = `${String(item.PK)}:${String(item.SK)}`;
2641
+ const path = `${dataset.kind === "entity" ? "entities" : "mutuals"}/${dataset.name}/event_date=${occurredAt.toISOString().slice(0, 10)}${dataset.granularity === "hour" ? `/event_hour=${occurredAt.toISOString().slice(11, 13)}` : ""}`;
2642
+ return {
2643
+ eventId: `snapshot:${key}:${occurredAt.toISOString()}`,
2644
+ idempotencyKey: `snapshot:${key}:${occurredAt.toISOString()}`,
2645
+ orderingKey: occurredAt.toISOString(),
2646
+ operation: "SNAPSHOT",
2647
+ occurredAt: occurredAt.toISOString(),
2648
+ dataset: dataset.name,
2649
+ kind: dataset.kind,
2650
+ path,
2651
+ after
2652
+ };
2653
+ }
2654
+ var handler3 = (config) => (event) => __async(null, null, function* () {
2655
+ var _a;
2656
+ if (!("Records" in event)) {
2657
+ if (event.action === "start") return startBackfill();
2658
+ if (event.action === "reconcile") return startBackfill(true);
2659
+ throw new Error("Unsupported analytics backfill event.");
2660
+ }
2661
+ const timestamp = yield backfillTimestamp();
2662
+ const omittedFields = new Set(JSON.parse((_a = process.env.ANALYTICS_OMIT_FIELDS) != null ? _a : "[]"));
2663
+ const deliveryStream = required("ANALYTICS_DELIVERY_STREAM");
2664
+ let delivered = 0;
2665
+ for (const record of event.Records) {
2666
+ const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, " "));
2667
+ if (!key.endsWith(".json.gz")) continue;
2668
+ const response = yield s3.send(new GetObjectCommand({ Bucket: record.s3.bucket.name, Key: key }));
2669
+ if (!response.Body) throw new Error(`Backfill export object ${key} has no body.`);
2670
+ const content = gunzipSync(yield streamToBuffer(response.Body)).toString("utf8");
2671
+ const events = content.split("\n").filter(Boolean).flatMap((line) => {
2672
+ const attributes = JSON.parse(line).Item;
2673
+ return attributes ? [snapshotEvent(unmarshall5(attributes), config, timestamp, omittedFields)].filter(Boolean) : [];
2674
+ });
2675
+ for (let index = 0; index < events.length; index += 500) {
2676
+ const batch = events.slice(index, index + 500);
2677
+ const result = yield firehose2.send(new PutRecordBatchCommand2({ DeliveryStreamName: deliveryStream, Records: batch.map((value) => ({ Data: Buffer.from(`${JSON.stringify(encodeAnalyticsEvent(value))}
2678
+ `) })) }));
2679
+ if (result.FailedPutCount) throw new Error(`Failed to deliver ${result.FailedPutCount} backfill records; retry this export object.`);
2680
+ delivered += batch.length;
2681
+ }
2682
+ }
2683
+ return { delivered, exportTime: timestamp.toISOString() };
2684
+ });
2685
+
2686
+ // processors/analytics-materialization-processor.ts
2687
+ import {
2688
+ AthenaClient,
2689
+ GetQueryExecutionCommand,
2690
+ GetQueryResultsCommand,
2691
+ StartQueryExecutionCommand
2692
+ } from "@aws-sdk/client-athena";
2693
+ var athena = new AthenaClient();
2694
+ function required2(name) {
2695
+ const value = process.env[name];
2696
+ if (!value) throw new Error(`${name} is required.`);
2697
+ return value;
2698
+ }
2699
+ function quoteIdentifier(identifier) {
2700
+ return `"${identifier.replaceAll('"', '""')}"`;
2701
+ }
2702
+ function quoteLiteral(value) {
2703
+ return `'${value.replaceAll("'", "''")}'`;
2704
+ }
2705
+ function manifest() {
2706
+ return JSON.parse(required2("ANALYTICS_MANIFEST"));
2707
+ }
2708
+ function valueExpression(column, kind) {
2709
+ const payload = "coalesce(after, before)";
2710
+ const path = `$.${kind === "mutual" ? "mutualData" : "data"}.${column.sourceName.replaceAll('"', '\\"')}`;
2711
+ const scalar = `json_extract_scalar(payload, ${quoteLiteral(path)})`;
2712
+ switch (column.type) {
2713
+ case "boolean":
2714
+ return `try_cast(${scalar} AS boolean)`;
2715
+ case "double":
2716
+ return `try_cast(${scalar} AS double)`;
2717
+ case "timestamp":
2718
+ return `try_cast(from_iso8601_timestamp(${scalar}) AS timestamp)`;
2719
+ case "json":
2720
+ return `json_format(json_extract(payload, ${quoteLiteral(path)}))`;
2721
+ default:
2722
+ return scalar;
2723
+ }
2724
+ }
2725
+ function datasetSql(dataset, database, bucket) {
2726
+ var _a;
2727
+ const history = `${quoteIdentifier(database)}.${quoteIdentifier(dataset.historyTable)}`;
2728
+ const current = `${quoteIdentifier(database)}.${quoteIdentifier(dataset.currentTable)}`;
2729
+ const raw = `${quoteIdentifier(database)}.${quoteIdentifier((_a = dataset.rawTable) != null ? _a : `${dataset.historyTable}_raw`)}`;
2730
+ const typedColumns = dataset.columns.map(
2731
+ (column) => `${quoteIdentifier(column.name)} ${column.type === "json" ? "varchar" : column.type}`
2732
+ );
2733
+ const names = dataset.columns.map((column) => quoteIdentifier(column.name));
2734
+ const values = dataset.columns.map(
2735
+ (column) => valueExpression(column, dataset.kind)
2736
+ );
2737
+ const payload = "coalesce(after, before)";
2738
+ const recordIdPath = dataset.kind === "entity" ? "$.entityId" : "$.mutualId";
2739
+ const selected = [
2740
+ "event_id",
2741
+ "idempotency_key",
2742
+ "ordering_key",
2743
+ "sequence_number",
2744
+ "operation",
2745
+ "try_cast(from_iso8601_timestamp(occurred_at) AS timestamp) AS occurred_at",
2746
+ `json_extract_scalar(${payload}, ${quoteLiteral(recordIdPath)}) AS record_id`,
2747
+ "before AS before_json",
2748
+ "after AS after_json",
2749
+ ...values.map((value, index) => `${value} AS ${names[index]}`)
2750
+ ];
2751
+ const allColumns = [
2752
+ "event_id varchar",
2753
+ "idempotency_key varchar",
2754
+ "ordering_key varchar",
2755
+ "sequence_number varchar",
2756
+ "operation varchar",
2757
+ "occurred_at timestamp",
2758
+ "record_id varchar",
2759
+ "before_json varchar",
2760
+ "after_json varchar",
2761
+ ...typedColumns
2762
+ ];
2763
+ const historyNames = [
2764
+ "event_id",
2765
+ "idempotency_key",
2766
+ "ordering_key",
2767
+ "sequence_number",
2768
+ "operation",
2769
+ "occurred_at",
2770
+ "record_id",
2771
+ "before_json",
2772
+ "after_json",
2773
+ ...names
2774
+ ].map(quoteIdentifier).join(", ");
2775
+ const insertValues = [
2776
+ "s.event_id",
2777
+ "s.idempotency_key",
2778
+ "s.ordering_key",
2779
+ "s.sequence_number",
2780
+ "s.operation",
2781
+ "s.occurred_at",
2782
+ "s.record_id",
2783
+ "s.before_json",
2784
+ "s.after_json",
2785
+ ...names.map((name) => `s.${name}`)
2786
+ ].join(", ");
2787
+ return [
2788
+ `CREATE TABLE IF NOT EXISTS ${history} (${allColumns.join(", ")}) LOCATION ${quoteLiteral(`s3://${bucket}/curated/history/${dataset.kind === "entity" ? "entities" : "mutuals"}/${dataset.name}/`)} TBLPROPERTIES ('table_type'='ICEBERG')`,
2789
+ `MERGE INTO ${history} h USING (SELECT * FROM (SELECT ${selected.join(", ")}, row_number() OVER (PARTITION BY event_id ORDER BY ordering_key DESC) AS row_number FROM ${raw}) WHERE row_number = 1) s ON h.event_id = s.event_id WHEN NOT MATCHED THEN INSERT (${historyNames}) VALUES (${insertValues})`,
2790
+ `CREATE TABLE IF NOT EXISTS ${current} (${allColumns.filter((column) => !column.startsWith("event_id ") && !column.startsWith("idempotency_key ") && !column.startsWith("sequence_number ") && !column.startsWith("before_json ") && !column.startsWith("after_json ")).join(", ")}) LOCATION ${quoteLiteral(`s3://${bucket}/current/${dataset.name}/`)} TBLPROPERTIES ('table_type'='ICEBERG')`,
2791
+ `MERGE INTO ${current} c USING (SELECT * FROM (SELECT h.*, row_number() OVER (PARTITION BY record_id ORDER BY occurred_at DESC, ordering_key DESC) AS row_number FROM ${history} h) WHERE row_number = 1) s ON c.record_id = s.record_id WHEN MATCHED AND s.operation = 'REMOVE' THEN DELETE WHEN MATCHED THEN UPDATE SET operation = s.operation, occurred_at = s.occurred_at, ordering_key = s.ordering_key${names.map((name) => `, ${name} = s.${name}`).join("")} WHEN NOT MATCHED AND s.operation <> 'REMOVE' THEN INSERT (operation, occurred_at, ordering_key, record_id${names.length ? `, ${names.join(", ")}` : ""}) VALUES (s.operation, s.occurred_at, s.ordering_key, s.record_id${names.length ? `, ${names.map((name) => `s.${name}`).join(", ")}` : ""})`
2792
+ ];
2793
+ }
2794
+ function execute(statement) {
2795
+ return __async(this, null, function* () {
2796
+ var _a, _b;
2797
+ const started = yield athena.send(
2798
+ new StartQueryExecutionCommand({
2799
+ QueryString: statement,
2800
+ WorkGroup: required2("ANALYTICS_WORKGROUP"),
2801
+ QueryExecutionContext: { Database: required2("ANALYTICS_DATABASE") },
2802
+ ResultConfiguration: {
2803
+ OutputLocation: required2("ANALYTICS_ATHENA_OUTPUT")
2804
+ }
2805
+ })
2806
+ );
2807
+ if (!started.QueryExecutionId)
2808
+ throw new Error("Athena did not return a query execution id.");
2809
+ for (; ; ) {
2810
+ const status = (_a = (yield athena.send(
2811
+ new GetQueryExecutionCommand({
2812
+ QueryExecutionId: started.QueryExecutionId
2813
+ })
2814
+ )).QueryExecution) == null ? void 0 : _a.Status;
2815
+ if ((status == null ? void 0 : status.State) === "SUCCEEDED") return started.QueryExecutionId;
2816
+ if ((status == null ? void 0 : status.State) === "FAILED" || (status == null ? void 0 : status.State) === "CANCELLED") {
2817
+ throw new Error(
2818
+ `Athena materialization query ${started.QueryExecutionId} ${status.State}: ${(_b = status.StateChangeReason) != null ? _b : "no reason provided"}`
2819
+ );
2820
+ }
2821
+ yield new Promise((resolve) => setTimeout(resolve, 1e3));
2822
+ }
2823
+ });
2824
+ }
2825
+ function tableColumns(database, table) {
2826
+ return __async(this, null, function* () {
2827
+ var _a, _b;
2828
+ const queryExecutionId = yield execute(
2829
+ `SELECT column_name FROM information_schema.columns WHERE table_schema = ${quoteLiteral(database)} AND table_name = ${quoteLiteral(table)}`
2830
+ );
2831
+ const result = yield athena.send(
2832
+ new GetQueryResultsCommand({ QueryExecutionId: queryExecutionId })
2833
+ );
2834
+ return new Set(
2835
+ ((_b = (_a = result.ResultSet) == null ? void 0 : _a.Rows) != null ? _b : []).slice(1).map((row) => {
2836
+ var _a2, _b2;
2837
+ return (_b2 = (_a2 = row.Data) == null ? void 0 : _a2[0]) == null ? void 0 : _b2.VarCharValue;
2838
+ }).filter((name) => Boolean(name))
2839
+ );
2840
+ });
2841
+ }
2842
+ function addMissingColumns(database, table, columns) {
2843
+ return __async(this, null, function* () {
2844
+ const existing = yield tableColumns(database, table);
2845
+ const missing = columns.filter(
2846
+ (column) => {
2847
+ var _a, _b;
2848
+ return !existing.has(
2849
+ (_b = (_a = column.match(/^"((?:[^"]|"")+)"/)) == null ? void 0 : _a[1].replaceAll('""', '"')) != null ? _b : ""
2850
+ );
2851
+ }
2852
+ );
2853
+ if (missing.length)
2854
+ yield execute(
2855
+ `ALTER TABLE ${quoteIdentifier(database)}.${quoteIdentifier(table)} ADD COLUMNS (${missing.join(", ")})`
2856
+ );
2857
+ });
2858
+ }
2859
+ var handler4 = () => __async(null, null, function* () {
2860
+ const database = required2("ANALYTICS_DATABASE");
2861
+ const bucket = required2("ANALYTICS_BUCKET");
2862
+ for (const dataset of manifest().datasets) {
2863
+ const statements = datasetSql(dataset, database, bucket);
2864
+ yield execute(statements[0]);
2865
+ yield addMissingColumns(
2866
+ database,
2867
+ dataset.historyTable,
2868
+ dataset.columns.map(
2869
+ (column) => `${quoteIdentifier(column.name)} ${column.type === "json" ? "varchar" : column.type}`
2870
+ )
2871
+ );
2872
+ yield execute(statements[2]);
2873
+ yield addMissingColumns(
2874
+ database,
2875
+ dataset.currentTable,
2876
+ dataset.columns.map(
2877
+ (column) => `${quoteIdentifier(column.name)} ${column.type === "json" ? "varchar" : column.type}`
2878
+ )
2879
+ );
2880
+ for (const statement of [statements[1], statements[3]]) {
2881
+ yield execute(statement);
2882
+ }
2883
+ }
2884
+ });
2885
+
2346
2886
  // processors/mutual-processor.ts
2347
2887
  import { TransactionCanceledException as TransactionCanceledException3 } from "@aws-sdk/client-dynamodb";
2348
2888
  var processEntities = (entityIds, action) => __async(null, null, function* () {
2349
2889
  return Promise.allSettled(entityIds.map(action));
2350
2890
  });
2351
- var handler2 = (container) => (ev) => __async(null, null, function* () {
2891
+ var handler5 = (container) => (ev) => __async(null, null, function* () {
2352
2892
  const batchItemFailures = [];
2353
2893
  const { entityRepository, mutualRepository, publishEvent: publishEvent2 } = container;
2354
2894
  yield Promise.allSettled(
@@ -2689,7 +3229,7 @@ function publishToSubscribers(_0) {
2689
3229
  );
2690
3230
  });
2691
3231
  }
2692
- var handler3 = (container) => (ev) => __async(null, null, function* () {
3232
+ var handler6 = (container) => (ev) => __async(null, null, function* () {
2693
3233
  var _a, _b, _c, _d, _e, _f, _g, _h;
2694
3234
  const batchItemFailures = [];
2695
3235
  const { mutualRepository, publishEvent: publishEvent2 } = container;
@@ -2742,7 +3282,7 @@ var handler3 = (container) => (ev) => __async(null, null, function* () {
2742
3282
 
2743
3283
  // processors/replication-processor.ts
2744
3284
  import { ConditionalCheckFailedException as ConditionalCheckFailedException2 } from "@aws-sdk/client-dynamodb";
2745
- var handler4 = (container) => (event) => __async(null, null, function* () {
3285
+ var handler7 = (container) => (event) => __async(null, null, function* () {
2746
3286
  var _a, _b, _c, _d, _e, _f, _g;
2747
3287
  const TableName = process.env.DDB_TABLE || container.coreTable;
2748
3288
  const batchItemFailures = [];
@@ -3006,7 +3546,7 @@ function batchUpdateTags(_0) {
3006
3546
  yield Promise.all(addPromises);
3007
3547
  });
3008
3548
  }
3009
- var handler5 = (container) => (ev) => __async(null, null, function* () {
3549
+ var handler8 = (container) => (ev) => __async(null, null, function* () {
3010
3550
  var _a;
3011
3551
  const batchItemFailures = [];
3012
3552
  for (const record of ev.Records) {
@@ -7720,10 +8260,10 @@ var UpdateMutualController = class {
7720
8260
  };
7721
8261
 
7722
8262
  // services/entity.service.ts
7723
- import { marshall as marshall6 } from "@aws-sdk/util-dynamodb";
8263
+ import { marshall as marshall7 } from "@aws-sdk/util-dynamodb";
7724
8264
 
7725
8265
  // data/utils/build-condition-expression.ts
7726
- import { marshall as marshall5 } from "@aws-sdk/util-dynamodb";
8266
+ import { marshall as marshall6 } from "@aws-sdk/util-dynamodb";
7727
8267
  function buildConditionExpression(where) {
7728
8268
  const conditions = ["attribute_exists(PK)"];
7729
8269
  const expressionAttributeNames = { "#data": "data" };
@@ -7779,7 +8319,7 @@ function buildConditionExpression(where) {
7779
8319
  return {
7780
8320
  ConditionExpression: conditions.join(" AND "),
7781
8321
  ExpressionAttributeNames: expressionAttributeNames,
7782
- ExpressionAttributeValues: marshall5(expressionAttributeValues)
8322
+ ExpressionAttributeValues: marshall6(expressionAttributeValues)
7783
8323
  };
7784
8324
  }
7785
8325
 
@@ -8112,7 +8652,7 @@ var EntityService = class {
8112
8652
  return {
8113
8653
  ConditionExpression: conditionParts.join(" AND "),
8114
8654
  ExpressionAttributeNames: names,
8115
- ExpressionAttributeValues: marshall6(values)
8655
+ ExpressionAttributeValues: marshall7(values)
8116
8656
  };
8117
8657
  }
8118
8658
  };
@@ -8416,6 +8956,68 @@ var ListTagsController = class {
8416
8956
  }
8417
8957
  };
8418
8958
 
8959
+ // controllers/transaction/execute-transaction.controller.ts
8960
+ import { createMiddleware as createMiddleware17 } from "hono/factory";
8961
+ import httpStatus15 from "http-status";
8962
+ var ExecuteTransactionController = class {
8963
+ constructor(transactionService) {
8964
+ this.transactionService = transactionService;
8965
+ // biome-ignore lint/suspicious/noExplicitAny: Hono createMiddleware requires consistent return types
8966
+ this.controller = createMiddleware17((c) => __async(this, null, function* () {
8967
+ var _a;
8968
+ const accountId = c.req.header("account-id") || "";
8969
+ try {
8970
+ const body = yield c.req.json();
8971
+ if (!body.operations || !Array.isArray(body.operations)) {
8972
+ c.status(httpStatus15.BAD_REQUEST);
8973
+ return c.json({
8974
+ code: "API_VALIDATION_ERROR",
8975
+ message: 'Request body must contain an "operations" array'
8976
+ });
8977
+ }
8978
+ const result = yield this.transactionService.executeTransaction(
8979
+ body.operations,
8980
+ accountId
8981
+ );
8982
+ c.status(httpStatus15.OK);
8983
+ return c.json(result);
8984
+ } catch (err) {
8985
+ if (((_a = err.constructor) == null ? void 0 : _a.name) === "ZodError") {
8986
+ c.status(httpStatus15.BAD_REQUEST);
8987
+ return c.json({
8988
+ code: "API_VALIDATION_ERROR",
8989
+ message: "Validation failed",
8990
+ details: err.flatten()
8991
+ });
8992
+ }
8993
+ if (err instanceof SyntaxError) {
8994
+ c.status(httpStatus15.BAD_REQUEST);
8995
+ return c.json({
8996
+ code: "API_VALIDATION_ERROR",
8997
+ message: "Request body must be valid JSON"
8998
+ });
8999
+ }
9000
+ if (err instanceof StandardError) {
9001
+ const code = err.code;
9002
+ if (code === StandardErrorCode.ENTITY_IS_UNDEFINED || code === StandardErrorCode.ENTITY_NOT_FOUND) {
9003
+ c.status(httpStatus15.NOT_FOUND);
9004
+ return c.json(__spreadValues({}, err.toJSON()));
9005
+ }
9006
+ if (code === StandardErrorCode.TRANSACTION_EMPTY || code === StandardErrorCode.TRANSACTION_ITEM_LIMIT_EXCEEDED || code === StandardErrorCode.TRANSACTION_UNIQUE_FIELD_UPDATE || code === StandardErrorCode.TRANSACTION_INVALID_OPERATION || code === StandardErrorCode.TRANSACTION_VALIDATION_ERROR || code === StandardErrorCode.INVALID_ENTITY_TYPE || code === StandardErrorCode.INVALID_CONDITION || code === StandardErrorCode.INVALID_UNIQUE_VALUE_TYPE) {
9007
+ c.status(httpStatus15.BAD_REQUEST);
9008
+ return c.json(__spreadValues({}, err.toJSON()));
9009
+ }
9010
+ if (code === StandardErrorCode.TRANSACTION_FAILED || code === StandardErrorCode.CONDITIONAL_CHECK_FAILED || code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
9011
+ c.status(httpStatus15.CONFLICT);
9012
+ return c.json(__spreadValues({}, err.toJSON()));
9013
+ }
9014
+ }
9015
+ throw err;
9016
+ }
9017
+ }));
9018
+ }
9019
+ };
9020
+
8419
9021
  // services/entity-service-lifecycle.ts
8420
9022
  var EntityServiceLifeCycle = class {
8421
9023
  constructor(EntityConfig, publishEvent2, eventUtils) {
@@ -8448,6 +9050,462 @@ var EntityServiceLifeCycle = class {
8448
9050
  }
8449
9051
  };
8450
9052
 
9053
+ // services/transaction.service.ts
9054
+ import { TransactionCanceledException as TransactionCanceledException5 } from "@aws-sdk/client-dynamodb";
9055
+ import { ulid as ulid4 } from "ulid";
9056
+ var MAX_TRANSACTION_ITEMS = 100;
9057
+ var TransactionService = class {
9058
+ constructor(EntityConfig, EmailAuthEnabledEntities, entityRepository, dynamodbClient, publishEvent2, entityServiceLifeCycle, eventUtils) {
9059
+ this.EntityConfig = EntityConfig;
9060
+ this.EmailAuthEnabledEntities = EmailAuthEnabledEntities;
9061
+ this.entityRepository = entityRepository;
9062
+ this.dynamodbClient = dynamodbClient;
9063
+ this.publishEvent = publishEvent2;
9064
+ this.entityServiceLifeCycle = entityServiceLifeCycle;
9065
+ this.eventUtils = eventUtils;
9066
+ this.executeTransaction = (operations, accountId) => __async(this, null, function* () {
9067
+ var _a;
9068
+ if (!operations || operations.length === 0) {
9069
+ throw new StandardError(
9070
+ StandardErrorCode.TRANSACTION_EMPTY,
9071
+ "Transaction must contain at least one operation"
9072
+ );
9073
+ }
9074
+ const allTransactItems = [];
9075
+ const pendingEvents = [];
9076
+ const resultEntries = [];
9077
+ const processed = yield Promise.all(
9078
+ operations.map((op) => this.processOperation(op, accountId))
9079
+ );
9080
+ for (const { items, events, resultEntry } of processed) {
9081
+ allTransactItems.push(...items);
9082
+ pendingEvents.push(...events);
9083
+ resultEntries.push(resultEntry);
9084
+ }
9085
+ if (allTransactItems.length > MAX_TRANSACTION_ITEMS) {
9086
+ throw new StandardError(
9087
+ StandardErrorCode.TRANSACTION_ITEM_LIMIT_EXCEEDED,
9088
+ `Transaction contains ${allTransactItems.length} items, exceeds limit of ${MAX_TRANSACTION_ITEMS}`
9089
+ );
9090
+ }
9091
+ try {
9092
+ yield this.dynamodbClient.transactWriteItems({
9093
+ TransactItems: allTransactItems
9094
+ });
9095
+ } catch (err) {
9096
+ if (err instanceof TransactionCanceledException5) {
9097
+ throw new StandardError(
9098
+ StandardErrorCode.TRANSACTION_FAILED,
9099
+ "Transaction failed",
9100
+ err,
9101
+ {
9102
+ reasons: (_a = err.CancellationReasons) == null ? void 0 : _a.map((r, i) => ({
9103
+ index: i,
9104
+ code: r.Code,
9105
+ message: r.Message
9106
+ }))
9107
+ }
9108
+ );
9109
+ }
9110
+ if ((err == null ? void 0 : err.name) === "ValidationException") {
9111
+ throw new StandardError(
9112
+ StandardErrorCode.TRANSACTION_VALIDATION_ERROR,
9113
+ "Transaction request is invalid (e.g. multiple operations on the same item, or an item exceeds a DynamoDB limit)",
9114
+ err
9115
+ );
9116
+ }
9117
+ throw err;
9118
+ }
9119
+ const readPromises = resultEntries.map((entry) => __async(this, null, function* () {
9120
+ if ((entry.operation === "updateEntity" || entry.operation === "adjustEntity") && !entry.data) {
9121
+ try {
9122
+ const entity = yield this.entityRepository.getEntity(
9123
+ entry.entityType,
9124
+ entry.entityId
9125
+ );
9126
+ entry.data = entity.data;
9127
+ } catch (e) {
9128
+ }
9129
+ }
9130
+ }));
9131
+ yield Promise.all(readPromises);
9132
+ const eventResults = yield Promise.allSettled(
9133
+ pendingEvents.map((ev) => this.publishEvent(ev))
9134
+ );
9135
+ for (const [i, result] of eventResults.entries()) {
9136
+ if (result.status === "rejected") {
9137
+ console.error(
9138
+ "[monorise] Failed to publish event after transaction commit:",
9139
+ {
9140
+ event: pendingEvents[i].event,
9141
+ payload: pendingEvents[i].payload,
9142
+ reason: result.reason
9143
+ }
9144
+ );
9145
+ }
9146
+ }
9147
+ return { results: resultEntries };
9148
+ });
9149
+ }
9150
+ processOperation(op, accountId) {
9151
+ return __async(this, null, function* () {
9152
+ switch (op.operation) {
9153
+ case "createEntity": {
9154
+ const { items, entity } = yield this.buildCreateItems(op);
9155
+ return {
9156
+ items,
9157
+ events: this.collectCreateEvents(entity, op.payload, accountId),
9158
+ resultEntry: {
9159
+ operation: "createEntity",
9160
+ entityType: op.entityType,
9161
+ entityId: entity.entityId,
9162
+ data: entity.data
9163
+ }
9164
+ };
9165
+ }
9166
+ case "updateEntity": {
9167
+ const { item, updatedAt } = yield this.buildUpdateItem(op);
9168
+ return {
9169
+ items: [item],
9170
+ events: this.collectUpdateEvents(op, updatedAt, accountId),
9171
+ resultEntry: {
9172
+ operation: "updateEntity",
9173
+ entityType: op.entityType,
9174
+ entityId: op.entityId
9175
+ }
9176
+ };
9177
+ }
9178
+ case "adjustEntity": {
9179
+ const { item, updatedAt } = yield this.buildAdjustItem(op);
9180
+ return {
9181
+ items: [item],
9182
+ events: [
9183
+ {
9184
+ event: EVENT.CORE.ENTITY_UPDATED,
9185
+ payload: {
9186
+ entityType: op.entityType,
9187
+ entityId: op.entityId,
9188
+ updatedByAccountId: accountId,
9189
+ publishedAt: updatedAt
9190
+ }
9191
+ }
9192
+ ],
9193
+ resultEntry: {
9194
+ operation: "adjustEntity",
9195
+ entityType: op.entityType,
9196
+ entityId: op.entityId
9197
+ }
9198
+ };
9199
+ }
9200
+ case "deleteEntity": {
9201
+ const item = this.buildDeleteItem(op);
9202
+ return {
9203
+ items: [item],
9204
+ events: [
9205
+ {
9206
+ event: EVENT.CORE.ENTITY_DELETED,
9207
+ payload: {
9208
+ entityType: op.entityType,
9209
+ entityId: op.entityId,
9210
+ deletedByAccountId: accountId
9211
+ }
9212
+ }
9213
+ ],
9214
+ resultEntry: {
9215
+ operation: "deleteEntity",
9216
+ entityType: op.entityType,
9217
+ entityId: op.entityId
9218
+ }
9219
+ };
9220
+ }
9221
+ default:
9222
+ throw new StandardError(
9223
+ StandardErrorCode.TRANSACTION_INVALID_OPERATION,
9224
+ `Unknown operation: '${op.operation}'`
9225
+ );
9226
+ }
9227
+ });
9228
+ }
9229
+ buildCreateItems(op) {
9230
+ return __async(this, null, function* () {
9231
+ const config = this.EntityConfig[op.entityType];
9232
+ if (!config) {
9233
+ throw new StandardError(
9234
+ StandardErrorCode.INVALID_ENTITY_TYPE,
9235
+ `Unknown entity type: '${op.entityType}'`
9236
+ );
9237
+ }
9238
+ const entitySchema = config.createSchema || config.baseSchema;
9239
+ if (!entitySchema) {
9240
+ throw new StandardError(
9241
+ StandardErrorCode.INVALID_ENTITY_TYPE,
9242
+ `No schema defined for entity type: '${op.entityType}'`
9243
+ );
9244
+ }
9245
+ if (config.finalSchema) {
9246
+ config.finalSchema.parse(op.payload);
9247
+ }
9248
+ const parsedPayload = entitySchema.parse(
9249
+ op.payload
9250
+ );
9251
+ const currentDatetime = /* @__PURE__ */ new Date();
9252
+ const entity = new Entity(
9253
+ op.entityType,
9254
+ op.entityId || ulid4(),
9255
+ parsedPayload,
9256
+ currentDatetime,
9257
+ currentDatetime
9258
+ );
9259
+ const uniqueFields = config.uniqueFields || [];
9260
+ const uniqueFieldValues = {};
9261
+ for (const field of uniqueFields) {
9262
+ if (!(field in parsedPayload)) continue;
9263
+ const value = parsedPayload[field];
9264
+ if (typeof value !== "string") {
9265
+ throw new StandardError(
9266
+ StandardErrorCode.INVALID_UNIQUE_VALUE_TYPE,
9267
+ `Invalid type. ${field} is not a 'string'.`
9268
+ );
9269
+ }
9270
+ uniqueFieldValues[field] = value;
9271
+ }
9272
+ const items = this.entityRepository.createEntityTransactItems(entity, {
9273
+ uniqueFieldValues
9274
+ });
9275
+ return { items, entity };
9276
+ });
9277
+ }
9278
+ buildUpdateItem(op) {
9279
+ return __async(this, null, function* () {
9280
+ const config = this.EntityConfig[op.entityType];
9281
+ if (!config) {
9282
+ throw new StandardError(
9283
+ StandardErrorCode.INVALID_ENTITY_TYPE,
9284
+ `Unknown entity type: '${op.entityType}'`
9285
+ );
9286
+ }
9287
+ const uniqueFields = config.uniqueFields || [];
9288
+ for (const field of uniqueFields) {
9289
+ if (field in op.payload) {
9290
+ throw new StandardError(
9291
+ StandardErrorCode.TRANSACTION_UNIQUE_FIELD_UPDATE,
9292
+ `Cannot update unique field '${field}' within a transaction. Use a standalone updateEntity call instead.`
9293
+ );
9294
+ }
9295
+ }
9296
+ const entitySchema = config.baseSchema;
9297
+ if (!entitySchema) {
9298
+ throw new StandardError(
9299
+ StandardErrorCode.INVALID_ENTITY_TYPE,
9300
+ `No schema defined for entity type: '${op.entityType}'`
9301
+ );
9302
+ }
9303
+ const parsedPayload = entitySchema.partial().parse(op.payload);
9304
+ const currentDatetime = (/* @__PURE__ */ new Date()).toISOString();
9305
+ const toUpdateExpressions = this.entityRepository.toUpdate({
9306
+ updatedAt: currentDatetime,
9307
+ data: parsedPayload
9308
+ });
9309
+ let conditionOpts;
9310
+ if (op.condition) {
9311
+ const updateConditions = config.updateConditions;
9312
+ if (!updateConditions) {
9313
+ throw new StandardError(
9314
+ StandardErrorCode.INVALID_CONDITION,
9315
+ `Entity '${op.entityType}' has no updateConditions defined`
9316
+ );
9317
+ }
9318
+ conditionOpts = yield resolveUpdateCondition({
9319
+ conditionName: op.condition,
9320
+ conditions: updateConditions,
9321
+ getEntityData: () => __async(this, null, function* () {
9322
+ var _a;
9323
+ const entity2 = yield this.entityRepository.getEntity(
9324
+ op.entityType,
9325
+ op.entityId
9326
+ );
9327
+ return (_a = entity2 == null ? void 0 : entity2.data) != null ? _a : {};
9328
+ })
9329
+ });
9330
+ }
9331
+ const entity = new Entity(op.entityType, op.entityId);
9332
+ const item = {
9333
+ Update: {
9334
+ TableName: this.entityRepository.TABLE_NAME,
9335
+ Key: entity.keys(),
9336
+ ConditionExpression: (conditionOpts == null ? void 0 : conditionOpts.ConditionExpression) || "attribute_exists(PK)",
9337
+ UpdateExpression: toUpdateExpressions.UpdateExpression,
9338
+ ExpressionAttributeNames: __spreadValues(__spreadValues({}, toUpdateExpressions.ExpressionAttributeNames), conditionOpts == null ? void 0 : conditionOpts.ExpressionAttributeNames),
9339
+ ExpressionAttributeValues: __spreadValues(__spreadValues({}, toUpdateExpressions.ExpressionAttributeValues), conditionOpts == null ? void 0 : conditionOpts.ExpressionAttributeValues)
9340
+ }
9341
+ };
9342
+ return { item, updatedAt: currentDatetime };
9343
+ });
9344
+ }
9345
+ buildAdjustItem(op) {
9346
+ return __async(this, null, function* () {
9347
+ const config = this.EntityConfig[op.entityType];
9348
+ if (!config) {
9349
+ throw new StandardError(
9350
+ StandardErrorCode.INVALID_ENTITY_TYPE,
9351
+ `Unknown entity type: '${op.entityType}'`
9352
+ );
9353
+ }
9354
+ for (const [key, value] of Object.entries(op.adjustments)) {
9355
+ if (typeof value !== "number" || !Number.isFinite(value)) {
9356
+ throw new StandardError(
9357
+ StandardErrorCode.TRANSACTION_INVALID_OPERATION,
9358
+ `Adjustment field "${key}" must be a finite number`
9359
+ );
9360
+ }
9361
+ }
9362
+ const {
9363
+ UpdateExpression,
9364
+ ExpressionAttributeNames,
9365
+ ExpressionAttributeValues
9366
+ } = this.entityRepository.toAdjustUpdate(op.adjustments);
9367
+ const currentDatetime = (/* @__PURE__ */ new Date()).toISOString();
9368
+ ExpressionAttributeNames["#updatedAt"] = "updatedAt";
9369
+ ExpressionAttributeValues[":updatedAt"] = { S: currentDatetime };
9370
+ const fullUpdateExpression = `${UpdateExpression}, #updatedAt = :updatedAt`;
9371
+ let conditionOpts;
9372
+ const adjustmentConditions = config.adjustmentConditions;
9373
+ if (adjustmentConditions) {
9374
+ if (!op.condition) {
9375
+ throw new StandardError(
9376
+ StandardErrorCode.INVALID_CONDITION,
9377
+ `Entity '${op.entityType}' has adjustmentConditions defined; condition is required`
9378
+ );
9379
+ }
9380
+ conditionOpts = yield resolveAdjustmentCondition({
9381
+ conditionName: op.condition,
9382
+ conditions: adjustmentConditions,
9383
+ adjustments: op.adjustments,
9384
+ getEntityData: () => __async(this, null, function* () {
9385
+ var _a;
9386
+ const entity2 = yield this.entityRepository.getEntity(
9387
+ op.entityType,
9388
+ op.entityId
9389
+ );
9390
+ return (_a = entity2 == null ? void 0 : entity2.data) != null ? _a : {};
9391
+ })
9392
+ });
9393
+ }
9394
+ const entity = new Entity(op.entityType, op.entityId);
9395
+ const item = {
9396
+ Update: {
9397
+ TableName: this.entityRepository.TABLE_NAME,
9398
+ Key: entity.keys(),
9399
+ UpdateExpression: fullUpdateExpression,
9400
+ ConditionExpression: (conditionOpts == null ? void 0 : conditionOpts.ConditionExpression) || "attribute_exists(PK)",
9401
+ ExpressionAttributeNames: __spreadValues(__spreadValues({}, ExpressionAttributeNames), conditionOpts == null ? void 0 : conditionOpts.ExpressionAttributeNames),
9402
+ ExpressionAttributeValues: __spreadValues(__spreadValues({}, ExpressionAttributeValues), conditionOpts == null ? void 0 : conditionOpts.ExpressionAttributeValues)
9403
+ }
9404
+ };
9405
+ return { item, updatedAt: currentDatetime };
9406
+ });
9407
+ }
9408
+ buildDeleteItem(op) {
9409
+ const config = this.EntityConfig[op.entityType];
9410
+ if (!config) {
9411
+ throw new StandardError(
9412
+ StandardErrorCode.INVALID_ENTITY_TYPE,
9413
+ `Unknown entity type: '${op.entityType}'`
9414
+ );
9415
+ }
9416
+ const entity = new Entity(op.entityType, op.entityId);
9417
+ return {
9418
+ Delete: {
9419
+ TableName: this.entityRepository.TABLE_NAME,
9420
+ Key: entity.keys(),
9421
+ ConditionExpression: "attribute_exists(PK)"
9422
+ }
9423
+ };
9424
+ }
9425
+ collectCreateEvents(entity, payload, accountId) {
9426
+ var _a, _b;
9427
+ const events = [];
9428
+ const publishedAt = entity.updatedAt || (/* @__PURE__ */ new Date()).toISOString();
9429
+ const config = this.EntityConfig[entity.entityType];
9430
+ const mutualSchema = (_a = config == null ? void 0 : config.mutual) == null ? void 0 : _a.mutualSchema;
9431
+ if (mutualSchema) {
9432
+ const parsedMutualPayload = mutualSchema.parse(payload);
9433
+ if (parsedMutualPayload) {
9434
+ for (const [fieldKey, fieldConfig] of Object.entries(
9435
+ ((_b = config.mutual) == null ? void 0 : _b.mutualFields) || {}
9436
+ )) {
9437
+ const toMutualIds = fieldConfig.toMutualIds;
9438
+ const mutualPayload = parsedMutualPayload[fieldKey];
9439
+ if (!mutualPayload) continue;
9440
+ events.push({
9441
+ event: EVENT.CORE.ENTITY_MUTUAL_TO_CREATE,
9442
+ payload: {
9443
+ byEntityType: entity.entityType,
9444
+ byEntityId: entity.entityId,
9445
+ entityType: fieldConfig.entityType,
9446
+ field: fieldKey,
9447
+ mutualIds: toMutualIds ? toMutualIds(mutualPayload) : mutualPayload,
9448
+ customContext: toMutualIds ? mutualPayload : {},
9449
+ publishedAt
9450
+ }
9451
+ });
9452
+ }
9453
+ }
9454
+ }
9455
+ events.push({
9456
+ event: EVENT.CORE.ENTITY_CREATED,
9457
+ payload: {
9458
+ entityType: entity.entityType,
9459
+ entityId: entity.entityId,
9460
+ data: entity.data,
9461
+ createdByAccountId: accountId,
9462
+ publishedAt
9463
+ }
9464
+ });
9465
+ return events;
9466
+ }
9467
+ collectUpdateEvents(op, updatedAt, accountId) {
9468
+ var _a, _b;
9469
+ const events = [];
9470
+ const config = this.EntityConfig[op.entityType];
9471
+ const mutualSchema = (_a = config == null ? void 0 : config.mutual) == null ? void 0 : _a.mutualSchema;
9472
+ if (mutualSchema) {
9473
+ const parsedMutualPayload = mutualSchema.parse(op.payload);
9474
+ if (parsedMutualPayload) {
9475
+ for (const [fieldKey, fieldConfig] of Object.entries(
9476
+ ((_b = config.mutual) == null ? void 0 : _b.mutualFields) || {}
9477
+ )) {
9478
+ const toMutualIds = fieldConfig.toMutualIds;
9479
+ const mutualPayload = parsedMutualPayload[fieldKey];
9480
+ if (!mutualPayload) continue;
9481
+ events.push({
9482
+ event: EVENT.CORE.ENTITY_MUTUAL_TO_UPDATE,
9483
+ payload: {
9484
+ byEntityType: op.entityType,
9485
+ byEntityId: op.entityId,
9486
+ entityType: fieldConfig.entityType,
9487
+ field: fieldKey,
9488
+ mutualIds: toMutualIds ? toMutualIds(mutualPayload) : mutualPayload,
9489
+ customContext: toMutualIds ? mutualPayload : {},
9490
+ publishedAt: updatedAt
9491
+ }
9492
+ });
9493
+ }
9494
+ }
9495
+ }
9496
+ events.push({
9497
+ event: EVENT.CORE.ENTITY_UPDATED,
9498
+ payload: {
9499
+ entityType: op.entityType,
9500
+ entityId: op.entityId,
9501
+ updatedByAccountId: accountId,
9502
+ publishedAt: updatedAt
9503
+ }
9504
+ });
9505
+ return events;
9506
+ }
9507
+ };
9508
+
8451
9509
  // services/DependencyContainer.ts
8452
9510
  var DependencyContainer = class {
8453
9511
  constructor(config) {
@@ -8624,6 +9682,59 @@ var DependencyContainer = class {
8624
9682
  get listTagsController() {
8625
9683
  return this.createCachedInstance(ListTagsController, this.tagRepository);
8626
9684
  }
9685
+ get transactionService() {
9686
+ return this.createCachedInstance(
9687
+ TransactionService,
9688
+ this.config.EntityConfig,
9689
+ this.config.EmailAuthEnabledEntities,
9690
+ this.entityRepository,
9691
+ this.dynamodbClient,
9692
+ this.publishEvent,
9693
+ this.entityServiceLifeCycle,
9694
+ this.eventUtils
9695
+ );
9696
+ }
9697
+ get executeTransactionController() {
9698
+ return this.createCachedInstance(
9699
+ ExecuteTransactionController,
9700
+ this.transactionService
9701
+ );
9702
+ }
9703
+ };
9704
+
9705
+ // helpers/transactional.ts
9706
+ var transactional = {
9707
+ createEntity: (entityType, payload) => {
9708
+ const _a = payload, { entityId } = _a, rest = __objRest(_a, ["entityId"]);
9709
+ return __spreadValues({
9710
+ operation: "createEntity",
9711
+ entityType,
9712
+ payload: rest
9713
+ }, entityId && { entityId });
9714
+ },
9715
+ updateEntity: (entityType, entityId, payload) => {
9716
+ const _a = payload, { $condition } = _a, rest = __objRest(_a, ["$condition"]);
9717
+ return __spreadValues({
9718
+ operation: "updateEntity",
9719
+ entityType,
9720
+ entityId,
9721
+ payload: rest
9722
+ }, $condition && { condition: $condition });
9723
+ },
9724
+ adjustEntity: (entityType, entityId, adjustments) => {
9725
+ const _a = adjustments, { $condition } = _a, rest = __objRest(_a, ["$condition"]);
9726
+ return __spreadValues({
9727
+ operation: "adjustEntity",
9728
+ entityType,
9729
+ entityId,
9730
+ adjustments: rest
9731
+ }, $condition && { condition: $condition });
9732
+ },
9733
+ deleteEntity: (entityType, entityId) => ({
9734
+ operation: "deleteEntity",
9735
+ entityType,
9736
+ entityId
9737
+ })
8627
9738
  };
8628
9739
 
8629
9740
  // index.ts
@@ -8633,11 +9744,13 @@ var CoreFactory = class {
8633
9744
  const dependencyContainer = new DependencyContainer(this.config);
8634
9745
  this.dependencyContainer = dependencyContainer;
8635
9746
  this.setupCommonRoutes = setupCommonRoutes(dependencyContainer);
8636
- this.mutualProcessor = handler2(dependencyContainer);
8637
- this.replicationProcessor = handler4(dependencyContainer);
9747
+ this.mutualProcessor = handler5(dependencyContainer);
9748
+ this.replicationProcessor = handler7(dependencyContainer);
8638
9749
  this.createEntityProcessor = handler(dependencyContainer);
8639
- this.prejoinProcessor = handler3(dependencyContainer);
8640
- this.tagProcessor = handler5(dependencyContainer);
9750
+ this.analyticsProcessor = handler2(this.config.EntityConfig);
9751
+ this.analyticsBackfillProcessor = handler3(this.config.EntityConfig);
9752
+ this.prejoinProcessor = handler6(dependencyContainer);
9753
+ this.tagProcessor = handler8(dependencyContainer);
8641
9754
  this.appHandler = appHandler(dependencyContainer);
8642
9755
  }
8643
9756
  };
@@ -8654,13 +9767,19 @@ export {
8654
9767
  StandardError,
8655
9768
  StandardErrorCode,
8656
9769
  TagRepository,
9770
+ TransactionService,
9771
+ handler3 as analyticsBackfillProcessor,
9772
+ handler4 as analyticsMaterializationProcessor,
9773
+ handler2 as analyticsProcessor,
8657
9774
  appHandler,
8658
9775
  handler as createEntityProcessor,
8659
9776
  index_default as default,
8660
- handler2 as mutualProcessor,
8661
- handler3 as prejoinProcessor,
8662
- handler4 as replicationProcessor,
9777
+ handler5 as mutualProcessor,
9778
+ handler6 as prejoinProcessor,
9779
+ handler7 as replicationProcessor,
8663
9780
  setupCommonRoutes,
8664
- handler5 as tagProcessor
9781
+ startBackfill as startAnalyticsBackfill,
9782
+ handler8 as tagProcessor,
9783
+ transactional
8665
9784
  };
8666
9785
  //# sourceMappingURL=index.js.map