@terreno/api 0.29.0 → 0.31.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 (79) hide show
  1. package/CHANGELOG.md +2 -43
  2. package/LICENSE +21 -202
  3. package/dist/actions.js +17 -8
  4. package/dist/actions.openApi.test.js +1 -3
  5. package/dist/actions.test.js +8 -5
  6. package/dist/api.arrayOperations.test.js +16 -8
  7. package/dist/api.coverage.test.js +2 -3
  8. package/dist/api.d.ts +3 -2
  9. package/dist/api.errorPaths.test.js +608 -1
  10. package/dist/api.errors.test.js +9 -0
  11. package/dist/api.js +137 -170
  12. package/dist/api.query.test.js +20 -8
  13. package/dist/api.test.js +12 -6
  14. package/dist/auth.coverage.test.d.ts +1 -0
  15. package/dist/auth.coverage.test.js +202 -0
  16. package/dist/auth.test.js +159 -0
  17. package/dist/betterAuthSetup.d.ts +15 -1
  18. package/dist/betterAuthSetup.js +4 -6
  19. package/dist/configurationPlugin.js +2 -2
  20. package/dist/consentApp.test.js +1 -5
  21. package/dist/docLoader.js +5 -1
  22. package/dist/envConfigurationPlugin.d.ts +1 -1
  23. package/dist/envConfigurationPlugin.js +0 -2
  24. package/dist/errors.d.ts +14 -0
  25. package/dist/errors.js +24 -2
  26. package/dist/errors.test.js +137 -0
  27. package/dist/expressServer.js +11 -5
  28. package/dist/githubAuth.js +1 -4
  29. package/dist/httpClient.js +5 -1
  30. package/dist/openApiBuilder.test.js +0 -2
  31. package/dist/openApiValidator.test.js +34 -0
  32. package/dist/plugins.d.ts +6 -5
  33. package/dist/plugins.js +56 -10
  34. package/dist/plugins.test.js +73 -17
  35. package/dist/populate.test.js +9 -12
  36. package/dist/realtime/realtime.test.js +231 -0
  37. package/dist/realtime/realtimeApp.d.ts +1 -1
  38. package/dist/realtime/realtimeApp.js +6 -2
  39. package/dist/realtime/realtimeAppSetup.test.d.ts +1 -0
  40. package/dist/realtime/realtimeAppSetup.test.js +213 -0
  41. package/dist/realtime/registry.d.ts +3 -2
  42. package/dist/tests/models.d.ts +27 -11
  43. package/dist/tests/models.js +5 -3
  44. package/dist/tests/testHelper.d.ts +9 -3
  45. package/package.json +4 -5
  46. package/src/actions.openApi.test.ts +7 -10
  47. package/src/actions.test.ts +27 -15
  48. package/src/actions.ts +21 -12
  49. package/src/api.arrayOperations.test.ts +16 -8
  50. package/src/api.coverage.test.ts +9 -10
  51. package/src/api.errorPaths.test.ts +360 -4
  52. package/src/api.errors.test.ts +12 -0
  53. package/src/api.query.test.ts +20 -8
  54. package/src/api.test.ts +12 -6
  55. package/src/api.ts +162 -171
  56. package/src/auth.coverage.test.ts +101 -0
  57. package/src/auth.test.ts +125 -2
  58. package/src/betterAuthSetup.ts +7 -7
  59. package/src/configurationPlugin.ts +2 -2
  60. package/src/consentApp.test.ts +12 -12
  61. package/src/docLoader.ts +6 -2
  62. package/src/envConfigurationPlugin.ts +2 -6
  63. package/src/errors.test.ts +106 -1
  64. package/src/errors.ts +25 -1
  65. package/src/expressServer.ts +11 -5
  66. package/src/githubAuth.ts +1 -3
  67. package/src/httpClient.ts +6 -2
  68. package/src/models/versionConfig.ts +1 -1
  69. package/src/openApiBuilder.test.ts +24 -9
  70. package/src/openApiValidator.test.ts +41 -0
  71. package/src/plugins.test.ts +59 -9
  72. package/src/plugins.ts +81 -39
  73. package/src/populate.test.ts +25 -16
  74. package/src/realtime/changeStreamWatcher.ts +8 -1
  75. package/src/realtime/realtime.test.ts +239 -0
  76. package/src/realtime/realtimeApp.ts +8 -5
  77. package/src/realtime/realtimeAppSetup.test.ts +161 -0
  78. package/src/realtime/registry.ts +3 -4
  79. package/src/tests/models.ts +8 -6
@@ -58,10 +58,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
58
58
  // noExplicitAny: test mock typing
59
59
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
60
60
  var bun_test_1 = require("bun:test");
61
+ var chai_1 = require("chai");
61
62
  var mongoose_1 = require("mongoose");
62
63
  var supertest_1 = __importDefault(require("supertest"));
63
64
  var api_1 = require("./api");
64
65
  var auth_1 = require("./auth");
66
+ var errors_1 = require("./errors");
65
67
  var permissions_1 = require("./permissions");
66
68
  var plugins_1 = require("./plugins");
67
69
  var tests_1 = require("./tests");
@@ -246,7 +248,7 @@ var StuffModel = (0, mongoose_1.model)("Stuff", stuffSchema);
246
248
  switch (_a.label) {
247
249
  case 0:
248
250
  fn = function () { return StuffModel.findOneOrNone({ ownerId: "123" }); };
249
- return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/Stuff\.findOne query returned multiple documents/)];
251
+ return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/^findOne query returned multiple documents$/)];
250
252
  case 1:
251
253
  _a.sent();
252
254
  return [2 /*return*/];
@@ -272,7 +274,8 @@ var StuffModel = (0, mongoose_1.model)("Stuff", stuffSchema);
272
274
  // Check if the error has title and status properties
273
275
  (0, bun_test_1.expect)(error_1.title).toBe("Oh no!");
274
276
  (0, bun_test_1.expect)(error_1.status).toBe(400);
275
- (0, bun_test_1.expect)(error_1.detail).toBe('query: {"ownerId":"123"}');
277
+ (0, bun_test_1.expect)(error_1.detail).toBe('Stuff.findOne query returned multiple documents. query: {"ownerId":"123"}');
278
+ (0, bun_test_1.expect)(error_1.code).toBe("find-one-multiple-documents");
276
279
  return [3 /*break*/, 4];
277
280
  case 4: return [2 /*return*/];
278
281
  }
@@ -348,7 +351,7 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
348
351
  switch (_a.label) {
349
352
  case 0:
350
353
  fn = function () { return (0, plugins_1.findOneOrNoneFor)(StuffModel, { ownerId: "123" }); };
351
- return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/Stuff\.findOne query returned multiple documents/)];
354
+ return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/^findOne query returned multiple documents$/)];
352
355
  case 1:
353
356
  _a.sent();
354
357
  return [2 /*return*/];
@@ -428,7 +431,7 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
428
431
  switch (_a.label) {
429
432
  case 0:
430
433
  fn = function () { return (0, plugins_1.findOneOrNoneFor)(BareThingModel, { ownerId: "123" }); };
431
- return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/BareThing\.findOne query returned multiple documents/)];
434
+ return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/^findOne query returned multiple documents$/)];
432
435
  case 1:
433
436
  _a.sent();
434
437
  return [2 /*return*/];
@@ -495,13 +498,38 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
495
498
  switch (_a.label) {
496
499
  case 0:
497
500
  fn = function () { return StuffModel.findExactlyOne({ name: "OtherStuff" }); };
498
- return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/Stuff\.findExactlyOne query returned no documents/)];
501
+ return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/^findExactlyOne query returned no documents$/)];
499
502
  case 1:
500
503
  _a.sent();
501
504
  return [2 /*return*/];
502
505
  }
503
506
  });
504
507
  }); });
508
+ (0, bun_test_1.it)("throws a NotFoundError carrying the model name in detail and meta", function () { return __awaiter(void 0, void 0, void 0, function () {
509
+ var error_4;
510
+ return __generator(this, function (_a) {
511
+ switch (_a.label) {
512
+ case 0:
513
+ _a.trys.push([0, 2, , 3]);
514
+ return [4 /*yield*/, StuffModel.findExactlyOne({ name: "OtherStuff" })];
515
+ case 1:
516
+ _a.sent();
517
+ throw new Error("Expected promise to reject");
518
+ case 2:
519
+ error_4 = _a.sent();
520
+ (0, bun_test_1.expect)(error_4).toBeInstanceOf(errors_1.NotFoundError);
521
+ if (!(0, errors_1.isAPIError)(error_4)) {
522
+ throw error_4;
523
+ }
524
+ (0, bun_test_1.expect)(error_4.status).toBe(404);
525
+ (0, bun_test_1.expect)(error_4.code).toBe("find-exactly-one-no-documents");
526
+ (0, bun_test_1.expect)(error_4.detail).toBe('Stuff.findExactlyOne query returned no documents. query: {"name":"OtherStuff"}');
527
+ (0, bun_test_1.expect)(error_4.meta).toEqual({ model: "Stuff" });
528
+ return [3 /*break*/, 3];
529
+ case 3: return [2 /*return*/];
530
+ }
531
+ });
532
+ }); });
505
533
  (0, bun_test_1.it)("returns a single match", function () { return __awaiter(void 0, void 0, void 0, function () {
506
534
  var result;
507
535
  return __generator(this, function (_a) {
@@ -520,7 +548,7 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
520
548
  switch (_a.label) {
521
549
  case 0:
522
550
  fn = function () { return StuffModel.findExactlyOne({ ownerId: "123" }); };
523
- return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/Stuff\.findExactlyOne query returned multiple documents/)];
551
+ return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/^findExactlyOne query returned multiple documents$/)];
524
552
  case 1:
525
553
  _a.sent();
526
554
  return [2 /*return*/];
@@ -528,7 +556,7 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
528
556
  });
529
557
  }); });
530
558
  (0, bun_test_1.it)("throws custom error with two matches.", function () { return __awaiter(void 0, void 0, void 0, function () {
531
- var fn, error_4;
559
+ var fn, error_5;
532
560
  return __generator(this, function (_a) {
533
561
  switch (_a.label) {
534
562
  case 0:
@@ -542,11 +570,12 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
542
570
  // If the promise doesn't reject, the test should fail
543
571
  throw new Error("Expected promise to reject");
544
572
  case 3:
545
- error_4 = _a.sent();
573
+ error_5 = _a.sent();
546
574
  // Check if the error has title and status properties
547
- (0, bun_test_1.expect)(error_4.title).toBe("Oh no!");
548
- (0, bun_test_1.expect)(error_4.status).toBe(400);
549
- (0, bun_test_1.expect)(error_4.detail).toBe('query: {"ownerId":"123"}');
575
+ (0, bun_test_1.expect)(error_5.title).toBe("Oh no!");
576
+ (0, bun_test_1.expect)(error_5.status).toBe(400);
577
+ (0, bun_test_1.expect)(error_5.detail).toBe('Stuff.findExactlyOne query returned multiple documents. query: {"ownerId":"123"}');
578
+ (0, bun_test_1.expect)(error_5.code).toBe("find-exactly-one-multiple-documents");
550
579
  return [3 /*break*/, 4];
551
580
  case 4: return [2 /*return*/];
552
581
  }
@@ -610,7 +639,7 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
610
639
  });
611
640
  }); });
612
641
  (0, bun_test_1.it)("throws error when multiple documents match conditions", function () { return __awaiter(void 0, void 0, void 0, function () {
613
- var fn;
642
+ var fn, error_6;
614
643
  return __generator(this, function (_a) {
615
644
  switch (_a.label) {
616
645
  case 0: return [4 /*yield*/, Promise.all([
@@ -620,10 +649,26 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
620
649
  case 1:
621
650
  _a.sent();
622
651
  fn = function () { return StuffModel.upsert({ ownerId: "123" }, { name: "Updated" }); };
623
- return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/Stuff\.upsert find query returned multiple documents/)];
652
+ return [4 /*yield*/, (0, bun_test_1.expect)(fn()).rejects.toThrow(/^upsert find query returned multiple documents$/)];
624
653
  case 2:
625
654
  _a.sent();
626
- return [2 /*return*/];
655
+ _a.label = 3;
656
+ case 3:
657
+ _a.trys.push([3, 5, , 6]);
658
+ return [4 /*yield*/, fn()];
659
+ case 4:
660
+ _a.sent();
661
+ return [3 /*break*/, 6];
662
+ case 5:
663
+ error_6 = _a.sent();
664
+ (0, bun_test_1.expect)(error_6).toBeInstanceOf(errors_1.InternalServerError);
665
+ if (!(0, errors_1.isAPIError)(error_6)) {
666
+ throw error_6;
667
+ }
668
+ (0, bun_test_1.expect)(error_6.code).toBe("upsert-multiple-documents");
669
+ (0, bun_test_1.expect)(error_6.detail).toBe('Stuff.upsert find query returned multiple documents. query: {"ownerId":"123"}');
670
+ return [3 /*break*/, 6];
671
+ case 6: return [2 /*return*/];
627
672
  }
628
673
  });
629
674
  }); });
@@ -708,8 +753,19 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
708
753
  }); });
709
754
  });
710
755
  (0, bun_test_1.describe)("DateOnly", function () {
756
+ (0, bun_test_1.it)("strips the time portion when getting a Date value", function () {
757
+ var dateOnly = new plugins_1.DateOnly("date", {});
758
+ var value = dateOnly.get(new Date("2005-10-10T17:17:17.017Z"));
759
+ chai_1.assert.instanceOf(value, Date);
760
+ chai_1.assert.equal(value.toISOString(), "2005-10-10T00:00:00.000Z");
761
+ });
762
+ (0, bun_test_1.it)("returns non-Date values unchanged when getting a value", function () {
763
+ var dateOnly = new plugins_1.DateOnly("date", {});
764
+ chai_1.assert.isNull(dateOnly.get(null));
765
+ chai_1.assert.equal(dateOnly.get("2005-10-10"), "2005-10-10");
766
+ });
711
767
  (0, bun_test_1.it)("throws error with invalid date", function () { return __awaiter(void 0, void 0, void 0, function () {
712
- var error_5;
768
+ var error_7;
713
769
  return __generator(this, function (_a) {
714
770
  switch (_a.label) {
715
771
  case 0:
@@ -723,8 +779,8 @@ var BareThingModel = (0, mongoose_1.model)("BareThing", bareThingSchema);
723
779
  _a.sent();
724
780
  return [3 /*break*/, 3];
725
781
  case 2:
726
- error_5 = _a.sent();
727
- (0, bun_test_1.expect)(error_5.message).toMatch(/Cast to DateOnly failed/);
782
+ error_7 = _a.sent();
783
+ (0, bun_test_1.expect)(error_7.message).toMatch(/Cast to DateOnly failed/);
728
784
  return [2 /*return*/];
729
785
  case 3: throw new Error("Expected error was not thrown");
730
786
  }
@@ -69,8 +69,6 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
69
69
  }
70
70
  };
71
71
  Object.defineProperty(exports, "__esModule", { value: true });
72
- // noExplicitAny: test mock typing
73
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
74
72
  var bun_test_1 = require("bun:test");
75
73
  var mongoose_1 = __importStar(require("mongoose"));
76
74
  var populate_1 = require("./populate");
@@ -78,7 +76,6 @@ var tests_1 = require("./tests");
78
76
  (0, bun_test_1.describe)("populate functions", function () {
79
77
  var admin;
80
78
  var notAdmin;
81
- // noExplicitAny: typing as HydratedDocument<Food> causes cascading errors on populated field access patterns (e.g. populated.ownerId.name)
82
79
  var spinach;
83
80
  (0, bun_test_1.beforeEach)(function () { return __awaiter(void 0, void 0, void 0, function () {
84
81
  var testData;
@@ -101,13 +98,14 @@ var tests_1 = require("./tests");
101
98
  switch (_c.label) {
102
99
  case 0: return [4 /*yield*/, spinach.populate("ownerId")];
103
100
  case 1:
104
- populated = _c.sent();
105
- return [4 /*yield*/, populated.populate("eatenBy")];
101
+ _c.sent();
102
+ return [4 /*yield*/, spinach.populate("eatenBy")];
106
103
  case 2:
107
- populated = _c.sent();
108
- return [4 /*yield*/, populated.populate("likesIds.userId")];
104
+ _c.sent();
105
+ return [4 /*yield*/, spinach.populate("likesIds.userId")];
109
106
  case 3:
110
- populated = _c.sent();
107
+ _c.sent();
108
+ populated = spinach;
111
109
  (0, bun_test_1.expect)(populated.ownerId.name).toBe("Not Admin");
112
110
  (0, bun_test_1.expect)(populated.eatenBy[0].id).toBe(admin.id);
113
111
  (0, bun_test_1.expect)(populated.eatenBy[0].name).toBe("Admin");
@@ -116,17 +114,17 @@ var tests_1 = require("./tests");
116
114
  (0, bun_test_1.expect)(populated.likesIds[1].userId.id).toBe(notAdmin.id);
117
115
  (0, bun_test_1.expect)(populated.likesIds[1].userId.name).toBe("Not Admin");
118
116
  unpopulated = (0, populate_1.unpopulate)(populated, "ownerId");
119
- (0, bun_test_1.expect)(spinach.ownerId.name).toBeUndefined();
117
+ (0, bun_test_1.expect)(populated.ownerId.name).toBeUndefined();
120
118
  (0, bun_test_1.expect)(unpopulated.ownerId.toString()).toBe(notAdmin.id);
121
119
  // Ensure nothing else was touched.
122
120
  (0, bun_test_1.expect)(populated.likesIds[0].userId.id).toBe(admin.id);
123
121
  (0, bun_test_1.expect)(populated.likesIds[0].userId.name).toBe("Admin");
124
122
  (0, bun_test_1.expect)(populated.likesIds[1].userId.id).toBe(notAdmin.id);
125
123
  (0, bun_test_1.expect)(populated.likesIds[1].userId.name).toBe("Not Admin");
126
- unpopulated = (0, populate_1.unpopulate)(populated, "eatenBy");
124
+ (0, populate_1.unpopulate)(populated, "eatenBy");
127
125
  (0, bun_test_1.expect)(populated.eatenBy.toString()).toBe(admin.id);
128
126
  (0, bun_test_1.expect)((_a = populated.eatenBy[0]) === null || _a === void 0 ? void 0 : _a.name).toBeUndefined();
129
- unpopulated = (0, populate_1.unpopulate)(populated, "likesIds.userId");
127
+ (0, populate_1.unpopulate)(populated, "likesIds.userId");
130
128
  (0, bun_test_1.expect)(populated.likesIds[0].userId.toString()).toBe(admin.id);
131
129
  (0, bun_test_1.expect)((_b = populated.likesIds[0].userId) === null || _b === void 0 ? void 0 : _b.name).toBeUndefined();
132
130
  (0, bun_test_1.expect)(populated.likesIds[1].userId.toString()).toBe(notAdmin.id);
@@ -364,7 +362,6 @@ var tests_1 = require("./tests");
364
362
  populatePaths: [{ fields: ["__proto__.polluted"], path: "ownerId" }],
365
363
  });
366
364
  (0, bun_test_1.expect)(result.properties).toBeDefined();
367
- // noExplicitAny: testing that prototype pollution did not add a 'polluted' property to Object.prototype
368
365
  (0, bun_test_1.expect)(Object.prototype.polluted).toBeUndefined();
369
366
  var ownerProps = result.properties.ownerId.properties;
370
367
  (0, bun_test_1.expect)(ownerProps).toBeDefined();
@@ -2180,6 +2180,112 @@ var createMockSocket = function (decodedToken) {
2180
2180
  }
2181
2181
  });
2182
2182
  }); });
2183
+ (0, bun_test_1.describe)("query room fanout with a registry entry", function () {
2184
+ var modelEntry = {
2185
+ collectionName: "todos",
2186
+ config: { methods: ["create", "update", "delete"], roomStrategy: "model" },
2187
+ modelName: "Todo",
2188
+ options: {
2189
+ permissions: {
2190
+ create: [function () { return true; }],
2191
+ delete: [function () { return true; }],
2192
+ list: [function () { return true; }],
2193
+ read: [function () { return true; }],
2194
+ update: [function () { return true; }],
2195
+ },
2196
+ },
2197
+ routePath: "/todos",
2198
+ };
2199
+ var makeEvent = function (method) { return ({
2200
+ collection: "todos",
2201
+ id: "doc-1",
2202
+ method: method,
2203
+ model: "Todo",
2204
+ timestamp: 1,
2205
+ }); };
2206
+ (0, bun_test_1.it)("emits creates through the permission-filtered path", function () { return __awaiter(void 0, void 0, void 0, function () {
2207
+ var queryId, _a, addSocketToRoom, emissions, io, queryEmissions;
2208
+ return __generator(this, function (_b) {
2209
+ switch (_b.label) {
2210
+ case 0:
2211
+ queryId = (0, queryStore_1.computeQueryId)("todos", { priority: 1 });
2212
+ (0, queryStore_1.addQuerySubscription)("socket-a", "todos", { priority: 1 }, queryId);
2213
+ _a = makeIo(), addSocketToRoom = _a.addSocketToRoom, emissions = _a.emissions, io = _a.io;
2214
+ addSocketToRoom("query:".concat(queryId), { id: "user-1" });
2215
+ return [4 /*yield*/, (0, changeStreamWatcher_1.emitToDocumentAndQueryRooms)(io, "todos", makeEvent("create"), { priority: 1 }, function () { }, modelEntry)];
2216
+ case 1:
2217
+ _b.sent();
2218
+ queryEmissions = emissions.filter(function (e) { return e.room === "query:".concat(queryId); });
2219
+ (0, bun_test_1.expect)(queryEmissions).toHaveLength(1);
2220
+ (0, bun_test_1.expect)(queryEmissions[0].payload).toMatchObject({ data: { priority: 1 }, method: "create" });
2221
+ return [2 /*return*/];
2222
+ }
2223
+ });
2224
+ }); });
2225
+ (0, bun_test_1.it)("emits updates through the permission-filtered path when the doc still matches", function () { return __awaiter(void 0, void 0, void 0, function () {
2226
+ var queryId, _a, addSocketToRoom, emissions, io, queryEmissions;
2227
+ return __generator(this, function (_b) {
2228
+ switch (_b.label) {
2229
+ case 0:
2230
+ queryId = (0, queryStore_1.computeQueryId)("todos", { priority: 1 });
2231
+ (0, queryStore_1.addQuerySubscription)("socket-a", "todos", { priority: 1 }, queryId);
2232
+ _a = makeIo(), addSocketToRoom = _a.addSocketToRoom, emissions = _a.emissions, io = _a.io;
2233
+ addSocketToRoom("query:".concat(queryId), { id: "user-1" });
2234
+ return [4 /*yield*/, (0, changeStreamWatcher_1.emitToDocumentAndQueryRooms)(io, "todos", makeEvent("update"), { priority: 1 }, function () { }, modelEntry)];
2235
+ case 1:
2236
+ _b.sent();
2237
+ queryEmissions = emissions.filter(function (e) { return e.room === "query:".concat(queryId); });
2238
+ (0, bun_test_1.expect)(queryEmissions).toHaveLength(1);
2239
+ (0, bun_test_1.expect)(queryEmissions[0].payload).toMatchObject({ method: "update" });
2240
+ return [2 /*return*/];
2241
+ }
2242
+ });
2243
+ }); });
2244
+ (0, bun_test_1.it)("converts non-matching updates into deletes through the permission-filtered path", function () { return __awaiter(void 0, void 0, void 0, function () {
2245
+ var queryId, _a, addSocketToRoom, emissions, io, queryEmissions;
2246
+ return __generator(this, function (_b) {
2247
+ switch (_b.label) {
2248
+ case 0:
2249
+ queryId = (0, queryStore_1.computeQueryId)("todos", { priority: 1 });
2250
+ (0, queryStore_1.addQuerySubscription)("socket-a", "todos", { priority: 1 }, queryId);
2251
+ _a = makeIo(), addSocketToRoom = _a.addSocketToRoom, emissions = _a.emissions, io = _a.io;
2252
+ addSocketToRoom("query:".concat(queryId), { id: "user-1" });
2253
+ return [4 /*yield*/, (0, changeStreamWatcher_1.emitToDocumentAndQueryRooms)(io, "todos", makeEvent("update"), { priority: 9 }, function () { }, modelEntry)];
2254
+ case 1:
2255
+ _b.sent();
2256
+ queryEmissions = emissions.filter(function (e) { return e.room === "query:".concat(queryId); });
2257
+ (0, bun_test_1.expect)(queryEmissions).toHaveLength(1);
2258
+ (0, bun_test_1.expect)(queryEmissions[0].payload).toMatchObject({ method: "delete" });
2259
+ return [2 /*return*/];
2260
+ }
2261
+ });
2262
+ }); });
2263
+ (0, bun_test_1.it)("skips query rooms whose subscribers cannot read the document", function () { return __awaiter(void 0, void 0, void 0, function () {
2264
+ var queryId, _a, addSocketToRoom, emissions, io, ownerEntry;
2265
+ return __generator(this, function (_b) {
2266
+ switch (_b.label) {
2267
+ case 0:
2268
+ queryId = (0, queryStore_1.computeQueryId)("todos", { priority: 1 });
2269
+ (0, queryStore_1.addQuerySubscription)("socket-a", "todos", { priority: 1 }, queryId);
2270
+ _a = makeIo(), addSocketToRoom = _a.addSocketToRoom, emissions = _a.emissions, io = _a.io;
2271
+ addSocketToRoom("query:".concat(queryId), { id: "other-user" });
2272
+ ownerEntry = __assign(__assign({}, modelEntry), { options: {
2273
+ permissions: __assign(__assign({}, modelEntry.options.permissions), { read: [
2274
+ function (_method, user, obj) {
2275
+ return (user === null || user === void 0 ? void 0 : user.admin) === true ||
2276
+ (user === null || user === void 0 ? void 0 : user.id) === (obj === null || obj === void 0 ? void 0 : obj.ownerId);
2277
+ },
2278
+ ] }),
2279
+ } });
2280
+ return [4 /*yield*/, (0, changeStreamWatcher_1.emitToDocumentAndQueryRooms)(io, "todos", makeEvent("create"), { ownerId: "user-1", priority: 1 }, function () { }, ownerEntry)];
2281
+ case 1:
2282
+ _b.sent();
2283
+ (0, bun_test_1.expect)(emissions.some(function (e) { return e.room === "query:".concat(queryId); })).toBe(false);
2284
+ return [2 /*return*/];
2285
+ }
2286
+ });
2287
+ }); });
2288
+ });
2183
2289
  });
2184
2290
  // ─────────────────────────────────────────────────────────────────────────────
2185
2291
  // redactCredentials — Redis URL logging
@@ -2535,6 +2641,131 @@ var createMockSocket = function (decodedToken) {
2535
2641
  }
2536
2642
  });
2537
2643
  }); });
2644
+ // Records every emission so hard-delete room routing can be asserted.
2645
+ var createRecordingIo = function (room, decodedToken) {
2646
+ if (decodedToken === void 0) { decodedToken = { admin: true, id: "admin" }; }
2647
+ var emissions = [];
2648
+ var rooms = new Map([[room, new Set(["socket-1"])]]);
2649
+ var sockets = new Map([
2650
+ [
2651
+ "socket-1",
2652
+ {
2653
+ decodedToken: decodedToken,
2654
+ emit: function (event, payload) {
2655
+ emissions.push({ event: event, payload: payload });
2656
+ },
2657
+ id: "socket-1",
2658
+ },
2659
+ ],
2660
+ ]);
2661
+ return {
2662
+ emissions: emissions,
2663
+ io: {
2664
+ sockets: { adapter: { rooms: rooms }, sockets: sockets },
2665
+ to: function (_room) { return ({ emit: function (_event, _data) { } }); },
2666
+ },
2667
+ };
2668
+ };
2669
+ (0, bun_test_1.it)("routes hard deletes for model-strategy models to the model room", function () { return __awaiter(void 0, void 0, void 0, function () {
2670
+ var mockStream, mockDb, startChangeStreamWatcher, _a, emissions, io;
2671
+ return __generator(this, function (_b) {
2672
+ switch (_b.label) {
2673
+ case 0:
2674
+ mockStream = createMockChangeStream();
2675
+ mockDb = {
2676
+ watch: (0, bun_test_1.mock)(function () { return mockStream; }),
2677
+ };
2678
+ mongoose_1.default.connection.db = mockDb;
2679
+ (0, registry_1.registerRealtime)({
2680
+ collectionName: "todos",
2681
+ config: {
2682
+ methods: ["create", "update", "delete"],
2683
+ roomStrategy: "model",
2684
+ },
2685
+ modelName: "Todo",
2686
+ options: {
2687
+ permissions: {
2688
+ create: [function () { return true; }],
2689
+ delete: [function () { return true; }],
2690
+ list: [function () { return true; }],
2691
+ read: [function () { return true; }],
2692
+ update: [function () { return true; }],
2693
+ },
2694
+ },
2695
+ routePath: "/todos",
2696
+ });
2697
+ return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require("./changeStreamWatcher")); })];
2698
+ case 1:
2699
+ startChangeStreamWatcher = (_b.sent()).startChangeStreamWatcher;
2700
+ _a = createRecordingIo("model:todos"), emissions = _a.emissions, io = _a.io;
2701
+ startChangeStreamWatcher(io, {}, true);
2702
+ return [4 /*yield*/, invokeRegisteredChangeHandler(mockStream, {
2703
+ documentKey: { _id: "doc-1" },
2704
+ ns: { coll: "todos" },
2705
+ operationType: "delete",
2706
+ })];
2707
+ case 2:
2708
+ _b.sent();
2709
+ (0, bun_test_1.expect)(emissions).toHaveLength(1);
2710
+ (0, bun_test_1.expect)(emissions[0].payload).toMatchObject({ id: "doc-1", method: "delete", model: "Todo" });
2711
+ return [2 /*return*/];
2712
+ }
2713
+ });
2714
+ }); });
2715
+ (0, bun_test_1.it)("swallows errors thrown while processing a change event", function () { return __awaiter(void 0, void 0, void 0, function () {
2716
+ var mockStream, mockDb, startChangeStreamWatcher, roomLookup, io;
2717
+ return __generator(this, function (_a) {
2718
+ switch (_a.label) {
2719
+ case 0:
2720
+ mockStream = createMockChangeStream();
2721
+ mockDb = {
2722
+ watch: (0, bun_test_1.mock)(function () { return mockStream; }),
2723
+ };
2724
+ mongoose_1.default.connection.db = mockDb;
2725
+ (0, registry_1.registerRealtime)({
2726
+ collectionName: "todos",
2727
+ config: {
2728
+ methods: ["create", "update", "delete"],
2729
+ roomStrategy: "model",
2730
+ },
2731
+ modelName: "Todo",
2732
+ options: {
2733
+ permissions: {
2734
+ create: [function () { return true; }],
2735
+ delete: [function () { return true; }],
2736
+ list: [function () { return true; }],
2737
+ read: [function () { return true; }],
2738
+ update: [function () { return true; }],
2739
+ },
2740
+ },
2741
+ routePath: "/todos",
2742
+ });
2743
+ return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require("./changeStreamWatcher")); })];
2744
+ case 1:
2745
+ startChangeStreamWatcher = (_a.sent()).startChangeStreamWatcher;
2746
+ roomLookup = (0, bun_test_1.mock)(function () {
2747
+ throw new Error("adapter unavailable");
2748
+ });
2749
+ io = {
2750
+ sockets: { adapter: { rooms: { get: roomLookup } }, sockets: new Map() },
2751
+ to: function (_room) { return ({ emit: function (_event, _data) { } }); },
2752
+ };
2753
+ startChangeStreamWatcher(io, {}, true);
2754
+ // The handler must not reject — a failed emission cannot take down the change stream.
2755
+ return [4 /*yield*/, invokeRegisteredChangeHandler(mockStream, {
2756
+ documentKey: { _id: "doc-1" },
2757
+ fullDocument: { _id: "doc-1", name: "Test Todo" },
2758
+ ns: { coll: "todos" },
2759
+ operationType: "insert",
2760
+ })];
2761
+ case 2:
2762
+ // The handler must not reject — a failed emission cannot take down the change stream.
2763
+ _a.sent();
2764
+ (0, bun_test_1.expect)(roomLookup).toHaveBeenCalled();
2765
+ return [2 /*return*/];
2766
+ }
2767
+ });
2768
+ }); });
2538
2769
  (0, bun_test_1.it)("includes updatedFields in event for update operations", function () { return __awaiter(void 0, void 0, void 0, function () {
2539
2770
  var mockStream, mockDb, startChangeStreamWatcher, io;
2540
2771
  return __generator(this, function (_a) {
@@ -28,7 +28,7 @@ export interface RealtimeSocketLike extends SocketWithDecodedToken {
28
28
  join: (room: string) => Promise<void> | void;
29
29
  leave: (room: string) => Promise<void> | void;
30
30
  emit: (event: string, payload: unknown) => void;
31
- on: (event: string, handler: (...args: any[]) => any) => void;
31
+ on: (event: string, handler: (...args: never[]) => void | Promise<void>) => void;
32
32
  }
33
33
  /**
34
34
  * Install the realtime subscription handlers on a single socket. Extracted from the
@@ -84,6 +84,7 @@ exports.RealtimeApp = exports.installRealtimeSocketHandlers = exports.redactCred
84
84
  var Sentry = __importStar(require("@sentry/bun"));
85
85
  var socketio_jwt_1 = require("@thream/socketio-jwt");
86
86
  var socket_io_1 = require("socket.io");
87
+ var errors_1 = require("../errors");
87
88
  var logger_1 = require("../logger");
88
89
  var permissions_1 = require("../permissions");
89
90
  var changeStreamWatcher_1 = require("./changeStreamWatcher");
@@ -462,8 +463,11 @@ var RealtimeApp = /** @class */ (function () {
462
463
  // JWT authentication middleware
463
464
  var tokenSecret = (_c = this.config.tokenSecret) !== null && _c !== void 0 ? _c : process.env.TOKEN_SECRET;
464
465
  if (!tokenSecret) {
465
- throw new Error("[realtime] TOKEN_SECRET is required for socket authentication. " +
466
- "Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions.");
466
+ throw new errors_1.APIError({
467
+ status: 500,
468
+ title: "[realtime] TOKEN_SECRET is required for socket authentication. " +
469
+ "Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions.",
470
+ });
467
471
  }
468
472
  this.io.use((0, socketio_jwt_1.authorize)({
469
473
  secret: tokenSecret,
@@ -0,0 +1 @@
1
+ export {};