@terreno/api 58.0.5 → 58.1.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 (75) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/dist/actions.d.ts +6 -0
  3. package/dist/api.d.ts +21 -0
  4. package/dist/api.js +57 -32
  5. package/dist/bulk.d.ts +79 -0
  6. package/dist/bulk.js +449 -0
  7. package/dist/bulkOpenApi.d.ts +15 -0
  8. package/dist/bulkOpenApi.js +103 -0
  9. package/dist/bulkTransaction.d.ts +33 -0
  10. package/dist/bulkTransaction.js +126 -0
  11. package/dist/errors.d.ts +2 -0
  12. package/dist/errors.js +8 -6
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +6 -3
  15. package/dist/mcp/actionTools.js +2 -0
  16. package/dist/mcp/grantAccess.d.ts +27 -0
  17. package/dist/mcp/grantAccess.js +29 -0
  18. package/dist/mcp/oauth.js +86 -5
  19. package/dist/mcp/oauthMetadata.d.ts +32 -1
  20. package/dist/mcp/oauthMetadata.js +53 -2
  21. package/dist/mcp/registry.d.ts +8 -1
  22. package/dist/mcp/server.js +6 -1
  23. package/dist/mcp/toolGenerator.d.ts +5 -1
  24. package/dist/mcp/toolGenerator.js +11 -0
  25. package/dist/mcp/types.d.ts +11 -0
  26. package/dist/modelRouterWrites.d.ts +23 -0
  27. package/dist/modelRouterWrites.js +54 -0
  28. package/dist/openApi.d.ts +7 -0
  29. package/dist/openApi.js +6 -6
  30. package/dist/permissions.js +5 -4
  31. package/dist/rbac/access.js +2 -0
  32. package/dist/rbac/routes.js +1 -0
  33. package/dist/rbac/statements.d.ts +12 -1
  34. package/dist/rbac/statements.js +89 -1
  35. package/dist/rbac/types.d.ts +9 -2
  36. package/dist/sync/executors.d.ts +6 -4
  37. package/dist/sync/executors.js +6 -2
  38. package/package.json +6 -6
  39. package/src/actions.ts +6 -0
  40. package/src/api.ts +95 -33
  41. package/src/bulk.test.ts +1256 -0
  42. package/src/bulk.ts +680 -0
  43. package/src/bulkOpenApi.test.ts +172 -0
  44. package/src/bulkOpenApi.ts +126 -0
  45. package/src/bulkTransaction.test.ts +197 -0
  46. package/src/bulkTransaction.ts +149 -0
  47. package/src/errors.ts +2 -2
  48. package/src/index.ts +6 -0
  49. package/src/isolated/bulkAtomic.isolated.ts +630 -0
  50. package/src/isolated/bulkStandalone.isolated.ts +133 -0
  51. package/src/isolated/mongoTopology.isolated.ts +29 -0
  52. package/src/mcp/actionTools.ts +2 -0
  53. package/src/mcp/grantAccess.test.ts +107 -0
  54. package/src/mcp/grantAccess.ts +49 -0
  55. package/src/mcp/oauth.test.ts +327 -0
  56. package/src/mcp/oauth.ts +113 -5
  57. package/src/mcp/oauthMetadata.test.ts +125 -1
  58. package/src/mcp/oauthMetadata.ts +99 -2
  59. package/src/mcp/registry.ts +8 -1
  60. package/src/mcp/server.test.ts +419 -2
  61. package/src/mcp/server.ts +8 -1
  62. package/src/mcp/toolGenerator.ts +17 -0
  63. package/src/mcp/types.ts +12 -0
  64. package/src/modelRouterWrites.ts +72 -0
  65. package/src/openApi.ts +1 -1
  66. package/src/permissions.ts +5 -5
  67. package/src/rbac/access.ts +3 -1
  68. package/src/rbac/routes.test.ts +15 -0
  69. package/src/rbac/routes.ts +1 -0
  70. package/src/rbac/statements.test.ts +23 -0
  71. package/src/rbac/statements.ts +100 -1
  72. package/src/rbac/types.ts +9 -2
  73. package/src/sync/executors.test.ts +27 -0
  74. package/src/sync/executors.ts +12 -4
  75. package/src/tests/mongoTopology.ts +53 -0
package/src/api.ts CHANGED
@@ -24,6 +24,12 @@ import {
24
24
  snapshotAuditBefore,
25
25
  } from "./audit/record";
26
26
  import {authenticateMiddleware, omitUserRolesFromWriteBody, type User} from "./auth";
27
+ import {
28
+ assertNoBulkCollision,
29
+ type BulkBodyValidator,
30
+ type ModelRouterBulkOptions,
31
+ registerBulkRoute,
32
+ } from "./bulk";
27
33
  import {registerCollection, replaceCollectionOptions} from "./collectionRegistry";
28
34
  import {
29
35
  APIError,
@@ -38,6 +44,7 @@ import {
38
44
  import {logger} from "./logger";
39
45
  import {registerMCPActionModel, registerMCPModel, updateMCPRegistryOptions} from "./mcp/registry";
40
46
  import type {MCPConfig} from "./mcp/types";
47
+ import {conflictResponseBody, timestampConcurrencyCheck} from "./modelRouterWrites";
41
48
  import {
42
49
  createOpenApiMiddleware,
43
50
  deleteOpenApiMiddleware,
@@ -58,11 +65,14 @@ import type {AnyTerrenoAccess, ModelRouterAccessOptions} from "./rbac/types";
58
65
  import {assertCanWriteTargetUser, assertCanWriteUserIdentity} from "./rbac/userWriteGuards";
59
66
  import {checkSortFields, getAllowedSortFields} from "./sortFields";
60
67
  import {
61
- type ExecutorConcurrencyCheck,
62
68
  executeCreate,
63
69
  executeDelete,
64
70
  executeUpdate,
65
71
  isExecutorConflictError,
72
+ loadDocOr404,
73
+ runPostCreate,
74
+ runPostDelete,
75
+ runPostUpdate,
66
76
  } from "./sync/executors";
67
77
  import type {SyncConfig} from "./sync/types";
68
78
  import {
@@ -102,7 +112,6 @@ export const addPopulateToQuery = (
102
112
  };
103
113
 
104
114
  // TODOS:
105
- // Support bulk actions
106
115
  // Support more complex query fields
107
116
  // Rate limiting
108
117
 
@@ -253,6 +262,13 @@ export interface ModelRouterOptions<T> {
253
262
  instanceActions?: Record<string, InstanceActionConfig<T, unknown, unknown, unknown>>;
254
263
  /** Named collection-scoped operations at `/:actionName` (GET or POST). */
255
264
  collectionActions?: Record<string, CollectionActionConfig<unknown, unknown, unknown>>;
265
+ /**
266
+ * Opt in to `POST /bulk`: many create/update/delete operations in one request, each run
267
+ * through this router's permissions, hooks, validation, audit, and `responseHandler`.
268
+ * `true` allows all three methods with at most 100 operations per request.
269
+ * See docs/reference/api.md ("modelRouter bulk writes").
270
+ */
271
+ bulk?: boolean | ModelRouterBulkOptions;
256
272
  /**
257
273
  * Hook that runs after `transformer.transform` but before the object is created.
258
274
  * Can update the body fields based on the request or the user.
@@ -362,6 +378,7 @@ export interface ModelRouterOptions<T> {
362
378
  create?: Record<string, unknown>;
363
379
  update?: Record<string, unknown>;
364
380
  delete?: Record<string, unknown>;
381
+ bulk?: Record<string, unknown>;
365
382
  };
366
383
  /**
367
384
  * Overwrite parts of the model properties for the OpenAPI generator.
@@ -638,6 +655,48 @@ const getBodyValidationMiddleware = <T>(
638
655
  return validateModelRequestBody(model, validationOptions);
639
656
  };
640
657
 
658
+ type BodyValidationMiddleware = (req: Request, res: Response, next: NextFunction) => void;
659
+
660
+ // Runs a body validation middleware against one body outside the Express chain and returns the
661
+ // cleaned body, throwing what the middleware would have passed to `next` or thrown.
662
+ const runBodyValidator = (
663
+ middleware: BodyValidationMiddleware,
664
+ body: Record<string, unknown>,
665
+ req?: Request
666
+ ): Record<string, unknown> => {
667
+ const stub = (req ? Object.create(req) : {headers: {}}) as Request;
668
+ stub.body = cloneDeep(body);
669
+ let nextError: unknown;
670
+ middleware(stub, {} as Response, (error?: unknown) => {
671
+ nextError = error;
672
+ });
673
+ if (nextError) {
674
+ throw nextError;
675
+ }
676
+ return stub.body as Record<string, unknown>;
677
+ };
678
+
679
+ /**
680
+ * Validates one create or update body exactly as `POST /` or `PATCH /:id` validate theirs
681
+ * (OpenAPI schema, coercion, additional-property removal), returning the cleaned body or
682
+ * throwing the same 400. A no-op until validation is enabled globally or on the router.
683
+ */
684
+ export const validateModelRouterBody = <T>({
685
+ model,
686
+ options,
687
+ method,
688
+ body,
689
+ req,
690
+ }: {
691
+ model: ModelLike<T>;
692
+ options: ModelRouterOptions<T>;
693
+ method: "create" | "update";
694
+ body: Record<string, unknown>;
695
+ req?: Request;
696
+ }): Record<string, unknown> => {
697
+ return runBodyValidator(getBodyValidationMiddleware(model, options, method), body, req);
698
+ };
699
+
641
700
  // Get query validation middleware if validation is enabled
642
701
  const getQueryValidationMiddleware = <T>(
643
702
  model: ModelLike<T>,
@@ -810,13 +869,9 @@ const _buildModelRouter = <T>(
810
869
  }
811
870
 
812
871
  assertNoActionCollisions(model, options);
872
+ assertNoBulkCollision(options);
813
873
  registerActionRoutes(router, model, options);
814
874
 
815
- // User endpoints run after actions; actions win on path conflicts.
816
- if (options.endpoints) {
817
- options.endpoints(router, options);
818
- }
819
-
820
875
  const responseHandler = options.responseHandler ?? defaultResponseHandler;
821
876
 
822
877
  // Always install validation middleware — they are no-ops until configureOpenApiValidator() is called
@@ -824,6 +879,33 @@ const _buildModelRouter = <T>(
824
879
  const updateValidation = getBodyValidationMiddleware(model, options, "update");
825
880
  const queryValidation = getQueryValidationMiddleware(model, options);
826
881
 
882
+ const validateBulkBody: BulkBodyValidator = ({method, body, req}) =>
883
+ runBodyValidator(method === "create" ? createValidation : updateValidation, body, req);
884
+ registerBulkRoute({
885
+ deps: {
886
+ authenticateMiddleware,
887
+ checkPermissions,
888
+ executeCreate,
889
+ executeDelete,
890
+ executeUpdate,
891
+ isExecutorConflictError,
892
+ loadDocOr404,
893
+ runPostCreate,
894
+ runPostDelete,
895
+ runPostUpdate,
896
+ },
897
+ model,
898
+ options,
899
+ responseHandler: responseHandler as NonNullable<ModelRouterOptions<T>["responseHandler"]>,
900
+ router,
901
+ validateBody: validateBulkBody,
902
+ });
903
+
904
+ // User endpoints run after actions and bulk; those win on path conflicts.
905
+ if (options.endpoints) {
906
+ options.endpoints(router, options);
907
+ }
908
+
827
909
  router.post(
828
910
  "/",
829
911
  [
@@ -1102,27 +1184,11 @@ const _buildModelRouter = <T>(
1102
1184
  ? httpUnmodifiedSince[0]
1103
1185
  : httpUnmodifiedSince;
1104
1186
 
1105
- let concurrencyCheck: ExecutorConcurrencyCheck | undefined;
1106
- if (timestampValue || httpTimestampValue || bodyUpdatedAt) {
1107
- const usingPreciseHeader = Boolean(timestampValue);
1108
- const usingHttpHeader = !usingPreciseHeader && Boolean(httpTimestampValue);
1109
- const clientTimestamp = timestampValue
1110
- ? DateTime.fromISO(timestampValue)
1111
- : httpTimestampValue
1112
- ? DateTime.fromHTTP(httpTimestampValue)
1113
- : DateTime.fromISO(bodyUpdatedAt);
1114
- concurrencyCheck = {
1115
- // An unparseable value round-trips as an invalid Date; the executor turns it into
1116
- // the 400 "Invalid conflict-detection timestamp" error after preUpdate has run.
1117
- ifUnmodifiedSince: clientTimestamp.toJSDate(),
1118
- invalidTimestampDetail: usingPreciseHeader
1119
- ? "X-Unmodified-Since-ISO header could not be parsed as an ISO date"
1120
- : usingHttpHeader
1121
- ? "If-Unmodified-Since header could not be parsed as an HTTP date"
1122
- : "_updatedAt body field could not be parsed as an ISO date",
1123
- type: "timestamp",
1124
- };
1125
- }
1187
+ const concurrencyCheck = timestampConcurrencyCheck({
1188
+ bodyUpdatedAt,
1189
+ httpHeader: httpTimestampValue,
1190
+ preciseHeader: timestampValue,
1191
+ });
1126
1192
 
1127
1193
  let doc: Document<unknown, unknown, unknown> & T;
1128
1194
  const previous = snapshotAuditBefore({audit: options.audit, doc: existingDoc});
@@ -1146,11 +1212,7 @@ const _buildModelRouter = <T>(
1146
1212
  req,
1147
1213
  options
1148
1214
  );
1149
- return res.status(409).json({
1150
- data: serialized,
1151
- error: "Conflict",
1152
- message: "Document was modified since your last read",
1153
- });
1215
+ return res.status(409).json(conflictResponseBody(serialized));
1154
1216
  }
1155
1217
  throw error;
1156
1218
  }