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