@terreno/api 0.31.0 → 56.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/dist/api.d.ts +10 -0
  2. package/dist/api.js +110 -361
  3. package/dist/auth.d.ts +26 -0
  4. package/dist/auth.js +121 -26
  5. package/dist/betterAuth.d.ts +5 -0
  6. package/dist/betterAuthSetup.js +23 -4
  7. package/dist/docLoader.js +12 -9
  8. package/dist/errors.d.ts +13 -0
  9. package/dist/errors.js +29 -1
  10. package/dist/index.d.ts +17 -1
  11. package/dist/index.js +29 -1
  12. package/dist/middleware.d.ts +7 -0
  13. package/dist/middleware.js +16 -1
  14. package/dist/openApiCompat.d.ts +10 -1
  15. package/dist/openApiCompat.js +115 -47
  16. package/dist/permissions.d.ts +27 -0
  17. package/dist/permissions.js +42 -1
  18. package/dist/plugins.d.ts +13 -0
  19. package/dist/plugins.js +47 -1
  20. package/dist/realtime/changeStreamWatcher.d.ts +100 -3
  21. package/dist/realtime/changeStreamWatcher.js +542 -137
  22. package/dist/realtime/realtimeApp.d.ts +2 -0
  23. package/dist/realtime/realtimeApp.js +83 -27
  24. package/dist/realtime/sessionRevalidation.d.ts +90 -0
  25. package/dist/realtime/sessionRevalidation.js +438 -0
  26. package/dist/realtime/socketAuth.d.ts +97 -0
  27. package/dist/realtime/socketAuth.js +272 -0
  28. package/dist/realtime/socketUser.d.ts +54 -0
  29. package/dist/realtime/socketUser.js +75 -5
  30. package/dist/realtime/types.d.ts +54 -0
  31. package/dist/secretProviders.d.ts +23 -0
  32. package/dist/secretProviders.js +9 -3
  33. package/dist/sync/executors.d.ts +198 -0
  34. package/dist/sync/executors.js +670 -0
  35. package/dist/sync/loadHarness.js +807 -0
  36. package/dist/sync/models.d.ts +216 -0
  37. package/dist/sync/models.js +644 -0
  38. package/dist/sync/mutationHandler.d.ts +97 -0
  39. package/dist/sync/mutationHandler.js +886 -0
  40. package/dist/sync/registry.d.ts +73 -0
  41. package/dist/sync/registry.js +223 -0
  42. package/dist/sync/routes.d.ts +62 -0
  43. package/dist/sync/routes.js +936 -0
  44. package/dist/sync/scripts/compactTombstones.d.ts +47 -0
  45. package/dist/sync/scripts/compactTombstones.js +270 -0
  46. package/dist/sync/serialize.d.ts +20 -0
  47. package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
  48. package/dist/sync/socketHandlers.d.ts +54 -0
  49. package/dist/sync/socketHandlers.js +470 -0
  50. package/dist/sync/streams.d.ts +85 -0
  51. package/dist/sync/streams.js +221 -0
  52. package/dist/sync/syncApp.d.ts +29 -0
  53. package/dist/sync/syncApp.js +44 -0
  54. package/dist/sync/syncBatch.d.ts +71 -0
  55. package/dist/sync/syncBatch.js +252 -0
  56. package/dist/sync/syncSeqPlugin.d.ts +8 -0
  57. package/dist/sync/syncSeqPlugin.js +899 -0
  58. package/dist/sync/types.d.ts +254 -0
  59. package/dist/sync/types.js +9 -0
  60. package/dist/terrenoApp.js +90 -27
  61. package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
  62. package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
  63. package/package.json +7 -6
  64. package/src/__tests__/openApiCompat.test.ts +20 -0
  65. package/src/api.errors.test.ts +32 -23
  66. package/src/api.test.ts +12 -0
  67. package/src/api.ts +87 -296
  68. package/src/auth.test.ts +202 -0
  69. package/src/auth.ts +134 -23
  70. package/src/betterAuth.ts +6 -0
  71. package/src/betterAuthSetup.test.ts +34 -0
  72. package/src/betterAuthSetup.ts +20 -1
  73. package/src/configuration.test.ts +59 -38
  74. package/src/configurationPlugin.test.ts +72 -42
  75. package/src/docLoader.ts +3 -1
  76. package/src/errors.ts +33 -0
  77. package/src/expressServer.test.ts +7 -1
  78. package/src/index.ts +42 -0
  79. package/src/middleware.test.ts +56 -1
  80. package/src/middleware.ts +15 -0
  81. package/src/openApiCompat.ts +99 -45
  82. package/src/permissions.test.ts +101 -17
  83. package/src/permissions.ts +49 -0
  84. package/src/plugins.test.ts +64 -0
  85. package/src/plugins.ts +56 -0
  86. package/src/realtime/changeStreamWatcher.ts +552 -114
  87. package/src/realtime/realtime.test.ts +157 -0
  88. package/src/realtime/realtimeApp.ts +82 -14
  89. package/src/realtime/realtimeAppSetup.test.ts +25 -27
  90. package/src/realtime/sessionRevalidation.test.ts +423 -0
  91. package/src/realtime/sessionRevalidation.ts +273 -0
  92. package/src/realtime/socketAuth.test.ts +355 -0
  93. package/src/realtime/socketAuth.ts +228 -0
  94. package/src/realtime/socketUser.ts +69 -0
  95. package/src/realtime/types.ts +54 -0
  96. package/src/secretProviders.test.ts +7 -1
  97. package/src/secretProviders.ts +15 -3
  98. package/src/secretProvidersGcpClient.test.ts +66 -0
  99. package/src/sync/ensureSyncIndexes.test.ts +144 -0
  100. package/src/sync/executors.test.ts +882 -0
  101. package/src/sync/executors.ts +705 -0
  102. package/src/sync/integration.test.ts +1160 -0
  103. package/src/sync/loadHarness.ts +618 -0
  104. package/src/sync/models.ts +641 -0
  105. package/src/sync/mutationHandler.test.ts +1252 -0
  106. package/src/sync/mutationHandler.ts +850 -0
  107. package/src/sync/registry.ts +232 -0
  108. package/src/sync/routes.ts +812 -0
  109. package/src/sync/scripts/compactTombstones.test.ts +249 -0
  110. package/src/sync/scripts/compactTombstones.ts +145 -0
  111. package/src/sync/serialize.ts +48 -0
  112. package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
  113. package/src/sync/socketHandlers.ts +320 -0
  114. package/src/sync/streams.ts +188 -0
  115. package/src/sync/sync.test.ts +582 -0
  116. package/src/sync/syncApp.ts +44 -0
  117. package/src/sync/syncBatch.ts +219 -0
  118. package/src/sync/syncFrontier.test.ts +494 -0
  119. package/src/sync/syncPhaseC.test.ts +718 -0
  120. package/src/sync/syncRoutes.test.ts +865 -0
  121. package/src/sync/syncSeqPlugin.ts +730 -0
  122. package/src/sync/syncSocket.test.ts +1440 -0
  123. package/src/sync/types.ts +270 -0
  124. package/src/terrenoApp.ts +37 -17
  125. package/src/tests/bunSetup.ts +8 -0
  126. package/tsconfig.json +4 -4
  127. package/tsconfig.typedoc.json +7 -1
  128. package/dist/__tests__/openApiCompat.test.js +0 -317
  129. package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
  130. package/dist/__tests__/versionCheckPlugin.test.js +0 -597
  131. package/dist/actions.openApi.test.d.ts +0 -1
  132. package/dist/actions.openApi.test.js +0 -253
  133. package/dist/actions.test.d.ts +0 -1
  134. package/dist/actions.test.js +0 -1087
  135. package/dist/api.arrayOperations.test.d.ts +0 -1
  136. package/dist/api.arrayOperations.test.js +0 -878
  137. package/dist/api.asyncHandler.test.d.ts +0 -1
  138. package/dist/api.asyncHandler.test.js +0 -236
  139. package/dist/api.coverage.test.d.ts +0 -1
  140. package/dist/api.coverage.test.js +0 -192
  141. package/dist/api.errorPaths.test.d.ts +0 -1
  142. package/dist/api.errorPaths.test.js +0 -887
  143. package/dist/api.errors.test.d.ts +0 -1
  144. package/dist/api.errors.test.js +0 -185
  145. package/dist/api.hooks.test.d.ts +0 -1
  146. package/dist/api.hooks.test.js +0 -950
  147. package/dist/api.query.test.d.ts +0 -1
  148. package/dist/api.query.test.js +0 -948
  149. package/dist/api.test.d.ts +0 -1
  150. package/dist/api.test.js +0 -2820
  151. package/dist/auth.compile.test.d.ts +0 -1
  152. package/dist/auth.compile.test.js +0 -201
  153. package/dist/auth.coverage.test.d.ts +0 -1
  154. package/dist/auth.coverage.test.js +0 -202
  155. package/dist/auth.test.d.ts +0 -1
  156. package/dist/auth.test.js +0 -2286
  157. package/dist/betterAuth.test.d.ts +0 -1
  158. package/dist/betterAuth.test.js +0 -181
  159. package/dist/betterAuthApp.test.d.ts +0 -1
  160. package/dist/betterAuthApp.test.js +0 -242
  161. package/dist/betterAuthSetup.test.d.ts +0 -1
  162. package/dist/betterAuthSetup.test.js +0 -762
  163. package/dist/config.test.d.ts +0 -1
  164. package/dist/config.test.js +0 -353
  165. package/dist/configuration.test.d.ts +0 -1
  166. package/dist/configuration.test.js +0 -980
  167. package/dist/configurationPlugin.test.d.ts +0 -1
  168. package/dist/configurationPlugin.test.js +0 -827
  169. package/dist/consentApp.test.d.ts +0 -1
  170. package/dist/consentApp.test.js +0 -1411
  171. package/dist/docLoader.test.d.ts +0 -1
  172. package/dist/docLoader.test.js +0 -137
  173. package/dist/envConfigurationPlugin.test.d.ts +0 -1
  174. package/dist/envConfigurationPlugin.test.js +0 -369
  175. package/dist/errors.test.d.ts +0 -1
  176. package/dist/errors.test.js +0 -607
  177. package/dist/expressServer.test.d.ts +0 -1
  178. package/dist/expressServer.test.js +0 -1249
  179. package/dist/githubAuth.test.d.ts +0 -1
  180. package/dist/githubAuth.test.js +0 -1142
  181. package/dist/httpClient.test.d.ts +0 -1
  182. package/dist/httpClient.test.js +0 -1471
  183. package/dist/logger.test.d.ts +0 -1
  184. package/dist/logger.test.js +0 -685
  185. package/dist/middleware.test.d.ts +0 -1
  186. package/dist/middleware.test.js +0 -241
  187. package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
  188. package/dist/notifiers/googleChatNotifier.test.js +0 -298
  189. package/dist/notifiers/slackNotifier.test.d.ts +0 -1
  190. package/dist/notifiers/slackNotifier.test.js +0 -297
  191. package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
  192. package/dist/notifiers/zoomNotifier.test.js +0 -373
  193. package/dist/openApi.test.d.ts +0 -1
  194. package/dist/openApi.test.js +0 -620
  195. package/dist/openApiBuilder.test.d.ts +0 -1
  196. package/dist/openApiBuilder.test.js +0 -599
  197. package/dist/openApiEtag.test.d.ts +0 -1
  198. package/dist/openApiEtag.test.js +0 -86
  199. package/dist/openApiValidator.test.d.ts +0 -1
  200. package/dist/openApiValidator.test.js +0 -795
  201. package/dist/permissions.middleware.test.d.ts +0 -1
  202. package/dist/permissions.middleware.test.js +0 -308
  203. package/dist/permissions.test.d.ts +0 -1
  204. package/dist/permissions.test.js +0 -439
  205. package/dist/plugins.test.d.ts +0 -1
  206. package/dist/plugins.test.js +0 -902
  207. package/dist/populate.test.d.ts +0 -1
  208. package/dist/populate.test.js +0 -370
  209. package/dist/realtime/realtime.test.d.ts +0 -10
  210. package/dist/realtime/realtime.test.js +0 -4213
  211. package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
  212. package/dist/realtime/realtimeAppSetup.test.js +0 -213
  213. package/dist/requestContext.test.d.ts +0 -1
  214. package/dist/requestContext.test.js +0 -412
  215. package/dist/scriptRunner.test.d.ts +0 -1
  216. package/dist/scriptRunner.test.js +0 -386
  217. package/dist/secretProviders.test.d.ts +0 -1
  218. package/dist/secretProviders.test.js +0 -726
  219. package/dist/syncConsents.test.d.ts +0 -1
  220. package/dist/syncConsents.test.js +0 -522
  221. package/dist/terrenoApp.test.d.ts +0 -1
  222. package/dist/terrenoApp.test.js +0 -489
  223. package/dist/tests/bunSetup.d.ts +0 -1
  224. package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
  225. package/dist/tests/fixtures/compileAuthEntry.js +0 -37
  226. package/dist/tests/testEnv.d.ts +0 -0
  227. package/dist/tests/testEnv.js +0 -6
  228. package/dist/transformers.test.d.ts +0 -1
  229. package/dist/transformers.test.js +0 -423
  230. package/dist/utils.test.d.ts +0 -1
  231. package/dist/utils.test.js +0 -242
  232. /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
package/src/api.ts CHANGED
@@ -18,15 +18,13 @@ import {
18
18
  import {authenticateMiddleware, type User} from "./auth";
19
19
  import {
20
20
  APIError,
21
- type APIErrorOptions,
22
21
  apiErrorMiddleware,
23
22
  BadRequestError,
24
23
  errorDetail,
25
24
  ForbiddenError,
26
- getDisableExternalErrorTracking,
27
- isAPIError,
28
- mongooseErrorToAPIError,
29
25
  NotFoundError,
26
+ passthroughOrWrap,
27
+ passthroughOrWrapWrite,
30
28
  } from "./errors";
31
29
  import {logger} from "./logger";
32
30
  import {
@@ -46,6 +44,15 @@ import {checkPermissions, permissionMiddleware, type RESTPermissions} from "./pe
46
44
  import type {PopulatePath} from "./populate";
47
45
  import {registerRealtime} from "./realtime/registry";
48
46
  import type {RealtimeConfig} from "./realtime/types";
47
+ import {
48
+ type ExecutorConcurrencyCheck,
49
+ executeCreate,
50
+ executeDelete,
51
+ executeUpdate,
52
+ isExecutorConflictError,
53
+ } from "./sync/executors";
54
+ import {registerSync} from "./sync/registry";
55
+ import type {SyncConfig} from "./sync/types";
49
56
  import {
50
57
  defaultResponseHandler,
51
58
  serialize,
@@ -65,39 +72,6 @@ export interface JSONObject {
65
72
  }
66
73
  export type JSONValue = JSONPrimitive | JSONObject | JSONArray;
67
74
 
68
- /**
69
- * Picks the error to throw for something caught in a hook, transformer, or Mongoose middleware.
70
- * An `APIError` is passed through untouched so its status, code, detail, and meta reach the client;
71
- * anything else is wrapped in the given framework error. `wrapper` may override any field,
72
- * including `detail`, which defaults to the caught error's text.
73
- */
74
- const passthroughOrWrap = (error: unknown, wrapper: APIErrorOptions): APIError => {
75
- if (isAPIError(error)) {
76
- return error;
77
- }
78
- return new APIError({
79
- cause: error,
80
- detail: errorDetail(error),
81
- disableExternalErrorTracking: getDisableExternalErrorTracking(error),
82
- ...wrapper,
83
- });
84
- };
85
-
86
- /**
87
- * `passthroughOrWrap` for write paths (`model.create`, `doc.save`). Mongoose validation and cast
88
- * errors are converted first so their per-field messages survive as `meta.fields` instead of being
89
- * flattened into the wrapper's `detail`.
90
- */
91
- const passthroughOrWrapWrite = (error: unknown, wrapper: APIErrorOptions): APIError => {
92
- if (!isAPIError(error) && error instanceof Error) {
93
- const converted = mongooseErrorToAPIError(error);
94
- if (converted) {
95
- return converted;
96
- }
97
- }
98
- return passthroughOrWrap(error, wrapper);
99
- };
100
-
101
75
  export const addPopulateToQuery = (
102
76
  // noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
103
77
  // biome-ignore lint/suspicious/noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
@@ -382,6 +356,15 @@ export interface ModelRouterOptions<T> {
382
356
  * Requires the RealtimeApp plugin to be registered with TerrenoApp.
383
357
  */
384
358
  realtime?: RealtimeConfig;
359
+ /**
360
+ * Enable local-first sync (@terreno/syncdb) for this model. Documents are scoped
361
+ * into streams (owner/tenant/broadcast/custom) with monotonic per-stream cursors.
362
+ *
363
+ * Requires the schema to use `isDeletedPlugin` (soft delete tombstones) and
364
+ * `syncPlugin` (per-stream `_syncSeq` stamping) — validated at registration.
365
+ * Only works with the three-argument form: modelRouter('/path', Model, options).
366
+ */
367
+ sync?: SyncConfig;
385
368
  }
386
369
 
387
370
  /**
@@ -646,6 +629,10 @@ export function modelRouter<T>(
646
629
  routePath: path,
647
630
  });
648
631
  }
632
+ // Register for local-first sync if configured (validates the schema contract)
633
+ if (options.sync) {
634
+ registerSync({config: options.sync, model, options, routePath: path});
635
+ }
649
636
  return {
650
637
  __type: "modelRouter",
651
638
  _buildWithOpenApi: (openApi: OpenApiMiddleware) =>
@@ -661,6 +648,12 @@ export function modelRouter<T>(
661
648
  "Realtime sync only works with the three-argument form: modelRouter('/path', Model, options)"
662
649
  );
663
650
  }
651
+ if (options.sync) {
652
+ logger.warn(
653
+ `modelRouter for ${model.modelName} has sync config but was called without a path. ` +
654
+ "Local-first sync only works with the three-argument form: modelRouter('/path', Model, options)"
655
+ );
656
+ }
664
657
 
665
658
  return router;
666
659
  }
@@ -695,88 +688,15 @@ const _buildModelRouter = <T>(
695
688
  createValidation,
696
689
  ],
697
690
  asyncHandler(async (req: Request, res: Response) => {
698
- let body: Partial<T> | (Partial<T> | undefined)[] | null | undefined;
699
- try {
700
- body = transform<T>(options, req.body, "create", req.user);
701
- } catch (error: unknown) {
702
- throw passthroughOrWrap(error, {
703
- code: "transform-error",
704
- status: 400,
705
- title: "Transform error",
706
- });
707
- }
708
- if (options.preCreate) {
709
- try {
710
- body = await options.preCreate(body, req);
711
- } catch (error: unknown) {
712
- throw passthroughOrWrap(error, {
713
- code: "pre-create-hook-error",
714
- status: 400,
715
- title: "preCreate hook error",
716
- });
717
- }
718
- if (body === undefined) {
719
- throw new ForbiddenError({
720
- code: "create-not-allowed",
721
- detail: "A body must be returned from preCreate",
722
- title: "Create not allowed",
723
- });
724
- }
725
- if (body === null) {
726
- throw new ForbiddenError({
727
- code: "create-not-allowed",
728
- detail: "preCreate hook returned null",
729
- title: "Create not allowed",
730
- });
731
- }
732
- }
733
- if (body === undefined) {
734
- throw new BadRequestError({
735
- code: "invalid-request-body",
736
- detail: "Body is undefined",
737
- title: "Invalid request body",
738
- });
739
- }
740
- let data: Document<unknown, unknown, unknown> & T;
741
- try {
742
- data = (await model.create(body as T)) as Document<unknown, unknown, unknown> & T;
743
- } catch (error: unknown) {
744
- throw passthroughOrWrapWrite(error, {
745
- code: "create-error",
746
- status: 400,
747
- title: "Create error",
748
- });
749
- }
750
-
751
- if (options.populatePaths) {
752
- try {
753
- // noExplicitAny: mongoose Query type varies based on populatePaths
754
- // biome-ignore lint/suspicious/noExplicitAny: mongoose Query type varies based on populatePaths
755
- let populateQuery: any = model.findById(data._id);
756
- populateQuery = addPopulateToQuery(populateQuery, options.populatePaths);
757
- data = await populateQuery.exec();
758
- } catch (error: unknown) {
759
- throw passthroughOrWrap(error, {
760
- code: "populate-error",
761
- status: 400,
762
- title: "Populate error",
763
- });
764
- }
765
- }
766
-
767
- if (options.postCreate) {
768
- try {
769
- await options.postCreate(data, req);
770
- } catch (error: unknown) {
771
- throw passthroughOrWrap(error, {
772
- code: "post-create-hook-error",
773
- status: 400,
774
- title: "postCreate hook error",
775
- });
776
- }
777
- }
691
+ const {doc} = await executeCreate<T>({
692
+ body: req.body,
693
+ model,
694
+ options,
695
+ req,
696
+ user: req.user,
697
+ });
778
698
  try {
779
- const serialized = await responseHandler(data, "create", req, options);
699
+ const serialized = await responseHandler(doc, "create", req, options);
780
700
  return res.status(201).json({data: serialized});
781
701
  } catch (error: unknown) {
782
702
  throw passthroughOrWrap(error, {
@@ -985,57 +905,12 @@ const _buildModelRouter = <T>(
985
905
  updateValidation,
986
906
  ],
987
907
  asyncHandler(async (req: Request, res: Response) => {
988
- let doc: mongoose.Document & T = (req as Request & {obj: mongoose.Document & T}).obj;
908
+ const existingDoc: mongoose.Document & T = (req as Request & {obj: mongoose.Document & T})
909
+ .obj;
989
910
 
990
- let body: Partial<T> | T | null | undefined;
991
-
992
- try {
993
- body = transform<T>(options, req.body, "update", req.user) as Partial<T>;
994
- } catch (error: unknown) {
995
- throw passthroughOrWrap(error, {
996
- code: "transform-error",
997
- detail: `PATCH failed on ${req.params.id} for user ${req.user?.id}: ${errorDetail(error)}`,
998
- status: 403,
999
- title: "PATCH failed",
1000
- });
1001
- }
1002
-
1003
- // Remove _updatedAt from body before preUpdate processes it
911
+ // Read `_updatedAt` before the executor strips it from the body; the executor's
912
+ // conflict detection still runs after preUpdate, matching the previous inline order.
1004
913
  const bodyUpdatedAt = req.body._updatedAt;
1005
- delete req.body._updatedAt;
1006
- if (body && typeof body === "object") {
1007
- delete (body as Record<string, unknown>)._updatedAt;
1008
- }
1009
-
1010
- if (options.preUpdate) {
1011
- try {
1012
- body = await options.preUpdate(body, req);
1013
- } catch (error: unknown) {
1014
- throw passthroughOrWrap(error, {
1015
- code: "pre-update-hook-error",
1016
- detail: `preUpdate hook error on ${req.params.id}: ${errorDetail(error)}`,
1017
- status: 400,
1018
- title: "preUpdate hook error",
1019
- });
1020
- }
1021
- if (body === undefined) {
1022
- throw new ForbiddenError({
1023
- code: "update-not-allowed",
1024
- detail: "A body must be returned from preUpdate",
1025
- title: "Update not allowed",
1026
- });
1027
- }
1028
- if (body === null) {
1029
- throw new ForbiddenError({
1030
- code: "update-not-allowed",
1031
- detail: `preUpdate hook on ${req.params.id} returned null`,
1032
- title: "Update not allowed",
1033
- });
1034
- }
1035
- }
1036
-
1037
- // Conflict detection runs after preUpdate so that unauthorized mutations
1038
- // are rejected before we leak document data in a 409 response.
1039
914
  const preciseUnmodifiedSince = req.headers["x-unmodified-since-iso"];
1040
915
  const httpUnmodifiedSince = req.headers["if-unmodified-since"];
1041
916
  const timestampValue = Array.isArray(preciseUnmodifiedSince)
@@ -1044,6 +919,8 @@ const _buildModelRouter = <T>(
1044
919
  const httpTimestampValue = Array.isArray(httpUnmodifiedSince)
1045
920
  ? httpUnmodifiedSince[0]
1046
921
  : httpUnmodifiedSince;
922
+
923
+ let concurrencyCheck: ExecutorConcurrencyCheck | undefined;
1047
924
  if (timestampValue || httpTimestampValue || bodyUpdatedAt) {
1048
925
  const usingPreciseHeader = Boolean(timestampValue);
1049
926
  const usingHttpHeader = !usingPreciseHeader && Boolean(httpTimestampValue);
@@ -1052,82 +929,47 @@ const _buildModelRouter = <T>(
1052
929
  : httpTimestampValue
1053
930
  ? DateTime.fromHTTP(httpTimestampValue)
1054
931
  : DateTime.fromISO(bodyUpdatedAt);
932
+ concurrencyCheck = {
933
+ // An unparseable value round-trips as an invalid Date; the executor turns it into
934
+ // the 400 "Invalid conflict-detection timestamp" error after preUpdate has run.
935
+ ifUnmodifiedSince: clientTimestamp.toJSDate(),
936
+ invalidTimestampDetail: usingPreciseHeader
937
+ ? "X-Unmodified-Since-ISO header could not be parsed as an ISO date"
938
+ : usingHttpHeader
939
+ ? "If-Unmodified-Since header could not be parsed as an HTTP date"
940
+ : "_updatedAt body field could not be parsed as an ISO date",
941
+ type: "timestamp",
942
+ };
943
+ }
1055
944
 
1056
- if (!clientTimestamp.isValid) {
1057
- throw new BadRequestError({
1058
- code: "invalid-conflict-detection-timestamp",
1059
- detail: usingPreciseHeader
1060
- ? "X-Unmodified-Since-ISO header could not be parsed as an ISO date"
1061
- : usingHttpHeader
1062
- ? "If-Unmodified-Since header could not be parsed as an HTTP date"
1063
- : "_updatedAt body field could not be parsed as an ISO date",
1064
- title: "Invalid conflict-detection timestamp",
1065
- });
1066
- }
1067
-
1068
- const docRecord = doc as {created?: Date | string; updated?: Date | string};
1069
- let serverTimestamp: DateTime | null = null;
1070
- const serverTimestampValue = docRecord.updated ?? docRecord.created;
1071
- if (serverTimestampValue instanceof Date) {
1072
- serverTimestamp = DateTime.fromJSDate(serverTimestampValue);
1073
- } else if (typeof serverTimestampValue === "string") {
1074
- serverTimestamp = DateTime.fromISO(serverTimestampValue);
1075
- }
1076
-
1077
- if (serverTimestamp && !serverTimestamp.isValid) {
1078
- throw new BadRequestError({
1079
- code: "invalid-server-timestamp",
1080
- detail: "Document timestamp could not be parsed as a date",
1081
- title: "Invalid server timestamp",
1082
- });
1083
- }
1084
-
1085
- if (serverTimestamp && clientTimestamp < serverTimestamp) {
1086
- const serialized = await responseHandler(doc, "update", req, options);
945
+ let doc: Document<unknown, unknown, unknown> & T;
946
+ try {
947
+ ({doc} = await executeUpdate<T>({
948
+ body: req.body,
949
+ concurrencyCheck,
950
+ existingDoc,
951
+ id: req.params.id as string,
952
+ model,
953
+ options,
954
+ req,
955
+ user: req.user,
956
+ }));
957
+ } catch (error: unknown) {
958
+ // Duck-typed: `instanceof` breaks for Error subclasses in the compiled ES5 dist.
959
+ if (isExecutorConflictError(error)) {
960
+ const serialized = await responseHandler(
961
+ error.doc as Document<unknown, unknown, unknown> & T,
962
+ "update",
963
+ req,
964
+ options
965
+ );
1087
966
  return res.status(409).json({
1088
967
  data: serialized,
1089
968
  error: "Conflict",
1090
969
  message: "Document was modified since your last read",
1091
970
  });
1092
971
  }
1093
- }
1094
-
1095
- // Make a copy for passing pre-saved values to hooks.
1096
- const prevDoc = cloneDeep(doc);
1097
-
1098
- // Using .save here runs the risk of a versioning error if you try to make two simultaneous
1099
- // updates. We won't wind up with corrupted data, just an API error.
1100
- try {
1101
- doc.set(body);
1102
- await doc.save();
1103
- } catch (error: unknown) {
1104
- throw passthroughOrWrapWrite(error, {
1105
- code: "update-save-error",
1106
- detail: `preUpdate hook save error on ${req.params.id}: ${errorDetail(error)}`,
1107
- status: 400,
1108
- title: "preUpdate hook save error",
1109
- });
1110
- }
1111
-
1112
- if (options.populatePaths) {
1113
- // noExplicitAny: mongoose Query type varies based on populatePaths
1114
- // biome-ignore lint/suspicious/noExplicitAny: mongoose Query type varies based on populatePaths
1115
- let populateQuery: any = model.findById(doc._id);
1116
- populateQuery = addPopulateToQuery(populateQuery, options.populatePaths);
1117
- doc = await populateQuery.exec();
1118
- }
1119
-
1120
- if (options.postUpdate) {
1121
- try {
1122
- await options.postUpdate(doc, body, req, prevDoc);
1123
- } catch (error: unknown) {
1124
- throw passthroughOrWrap(error, {
1125
- code: "post-update-hook-error",
1126
- detail: `postUpdate hook error on ${req.params.id}: ${errorDetail(error)}`,
1127
- status: 400,
1128
- title: "postUpdate hook error",
1129
- });
1130
- }
972
+ throw error;
1131
973
  }
1132
974
 
1133
975
  try {
@@ -1150,69 +992,18 @@ const _buildModelRouter = <T>(
1150
992
  permissionMiddleware(model, options),
1151
993
  ],
1152
994
  asyncHandler(async (req: Request, res: Response) => {
1153
- const doc: mongoose.Document & T & {deleted?: boolean} = (
995
+ const existingDoc: mongoose.Document & T & {deleted?: boolean} = (
1154
996
  req as Request & {obj: mongoose.Document & T & {deleted?: boolean}}
1155
997
  ).obj;
1156
998
 
1157
- if (options.preDelete) {
1158
- let body: T | null | undefined;
1159
- try {
1160
- body = await options.preDelete(doc, req);
1161
- } catch (error: unknown) {
1162
- throw passthroughOrWrap(error, {
1163
- code: "pre-delete-hook-error",
1164
- detail: `preDelete hook error on ${req.params.id}: ${errorDetail(error)}`,
1165
- status: 403,
1166
- title: "preDelete hook error",
1167
- });
1168
- }
1169
- if (body === undefined) {
1170
- throw new ForbiddenError({
1171
- code: "delete-not-allowed",
1172
- detail: "A body must be returned from preDelete",
1173
- title: "Delete not allowed",
1174
- });
1175
- }
1176
- if (body === null) {
1177
- throw new ForbiddenError({
1178
- code: "delete-not-allowed",
1179
- detail: `preDelete hook for ${req.params.id} returned null`,
1180
- title: "Delete not allowed",
1181
- });
1182
- }
1183
- }
1184
-
1185
- // Support .deleted from isDeleted plugin
1186
- if (
1187
- Object.keys(model.schema.paths).includes("deleted") &&
1188
- model.schema.paths.deleted.instance === "Boolean"
1189
- ) {
1190
- doc.deleted = true;
1191
- await doc.save();
1192
- } else {
1193
- // For models without the isDeleted plugin
1194
- try {
1195
- await doc.deleteOne();
1196
- } catch (error: unknown) {
1197
- throw passthroughOrWrap(error, {
1198
- code: "delete-error",
1199
- status: 400,
1200
- title: "Delete error",
1201
- });
1202
- }
1203
- }
1204
-
1205
- if (options.postDelete) {
1206
- try {
1207
- await options.postDelete(req, doc);
1208
- } catch (error: unknown) {
1209
- throw passthroughOrWrap(error, {
1210
- code: "post-delete-hook-error",
1211
- status: 400,
1212
- title: "postDelete hook error",
1213
- });
1214
- }
1215
- }
999
+ await executeDelete<T>({
1000
+ existingDoc,
1001
+ id: req.params.id as string,
1002
+ model,
1003
+ options,
1004
+ req,
1005
+ user: req.user,
1006
+ });
1216
1007
 
1217
1008
  return res.status(204).json({});
1218
1009
  })