@terreno/api 0.31.0 → 56.0.0-beta.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 (250) hide show
  1. package/CHANGELOG.md +122 -2
  2. package/LICENSE +202 -21
  3. package/dist/api.d.ts +12 -3
  4. package/dist/api.js +110 -361
  5. package/dist/auth.d.ts +26 -0
  6. package/dist/auth.js +100 -1
  7. package/dist/betterAuth.d.ts +5 -0
  8. package/dist/betterAuthSetup.d.ts +1 -15
  9. package/dist/betterAuthSetup.js +29 -8
  10. package/dist/configurationPlugin.js +2 -2
  11. package/dist/docLoader.js +12 -9
  12. package/dist/errors.d.ts +13 -0
  13. package/dist/errors.js +29 -1
  14. package/dist/expressServer.js +5 -11
  15. package/dist/githubAuth.js +4 -1
  16. package/dist/index.d.ts +17 -1
  17. package/dist/index.js +29 -1
  18. package/dist/middleware.d.ts +7 -0
  19. package/dist/middleware.js +16 -1
  20. package/dist/openApiCompat.d.ts +10 -1
  21. package/dist/openApiCompat.js +115 -47
  22. package/dist/permissions.d.ts +27 -0
  23. package/dist/permissions.js +42 -1
  24. package/dist/plugins.d.ts +15 -3
  25. package/dist/plugins.js +36 -6
  26. package/dist/realtime/changeStreamWatcher.d.ts +100 -3
  27. package/dist/realtime/changeStreamWatcher.js +542 -137
  28. package/dist/realtime/realtimeApp.d.ts +3 -1
  29. package/dist/realtime/realtimeApp.js +75 -27
  30. package/dist/realtime/sessionRevalidation.d.ts +90 -0
  31. package/dist/realtime/sessionRevalidation.js +438 -0
  32. package/dist/realtime/socketAuth.d.ts +97 -0
  33. package/dist/realtime/socketAuth.js +272 -0
  34. package/dist/realtime/socketUser.d.ts +54 -0
  35. package/dist/realtime/socketUser.js +75 -5
  36. package/dist/realtime/types.d.ts +40 -0
  37. package/dist/secretProviders.d.ts +23 -0
  38. package/dist/secretProviders.js +9 -3
  39. package/dist/sync/executors.d.ts +198 -0
  40. package/dist/sync/executors.js +670 -0
  41. package/dist/sync/loadHarness.js +807 -0
  42. package/dist/sync/models.d.ts +216 -0
  43. package/dist/sync/models.js +644 -0
  44. package/dist/sync/mutationHandler.d.ts +97 -0
  45. package/dist/sync/mutationHandler.js +886 -0
  46. package/dist/sync/registry.d.ts +73 -0
  47. package/dist/sync/registry.js +223 -0
  48. package/dist/sync/routes.d.ts +62 -0
  49. package/dist/sync/routes.js +936 -0
  50. package/dist/sync/scripts/compactTombstones.d.ts +47 -0
  51. package/dist/sync/scripts/compactTombstones.js +270 -0
  52. package/dist/sync/serialize.d.ts +20 -0
  53. package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
  54. package/dist/sync/socketHandlers.d.ts +54 -0
  55. package/dist/sync/socketHandlers.js +470 -0
  56. package/dist/sync/streams.d.ts +85 -0
  57. package/dist/sync/streams.js +221 -0
  58. package/dist/sync/syncApp.d.ts +29 -0
  59. package/dist/sync/syncApp.js +44 -0
  60. package/dist/sync/syncBatch.d.ts +71 -0
  61. package/dist/sync/syncBatch.js +252 -0
  62. package/dist/sync/syncSeqPlugin.d.ts +8 -0
  63. package/dist/sync/syncSeqPlugin.js +903 -0
  64. package/dist/sync/types.d.ts +254 -0
  65. package/dist/sync/types.js +9 -0
  66. package/dist/terrenoApp.js +90 -27
  67. package/dist/tests/models.d.ts +11 -27
  68. package/dist/tests/models.js +3 -5
  69. package/dist/tests/testHelper.d.ts +3 -9
  70. package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
  71. package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
  72. package/package.json +10 -8
  73. package/src/__tests__/openApiCompat.test.ts +20 -0
  74. package/src/actions.test.ts +12 -19
  75. package/src/actions.ts +2 -2
  76. package/src/api.coverage.test.ts +9 -7
  77. package/src/api.errorPaths.test.ts +1 -47
  78. package/src/api.test.ts +12 -0
  79. package/src/api.ts +98 -317
  80. package/src/auth.test.ts +128 -176
  81. package/src/auth.ts +109 -0
  82. package/src/betterAuth.ts +6 -0
  83. package/src/betterAuthSetup.test.ts +34 -0
  84. package/src/betterAuthSetup.ts +27 -8
  85. package/src/configurationPlugin.ts +2 -2
  86. package/src/consentApp.test.ts +12 -12
  87. package/src/docLoader.ts +3 -1
  88. package/src/errors.ts +33 -0
  89. package/src/expressServer.test.ts +7 -1
  90. package/src/expressServer.ts +5 -11
  91. package/src/githubAuth.ts +3 -1
  92. package/src/index.ts +42 -0
  93. package/src/middleware.test.ts +40 -1
  94. package/src/middleware.ts +15 -0
  95. package/src/models/versionConfig.ts +1 -1
  96. package/src/openApiBuilder.test.ts +9 -24
  97. package/src/openApiCompat.ts +99 -45
  98. package/src/openApiValidator.test.ts +0 -41
  99. package/src/permissions.test.ts +75 -1
  100. package/src/permissions.ts +49 -0
  101. package/src/plugins.test.ts +54 -14
  102. package/src/plugins.ts +47 -9
  103. package/src/populate.test.ts +16 -25
  104. package/src/realtime/changeStreamWatcher.ts +552 -114
  105. package/src/realtime/realtime.test.ts +157 -239
  106. package/src/realtime/realtimeApp.ts +80 -19
  107. package/src/realtime/sessionRevalidation.test.ts +423 -0
  108. package/src/realtime/sessionRevalidation.ts +273 -0
  109. package/src/realtime/socketAuth.test.ts +355 -0
  110. package/src/realtime/socketAuth.ts +228 -0
  111. package/src/realtime/socketUser.ts +69 -0
  112. package/src/realtime/types.ts +40 -0
  113. package/src/secretProviders.test.ts +7 -1
  114. package/src/secretProviders.ts +15 -3
  115. package/src/sync/ensureSyncIndexes.test.ts +144 -0
  116. package/src/sync/executors.test.ts +882 -0
  117. package/src/sync/executors.ts +703 -0
  118. package/src/sync/integration.test.ts +1160 -0
  119. package/src/sync/loadHarness.ts +618 -0
  120. package/src/sync/models.ts +640 -0
  121. package/src/sync/mutationHandler.test.ts +1252 -0
  122. package/src/sync/mutationHandler.ts +850 -0
  123. package/src/sync/registry.ts +232 -0
  124. package/src/sync/routes.ts +812 -0
  125. package/src/sync/scripts/compactTombstones.test.ts +249 -0
  126. package/src/sync/scripts/compactTombstones.ts +145 -0
  127. package/src/sync/serialize.ts +48 -0
  128. package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
  129. package/src/sync/socketHandlers.ts +320 -0
  130. package/src/sync/streams.ts +188 -0
  131. package/src/sync/sync.test.ts +582 -0
  132. package/src/sync/syncApp.ts +44 -0
  133. package/src/sync/syncBatch.ts +219 -0
  134. package/src/sync/syncFrontier.test.ts +494 -0
  135. package/src/sync/syncPhaseC.test.ts +718 -0
  136. package/src/sync/syncRoutes.test.ts +865 -0
  137. package/src/sync/syncSeqPlugin.ts +738 -0
  138. package/src/sync/syncSocket.test.ts +1440 -0
  139. package/src/sync/types.ts +270 -0
  140. package/src/terrenoApp.ts +37 -17
  141. package/src/tests/bunSetup.ts +8 -0
  142. package/src/tests/models.ts +6 -8
  143. package/tsconfig.json +4 -4
  144. package/tsconfig.typedoc.json +7 -1
  145. package/dist/__tests__/openApiCompat.test.js +0 -317
  146. package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
  147. package/dist/__tests__/versionCheckPlugin.test.js +0 -597
  148. package/dist/actions.openApi.test.d.ts +0 -1
  149. package/dist/actions.openApi.test.js +0 -253
  150. package/dist/actions.test.d.ts +0 -1
  151. package/dist/actions.test.js +0 -1087
  152. package/dist/api.arrayOperations.test.d.ts +0 -1
  153. package/dist/api.arrayOperations.test.js +0 -878
  154. package/dist/api.asyncHandler.test.d.ts +0 -1
  155. package/dist/api.asyncHandler.test.js +0 -236
  156. package/dist/api.coverage.test.d.ts +0 -1
  157. package/dist/api.coverage.test.js +0 -192
  158. package/dist/api.errorPaths.test.d.ts +0 -1
  159. package/dist/api.errorPaths.test.js +0 -887
  160. package/dist/api.errors.test.d.ts +0 -1
  161. package/dist/api.errors.test.js +0 -185
  162. package/dist/api.hooks.test.d.ts +0 -1
  163. package/dist/api.hooks.test.js +0 -950
  164. package/dist/api.query.test.d.ts +0 -1
  165. package/dist/api.query.test.js +0 -948
  166. package/dist/api.test.d.ts +0 -1
  167. package/dist/api.test.js +0 -2820
  168. package/dist/auth.compile.test.d.ts +0 -1
  169. package/dist/auth.compile.test.js +0 -201
  170. package/dist/auth.coverage.test.d.ts +0 -1
  171. package/dist/auth.coverage.test.js +0 -202
  172. package/dist/auth.test.d.ts +0 -1
  173. package/dist/auth.test.js +0 -2286
  174. package/dist/betterAuth.test.d.ts +0 -1
  175. package/dist/betterAuth.test.js +0 -181
  176. package/dist/betterAuthApp.test.d.ts +0 -1
  177. package/dist/betterAuthApp.test.js +0 -242
  178. package/dist/betterAuthSetup.test.d.ts +0 -1
  179. package/dist/betterAuthSetup.test.js +0 -762
  180. package/dist/config.test.d.ts +0 -1
  181. package/dist/config.test.js +0 -353
  182. package/dist/configuration.test.d.ts +0 -1
  183. package/dist/configuration.test.js +0 -980
  184. package/dist/configurationPlugin.test.d.ts +0 -1
  185. package/dist/configurationPlugin.test.js +0 -827
  186. package/dist/consentApp.test.d.ts +0 -1
  187. package/dist/consentApp.test.js +0 -1411
  188. package/dist/docLoader.test.d.ts +0 -1
  189. package/dist/docLoader.test.js +0 -137
  190. package/dist/envConfigurationPlugin.test.d.ts +0 -1
  191. package/dist/envConfigurationPlugin.test.js +0 -369
  192. package/dist/errors.test.d.ts +0 -1
  193. package/dist/errors.test.js +0 -607
  194. package/dist/expressServer.test.d.ts +0 -1
  195. package/dist/expressServer.test.js +0 -1249
  196. package/dist/githubAuth.test.d.ts +0 -1
  197. package/dist/githubAuth.test.js +0 -1142
  198. package/dist/httpClient.test.d.ts +0 -1
  199. package/dist/httpClient.test.js +0 -1471
  200. package/dist/logger.test.d.ts +0 -1
  201. package/dist/logger.test.js +0 -685
  202. package/dist/middleware.test.d.ts +0 -1
  203. package/dist/middleware.test.js +0 -241
  204. package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
  205. package/dist/notifiers/googleChatNotifier.test.js +0 -298
  206. package/dist/notifiers/slackNotifier.test.d.ts +0 -1
  207. package/dist/notifiers/slackNotifier.test.js +0 -297
  208. package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
  209. package/dist/notifiers/zoomNotifier.test.js +0 -373
  210. package/dist/openApi.test.d.ts +0 -1
  211. package/dist/openApi.test.js +0 -620
  212. package/dist/openApiBuilder.test.d.ts +0 -1
  213. package/dist/openApiBuilder.test.js +0 -599
  214. package/dist/openApiEtag.test.d.ts +0 -1
  215. package/dist/openApiEtag.test.js +0 -86
  216. package/dist/openApiValidator.test.d.ts +0 -1
  217. package/dist/openApiValidator.test.js +0 -795
  218. package/dist/permissions.middleware.test.d.ts +0 -1
  219. package/dist/permissions.middleware.test.js +0 -308
  220. package/dist/permissions.test.d.ts +0 -1
  221. package/dist/permissions.test.js +0 -439
  222. package/dist/plugins.test.d.ts +0 -1
  223. package/dist/plugins.test.js +0 -902
  224. package/dist/populate.test.d.ts +0 -1
  225. package/dist/populate.test.js +0 -370
  226. package/dist/realtime/realtime.test.d.ts +0 -10
  227. package/dist/realtime/realtime.test.js +0 -4213
  228. package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
  229. package/dist/realtime/realtimeAppSetup.test.js +0 -213
  230. package/dist/requestContext.test.d.ts +0 -1
  231. package/dist/requestContext.test.js +0 -412
  232. package/dist/scriptRunner.test.d.ts +0 -1
  233. package/dist/scriptRunner.test.js +0 -386
  234. package/dist/secretProviders.test.d.ts +0 -1
  235. package/dist/secretProviders.test.js +0 -726
  236. package/dist/syncConsents.test.d.ts +0 -1
  237. package/dist/syncConsents.test.js +0 -522
  238. package/dist/terrenoApp.test.d.ts +0 -1
  239. package/dist/terrenoApp.test.js +0 -489
  240. package/dist/tests/bunSetup.d.ts +0 -1
  241. package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
  242. package/dist/tests/fixtures/compileAuthEntry.js +0 -37
  243. package/dist/tests/testEnv.d.ts +0 -0
  244. package/dist/tests/testEnv.js +0 -6
  245. package/dist/transformers.test.d.ts +0 -1
  246. package/dist/transformers.test.js +0 -423
  247. package/dist/utils.test.d.ts +0 -1
  248. package/dist/utils.test.js +0 -242
  249. package/src/realtime/realtimeAppSetup.test.ts +0 -161
  250. /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
@@ -1,4 +1,15 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
2
13
  var __values = (this && this.__values) || function(o) {
3
14
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
4
15
  if (m) return m.call(o);
@@ -35,9 +46,24 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
35
46
  }
36
47
  return to.concat(ar || Array.prototype.slice.call(from));
37
48
  };
49
+ var __importDefault = (this && this.__importDefault) || function (mod) {
50
+ return (mod && mod.__esModule) ? mod : { "default": mod };
51
+ };
38
52
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.openApiCompatMiddleware = exports.patchAppUse = void 0;
53
+ exports.openApiCompatMiddleware = exports.patchAppUse = exports.patchExpressRouterUse = void 0;
54
+ /**
55
+ * Patches the Express router stack to add `.regexp` on layers for
56
+ * compatibility with @wesleytodd/openapi, which expects Express 4-style
57
+ * layers with `.regexp.fast_slash`.
58
+ *
59
+ * In Express 5 (router@2.x), layers use `.slash` (boolean) and `.matchers`
60
+ * (array of functions) instead of `.regexp`.
61
+ *
62
+ * @see https://github.com/wesleytodd/express-openapi/issues/70
63
+ */
64
+ var express_1 = __importDefault(require("express"));
40
65
  var MOUNT_PATH_KEY = "__openApiMountPath";
66
+ var isExpressRouterUsePatched = false;
41
67
  /**
42
68
  * Extract Express 4-style keys from a path string.
43
69
  * Parses `:paramName` and `*paramName` segments into `{name, optional}` objects
@@ -77,52 +103,64 @@ var buildRegexpForPath = function (pathStr, isMount) {
77
103
  }
78
104
  return new RegExp("^".concat(pattern, "\\/?$"));
79
105
  };
106
+ var annotateMountLayers = function (stack, stackBefore, args) {
107
+ if (!stack) {
108
+ return;
109
+ }
110
+ var mountPath = typeof args[0] === "string" ? args[0] : undefined;
111
+ if (!mountPath || mountPath === "/") {
112
+ return;
113
+ }
114
+ var normalizedMountPath = mountPath.replace(/\/+$/, "");
115
+ for (var i = stackBefore; i < stack.length; i++) {
116
+ stack[i][MOUNT_PATH_KEY] = normalizedMountPath;
117
+ }
118
+ };
80
119
  var patchRouterStack = function (stack) {
81
120
  var e_1, _a;
82
121
  var _b, _c, _d, _e;
83
122
  try {
84
123
  for (var stack_1 = __values(stack), stack_1_1 = stack_1.next(); !stack_1_1.done; stack_1_1 = stack_1.next()) {
85
124
  var layer = stack_1_1.value;
86
- if (layer.regexp !== undefined) {
87
- continue;
88
- }
89
- // Determine the path string for this layer
90
- var pathStr = void 0;
91
- var isMount = layer.name === "router" || !!((_b = layer.handle) === null || _b === void 0 ? void 0 : _b.stack);
92
- if (layer.slash) {
93
- // Express 5 layers use .slash instead of .regexp.fast_slash
94
- layer.regexp = { fast_slash: true };
95
- }
96
- else if (layer[MOUNT_PATH_KEY]) {
97
- pathStr = layer[MOUNT_PATH_KEY];
98
- layer.regexp = buildRegexpForPath(pathStr, isMount);
99
- }
100
- else if (layer.path && typeof layer.path === "string") {
101
- pathStr = layer.path;
102
- layer.regexp = buildRegexpForPath(pathStr, false);
103
- }
104
- else if (((_c = layer.route) === null || _c === void 0 ? void 0 : _c.path) && typeof layer.route.path === "string") {
105
- pathStr = layer.route.path;
106
- layer.regexp = buildRegexpForPath(pathStr, false);
107
- }
108
- else {
109
- layer.regexp = /^\/?$/;
110
- }
111
- // Populate keys in Express 4 format: [{name, optional}]
112
- // @wesleytodd/openapi reads layer.keys[i].name for path parameters
113
- if (!layer.keys || (Array.isArray(layer.keys) && layer.keys.length === 0)) {
114
- if (pathStr) {
115
- layer.keys = extractKeysFromPath(pathStr);
125
+ if (layer.regexp === undefined) {
126
+ // Determine the path string for this layer
127
+ var pathStr = void 0;
128
+ var isMount = layer.name === "router" || !!((_b = layer.handle) === null || _b === void 0 ? void 0 : _b.stack);
129
+ if (layer.slash) {
130
+ // Express 5 layers use .slash instead of .regexp.fast_slash
131
+ layer.regexp = { fast_slash: true };
132
+ }
133
+ else if (layer[MOUNT_PATH_KEY]) {
134
+ pathStr = layer[MOUNT_PATH_KEY];
135
+ layer.regexp = buildRegexpForPath(pathStr, isMount);
136
+ }
137
+ else if (layer.path && typeof layer.path === "string") {
138
+ pathStr = layer.path;
139
+ layer.regexp = buildRegexpForPath(pathStr, false);
140
+ }
141
+ else if (((_c = layer.route) === null || _c === void 0 ? void 0 : _c.path) && typeof layer.route.path === "string") {
142
+ pathStr = layer.route.path;
143
+ layer.regexp = buildRegexpForPath(pathStr, false);
116
144
  }
117
145
  else {
118
- layer.keys = [];
146
+ layer.regexp = /^\/?$/;
147
+ }
148
+ // Populate keys in Express 4 format: [{name, optional}]
149
+ // @wesleytodd/openapi reads layer.keys[i].name for path parameters
150
+ if (!layer.keys || (Array.isArray(layer.keys) && layer.keys.length === 0)) {
151
+ if (pathStr) {
152
+ layer.keys = extractKeysFromPath(pathStr);
153
+ }
154
+ else {
155
+ layer.keys = [];
156
+ }
157
+ }
158
+ else if (Array.isArray(layer.keys) && typeof layer.keys[0] === "string") {
159
+ // Express 5 stores keys as plain strings after match() — convert to objects
160
+ layer.keys = layer.keys.map(function (k) { return ({ name: k, optional: false }); });
119
161
  }
120
162
  }
121
- else if (Array.isArray(layer.keys) && typeof layer.keys[0] === "string") {
122
- // Express 5 stores keys as plain strings after match() — convert to objects
123
- layer.keys = layer.keys.map(function (k) { return ({ name: k, optional: false }); });
124
- }
125
- // Recursively patch nested stacks
163
+ // Recursively patch nested stacks even when this layer already had a regexp.
126
164
  if ((_d = layer.handle) === null || _d === void 0 ? void 0 : _d.stack) {
127
165
  patchRouterStack(layer.handle.stack);
128
166
  }
@@ -139,6 +177,44 @@ var patchRouterStack = function (stack) {
139
177
  finally { if (e_1) throw e_1.error; }
140
178
  }
141
179
  };
180
+ /**
181
+ * Patches `express.Router().use` so nested mounts (e.g. `router.use("/gpt/histories", ...)`)
182
+ * record `__openApiMountPath` the same way `app.use` does. Without this, nested
183
+ * modelRouter OpenAPI paths are omitted from `/openapi.json`.
184
+ *
185
+ * Express 5's Router puts `use` a few prototypes up from the instance, so we walk
186
+ * the chain until we find the own `use` descriptor.
187
+ */
188
+ var patchExpressRouterUse = function () {
189
+ if (isExpressRouterUsePatched) {
190
+ return;
191
+ }
192
+ isExpressRouterUsePatched = true;
193
+ var routerPrototype = Object.getPrototypeOf(express_1.default.Router());
194
+ while (routerPrototype && !Object.getOwnPropertyDescriptor(routerPrototype, "use")) {
195
+ routerPrototype = Object.getPrototypeOf(routerPrototype);
196
+ }
197
+ if (!routerPrototype) {
198
+ return;
199
+ }
200
+ var useDescriptor = Object.getOwnPropertyDescriptor(routerPrototype, "use");
201
+ if (!(useDescriptor === null || useDescriptor === void 0 ? void 0 : useDescriptor.value)) {
202
+ return;
203
+ }
204
+ var originalUse = useDescriptor.value;
205
+ Object.defineProperty(routerPrototype, "use", __assign(__assign({}, useDescriptor), { value: function patchedRouterUse() {
206
+ var _a, _b;
207
+ var args = [];
208
+ for (var _i = 0; _i < arguments.length; _i++) {
209
+ args[_i] = arguments[_i];
210
+ }
211
+ var stackBefore = (_b = (_a = this.stack) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
212
+ var result = originalUse.apply(this, args);
213
+ annotateMountLayers(this.stack, stackBefore, args);
214
+ return result;
215
+ } }));
216
+ };
217
+ exports.patchExpressRouterUse = patchExpressRouterUse;
142
218
  /**
143
219
  * Wraps an Express app's `use` method to record the mount path on each
144
220
  * layer added to the router stack. This runs at setup time so that
@@ -147,6 +223,7 @@ var patchRouterStack = function (stack) {
147
223
  * Must be called before any routes are registered.
148
224
  */
149
225
  var patchAppUse = function (app) {
226
+ (0, exports.patchExpressRouterUse)();
150
227
  var internal = app;
151
228
  var originalUse = app.use.bind(app);
152
229
  var patchedUse = function () {
@@ -161,16 +238,7 @@ var patchAppUse = function (app) {
161
238
  var result = originalUse.apply(void 0, __spreadArray([], __read(args), false));
162
239
  // After use(), check if new layers were added and annotate them
163
240
  var routerAfter = (_d = internal._router) !== null && _d !== void 0 ? _d : internal.router;
164
- if (routerAfter === null || routerAfter === void 0 ? void 0 : routerAfter.stack) {
165
- var stackAfter = routerAfter.stack.length;
166
- // The first arg is the mount path if it's a string
167
- var mountPath = typeof args[0] === "string" ? args[0] : undefined;
168
- if (mountPath && mountPath !== "/") {
169
- for (var i = stackBefore; i < stackAfter; i++) {
170
- routerAfter.stack[i][MOUNT_PATH_KEY] = mountPath.replace(/\/+$/, "");
171
- }
172
- }
173
- }
241
+ annotateMountLayers(routerAfter === null || routerAfter === void 0 ? void 0 : routerAfter.stack, stackBefore, args);
174
242
  return result;
175
243
  };
176
244
  app.use = patchedUse;
@@ -14,11 +14,38 @@ export interface RESTPermissions<T> {
14
14
  export declare const OwnerQueryFilter: (user?: User) => {
15
15
  ownerId: string;
16
16
  } | null;
17
+ /**
18
+ * A user that may belong to one or more organizations (tenants). Backends that use tenant-scoped
19
+ * models add an `organizationIds` array to their user model; this interface lets the shared
20
+ * permission/query-filter helpers read it without every consumer casting by hand.
21
+ */
22
+ export interface OrganizationScopedUser extends User {
23
+ organizationIds?: string[];
24
+ }
25
+ /** Reads the caller's organization ids, tolerating users without the `organizationIds` field. */
26
+ export declare const getUserOrganizationIds: (user?: User) => string[];
27
+ /**
28
+ * Restricts list queries to documents belonging to one of the caller's organizations. This is the
29
+ * tenant-scoped analog of {@link OwnerQueryFilter}: it filters on the document's `organizationId`
30
+ * field using the user's `organizationIds`. Returns `null` for anonymous callers (no user).
31
+ */
32
+ export declare const OrganizationQueryFilter: (user?: User) => {
33
+ organizationId: {
34
+ $in: string[];
35
+ };
36
+ } | null;
17
37
  export declare const Permissions: {
18
38
  IsAdmin: (_method: RESTMethod, user?: User) => boolean;
19
39
  IsAny: () => boolean;
20
40
  IsAuthenticated: (_method: RESTMethod, user?: User) => boolean;
21
41
  IsAuthenticatedOrReadOnly: (method: RESTMethod, user?: User) => boolean;
42
+ /**
43
+ * Object-level permission for tenant-scoped documents: the caller must belong to the document's
44
+ * organization (admins always pass). With no object (list/create checks) it returns true and
45
+ * defers to the {@link OrganizationQueryFilter} / a `preCreate` hook to scope access. Expects the
46
+ * document to expose an `organizationId` and the user an `organizationIds` array.
47
+ */
48
+ IsOrganizationMember: (_method: RESTMethod, user?: User, obj?: unknown) => boolean;
22
49
  IsOwner: (_method: RESTMethod, user?: User, obj?: unknown) => boolean;
23
50
  IsOwnerOrReadOnly: (method: RESTMethod, user?: User, obj?: unknown) => boolean;
24
51
  };
@@ -47,7 +47,7 @@ var __values = (this && this.__values) || function(o) {
47
47
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
48
48
  };
49
49
  Object.defineProperty(exports, "__esModule", { value: true });
50
- exports.permissionMiddleware = exports.checkPermissions = exports.Permissions = exports.OwnerQueryFilter = void 0;
50
+ exports.permissionMiddleware = exports.checkPermissions = exports.Permissions = exports.OrganizationQueryFilter = exports.getUserOrganizationIds = exports.OwnerQueryFilter = void 0;
51
51
  var docLoader_1 = require("./docLoader");
52
52
  var errors_1 = require("./errors");
53
53
  var OwnerQueryFilter = function (user) {
@@ -57,6 +57,24 @@ var OwnerQueryFilter = function (user) {
57
57
  return null;
58
58
  };
59
59
  exports.OwnerQueryFilter = OwnerQueryFilter;
60
+ /** Reads the caller's organization ids, tolerating users without the `organizationIds` field. */
61
+ var getUserOrganizationIds = function (user) {
62
+ var _a;
63
+ return (_a = user === null || user === void 0 ? void 0 : user.organizationIds) !== null && _a !== void 0 ? _a : [];
64
+ };
65
+ exports.getUserOrganizationIds = getUserOrganizationIds;
66
+ /**
67
+ * Restricts list queries to documents belonging to one of the caller's organizations. This is the
68
+ * tenant-scoped analog of {@link OwnerQueryFilter}: it filters on the document's `organizationId`
69
+ * field using the user's `organizationIds`. Returns `null` for anonymous callers (no user).
70
+ */
71
+ var OrganizationQueryFilter = function (user) {
72
+ if (!user) {
73
+ return null;
74
+ }
75
+ return { organizationId: { $in: (0, exports.getUserOrganizationIds)(user) } };
76
+ };
77
+ exports.OrganizationQueryFilter = OrganizationQueryFilter;
60
78
  exports.Permissions = {
61
79
  IsAdmin: function (_method, user) {
62
80
  return Boolean(user === null || user === void 0 ? void 0 : user.admin);
@@ -76,6 +94,29 @@ exports.Permissions = {
76
94
  }
77
95
  return method === "list" || method === "read";
78
96
  },
97
+ /**
98
+ * Object-level permission for tenant-scoped documents: the caller must belong to the document's
99
+ * organization (admins always pass). With no object (list/create checks) it returns true and
100
+ * defers to the {@link OrganizationQueryFilter} / a `preCreate` hook to scope access. Expects the
101
+ * document to expose an `organizationId` and the user an `organizationIds` array.
102
+ */
103
+ IsOrganizationMember: function (_method, user, obj) {
104
+ // When checking if we can possibly perform the action, return true.
105
+ if (!obj) {
106
+ return true;
107
+ }
108
+ if (!user) {
109
+ return false;
110
+ }
111
+ if (user === null || user === void 0 ? void 0 : user.admin) {
112
+ return true;
113
+ }
114
+ var organizationId = obj.organizationId;
115
+ if (!organizationId) {
116
+ return false;
117
+ }
118
+ return (0, exports.getUserOrganizationIds)(user).includes(organizationId);
119
+ },
79
120
  IsOwner: function (_method, user, obj) {
80
121
  var _a;
81
122
  // When checking if we can possibly perform the action, return true.
package/dist/plugins.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- import mongoose, { type Document, type Schema, SchemaType, type SchemaTypeOptions } from "mongoose";
1
+ import mongoose, { type Document, type FilterQuery, type Schema, SchemaType, type SchemaTypeOptions } from "mongoose";
2
2
  import { type APIErrorOptions } from "./errors";
3
- export type ModelQuery<T> = Partial<Record<keyof T, unknown>> & Record<string, unknown>;
4
3
  export interface BaseUser {
5
4
  admin: boolean;
6
5
  email: string;
@@ -42,7 +41,7 @@ export declare const findOneOrNone: <T>(schema: Schema<T>) => void;
42
41
  * @param query Mongoose query object
43
42
  * @param errorArgs Optional overrides for the thrown {@link APIError} when multiple match
44
43
  */
45
- export declare const findOneOrNoneFor: <T>(model: mongoose.Model<T>, query: ModelQuery<T>, errorArgs?: Partial<APIErrorOptions>) => Promise<(Document & T) | null>;
44
+ export declare const findOneOrNoneFor: <T>(model: mongoose.Model<T>, query: FilterQuery<T>, errorArgs?: Partial<APIErrorOptions>) => Promise<(Document & T) | null>;
46
45
  /**
47
46
  * This adds a static method `Model.findExactlyOne` to the schema. This or findOneOrNone should replace `Model.findOne`
48
47
  * in most instances.
@@ -63,6 +62,19 @@ export declare const upsertPlugin: <T>(schema: Schema<any, any, any, any>) => vo
63
62
  export interface HasUpsert<T> {
64
63
  upsert(conditions: Record<string, unknown>, update: Record<string, unknown>): Promise<T>;
65
64
  }
65
+ /** For models with the excludeArchivedPlugin, extend this interface to add the archived field. */
66
+ export interface IsArchived {
67
+ archived: boolean;
68
+ }
69
+ /**
70
+ * Adds an `archived` boolean field and excludes archived documents from `find()` queries by
71
+ * default. Pass `{archived: true}` explicitly to include them. This is a soft-archive analog to
72
+ * {@link isDeletedPlugin}: use it when documents should be hidden from normal listings but kept
73
+ * (and still directly queryable) rather than treated as deleted.
74
+ * @param schema Mongoose Schema
75
+ * @param defaultValue Default value for the `archived` field (defaults to `false`)
76
+ */
77
+ export declare const excludeArchivedPlugin: (schema: Schema<any, any, any, any>, defaultValue?: boolean) => void;
66
78
  export interface FindOneOrNonePlugin<T> {
67
79
  findOneOrNone(query: Record<string, unknown>, errorArgs?: Partial<APIErrorOptions>): Promise<(Document & T) | null>;
68
80
  }
package/dist/plugins.js CHANGED
@@ -95,7 +95,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
95
95
  }
96
96
  };
97
97
  Object.defineProperty(exports, "__esModule", { value: true });
98
- exports.DateOnly = exports.upsertPlugin = exports.findExactlyOne = exports.findOneOrNoneFor = exports.findOneOrNone = exports.firebaseJWTPlugin = exports.createdUpdatedPlugin = exports.isDisabledPlugin = exports.isDeletedPlugin = exports.baseUserPlugin = void 0;
98
+ exports.DateOnly = exports.excludeArchivedPlugin = exports.upsertPlugin = exports.findExactlyOne = exports.findOneOrNoneFor = exports.findOneOrNone = exports.firebaseJWTPlugin = exports.createdUpdatedPlugin = exports.isDisabledPlugin = exports.isDeletedPlugin = exports.baseUserPlugin = void 0;
99
99
  var luxon_1 = require("luxon");
100
100
  var mongoose_1 = __importStar(require("mongoose"));
101
101
  var errors_1 = require("./errors");
@@ -354,6 +354,40 @@ var upsertPlugin = function (schema) {
354
354
  };
355
355
  };
356
356
  exports.upsertPlugin = upsertPlugin;
357
+ /**
358
+ * Adds an `archived` boolean field and excludes archived documents from `find()` queries by
359
+ * default. Pass `{archived: true}` explicitly to include them. This is a soft-archive analog to
360
+ * {@link isDeletedPlugin}: use it when documents should be hidden from normal listings but kept
361
+ * (and still directly queryable) rather than treated as deleted.
362
+ * @param schema Mongoose Schema
363
+ * @param defaultValue Default value for the `archived` field (defaults to `false`)
364
+ */
365
+ var excludeArchivedPlugin = function (
366
+ // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
367
+ // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
368
+ schema, defaultValue) {
369
+ if (defaultValue === void 0) { defaultValue = false; }
370
+ schema.add({
371
+ archived: {
372
+ default: defaultValue,
373
+ description: "Archived objects are not returned in any find() by default. " +
374
+ "Add {archived: true} to find them.",
375
+ index: true,
376
+ type: Boolean,
377
+ },
378
+ });
379
+ // noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
380
+ // biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
381
+ schema.pre("find", function () {
382
+ var conditions = this.getFilter();
383
+ // Only apply the default filter when the query does not mention `archived` at all, so an
384
+ // explicit `{archived: true}` (or `false`) is always respected.
385
+ if (conditions.archived === undefined) {
386
+ this.setQuery(__assign(__assign({}, conditions), { archived: { $ne: true } }));
387
+ }
388
+ });
389
+ };
390
+ exports.excludeArchivedPlugin = excludeArchivedPlugin;
357
391
  var DateOnly = /** @class */ (function (_super) {
358
392
  __extends(DateOnly, _super);
359
393
  function DateOnly(key, options) {
@@ -374,11 +408,7 @@ var DateOnly = /** @class */ (function (_super) {
374
408
  }
375
409
  var handler = this.$conditionalHandlers[$conditional];
376
410
  if (!handler) {
377
- throw new errors_1.APIError({
378
- detail: "Can't use ".concat($conditional, " with DateOnly."),
379
- status: 400,
380
- title: "Unsupported query conditional for DateOnly",
381
- });
411
+ throw new Error("Can't use ".concat($conditional, " with DateOnly."));
382
412
  }
383
413
  return handler.call(this, val);
384
414
  };
@@ -1,9 +1,35 @@
1
- import mongoose from "mongoose";
1
+ import type { ChangeStreamDocument } from "mongodb";
2
2
  import type { Server } from "socket.io";
3
- type ChangeStreamDocument = mongoose.mongo.ChangeStreamDocument;
4
3
  import type { User } from "../auth";
4
+ import { type PermissionMethod } from "../permissions";
5
+ import { type SyncRegistryEntry } from "../sync/registry";
5
6
  import { type RealtimeRegistryEntry } from "./registry";
6
7
  import type { ChangeStreamConfig, RealtimeEvent } from "./types";
8
+ /**
9
+ * The subset of ChangeStreamDocument variants this watcher actually processes.
10
+ * The pipeline filters for ["insert", "update", "replace", "delete"], so we never
11
+ * see drop / rename / invalidate / index events at runtime.
12
+ */
13
+ type WatchedChange = Extract<ChangeStreamDocument, {
14
+ operationType: "insert" | "update" | "replace" | "delete";
15
+ }>;
16
+ /** First restart delay; doubles per consecutive attempt up to the max. */
17
+ export declare const CHANGE_STREAM_RESTART_BASE_DELAY_MS = 250;
18
+ /** Ceiling for the restart backoff — a long outage retries once every 30s, forever. */
19
+ export declare const CHANGE_STREAM_RESTART_MAX_DELAY_MS = 30000;
20
+ /**
21
+ * Socket event telling clients their cached cursors may have gaps and they must
22
+ * re-bootstrap. Emitted when the change stream's oplog history is gone
23
+ * (`ChangeStreamHistoryLost`), which is the one failure a resume token cannot repair.
24
+ * Payload: {@link SyncResyncHint}.
25
+ */
26
+ export declare const SYNC_RESYNC_EVENT = "sync:resync-required";
27
+ /**
28
+ * C7: the sync bookkeeping collections must never drive fan-out — their own change
29
+ * events are internal (counters/ledger/markers/keys), and processing them would emit
30
+ * spurious deltas or reprocess scope-move markers. Exported for testing.
31
+ */
32
+ export declare const DEFAULT_IGNORED_COLLECTIONS: string[];
7
33
  /**
8
34
  * Map MongoDB change stream operation types to our method names.
9
35
  *
@@ -17,6 +43,18 @@ import type { ChangeStreamConfig, RealtimeEvent } from "./types";
17
43
  * Exported for testing.
18
44
  */
19
45
  export declare const mapOperationType: (operationType: string, change: ChangeStreamDocument, enabledMethods?: ReadonlyArray<"create" | "update" | "delete">) => "create" | "update" | "delete" | null;
46
+ /**
47
+ * The minimal registry-entry shape the authorized-room emitters need. Both
48
+ * `RealtimeRegistryEntry` and `SyncRegistryEntry` satisfy it structurally.
49
+ */
50
+ export interface AuthorizedEmitEntry {
51
+ modelName: string;
52
+ options: {
53
+ permissions: {
54
+ read: PermissionMethod<any>[];
55
+ };
56
+ };
57
+ }
20
58
  /**
21
59
  * Determine which Socket.io rooms to emit to based on the room strategy.
22
60
  * Exported for testing.
@@ -44,6 +82,24 @@ export declare const ensureApiId: (data: unknown) => unknown;
44
82
  * was supposed to strip.
45
83
  */
46
84
  export declare const serializeDoc: (entry: RealtimeRegistryEntry, doc: Record<string, unknown>, method: "create" | "update" | "delete", user?: User) => Promise<unknown>;
85
+ /**
86
+ * Generalized authorized-room emitter: iterates the sockets in `room`, runs the per-socket
87
+ * read-permission check against `fullDocument`, builds the payload per socket (so
88
+ * responseHandlers can tailor output to the receiving user), and emits `eventName`.
89
+ *
90
+ * `emitToAuthorizedRoom` (legacy "sync" events) and the sync layer's `sync:delta`
91
+ * emission both delegate here.
92
+ */
93
+ export declare const emitPayloadToAuthorizedRoom: ({ io, room, eventName, entry, fullDocument, buildPayload, logDebug, }: {
94
+ io: Server;
95
+ room: string;
96
+ eventName: string;
97
+ entry: AuthorizedEmitEntry;
98
+ fullDocument: Record<string, unknown> | undefined;
99
+ /** Build the per-socket payload; a throw drops the emission for that socket only. */
100
+ buildPayload: (user: User | undefined) => Promise<unknown> | unknown;
101
+ logDebug: (msg: string) => void;
102
+ }) => Promise<void>;
47
103
  export declare const emitToAuthorizedRoom: (io: Server, room: string, event: RealtimeEvent, entry: RealtimeRegistryEntry, fullDocument: Record<string, unknown> | undefined, logDebug: (msg: string) => void) => Promise<void>;
48
104
  /**
49
105
  * Emit a sync event to document-specific and query rooms.
@@ -62,12 +118,53 @@ export declare const emitToAuthorizedRoom: (io: Server, room: string, event: Rea
62
118
  * Exported for testing.
63
119
  */
64
120
  export declare const emitToDocumentAndQueryRooms: (io: Server, collection: string, event: RealtimeEvent, fullDocument: Record<string, unknown> | undefined, logDebug: (msg: string) => void, entry?: RealtimeRegistryEntry) => Promise<void>;
121
+ /**
122
+ * Emit `sync:delta` events for a change on a sync-registered collection.
123
+ *
124
+ * Deltas fan out to the dedicated `sync:{stream}` rooms joined via `sync:subscribe`
125
+ * (independent of the legacy realtime rooms), with the same per-socket read-permission
126
+ * checks as legacy events. `seq` and `stream` come from the post-image: the `syncPlugin`
127
+ * stamps `_syncSeq` on every synced write and the watcher runs `updateLookup`.
128
+ *
129
+ * Soft deletes (an update setting `deleted: true`, reclassified by `mapOperationType`)
130
+ * produce a `method: "delete"` delta with `deleted: true` and the tombstone data intact.
131
+ *
132
+ * Scope moves (C4): the old-stream tombstone is derived from durable `SyncScopeMove`
133
+ * markers (written by `syncPlugin` in the same op-scope as the move), NOT from the racy
134
+ * `_syncPrevStream` post-image — a second write racing this event's processing can reset
135
+ * `_syncPrevStream`, but it cannot erase the durable marker. For each marker on this
136
+ * document, a data-less tombstone is emitted to the marker's `fromStream` (carrying the
137
+ * marker's old-stream seq), and the new-stream delta is reported as `method: "create"`.
138
+ * Client tombstone application is idempotent by seq, so re-emitting a marker on a later
139
+ * change of the same doc is harmless.
140
+ *
141
+ * Every emitted delta carries `frontierSeq` (the emitting stream's stable frontier at
142
+ * emit time, C1); the client advances its cursor to `min(delta.seq, delta.frontierSeq)`
143
+ * so a delta observed out of commit order never advances a cursor past an uncommitted hole.
144
+ *
145
+ * A model with both `realtime` and `sync` configs emits both the legacy "sync" event and
146
+ * "sync:delta" — distinct event names, no interference (documented as transitional).
147
+ *
148
+ * Exported for testing.
149
+ */
150
+ export declare const emitSyncDeltaForChange: ({ io, entry, change, docId, logDebug, }: {
151
+ io: Server;
152
+ entry: SyncRegistryEntry;
153
+ change: WatchedChange;
154
+ docId: string;
155
+ logDebug: (msg: string) => void;
156
+ }) => Promise<void>;
65
157
  /**
66
158
  * Start watching MongoDB change streams and emitting real-time events.
159
+ *
160
+ * Task 9.16: the stream is supervised — an `error`/`close`/`end` schedules a re-open with
161
+ * exponential backoff, resuming from the last seen token. Call
162
+ * {@link stopChangeStreamWatcher} to end supervision.
67
163
  */
68
164
  export declare const startChangeStreamWatcher: (io: Server, config?: ChangeStreamConfig, debug?: boolean) => void;
69
165
  /**
70
- * Stop the change stream watcher.
166
+ * Stop the change stream watcher and end Task 9.16's restart supervision (a pending
167
+ * reopen is cancelled, and terminal events from the closing stream are ignored).
71
168
  */
72
169
  export declare const stopChangeStreamWatcher: () => Promise<void>;
73
170
  export {};