@terreno/api 57.3.0 → 57.6.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.
- package/.ai/skills/mongoose-schema-safety/SKILL.md +23 -10
- package/README.md +11 -5
- package/bunfig.toml +1 -1
- package/dist/actions.js +197 -368
- package/dist/adminModelRouter.js +88 -173
- package/dist/adminTypes.d.ts +7 -0
- package/dist/adminTypes.js +6 -1
- package/dist/api.d.ts +10 -0
- package/dist/api.js +601 -792
- package/dist/audit/auditApp.d.ts +30 -0
- package/dist/audit/auditApp.js +114 -0
- package/dist/audit/auditEventModel.d.ts +29 -0
- package/dist/audit/auditEventModel.js +101 -0
- package/dist/audit/cloudTasksEnqueue.d.ts +32 -0
- package/dist/audit/cloudTasksEnqueue.js +69 -0
- package/dist/audit/diff.d.ts +10 -0
- package/dist/audit/diff.js +140 -0
- package/dist/audit/processQueue.d.ts +6 -0
- package/dist/audit/processQueue.js +56 -0
- package/dist/audit/rbacSink.d.ts +2 -0
- package/dist/audit/rbacSink.js +41 -0
- package/dist/audit/record.d.ts +56 -0
- package/dist/audit/record.js +251 -0
- package/dist/auth.js +432 -681
- package/dist/authRecovery.js +155 -269
- package/dist/authTokens.js +43 -118
- package/dist/betterAuth.d.ts +6 -0
- package/dist/betterAuthApp.js +25 -26
- package/dist/betterAuthSetup.js +258 -413
- package/dist/browserLogsRoute.d.ts +6 -0
- package/dist/browserLogsRoute.js +97 -0
- package/dist/collectionRegistry.d.ts +3 -1
- package/dist/collectionRegistry.js +43 -33
- package/dist/config.js +53 -122
- package/dist/configurationApp.js +180 -361
- package/dist/configurationPlugin.js +130 -302
- package/dist/consentApp.js +276 -421
- package/dist/docLoader.js +78 -126
- package/dist/envConfigurationPlugin.js +25 -147
- package/dist/errors.js +151 -247
- package/dist/example.js +28 -34
- package/dist/expressServer.d.ts +10 -0
- package/dist/expressServer.js +109 -255
- package/dist/frameworkModelNames.d.ts +24 -0
- package/dist/frameworkModelNames.js +31 -0
- package/dist/githubAuth.js +152 -216
- package/dist/httpClient.js +176 -264
- package/dist/index.d.ts +28 -1
- package/dist/index.js +53 -2
- package/dist/logger.js +145 -278
- package/dist/mcp/auth.js +76 -128
- package/dist/mcp/createMCPRequest.js +4 -5
- package/dist/mcp/handlers.js +268 -480
- package/dist/mcp/query.d.ts +0 -13
- package/dist/mcp/query.js +57 -151
- package/dist/mcp/registry.js +17 -30
- package/dist/mcp/schemaGenerator.js +95 -181
- package/dist/mcp/server.js +28 -100
- package/dist/mcp/serviceTokens.js +102 -191
- package/dist/mcp/toolGenerator.js +78 -191
- package/dist/middleware.js +15 -27
- package/dist/migrations/fixtures/all-down/20260910120000-one.d.ts +4 -0
- package/dist/migrations/fixtures/all-down/20260910120000-one.js +9 -0
- package/dist/migrations/fixtures/all-down/20260910120001-two.d.ts +4 -0
- package/dist/migrations/fixtures/all-down/20260910120001-two.js +9 -0
- package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.d.ts +3 -0
- package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +7 -0
- package/dist/migrations/fixtures/bad-name/not-a-migration.d.ts +3 -0
- package/dist/migrations/fixtures/bad-name/not-a-migration.js +7 -0
- package/dist/migrations/fixtures/missing-up/20260910120000-noup.d.ts +2 -0
- package/dist/migrations/fixtures/missing-up/20260910120000-noup.js +5 -0
- package/dist/migrations/fixtures/valid/20260910120000-alpha.d.ts +3 -0
- package/dist/migrations/fixtures/valid/20260910120000-alpha.js +7 -0
- package/dist/migrations/fixtures/valid/20260910120001-beta.d.ts +4 -0
- package/dist/migrations/fixtures/valid/20260910120001-beta.js +9 -0
- package/dist/migrations/generate.d.ts +17 -0
- package/dist/migrations/generate.js +155 -0
- package/dist/migrations/load.d.ts +20 -0
- package/dist/migrations/load.js +110 -0
- package/dist/migrations/lock.d.ts +13 -0
- package/dist/migrations/lock.js +73 -0
- package/dist/migrations/runner.d.ts +42 -0
- package/dist/migrations/runner.js +249 -0
- package/dist/migrations/schemaCatalog.d.ts +44 -0
- package/dist/migrations/schemaCatalog.js +185 -0
- package/dist/migrations/types.d.ts +87 -0
- package/dist/migrations/types.js +7 -0
- package/dist/models/consentForm.js +6 -6
- package/dist/models/consentResponse.js +5 -5
- package/dist/models/mcpServiceToken.js +66 -156
- package/dist/models/notification.d.ts +2 -0
- package/dist/models/notification.js +62 -0
- package/dist/models/notificationPreference.d.ts +2 -0
- package/dist/models/notificationPreference.js +49 -0
- package/dist/models/versionConfig.js +5 -5
- package/dist/notifications/notificationService.d.ts +40 -0
- package/dist/notifications/notificationService.js +183 -0
- package/dist/notifications/notificationsApp.d.ts +18 -0
- package/dist/notifications/notificationsApp.js +156 -0
- package/dist/notifications/notificationsBeforeSend.d.ts +14 -0
- package/dist/notifications/notificationsBeforeSend.js +32 -0
- package/dist/notifiers/googleChatNotifier.js +36 -117
- package/dist/notifiers/slackNotifier.d.ts +31 -2
- package/dist/notifiers/slackNotifier.js +170 -119
- package/dist/notifiers/zoomNotifier.js +60 -111
- package/dist/openApi.d.ts +1 -7
- package/dist/openApi.js +113 -127
- package/dist/openApiBuilder.d.ts +14 -3
- package/dist/openApiBuilder.js +117 -159
- package/dist/openApiCompat.js +81 -148
- package/dist/openApiEtag.js +7 -7
- package/dist/openApiValidator.d.ts +13 -1
- package/dist/openApiValidator.js +301 -246
- package/dist/orgs/orgContext.d.ts +23 -0
- package/dist/orgs/orgContext.js +128 -0
- package/dist/orgs/orgPermissions.d.ts +4 -0
- package/dist/orgs/orgPermissions.js +38 -0
- package/dist/orgs/orgPlugin.d.ts +13 -0
- package/dist/orgs/orgPlugin.js +66 -0
- package/dist/orgs/organizationModel.d.ts +13 -0
- package/dist/orgs/organizationModel.js +200 -0
- package/dist/orgs/organizationSettings.d.ts +19 -0
- package/dist/orgs/organizationSettings.js +113 -0
- package/dist/orgs/orgsApp.d.ts +28 -0
- package/dist/orgs/orgsApp.js +416 -0
- package/dist/permissions.d.ts +7 -13
- package/dist/permissions.js +95 -211
- package/dist/plugins.js +125 -218
- package/dist/populate.js +130 -240
- package/dist/rateLimit/applyTrustProxy.js +1 -1
- package/dist/rateLimit/createStore.js +7 -8
- package/dist/rateLimit/memoryStore.js +22 -100
- package/dist/rateLimit/middleware.d.ts +0 -8
- package/dist/rateLimit/middleware.js +49 -101
- package/dist/rateLimit/mongoStore.d.ts +1 -0
- package/dist/rateLimit/mongoStore.js +55 -112
- package/dist/rateLimit/policies.d.ts +0 -4
- package/dist/rateLimit/policies.js +44 -80
- package/dist/rateLimit/redisStore.d.ts +1 -0
- package/dist/rateLimit/redisStore.js +40 -133
- package/dist/rbac/access.js +122 -253
- package/dist/rbac/assertAllowed.js +95 -171
- package/dist/rbac/auditModel.js +14 -58
- package/dist/rbac/backfillAdmins.js +24 -130
- package/dist/rbac/fieldViews.js +46 -141
- package/dist/rbac/membershipOrgAdminSource.d.ts +6 -0
- package/dist/rbac/membershipOrgAdminSource.js +51 -0
- package/dist/rbac/middleware.js +30 -96
- package/dist/rbac/modelRouterAccess.d.ts +3 -0
- package/dist/rbac/modelRouterAccess.js +133 -307
- package/dist/rbac/permissionUtils.js +40 -179
- package/dist/rbac/realtimeAccess.js +81 -147
- package/dist/rbac/resolve.d.ts +1 -1
- package/dist/rbac/resolve.js +154 -319
- package/dist/rbac/roleManager.js +318 -700
- package/dist/rbac/roleModel.d.ts +2 -5
- package/dist/rbac/roleModel.js +60 -173
- package/dist/rbac/routes.js +93 -196
- package/dist/rbac/scopes.js +39 -133
- package/dist/rbac/statements.d.ts +10 -1
- package/dist/rbac/statements.js +42 -93
- package/dist/rbac/types.d.ts +5 -0
- package/dist/rbac/userPlugin.js +3 -29
- package/dist/realtime/changeStreamWatcher.d.ts +10 -4
- package/dist/realtime/changeStreamWatcher.js +499 -764
- package/dist/realtime/deprecation.d.ts +1 -0
- package/dist/realtime/deprecation.js +9 -10
- package/dist/realtime/queryMatcher.js +110 -191
- package/dist/realtime/queryStore.js +35 -118
- package/dist/realtime/realtimeApp.d.ts +1 -0
- package/dist/realtime/realtimeApp.js +248 -401
- package/dist/realtime/registry.js +19 -30
- package/dist/realtime/sessionRevalidation.js +132 -358
- package/dist/realtime/socketAuth.js +89 -208
- package/dist/realtime/socketUser.js +10 -56
- package/dist/requestContext.js +93 -139
- package/dist/schemaMetadata.js +181 -265
- package/dist/scriptRunner.js +96 -266
- package/dist/scrubAdminFields.js +36 -108
- package/dist/secretProviders.js +130 -299
- package/dist/seedRunner.js +221 -514
- package/dist/sync/adminBroadcastScope.d.ts +40 -0
- package/dist/sync/adminBroadcastScope.js +82 -0
- package/dist/sync/adminWindowAccess.d.ts +13 -0
- package/dist/sync/adminWindowAccess.js +25 -0
- package/dist/sync/adminWindowMutation.d.ts +88 -0
- package/dist/sync/adminWindowMutation.js +176 -0
- package/dist/sync/executors.d.ts +9 -3
- package/dist/sync/executors.js +425 -598
- package/dist/sync/loadHarness.js +392 -689
- package/dist/sync/models.js +181 -341
- package/dist/sync/mutationHandler.d.ts +5 -2
- package/dist/sync/mutationHandler.js +549 -697
- package/dist/sync/registrationSideEffects.js +41 -95
- package/dist/sync/registry.js +31 -47
- package/dist/sync/routes.d.ts +13 -0
- package/dist/sync/routes.js +484 -760
- package/dist/sync/scripts/compactTombstones.js +83 -228
- package/dist/sync/serialize.js +18 -58
- package/dist/sync/socketHandlers.d.ts +8 -2
- package/dist/sync/socketHandlers.js +271 -402
- package/dist/sync/streams.d.ts +2 -0
- package/dist/sync/streams.js +54 -116
- package/dist/sync/syncApp.d.ts +2 -1
- package/dist/sync/syncApp.js +14 -16
- package/dist/sync/syncBatch.d.ts +5 -2
- package/dist/sync/syncBatch.js +63 -168
- package/dist/sync/syncSeqPlugin.js +430 -702
- package/dist/sync/types.d.ts +18 -0
- package/dist/syncConsents.js +113 -253
- package/dist/terrenoApp.d.ts +29 -0
- package/dist/terrenoApp.js +184 -257
- package/dist/tests/createTestData.d.ts +1 -3
- package/dist/tests/createTestData.js +147 -259
- package/dist/tests/models.d.ts +1 -0
- package/dist/tests/models.js +23 -56
- package/dist/tests/mongoTestSetup.js +42 -103
- package/dist/tests/testHelper.d.ts +0 -5
- package/dist/tests/testHelper.js +32 -101
- package/dist/tests.js +12 -51
- package/dist/transformers.js +61 -164
- package/dist/types/authToken.d.ts +3 -3
- package/dist/types/mcpServiceToken.d.ts +2 -2
- package/dist/types/membership.d.ts +23 -0
- package/dist/types/membership.js +2 -0
- package/dist/types/notification.d.ts +28 -0
- package/dist/types/notification.js +2 -0
- package/dist/types/notificationPreference.d.ts +20 -0
- package/dist/types/notificationPreference.js +2 -0
- package/dist/types/organization.d.ts +36 -0
- package/dist/types/organization.js +2 -0
- package/dist/utils.js +31 -93
- package/dist/vendor/wesleytodd-openapi/index.js +37 -51
- package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
- package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
- package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
- package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
- package/dist/versionCheckPlugin.js +52 -100
- package/dist/webhooks/headerValue.js +2 -2
- package/dist/webhooks/idempotency/memoryStore.js +16 -59
- package/dist/webhooks/idempotency/mongoStore.js +55 -130
- package/dist/webhooks/idempotency/webhookReceipt.d.ts +4 -49
- package/dist/webhooks/idempotency/webhookReceipt.js +14 -14
- package/dist/webhooks/rawBody.d.ts +1 -0
- package/dist/webhooks/rawBody.js +2 -1
- package/dist/webhooks/timingSafeEqual.js +4 -5
- package/dist/webhooks/verifiers/hmac.js +17 -18
- package/dist/webhooks/verifiers/sendgrid.js +20 -22
- package/dist/webhooks/verifiers/stripe.js +31 -65
- package/dist/webhooks/verifiers/twilio.js +23 -73
- package/dist/webhooks/webhooksApp.js +78 -177
- package/dist/zodOpenApi.js +2 -2
- package/package.json +34 -28
- package/src/__snapshots__/openApi.test.ts.snap +192 -54
- package/src/__snapshots__/openApiBuilder.test.ts.snap +0 -18
- package/src/__snapshots__/schemaMetadata.test.ts.snap +0 -1
- package/src/__tests__/browserLogsRoute.test.ts +165 -0
- package/src/adminTypes.ts +8 -0
- package/src/api.test.ts +39 -2
- package/src/api.ts +68 -0
- package/src/audit/auditApp.test.ts +243 -0
- package/src/audit/auditApp.ts +139 -0
- package/src/audit/auditEventModel.ts +160 -0
- package/src/audit/auditRouter.test.ts +456 -0
- package/src/audit/cloudTasksEnqueue.test.ts +124 -0
- package/src/audit/cloudTasksEnqueue.ts +104 -0
- package/src/audit/diff.ts +163 -0
- package/src/audit/processQueue.ts +69 -0
- package/src/audit/rbacSink.test.ts +86 -0
- package/src/audit/rbacSink.ts +42 -0
- package/src/audit/record.test.ts +402 -0
- package/src/audit/record.ts +329 -0
- package/src/auth.test.ts +1 -1
- package/src/auth.ts +1 -1
- package/src/authRecovery.test.ts +43 -0
- package/src/authRecovery.ts +16 -10
- package/src/authTokens.ts +6 -2
- package/src/authVerification.test.ts +22 -0
- package/src/betterAuth.ts +7 -0
- package/src/betterAuthSetup.test.ts +27 -0
- package/src/betterAuthSetup.ts +1 -0
- package/src/browserLogsRoute.ts +110 -0
- package/src/collectionRegistry.test.ts +8 -9
- package/src/collectionRegistry.ts +21 -1
- package/src/configurationPlugin.test.ts +1 -11
- package/src/express.d.ts +2 -0
- package/src/expressServer.test.ts +50 -2
- package/src/expressServer.ts +10 -0
- package/src/frameworkModelNames.test.ts +62 -0
- package/src/frameworkModelNames.ts +33 -0
- package/src/index.ts +76 -0
- package/src/isolated/migrateCliConnect.isolated.ts +51 -0
- package/src/mcp/auth.test.ts +34 -1
- package/src/mcp/handlers.test.ts +275 -0
- package/src/mcp/query.ts +3 -3
- package/src/mcp/toolGenerator.test.ts +81 -0
- package/src/migrations/cli.test.ts +353 -0
- package/src/migrations/cli.ts +283 -0
- package/src/migrations/fixtures/all-down/20260910120000-one.ts +6 -0
- package/src/migrations/fixtures/all-down/20260910120001-two.ts +6 -0
- package/src/migrations/fixtures/bad-id/20260910120000-mismatch.ts +4 -0
- package/src/migrations/fixtures/bad-name/not-a-migration.ts +4 -0
- package/src/migrations/fixtures/missing-up/20260910120000-noup.ts +2 -0
- package/src/migrations/fixtures/valid/20260910120000-alpha.ts +4 -0
- package/src/migrations/fixtures/valid/20260910120001-beta.ts +6 -0
- package/src/migrations/generate.test.ts +333 -0
- package/src/migrations/generate.ts +216 -0
- package/src/migrations/load.test.ts +103 -0
- package/src/migrations/load.ts +124 -0
- package/src/migrations/lock.test.ts +133 -0
- package/src/migrations/lock.ts +118 -0
- package/src/migrations/runner.test.ts +504 -0
- package/src/migrations/runner.ts +358 -0
- package/src/migrations/schemaCatalog.test.ts +159 -0
- package/src/migrations/schemaCatalog.ts +262 -0
- package/src/migrations/types.ts +94 -0
- package/src/models/mcpServiceToken.ts +4 -3
- package/src/models/notification.ts +69 -0
- package/src/models/notificationPreference.ts +62 -0
- package/src/notifications/notificationService.ts +254 -0
- package/src/notifications/notificationsApp.test.ts +528 -0
- package/src/notifications/notificationsApp.ts +200 -0
- package/src/notifications/notificationsBeforeSend.ts +51 -0
- package/src/notifiers/slackNotifier.test.ts +186 -1
- package/src/notifiers/slackNotifier.ts +167 -8
- package/src/openApi.test.ts +0 -1
- package/src/openApi.ts +2 -1
- package/src/openApiBuilder.ts +14 -3
- package/src/openApiValidator.test.ts +221 -2
- package/src/openApiValidator.ts +218 -33
- package/src/orgs/orgAccessOptIn.test.ts +87 -0
- package/src/orgs/orgContext.test.ts +259 -0
- package/src/orgs/orgContext.ts +151 -0
- package/src/orgs/orgPermissions.test.ts +105 -0
- package/src/orgs/orgPermissions.ts +40 -0
- package/src/orgs/orgPlugin.test.ts +130 -0
- package/src/orgs/orgPlugin.ts +70 -0
- package/src/orgs/orgRbac.test.ts +267 -0
- package/src/orgs/orgSecurityDefects.test.ts +415 -0
- package/src/orgs/organizationModel.test.ts +205 -0
- package/src/orgs/organizationModel.ts +262 -0
- package/src/orgs/organizationSettings.test.ts +113 -0
- package/src/orgs/organizationSettings.ts +126 -0
- package/src/orgs/orgsApp.test.ts +382 -0
- package/src/orgs/orgsApp.ts +563 -0
- package/src/permissions.test.ts +62 -36
- package/src/permissions.ts +8 -30
- package/src/plugins.test.ts +5 -0
- package/src/plugins.ts +3 -0
- package/src/rateLimit/middleware.ts +1 -1
- package/src/rateLimit/mongoStore.ts +1 -0
- package/src/rateLimit/policies.ts +2 -2
- package/src/rateLimit/redisStore.ts +1 -0
- package/src/rbac/access.ts +11 -3
- package/src/rbac/membershipOrgAdminSource.ts +59 -0
- package/src/rbac/modelRouterAccess.ts +3 -0
- package/src/rbac/permissionUtils.test.ts +26 -5
- package/src/rbac/resolve.test.ts +34 -2
- package/src/rbac/resolve.ts +26 -7
- package/src/rbac/roleModel.test.ts +34 -1
- package/src/rbac/roleModel.ts +17 -1
- package/src/rbac/statements.test.ts +19 -0
- package/src/rbac/statements.ts +19 -1
- package/src/rbac/types.ts +5 -0
- package/src/realtime/changeStreamWatcher.ts +73 -33
- package/src/realtime/deprecation.ts +1 -0
- package/src/realtime/realtime.test.ts +357 -185
- package/src/realtime/realtimeApp.ts +2 -1
- package/src/schemaMetadata.test.ts +14 -0
- package/src/schemaMetadata.ts +5 -5
- package/src/sync/adminBroadcastConfig.test.ts +96 -0
- package/src/sync/adminBroadcastScope.test.ts +155 -0
- package/src/sync/adminBroadcastScope.ts +123 -0
- package/src/sync/adminWindowAccess.test.ts +57 -0
- package/src/sync/adminWindowAccess.ts +32 -0
- package/src/sync/adminWindowMutation.test.ts +450 -0
- package/src/sync/adminWindowMutation.ts +283 -0
- package/src/sync/executors.ts +33 -6
- package/src/sync/integration.test.ts +2 -2
- package/src/sync/mutationHandler.test.ts +277 -1
- package/src/sync/mutationHandler.ts +171 -29
- package/src/sync/registry.ts +4 -0
- package/src/sync/routes.ts +52 -8
- package/src/sync/socketHandlers.ts +154 -58
- package/src/sync/streams.ts +6 -0
- package/src/sync/sync.test.ts +3 -2
- package/src/sync/syncApp.ts +2 -1
- package/src/sync/syncBatch.ts +7 -2
- package/src/sync/syncRoutes.test.ts +297 -3
- package/src/sync/syncSocket.test.ts +229 -0
- package/src/sync/types.ts +20 -0
- package/src/terrenoApp.migrations.test.ts +114 -0
- package/src/terrenoApp.test.ts +41 -0
- package/src/terrenoApp.ts +97 -31
- package/src/tests/createTestData.ts +2 -2
- package/src/tests/models.ts +10 -2
- package/src/tests/testHelper.ts +1 -7
- package/src/types/authToken.ts +2 -4
- package/src/types/mcpServiceToken.ts +1 -7
- package/src/types/membership.ts +48 -0
- package/src/types/notification.ts +34 -0
- package/src/types/notificationPreference.ts +28 -0
- package/src/types/organization.ts +49 -0
- package/src/types.d.ts +1 -0
- package/src/webhooks/idempotency/webhookReceipt.ts +8 -10
- package/src/webhooks/rawBody.test.ts +33 -0
- package/src/webhooks/rawBody.ts +1 -0
- package/tsconfig.json +13 -54
- package/tsconfig.typedoc.json +4 -1
- package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.d.ts +0 -2
- package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
- package/src/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
package/dist/api.js
CHANGED
|
@@ -1,15 +1,4 @@
|
|
|
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
|
-
};
|
|
13
2
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
14
3
|
if (k2 === undefined) k2 = k;
|
|
15
4
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
@@ -43,78 +32,6 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
43
32
|
return result;
|
|
44
33
|
};
|
|
45
34
|
})();
|
|
46
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
47
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
48
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
49
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
50
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
51
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
52
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
53
|
-
});
|
|
54
|
-
};
|
|
55
|
-
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
56
|
-
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
57
|
-
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
58
|
-
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
59
|
-
function step(op) {
|
|
60
|
-
if (f) throw new TypeError("Generator is already executing.");
|
|
61
|
-
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
62
|
-
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
63
|
-
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
64
|
-
switch (op[0]) {
|
|
65
|
-
case 0: case 1: t = op; break;
|
|
66
|
-
case 4: _.label++; return { value: op[1], done: false };
|
|
67
|
-
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
68
|
-
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
69
|
-
default:
|
|
70
|
-
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
71
|
-
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
72
|
-
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
73
|
-
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
74
|
-
if (t[2]) _.ops.pop();
|
|
75
|
-
_.trys.pop(); continue;
|
|
76
|
-
}
|
|
77
|
-
op = body.call(thisArg, _);
|
|
78
|
-
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
79
|
-
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
80
|
-
}
|
|
81
|
-
};
|
|
82
|
-
var __values = (this && this.__values) || function(o) {
|
|
83
|
-
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
|
84
|
-
if (m) return m.call(o);
|
|
85
|
-
if (o && typeof o.length === "number") return {
|
|
86
|
-
next: function () {
|
|
87
|
-
if (o && i >= o.length) o = void 0;
|
|
88
|
-
return { value: o && o[i++], done: !o };
|
|
89
|
-
}
|
|
90
|
-
};
|
|
91
|
-
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
|
92
|
-
};
|
|
93
|
-
var __read = (this && this.__read) || function (o, n) {
|
|
94
|
-
var m = typeof Symbol === "function" && o[Symbol.iterator];
|
|
95
|
-
if (!m) return o;
|
|
96
|
-
var i = m.call(o), r, ar = [], e;
|
|
97
|
-
try {
|
|
98
|
-
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
|
|
99
|
-
}
|
|
100
|
-
catch (error) { e = { error: error }; }
|
|
101
|
-
finally {
|
|
102
|
-
try {
|
|
103
|
-
if (r && !r.done && (m = i["return"])) m.call(i);
|
|
104
|
-
}
|
|
105
|
-
finally { if (e) throw e.error; }
|
|
106
|
-
}
|
|
107
|
-
return ar;
|
|
108
|
-
};
|
|
109
|
-
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
|
|
110
|
-
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
|
111
|
-
if (ar || !(i in from)) {
|
|
112
|
-
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
|
113
|
-
ar[i] = from[i];
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
return to.concat(ar || Array.prototype.slice.call(from));
|
|
117
|
-
};
|
|
118
35
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
119
36
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
120
37
|
};
|
|
@@ -126,47 +43,37 @@ exports.modelRouter = modelRouter;
|
|
|
126
43
|
*
|
|
127
44
|
* @packageDocumentation
|
|
128
45
|
*/
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
46
|
+
const Sentry = __importStar(require("@sentry/bun"));
|
|
47
|
+
const express_1 = __importDefault(require("express"));
|
|
48
|
+
const cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
|
|
49
|
+
const luxon_1 = require("luxon");
|
|
50
|
+
const mongoose_1 = __importDefault(require("mongoose"));
|
|
51
|
+
const actions_1 = require("./actions");
|
|
52
|
+
const adminModelRouter_1 = require("./adminModelRouter");
|
|
53
|
+
const record_1 = require("./audit/record");
|
|
54
|
+
const auth_1 = require("./auth");
|
|
55
|
+
const collectionRegistry_1 = require("./collectionRegistry");
|
|
56
|
+
const errors_1 = require("./errors");
|
|
57
|
+
const logger_1 = require("./logger");
|
|
58
|
+
const registry_1 = require("./mcp/registry");
|
|
59
|
+
const openApi_1 = require("./openApi");
|
|
60
|
+
const openApiValidator_1 = require("./openApiValidator");
|
|
61
|
+
const permissions_1 = require("./permissions");
|
|
62
|
+
const modelRouterAccess_1 = require("./rbac/modelRouterAccess");
|
|
63
|
+
const deprecation_1 = require("./realtime/deprecation");
|
|
64
|
+
const executors_1 = require("./sync/executors");
|
|
65
|
+
const transformers_1 = require("./transformers");
|
|
66
|
+
const utils_1 = require("./utils");
|
|
67
|
+
const addPopulateToQuery = (
|
|
150
68
|
// noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
|
|
151
69
|
// biome-ignore lint/suspicious/noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
|
|
152
|
-
builtQuery, populatePaths) {
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
var path = populatePath.path;
|
|
160
|
-
var select = populatePath.fields;
|
|
161
|
-
query = builtQuery.populate({ path: path, select: select });
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
165
|
-
finally {
|
|
166
|
-
try {
|
|
167
|
-
if (paths_1_1 && !paths_1_1.done && (_a = paths_1.return)) _a.call(paths_1);
|
|
168
|
-
}
|
|
169
|
-
finally { if (e_1) throw e_1.error; }
|
|
70
|
+
builtQuery, populatePaths) => {
|
|
71
|
+
const paths = populatePaths ?? [];
|
|
72
|
+
let query = builtQuery;
|
|
73
|
+
for (const populatePath of paths) {
|
|
74
|
+
const path = populatePath.path;
|
|
75
|
+
const select = populatePath.fields;
|
|
76
|
+
query = builtQuery.populate({ path, select });
|
|
170
77
|
}
|
|
171
78
|
return query;
|
|
172
79
|
};
|
|
@@ -176,20 +83,20 @@ exports.addPopulateToQuery = addPopulateToQuery;
|
|
|
176
83
|
// Support more complex query fields
|
|
177
84
|
// Rate limiting
|
|
178
85
|
// These are the query params that are reserved for pagination.
|
|
179
|
-
|
|
86
|
+
const PAGINATION_QUERY_PARAMS = ["limit", "page", "sort"];
|
|
180
87
|
// Add support for more complex queries.
|
|
181
|
-
|
|
88
|
+
const COMPLEX_QUERY_PARAMS = ["$and", "$or"];
|
|
182
89
|
/**
|
|
183
90
|
* Parses a date-range query bound from an ISO-8601 string using Luxon, throwing a 400
|
|
184
91
|
* APIError when the value cannot be parsed. Centralizes date-string parsing so the repo's
|
|
185
92
|
* Luxon convention is honored for admin changelist date-range filters.
|
|
186
93
|
*/
|
|
187
|
-
|
|
188
|
-
|
|
94
|
+
const parseDateRangeBound = (rawValue, queryKey) => {
|
|
95
|
+
const parsed = luxon_1.DateTime.fromISO(String(rawValue), { zone: "utc" });
|
|
189
96
|
if (!parsed.isValid) {
|
|
190
97
|
throw new errors_1.BadRequestError({
|
|
191
98
|
code: "invalid-date-query-parameter",
|
|
192
|
-
detail:
|
|
99
|
+
detail: `Invalid date for query parameter ${queryKey}`,
|
|
193
100
|
source: { parameter: queryKey },
|
|
194
101
|
title: "Invalid date query parameter",
|
|
195
102
|
});
|
|
@@ -200,114 +107,71 @@ var parseDateRangeBound = function (rawValue, queryKey) {
|
|
|
200
107
|
* Collapses `field_gte` / `field_lte` query pairs into `{ field: { $gte, $lte } }` for Date paths,
|
|
201
108
|
* so admin changelist date-range filters map to valid Mongoose range queries.
|
|
202
109
|
*/
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
var match = /^(.+)_(gte|lte)$/.exec(key);
|
|
212
|
-
if (!match) {
|
|
213
|
-
continue;
|
|
214
|
-
}
|
|
215
|
-
var baseField = match[1];
|
|
216
|
-
var path = schema.path(baseField);
|
|
217
|
-
if ((path === null || path === void 0 ? void 0 : path.instance) !== "Date") {
|
|
218
|
-
continue;
|
|
219
|
-
}
|
|
220
|
-
dateRangeBases.add(baseField);
|
|
110
|
+
const mergeDateRangeQueryParams = (model, query) => {
|
|
111
|
+
const schema = model.schema;
|
|
112
|
+
const result = { ...query };
|
|
113
|
+
const dateRangeBases = new Set();
|
|
114
|
+
for (const key of Object.keys(result)) {
|
|
115
|
+
const match = /^(.+)_(gte|lte)$/.exec(key);
|
|
116
|
+
if (!match) {
|
|
117
|
+
continue;
|
|
221
118
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
|
|
119
|
+
const baseField = match[1];
|
|
120
|
+
const path = schema.path(baseField);
|
|
121
|
+
if (path?.instance !== "Date") {
|
|
122
|
+
continue;
|
|
227
123
|
}
|
|
228
|
-
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
if (gteRaw !== undefined && gteRaw !== null && String(gteRaw).trim() !== "") {
|
|
239
|
-
bounds.$gte = parseDateRangeBound(gteRaw, gteKey);
|
|
240
|
-
}
|
|
241
|
-
if (lteRaw !== undefined && lteRaw !== null && String(lteRaw).trim() !== "") {
|
|
242
|
-
bounds.$lte = parseDateRangeBound(lteRaw, lteKey);
|
|
243
|
-
}
|
|
244
|
-
if (Object.keys(bounds).length === 0) {
|
|
245
|
-
continue;
|
|
246
|
-
}
|
|
247
|
-
delete result[gteKey];
|
|
248
|
-
delete result[lteKey];
|
|
249
|
-
var direct = result[baseField];
|
|
250
|
-
if (direct !== undefined && direct !== null && typeof direct !== "object") {
|
|
251
|
-
delete result[baseField];
|
|
252
|
-
}
|
|
253
|
-
if (typeof direct === "object" && direct !== null && !Array.isArray(direct)) {
|
|
254
|
-
result[baseField] = __assign(__assign({}, direct), bounds);
|
|
255
|
-
}
|
|
256
|
-
else {
|
|
257
|
-
result[baseField] = bounds;
|
|
258
|
-
}
|
|
124
|
+
dateRangeBases.add(baseField);
|
|
125
|
+
}
|
|
126
|
+
for (const baseField of dateRangeBases) {
|
|
127
|
+
const gteKey = `${baseField}_gte`;
|
|
128
|
+
const lteKey = `${baseField}_lte`;
|
|
129
|
+
const gteRaw = result[gteKey];
|
|
130
|
+
const lteRaw = result[lteKey];
|
|
131
|
+
const bounds = {};
|
|
132
|
+
if (gteRaw !== undefined && gteRaw !== null && String(gteRaw).trim() !== "") {
|
|
133
|
+
bounds.$gte = parseDateRangeBound(gteRaw, gteKey);
|
|
259
134
|
}
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
135
|
+
if (lteRaw !== undefined && lteRaw !== null && String(lteRaw).trim() !== "") {
|
|
136
|
+
bounds.$lte = parseDateRangeBound(lteRaw, lteKey);
|
|
137
|
+
}
|
|
138
|
+
if (Object.keys(bounds).length === 0) {
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
delete result[gteKey];
|
|
142
|
+
delete result[lteKey];
|
|
143
|
+
const direct = result[baseField];
|
|
144
|
+
if (direct !== undefined && direct !== null && typeof direct !== "object") {
|
|
145
|
+
delete result[baseField];
|
|
146
|
+
}
|
|
147
|
+
if (typeof direct === "object" && direct !== null && !Array.isArray(direct)) {
|
|
148
|
+
result[baseField] = { ...direct, ...bounds };
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
result[baseField] = bounds;
|
|
265
152
|
}
|
|
266
|
-
finally { if (e_3) throw e_3.error; }
|
|
267
153
|
}
|
|
268
154
|
return result;
|
|
269
155
|
};
|
|
270
156
|
// Ensures query params are allowed. Also checks nested query params when using $and/$or.
|
|
271
|
-
|
|
272
|
-
var e_4, _a, e_5, _b;
|
|
273
|
-
if (queryFields === void 0) { queryFields = []; }
|
|
157
|
+
const checkQueryParamAllowed = (queryParam, queryParamValue, queryFields = []) => {
|
|
274
158
|
// Cast for iteration through complex query values
|
|
275
|
-
|
|
159
|
+
const complexValue = queryParamValue;
|
|
276
160
|
// Check the values of each of the complex query params. We don't support recursive queries here,
|
|
277
161
|
// just one level of and/or
|
|
278
162
|
if (COMPLEX_QUERY_PARAMS.includes(queryParam)) {
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
for (
|
|
282
|
-
|
|
283
|
-
try {
|
|
284
|
-
for (var _c = (e_5 = void 0, __values(Object.keys(subQuery))), _d = _c.next(); !_d.done; _d = _c.next()) {
|
|
285
|
-
var subKey = _d.value;
|
|
286
|
-
checkQueryParamAllowed(subKey, subQuery[subKey], queryFields);
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
catch (e_5_1) { e_5 = { error: e_5_1 }; }
|
|
290
|
-
finally {
|
|
291
|
-
try {
|
|
292
|
-
if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
|
|
293
|
-
}
|
|
294
|
-
finally { if (e_5) throw e_5.error; }
|
|
295
|
-
}
|
|
163
|
+
// Complex query of the form `$and: [{key1: value1}, {key2: value2}]`
|
|
164
|
+
for (const subQuery of complexValue) {
|
|
165
|
+
for (const subKey of Object.keys(subQuery)) {
|
|
166
|
+
checkQueryParamAllowed(subKey, subQuery[subKey], queryFields);
|
|
296
167
|
}
|
|
297
168
|
}
|
|
298
|
-
catch (e_4_1) { e_4 = { error: e_4_1 }; }
|
|
299
|
-
finally {
|
|
300
|
-
try {
|
|
301
|
-
if (complexValue_1_1 && !complexValue_1_1.done && (_a = complexValue_1.return)) _a.call(complexValue_1);
|
|
302
|
-
}
|
|
303
|
-
finally { if (e_4) throw e_4.error; }
|
|
304
|
-
}
|
|
305
169
|
return;
|
|
306
170
|
}
|
|
307
171
|
if (!queryFields.includes(queryParam)) {
|
|
308
172
|
throw new errors_1.BadRequestError({
|
|
309
173
|
code: "query-param-not-allowed",
|
|
310
|
-
detail:
|
|
174
|
+
detail: `${queryParam} is not allowed as a query param.`,
|
|
311
175
|
source: { parameter: queryParam },
|
|
312
176
|
title: "Query parameter not allowed",
|
|
313
177
|
});
|
|
@@ -334,27 +198,26 @@ var checkQueryParamAllowed = function (queryParam, queryParamValue, queryFields)
|
|
|
334
198
|
// Helper to determine if validation should be enabled for a specific operation.
|
|
335
199
|
// When options.validation is not set, returns true — the middleware's own
|
|
336
200
|
// isConfigured check will decide whether to actually validate.
|
|
337
|
-
|
|
338
|
-
var _a, _b, _c;
|
|
201
|
+
const shouldValidate = (options, operation) => {
|
|
339
202
|
// Check route-specific validation option first
|
|
340
203
|
if (options.validation !== undefined) {
|
|
341
204
|
if (typeof options.validation === "boolean") {
|
|
342
205
|
return options.validation;
|
|
343
206
|
}
|
|
344
207
|
if (operation === "create") {
|
|
345
|
-
return
|
|
208
|
+
return options.validation.validateCreate ?? true;
|
|
346
209
|
}
|
|
347
210
|
if (operation === "update") {
|
|
348
|
-
return
|
|
211
|
+
return options.validation.validateUpdate ?? true;
|
|
349
212
|
}
|
|
350
|
-
return
|
|
213
|
+
return options.validation.validateQuery ?? true;
|
|
351
214
|
}
|
|
352
215
|
// Default: let middleware's isConfigured check decide
|
|
353
216
|
return true;
|
|
354
217
|
};
|
|
355
218
|
// Get body validation middleware if validation is enabled
|
|
356
|
-
|
|
357
|
-
|
|
219
|
+
const getBodyValidationMiddleware = (model, options, operation) => {
|
|
220
|
+
const validationOptions = {};
|
|
358
221
|
if (!shouldValidate(options, operation)) {
|
|
359
222
|
validationOptions.enabled = false;
|
|
360
223
|
}
|
|
@@ -366,19 +229,22 @@ var getBodyValidationMiddleware = function (model, options, operation) {
|
|
|
366
229
|
validationOptions.onAdditionalPropertiesRemoved =
|
|
367
230
|
options.validation.onAdditionalPropertiesRemoved;
|
|
368
231
|
}
|
|
369
|
-
|
|
232
|
+
const excludeFields = operation === "create"
|
|
370
233
|
? options.validation.excludeFromCreate
|
|
371
234
|
: options.validation.excludeFromUpdate;
|
|
372
|
-
if (excludeFields
|
|
235
|
+
if (excludeFields?.length) {
|
|
373
236
|
validationOptions.excludeFields = excludeFields;
|
|
374
237
|
}
|
|
375
238
|
}
|
|
239
|
+
if (operation === "update") {
|
|
240
|
+
validationOptions.partial = true;
|
|
241
|
+
}
|
|
376
242
|
return (0, openApiValidator_1.validateModelRequestBody)(model, validationOptions);
|
|
377
243
|
};
|
|
378
244
|
// Get query validation middleware if validation is enabled
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
245
|
+
const getQueryValidationMiddleware = (model, options) => {
|
|
246
|
+
const querySchema = (0, openApiValidator_1.buildQuerySchemaFromFields)(model, options.queryFields);
|
|
247
|
+
const validationOptions = {};
|
|
382
248
|
if (!shouldValidate(options, "query")) {
|
|
383
249
|
validationOptions.enabled = false;
|
|
384
250
|
}
|
|
@@ -388,9 +254,9 @@ var getQueryValidationMiddleware = function (model, options) {
|
|
|
388
254
|
return (0, openApiValidator_1.validateQueryParams)(querySchema, validationOptions);
|
|
389
255
|
};
|
|
390
256
|
function modelRouter(pathOrModel, modelOrOptions, maybeOptions) {
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
257
|
+
let model;
|
|
258
|
+
let options;
|
|
259
|
+
let path;
|
|
394
260
|
if (typeof pathOrModel === "string") {
|
|
395
261
|
path = pathOrModel;
|
|
396
262
|
model = modelOrOptions;
|
|
@@ -405,53 +271,62 @@ function modelRouter(pathOrModel, modelOrOptions, maybeOptions) {
|
|
|
405
271
|
if (options.mcp && path === undefined) {
|
|
406
272
|
(0, registry_1.registerMCPModel)(model, options.mcp, options);
|
|
407
273
|
}
|
|
408
|
-
|
|
274
|
+
const shouldDeferBuild = path !== undefined && Boolean(options.access) && !options.accessControl;
|
|
409
275
|
if (path !== undefined) {
|
|
410
276
|
if (options.realtime) {
|
|
411
277
|
(0, deprecation_1.warnRealtimeDeprecated)(model.modelName, path);
|
|
412
278
|
}
|
|
413
|
-
(0, collectionRegistry_1.registerCollection)({ model
|
|
279
|
+
(0, collectionRegistry_1.registerCollection)({ model, options, routePath: path });
|
|
414
280
|
}
|
|
415
|
-
|
|
281
|
+
const router = shouldDeferBuild ? express_1.default.Router() : _buildModelRouter(model, options, path);
|
|
416
282
|
if (path !== undefined) {
|
|
417
283
|
return {
|
|
418
284
|
__type: "modelRouter",
|
|
419
|
-
_buildWithContext:
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
285
|
+
_buildWithContext: (context) => {
|
|
286
|
+
const enrichedOptions = (0, adminModelRouter_1.enrichModelRouterOptions)(model, { ...options, openApi: context.openApi }, context);
|
|
287
|
+
const runtimeOptions = {
|
|
288
|
+
...enrichedOptions,
|
|
289
|
+
accessControl: enrichedOptions.accessControl ?? context.accessControl,
|
|
290
|
+
};
|
|
423
291
|
(0, collectionRegistry_1.replaceCollectionOptions)(path, runtimeOptions);
|
|
424
292
|
return _buildModelRouter(model, runtimeOptions, path);
|
|
425
293
|
},
|
|
426
|
-
model
|
|
427
|
-
options
|
|
428
|
-
path
|
|
429
|
-
router
|
|
294
|
+
model,
|
|
295
|
+
options,
|
|
296
|
+
path,
|
|
297
|
+
router,
|
|
430
298
|
};
|
|
431
299
|
}
|
|
432
300
|
if (options.realtime) {
|
|
433
301
|
(0, deprecation_1.warnRealtimeDeprecated)(model.modelName);
|
|
434
|
-
logger_1.logger.warn(
|
|
302
|
+
logger_1.logger.warn(`modelRouter for ${model.modelName} has realtime config but was called without a path. ` +
|
|
435
303
|
"Realtime sync only works with the three-argument form: modelRouter('/path', Model, options)");
|
|
436
304
|
}
|
|
437
305
|
if (options.sync) {
|
|
438
|
-
logger_1.logger.warn(
|
|
306
|
+
logger_1.logger.warn(`modelRouter for ${model.modelName} has sync config but was called without a path. ` +
|
|
439
307
|
"Local-first sync only works with the three-argument form: modelRouter('/path', Model, options)");
|
|
440
308
|
}
|
|
441
309
|
return router;
|
|
442
310
|
}
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
var resolvedAccess = (0, modelRouterAccess_1.resolveModelRouterAccess)({
|
|
311
|
+
const _buildModelRouter = (model, options, routePath) => {
|
|
312
|
+
const router = express_1.default.Router();
|
|
313
|
+
const resolvedAccess = (0, modelRouterAccess_1.resolveModelRouterAccess)({
|
|
447
314
|
access: options.access,
|
|
448
315
|
accessControl: options.accessControl,
|
|
449
316
|
permissions: options.permissions,
|
|
450
317
|
queryFilter: options.queryFilter,
|
|
451
318
|
responseHandler: options.responseHandler,
|
|
452
|
-
scope:
|
|
319
|
+
scope: options.access?.scope,
|
|
453
320
|
});
|
|
454
|
-
options =
|
|
321
|
+
options = {
|
|
322
|
+
...options,
|
|
323
|
+
permissions: resolvedAccess.permissions,
|
|
324
|
+
queryFilter: (resolvedAccess.queryFilter ??
|
|
325
|
+
options.queryFilter),
|
|
326
|
+
responseHandler: (resolvedAccess.responseHandler ??
|
|
327
|
+
options.responseHandler ??
|
|
328
|
+
transformers_1.defaultResponseHandler),
|
|
329
|
+
};
|
|
455
330
|
if (routePath) {
|
|
456
331
|
(0, collectionRegistry_1.replaceCollectionOptions)(routePath, options);
|
|
457
332
|
}
|
|
@@ -464,577 +339,512 @@ var _buildModelRouter = function (model, options, routePath) {
|
|
|
464
339
|
if (options.endpoints) {
|
|
465
340
|
options.endpoints(router, options);
|
|
466
341
|
}
|
|
467
|
-
|
|
342
|
+
const responseHandler = options.responseHandler ?? transformers_1.defaultResponseHandler;
|
|
468
343
|
// Always install validation middleware — they are no-ops until configureOpenApiValidator() is called
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
344
|
+
const createValidation = getBodyValidationMiddleware(model, options, "create");
|
|
345
|
+
const updateValidation = getBodyValidationMiddleware(model, options, "update");
|
|
346
|
+
const queryValidation = getQueryValidationMiddleware(model, options);
|
|
472
347
|
router.post("/", [
|
|
473
348
|
(0, auth_1.authenticateMiddleware)(options.allowAnonymous),
|
|
474
349
|
(0, openApi_1.createOpenApiMiddleware)(model, options),
|
|
475
350
|
(0, permissions_1.permissionMiddleware)(model, options),
|
|
476
351
|
createValidation,
|
|
477
|
-
], (0, exports.asyncHandler)(
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
return [4 /*yield*/, responseHandler(doc, "create", req, options)];
|
|
494
|
-
case 3:
|
|
495
|
-
serialized = _a.sent();
|
|
496
|
-
return [2 /*return*/, res.status(201).json({ data: serialized })];
|
|
497
|
-
case 4:
|
|
498
|
-
error_1 = _a.sent();
|
|
499
|
-
throw (0, errors_1.passthroughOrWrap)(error_1, {
|
|
500
|
-
code: "response-handler-error",
|
|
501
|
-
title: "responseHandler error",
|
|
502
|
-
});
|
|
503
|
-
case 5: return [2 /*return*/];
|
|
504
|
-
}
|
|
352
|
+
], (0, exports.asyncHandler)(async (req, res) => {
|
|
353
|
+
const { doc } = await (0, executors_1.executeCreate)({
|
|
354
|
+
body: req.body,
|
|
355
|
+
model,
|
|
356
|
+
options,
|
|
357
|
+
req,
|
|
358
|
+
user: req.user,
|
|
359
|
+
});
|
|
360
|
+
void (0, record_1.maybeRecordModelRouterAudit)({
|
|
361
|
+
after: doc,
|
|
362
|
+
audit: options.audit,
|
|
363
|
+
modelName: model.modelName,
|
|
364
|
+
operation: "create",
|
|
365
|
+
recordId: String(doc._id),
|
|
366
|
+
req,
|
|
367
|
+
verb: "created",
|
|
505
368
|
});
|
|
506
|
-
|
|
369
|
+
try {
|
|
370
|
+
const serialized = await responseHandler(doc, "create", req, options);
|
|
371
|
+
return res.status(201).json({ data: serialized });
|
|
372
|
+
}
|
|
373
|
+
catch (error) {
|
|
374
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
375
|
+
code: "response-handler-error",
|
|
376
|
+
title: "responseHandler error",
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
}));
|
|
507
380
|
router.get("/", [
|
|
508
381
|
(0, auth_1.authenticateMiddleware)(options.allowAnonymous),
|
|
509
382
|
(0, permissions_1.permissionMiddleware)(model, options),
|
|
510
383
|
(0, openApi_1.listOpenApiMiddleware)(model, options, routePath),
|
|
511
384
|
queryValidation,
|
|
512
|
-
], (0, exports.asyncHandler)(
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
385
|
+
], (0, exports.asyncHandler)(async (req, res) => {
|
|
386
|
+
let query = {};
|
|
387
|
+
for (const queryParam of Object.keys(options.defaultQueryParams ?? [])) {
|
|
388
|
+
query[queryParam] = options.defaultQueryParams?.[queryParam];
|
|
389
|
+
}
|
|
390
|
+
for (const queryParam of Object.keys(req.query)) {
|
|
391
|
+
if (PAGINATION_QUERY_PARAMS.includes(queryParam)) {
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
checkQueryParamAllowed(queryParam, req.query[queryParam], options.queryFields);
|
|
395
|
+
// Not sure if this is necessary or if mongoose does the right thing.
|
|
396
|
+
if (req.query[queryParam] === "true") {
|
|
397
|
+
query[queryParam] = true;
|
|
398
|
+
}
|
|
399
|
+
else if (req.query[queryParam] === "false") {
|
|
400
|
+
query[queryParam] = false;
|
|
401
|
+
}
|
|
402
|
+
else {
|
|
403
|
+
query[queryParam] = req.query[queryParam];
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
query = mergeDateRangeQueryParams(model, query);
|
|
407
|
+
// Special operators. NOTE: these request Mongo Atlas.
|
|
408
|
+
if (req.query.$search) {
|
|
409
|
+
mongoose_1.default.connection.db?.collection(model.collection.collectionName);
|
|
410
|
+
}
|
|
411
|
+
if (req.query.$autocomplete) {
|
|
412
|
+
mongoose_1.default.connection.db?.collection(model.collection.collectionName);
|
|
413
|
+
}
|
|
414
|
+
// Check if any of the keys in the query are not allowed by options.queryFilter
|
|
415
|
+
if (options.queryFilter) {
|
|
416
|
+
let queryFilter;
|
|
417
|
+
try {
|
|
418
|
+
queryFilter = await options.queryFilter(req.user, query);
|
|
419
|
+
}
|
|
420
|
+
catch (error) {
|
|
421
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
422
|
+
code: "query-filter-error",
|
|
423
|
+
status: 400,
|
|
424
|
+
title: "Query filter error",
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
// If the query filter returns null specifically, we know this is a query that shouldn't
|
|
428
|
+
// return any results.
|
|
429
|
+
if (queryFilter === null) {
|
|
430
|
+
return res.json({ data: [] });
|
|
431
|
+
}
|
|
432
|
+
query = { ...query, ...queryFilter };
|
|
433
|
+
for (const [key, value] of Object.entries(queryFilter)) {
|
|
434
|
+
if (value === undefined) {
|
|
435
|
+
delete query[key];
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
let limit = options.defaultLimit ?? 100;
|
|
440
|
+
if (Number(req.query.limit)) {
|
|
441
|
+
limit = Math.min(Number(req.query.limit), options.maxLimit ?? 500);
|
|
442
|
+
}
|
|
443
|
+
if (query.period) {
|
|
444
|
+
// need to remove 'period' since it isn't part of any schemas but parsed and applied in
|
|
445
|
+
// queryFilter instead
|
|
446
|
+
query.period = undefined;
|
|
447
|
+
}
|
|
448
|
+
let builtQuery = model.find(query).limit(limit + 1);
|
|
449
|
+
const total = await model.countDocuments(query);
|
|
450
|
+
if (req.query.page) {
|
|
451
|
+
if (Number(req.query.page) === 0 || Number.isNaN(Number(req.query.page))) {
|
|
452
|
+
throw new errors_1.BadRequestError({
|
|
453
|
+
code: "invalid-page",
|
|
454
|
+
detail: `Invalid page: ${req.query.page}`,
|
|
455
|
+
source: { parameter: "page" },
|
|
456
|
+
title: "Invalid page",
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
builtQuery = builtQuery.skip((Number(req.query.page) - 1) * limit);
|
|
460
|
+
}
|
|
461
|
+
// Query param sort takes precedence over options.sort.
|
|
462
|
+
if (req.query.sort) {
|
|
463
|
+
builtQuery = builtQuery.sort(req.query.sort);
|
|
464
|
+
}
|
|
465
|
+
else if (options.sort) {
|
|
466
|
+
builtQuery = builtQuery.sort(options.sort);
|
|
467
|
+
}
|
|
468
|
+
const populatedQuery = (0, exports.addPopulateToQuery)(builtQuery, options.populatePaths);
|
|
469
|
+
let data;
|
|
470
|
+
try {
|
|
471
|
+
data = (await populatedQuery.exec());
|
|
472
|
+
}
|
|
473
|
+
catch (error) {
|
|
474
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
475
|
+
code: "list-error",
|
|
476
|
+
title: "List error",
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
let serialized;
|
|
480
|
+
try {
|
|
481
|
+
serialized = await responseHandler(data, "list", req, options);
|
|
482
|
+
}
|
|
483
|
+
catch (error) {
|
|
484
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
485
|
+
code: "response-handler-error",
|
|
486
|
+
title: "responseHandler error",
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
let more;
|
|
490
|
+
try {
|
|
491
|
+
if (serialized && Array.isArray(serialized)) {
|
|
492
|
+
more = serialized.length === limit + 1 && serialized.length > 0;
|
|
493
|
+
if (more) {
|
|
494
|
+
// Slice off the extra document we fetched to determine if more is true or not.
|
|
495
|
+
serialized = serialized.slice(0, limit);
|
|
496
|
+
if (!req.query.page) {
|
|
497
|
+
const msg = `More than ${limit} results returned for ${model.collection.name} without pagination, data may be silently truncated. req.query: ${JSON.stringify(req.query)}`;
|
|
498
|
+
logger_1.logger.warn(msg);
|
|
554
499
|
try {
|
|
555
|
-
|
|
500
|
+
Sentry.captureMessage(msg);
|
|
556
501
|
}
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
query = mergeDateRangeQueryParams(model, query);
|
|
560
|
-
// Special operators. NOTE: these request Mongo Atlas.
|
|
561
|
-
if (req.query.$search) {
|
|
562
|
-
(_j = mongoose_1.default.connection.db) === null || _j === void 0 ? void 0 : _j.collection(model.collection.collectionName);
|
|
563
|
-
}
|
|
564
|
-
if (req.query.$autocomplete) {
|
|
565
|
-
(_k = mongoose_1.default.connection.db) === null || _k === void 0 ? void 0 : _k.collection(model.collection.collectionName);
|
|
566
|
-
}
|
|
567
|
-
if (!options.queryFilter) return [3 /*break*/, 5];
|
|
568
|
-
queryFilter = void 0;
|
|
569
|
-
_o.label = 1;
|
|
570
|
-
case 1:
|
|
571
|
-
_o.trys.push([1, 3, , 4]);
|
|
572
|
-
return [4 /*yield*/, options.queryFilter(req.user, query)];
|
|
573
|
-
case 2:
|
|
574
|
-
queryFilter = _o.sent();
|
|
575
|
-
return [3 /*break*/, 4];
|
|
576
|
-
case 3:
|
|
577
|
-
error_2 = _o.sent();
|
|
578
|
-
throw (0, errors_1.passthroughOrWrap)(error_2, {
|
|
579
|
-
code: "query-filter-error",
|
|
580
|
-
status: 400,
|
|
581
|
-
title: "Query filter error",
|
|
582
|
-
});
|
|
583
|
-
case 4:
|
|
584
|
-
// If the query filter returns null specifically, we know this is a query that shouldn't
|
|
585
|
-
// return any results.
|
|
586
|
-
if (queryFilter === null) {
|
|
587
|
-
return [2 /*return*/, res.json({ data: [] })];
|
|
588
|
-
}
|
|
589
|
-
query = __assign(__assign({}, query), queryFilter);
|
|
590
|
-
_o.label = 5;
|
|
591
|
-
case 5:
|
|
592
|
-
limit = (_l = options.defaultLimit) !== null && _l !== void 0 ? _l : 100;
|
|
593
|
-
if (Number(req.query.limit)) {
|
|
594
|
-
limit = Math.min(Number(req.query.limit), (_m = options.maxLimit) !== null && _m !== void 0 ? _m : 500);
|
|
595
|
-
}
|
|
596
|
-
if (query.period) {
|
|
597
|
-
// need to remove 'period' since it isn't part of any schemas but parsed and applied in
|
|
598
|
-
// queryFilter instead
|
|
599
|
-
query.period = undefined;
|
|
600
|
-
}
|
|
601
|
-
builtQuery = model.find(query).limit(limit + 1);
|
|
602
|
-
return [4 /*yield*/, model.countDocuments(query)];
|
|
603
|
-
case 6:
|
|
604
|
-
total = _o.sent();
|
|
605
|
-
if (req.query.page) {
|
|
606
|
-
if (Number(req.query.page) === 0 || Number.isNaN(Number(req.query.page))) {
|
|
607
|
-
throw new errors_1.BadRequestError({
|
|
608
|
-
code: "invalid-page",
|
|
609
|
-
detail: "Invalid page: ".concat(req.query.page),
|
|
610
|
-
source: { parameter: "page" },
|
|
611
|
-
title: "Invalid page",
|
|
612
|
-
});
|
|
502
|
+
catch (error) {
|
|
503
|
+
logger_1.logger.error(`Error capturing message: ${error}`);
|
|
613
504
|
}
|
|
614
|
-
builtQuery = builtQuery.skip((Number(req.query.page) - 1) * limit);
|
|
615
505
|
}
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
_o.label = 7;
|
|
625
|
-
case 7:
|
|
626
|
-
_o.trys.push([7, 9, , 10]);
|
|
627
|
-
return [4 /*yield*/, populatedQuery.exec()];
|
|
628
|
-
case 8:
|
|
629
|
-
data = (_o.sent());
|
|
630
|
-
return [3 /*break*/, 10];
|
|
631
|
-
case 9:
|
|
632
|
-
error_3 = _o.sent();
|
|
633
|
-
throw (0, errors_1.passthroughOrWrap)(error_3, {
|
|
634
|
-
code: "list-error",
|
|
635
|
-
title: "List error",
|
|
636
|
-
});
|
|
637
|
-
case 10:
|
|
638
|
-
_o.trys.push([10, 12, , 13]);
|
|
639
|
-
return [4 /*yield*/, responseHandler(data, "list", req, options)];
|
|
640
|
-
case 11:
|
|
641
|
-
serialized = _o.sent();
|
|
642
|
-
return [3 /*break*/, 13];
|
|
643
|
-
case 12:
|
|
644
|
-
error_4 = _o.sent();
|
|
645
|
-
throw (0, errors_1.passthroughOrWrap)(error_4, {
|
|
646
|
-
code: "response-handler-error",
|
|
647
|
-
title: "responseHandler error",
|
|
648
|
-
});
|
|
649
|
-
case 13:
|
|
650
|
-
try {
|
|
651
|
-
if (serialized && Array.isArray(serialized)) {
|
|
652
|
-
more = serialized.length === limit + 1 && serialized.length > 0;
|
|
653
|
-
if (more) {
|
|
654
|
-
// Slice off the extra document we fetched to determine if more is true or not.
|
|
655
|
-
serialized = serialized.slice(0, limit);
|
|
656
|
-
if (!req.query.page) {
|
|
657
|
-
msg = "More than ".concat(limit, " results returned for ").concat(model.collection.name, " without pagination, data may be silently truncated. req.query: ").concat(JSON.stringify(req.query));
|
|
658
|
-
logger_1.logger.warn(msg);
|
|
659
|
-
try {
|
|
660
|
-
Sentry.captureMessage(msg);
|
|
661
|
-
}
|
|
662
|
-
catch (error) {
|
|
663
|
-
logger_1.logger.error("Error capturing message: ".concat(error));
|
|
664
|
-
}
|
|
665
|
-
}
|
|
666
|
-
}
|
|
667
|
-
return [2 /*return*/, res.json({
|
|
668
|
-
data: serialized,
|
|
669
|
-
limit: limit,
|
|
670
|
-
more: more,
|
|
671
|
-
page: req.query.page,
|
|
672
|
-
total: total,
|
|
673
|
-
})];
|
|
674
|
-
}
|
|
675
|
-
return [2 /*return*/, res.json({ data: serialized })];
|
|
676
|
-
}
|
|
677
|
-
catch (error) {
|
|
678
|
-
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
679
|
-
code: "serialization-error",
|
|
680
|
-
title: "Serialization error",
|
|
681
|
-
});
|
|
682
|
-
}
|
|
683
|
-
return [2 /*return*/];
|
|
506
|
+
}
|
|
507
|
+
return res.json({
|
|
508
|
+
data: serialized,
|
|
509
|
+
limit,
|
|
510
|
+
more,
|
|
511
|
+
page: req.query.page,
|
|
512
|
+
total,
|
|
513
|
+
});
|
|
684
514
|
}
|
|
685
|
-
|
|
686
|
-
|
|
515
|
+
return res.json({ data: serialized });
|
|
516
|
+
}
|
|
517
|
+
catch (error) {
|
|
518
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
519
|
+
code: "serialization-error",
|
|
520
|
+
title: "Serialization error",
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
}));
|
|
687
524
|
router.get("/:id", [
|
|
688
525
|
(0, auth_1.authenticateMiddleware)(options.allowAnonymous),
|
|
689
526
|
(0, openApi_1.getOpenApiMiddleware)(model, options),
|
|
690
527
|
(0, permissions_1.permissionMiddleware)(model, options),
|
|
691
|
-
], (0, exports.asyncHandler)(
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
case 2:
|
|
702
|
-
serialized = _a.sent();
|
|
703
|
-
return [2 /*return*/, res.json({ data: serialized })];
|
|
704
|
-
case 3:
|
|
705
|
-
error_5 = _a.sent();
|
|
706
|
-
throw (0, errors_1.passthroughOrWrap)(error_5, {
|
|
707
|
-
code: "response-handler-error",
|
|
708
|
-
title: "responseHandler error",
|
|
709
|
-
});
|
|
710
|
-
case 4: return [2 /*return*/];
|
|
711
|
-
}
|
|
712
|
-
});
|
|
713
|
-
}); }));
|
|
714
|
-
router.put("/:id", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(function (_req, _res) { return __awaiter(void 0, void 0, void 0, function () {
|
|
715
|
-
return __generator(this, function (_a) {
|
|
716
|
-
// Patch is what we want 90% of the time
|
|
717
|
-
throw new errors_1.APIError({
|
|
718
|
-
code: "put-not-supported",
|
|
719
|
-
detail: "Use PATCH to update a document.",
|
|
720
|
-
title: "PUT is not supported.",
|
|
528
|
+
], (0, exports.asyncHandler)(async (req, res) => {
|
|
529
|
+
const data = req.obj;
|
|
530
|
+
try {
|
|
531
|
+
const serialized = await responseHandler(data, "read", req, options);
|
|
532
|
+
return res.json({ data: serialized });
|
|
533
|
+
}
|
|
534
|
+
catch (error) {
|
|
535
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
536
|
+
code: "response-handler-error",
|
|
537
|
+
title: "responseHandler error",
|
|
721
538
|
});
|
|
539
|
+
}
|
|
540
|
+
}));
|
|
541
|
+
router.put("/:id", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(async (_req, _res) => {
|
|
542
|
+
// Patch is what we want 90% of the time
|
|
543
|
+
throw new errors_1.APIError({
|
|
544
|
+
code: "put-not-supported",
|
|
545
|
+
detail: "Use PATCH to update a document.",
|
|
546
|
+
title: "PUT is not supported.",
|
|
722
547
|
});
|
|
723
|
-
})
|
|
548
|
+
}));
|
|
724
549
|
router.patch("/:id", [
|
|
725
550
|
(0, auth_1.authenticateMiddleware)(options.allowAnonymous),
|
|
726
551
|
(0, openApi_1.patchOpenApiMiddleware)(model, options),
|
|
727
552
|
(0, permissions_1.permissionMiddleware)(model, options),
|
|
728
553
|
updateValidation,
|
|
729
|
-
], (0, exports.asyncHandler)(
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
return [2 /*return*/, res.status(409).json({
|
|
788
|
-
data: serialized,
|
|
789
|
-
error: "Conflict",
|
|
790
|
-
message: "Document was modified since your last read",
|
|
791
|
-
})];
|
|
792
|
-
case 5: throw error_6;
|
|
793
|
-
case 6:
|
|
794
|
-
_a.trys.push([6, 8, , 9]);
|
|
795
|
-
return [4 /*yield*/, responseHandler(doc, "update", req, options)];
|
|
796
|
-
case 7:
|
|
797
|
-
serialized = _a.sent();
|
|
798
|
-
return [2 /*return*/, res.json({ data: serialized })];
|
|
799
|
-
case 8:
|
|
800
|
-
error_7 = _a.sent();
|
|
801
|
-
throw (0, errors_1.passthroughOrWrap)(error_7, {
|
|
802
|
-
code: "response-handler-error",
|
|
803
|
-
title: "responseHandler error",
|
|
804
|
-
});
|
|
805
|
-
case 9: return [2 /*return*/];
|
|
554
|
+
], (0, exports.asyncHandler)(async (req, res) => {
|
|
555
|
+
const existingDoc = req
|
|
556
|
+
.obj;
|
|
557
|
+
// Read `_updatedAt` before the executor strips it from the body; the executor's
|
|
558
|
+
// conflict detection still runs after preUpdate, matching the previous inline order.
|
|
559
|
+
const bodyUpdatedAt = req.body._updatedAt;
|
|
560
|
+
const preciseUnmodifiedSince = req.headers["x-unmodified-since-iso"];
|
|
561
|
+
const httpUnmodifiedSince = req.headers["if-unmodified-since"];
|
|
562
|
+
const timestampValue = Array.isArray(preciseUnmodifiedSince)
|
|
563
|
+
? preciseUnmodifiedSince[0]
|
|
564
|
+
: preciseUnmodifiedSince;
|
|
565
|
+
const httpTimestampValue = Array.isArray(httpUnmodifiedSince)
|
|
566
|
+
? httpUnmodifiedSince[0]
|
|
567
|
+
: httpUnmodifiedSince;
|
|
568
|
+
let concurrencyCheck;
|
|
569
|
+
if (timestampValue || httpTimestampValue || bodyUpdatedAt) {
|
|
570
|
+
const usingPreciseHeader = Boolean(timestampValue);
|
|
571
|
+
const usingHttpHeader = !usingPreciseHeader && Boolean(httpTimestampValue);
|
|
572
|
+
const clientTimestamp = timestampValue
|
|
573
|
+
? luxon_1.DateTime.fromISO(timestampValue)
|
|
574
|
+
: httpTimestampValue
|
|
575
|
+
? luxon_1.DateTime.fromHTTP(httpTimestampValue)
|
|
576
|
+
: luxon_1.DateTime.fromISO(bodyUpdatedAt);
|
|
577
|
+
concurrencyCheck = {
|
|
578
|
+
// An unparseable value round-trips as an invalid Date; the executor turns it into
|
|
579
|
+
// the 400 "Invalid conflict-detection timestamp" error after preUpdate has run.
|
|
580
|
+
ifUnmodifiedSince: clientTimestamp.toJSDate(),
|
|
581
|
+
invalidTimestampDetail: usingPreciseHeader
|
|
582
|
+
? "X-Unmodified-Since-ISO header could not be parsed as an ISO date"
|
|
583
|
+
: usingHttpHeader
|
|
584
|
+
? "If-Unmodified-Since header could not be parsed as an HTTP date"
|
|
585
|
+
: "_updatedAt body field could not be parsed as an ISO date",
|
|
586
|
+
type: "timestamp",
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
let doc;
|
|
590
|
+
const previous = (0, record_1.snapshotAuditBefore)({ audit: options.audit, doc: existingDoc });
|
|
591
|
+
try {
|
|
592
|
+
({ doc } = await (0, executors_1.executeUpdate)({
|
|
593
|
+
body: req.body,
|
|
594
|
+
concurrencyCheck,
|
|
595
|
+
existingDoc,
|
|
596
|
+
id: req.params.id,
|
|
597
|
+
model,
|
|
598
|
+
options,
|
|
599
|
+
req,
|
|
600
|
+
user: req.user,
|
|
601
|
+
}));
|
|
602
|
+
}
|
|
603
|
+
catch (error) {
|
|
604
|
+
// Duck-typed: `instanceof` breaks for Error subclasses in the compiled ES5 dist.
|
|
605
|
+
if ((0, executors_1.isExecutorConflictError)(error)) {
|
|
606
|
+
const serialized = await responseHandler(error.doc, "update", req, options);
|
|
607
|
+
return res.status(409).json({
|
|
608
|
+
data: serialized,
|
|
609
|
+
error: "Conflict",
|
|
610
|
+
message: "Document was modified since your last read",
|
|
611
|
+
});
|
|
806
612
|
}
|
|
613
|
+
throw error;
|
|
614
|
+
}
|
|
615
|
+
void (0, record_1.maybeRecordModelRouterAudit)({
|
|
616
|
+
after: doc,
|
|
617
|
+
audit: options.audit,
|
|
618
|
+
before: previous,
|
|
619
|
+
modelName: model.modelName,
|
|
620
|
+
operation: "update",
|
|
621
|
+
recordId: String(doc._id),
|
|
622
|
+
req,
|
|
623
|
+
verb: "updated",
|
|
807
624
|
});
|
|
808
|
-
|
|
625
|
+
try {
|
|
626
|
+
const serialized = await responseHandler(doc, "update", req, options);
|
|
627
|
+
return res.json({ data: serialized });
|
|
628
|
+
}
|
|
629
|
+
catch (error) {
|
|
630
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
631
|
+
code: "response-handler-error",
|
|
632
|
+
title: "responseHandler error",
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
}));
|
|
809
636
|
router.delete("/:id", [
|
|
810
637
|
(0, auth_1.authenticateMiddleware)(options.allowAnonymous),
|
|
811
638
|
(0, openApi_1.deleteOpenApiMiddleware)(model, options),
|
|
812
639
|
(0, permissions_1.permissionMiddleware)(model, options),
|
|
813
|
-
], (0, exports.asyncHandler)(
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
options: options,
|
|
824
|
-
req: req,
|
|
825
|
-
user: req.user,
|
|
826
|
-
})];
|
|
827
|
-
case 1:
|
|
828
|
-
_a.sent();
|
|
829
|
-
return [2 /*return*/, res.status(204).json({})];
|
|
830
|
-
}
|
|
640
|
+
], (0, exports.asyncHandler)(async (req, res) => {
|
|
641
|
+
const existingDoc = req.obj;
|
|
642
|
+
const previous = (0, record_1.snapshotAuditBefore)({ audit: options.audit, doc: existingDoc });
|
|
643
|
+
await (0, executors_1.executeDelete)({
|
|
644
|
+
existingDoc,
|
|
645
|
+
id: req.params.id,
|
|
646
|
+
model,
|
|
647
|
+
options,
|
|
648
|
+
req,
|
|
649
|
+
user: req.user,
|
|
831
650
|
});
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
case 1:
|
|
841
|
-
// TODO Combine array operations and .patch(), as they are very similar.
|
|
842
|
-
if (!(_d.sent())) {
|
|
843
|
-
throw new errors_1.APIError({
|
|
844
|
-
code: "array-update-not-allowed",
|
|
845
|
-
detail: "Access to PATCH on ".concat(model.modelName, " denied for ").concat((_b = req.user) === null || _b === void 0 ? void 0 : _b.id),
|
|
846
|
-
meta: { method: "PATCH", model: model.modelName },
|
|
847
|
-
status: 405,
|
|
848
|
-
title: "Access denied",
|
|
849
|
-
});
|
|
850
|
-
}
|
|
851
|
-
return [4 /*yield*/, model.findById(req.params.id)];
|
|
852
|
-
case 2:
|
|
853
|
-
doc = _d.sent();
|
|
854
|
-
prevDoc = (0, cloneDeep_1.default)(doc);
|
|
855
|
-
if (!doc) {
|
|
856
|
-
throw new errors_1.NotFoundError({
|
|
857
|
-
code: "document-not-found",
|
|
858
|
-
detail: "Could not find document to PATCH: ".concat(req.params.id),
|
|
859
|
-
meta: { model: model.modelName },
|
|
860
|
-
title: "Document not found",
|
|
861
|
-
});
|
|
862
|
-
}
|
|
863
|
-
return [4 /*yield*/, (0, permissions_1.checkPermissions)("update", options.permissions.update, req.user, doc)];
|
|
864
|
-
case 3:
|
|
865
|
-
if (!(_d.sent())) {
|
|
866
|
-
throw new errors_1.ForbiddenError({
|
|
867
|
-
code: "update-not-allowed",
|
|
868
|
-
detail: "Patch not allowed for user ".concat((_c = req.user) === null || _c === void 0 ? void 0 : _c.id, " on doc ").concat(doc._id),
|
|
869
|
-
meta: { model: model.modelName },
|
|
870
|
-
title: "Update not allowed",
|
|
871
|
-
});
|
|
872
|
-
}
|
|
873
|
-
field = req.params.field;
|
|
874
|
-
itemId = req.params.itemId;
|
|
875
|
-
// We apply the operation *before* the hooks. As far as the callers are concerned, this should
|
|
876
|
-
// be like PATCHing the field and replacing the whole thing.
|
|
877
|
-
if (operation !== "DELETE" && req.body[field] === undefined) {
|
|
878
|
-
throw new errors_1.BadRequestError({
|
|
879
|
-
code: "malformed-array-operation-body",
|
|
880
|
-
detail: "Malformed body, array operations should have a single, top level key, got: ".concat(Object.keys(req.body).join(",")),
|
|
881
|
-
meta: { field: field },
|
|
882
|
-
title: "Malformed array operation body",
|
|
883
|
-
});
|
|
884
|
-
}
|
|
885
|
-
array = __spreadArray([], __read(doc[field]), false);
|
|
886
|
-
if (operation === "POST") {
|
|
887
|
-
array.push(req.body[field]);
|
|
888
|
-
}
|
|
889
|
-
else if (operation === "PATCH" || operation === "DELETE") {
|
|
890
|
-
index = void 0;
|
|
891
|
-
if ((0, utils_1.isValidObjectId)(itemId)) {
|
|
892
|
-
index = array.findIndex(function (x) { return (x === null || x === void 0 ? void 0 : x.id) === itemId; });
|
|
893
|
-
}
|
|
894
|
-
else {
|
|
895
|
-
index = array.indexOf(itemId);
|
|
896
|
-
}
|
|
897
|
-
if (index === -1) {
|
|
898
|
-
throw new errors_1.NotFoundError({
|
|
899
|
-
code: "array-item-not-found",
|
|
900
|
-
detail: "Could not find ".concat(field, "/").concat(itemId),
|
|
901
|
-
meta: { field: field, itemId: itemId },
|
|
902
|
-
title: "Array item not found",
|
|
903
|
-
});
|
|
904
|
-
}
|
|
905
|
-
// For PATCHing an item by ID, we need to merge the objects so we don't override the _id or
|
|
906
|
-
// other parts of the subdocument.
|
|
907
|
-
if (operation === "PATCH" && (0, utils_1.isValidObjectId)(itemId)) {
|
|
908
|
-
Object.assign(array[index], req.body[field]);
|
|
909
|
-
}
|
|
910
|
-
else if (operation === "PATCH") {
|
|
911
|
-
// For PATCHing a string array, we can replace the whole object.
|
|
912
|
-
array[index] = req.body[field];
|
|
913
|
-
}
|
|
914
|
-
else {
|
|
915
|
-
array.splice(index, 1);
|
|
916
|
-
}
|
|
917
|
-
}
|
|
918
|
-
else {
|
|
919
|
-
throw new errors_1.BadRequestError({
|
|
920
|
-
code: "invalid-array-operation",
|
|
921
|
-
detail: "Invalid array operation: ".concat(operation),
|
|
922
|
-
meta: { operation: operation },
|
|
923
|
-
title: "Invalid array operation",
|
|
924
|
-
});
|
|
925
|
-
}
|
|
926
|
-
body = (_a = {}, _a[field] = array, _a);
|
|
927
|
-
try {
|
|
928
|
-
body = (0, transformers_1.transform)(options, body, "update", req.user);
|
|
929
|
-
}
|
|
930
|
-
catch (error) {
|
|
931
|
-
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
932
|
-
code: "transform-error",
|
|
933
|
-
status: 403,
|
|
934
|
-
title: "Transform error",
|
|
935
|
-
});
|
|
936
|
-
}
|
|
937
|
-
if (!options.preUpdate) return [3 /*break*/, 8];
|
|
938
|
-
_d.label = 4;
|
|
939
|
-
case 4:
|
|
940
|
-
_d.trys.push([4, 6, , 7]);
|
|
941
|
-
return [4 /*yield*/, options.preUpdate(body, req)];
|
|
942
|
-
case 5:
|
|
943
|
-
body = _d.sent();
|
|
944
|
-
return [3 /*break*/, 7];
|
|
945
|
-
case 6:
|
|
946
|
-
error_8 = _d.sent();
|
|
947
|
-
throw (0, errors_1.passthroughOrWrap)(error_8, {
|
|
948
|
-
code: "pre-update-hook-error",
|
|
949
|
-
detail: "preUpdate hook error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_8)),
|
|
950
|
-
status: 400,
|
|
951
|
-
title: "preUpdate hook error",
|
|
952
|
-
});
|
|
953
|
-
case 7:
|
|
954
|
-
if (body === undefined) {
|
|
955
|
-
throw new errors_1.ForbiddenError({
|
|
956
|
-
code: "update-not-allowed",
|
|
957
|
-
detail: "A body must be returned from preUpdate",
|
|
958
|
-
title: "Update not allowed",
|
|
959
|
-
});
|
|
960
|
-
}
|
|
961
|
-
if (body === null) {
|
|
962
|
-
throw new errors_1.ForbiddenError({
|
|
963
|
-
code: "update-not-allowed",
|
|
964
|
-
detail: "preUpdate hook on ".concat(req.params.id, " returned null"),
|
|
965
|
-
title: "Update not allowed",
|
|
966
|
-
});
|
|
967
|
-
}
|
|
968
|
-
_d.label = 8;
|
|
969
|
-
case 8:
|
|
970
|
-
body = (0, auth_1.omitUserRolesFromWriteBody)(model.modelName, options.accessControl, body, req.terrenoAllowUserAdminWrite === true);
|
|
971
|
-
if (!(options.access && options.accessControl && body && typeof body === "object")) return [3 /*break*/, 10];
|
|
972
|
-
return [4 /*yield*/, (0, modelRouterAccess_1.validateAccessWriteBody)({
|
|
973
|
-
access: options.access,
|
|
974
|
-
accessControl: options.accessControl,
|
|
975
|
-
body: body,
|
|
976
|
-
doc: doc,
|
|
977
|
-
phase: "write",
|
|
978
|
-
user: req.user,
|
|
979
|
-
})];
|
|
980
|
-
case 9:
|
|
981
|
-
_d.sent();
|
|
982
|
-
_d.label = 10;
|
|
983
|
-
case 10:
|
|
984
|
-
_d.trys.push([10, 12, , 13]);
|
|
985
|
-
Object.assign(doc, body);
|
|
986
|
-
return [4 /*yield*/, doc.save()];
|
|
987
|
-
case 11:
|
|
988
|
-
_d.sent();
|
|
989
|
-
return [3 /*break*/, 13];
|
|
990
|
-
case 12:
|
|
991
|
-
error_9 = _d.sent();
|
|
992
|
-
throw (0, errors_1.passthroughOrWrapWrite)(error_9, {
|
|
993
|
-
code: "update-save-error",
|
|
994
|
-
detail: "PATCH Pre Update error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_9)),
|
|
995
|
-
status: 400,
|
|
996
|
-
title: "PATCH Pre Update error",
|
|
997
|
-
});
|
|
998
|
-
case 13:
|
|
999
|
-
if (!options.postUpdate) return [3 /*break*/, 17];
|
|
1000
|
-
_d.label = 14;
|
|
1001
|
-
case 14:
|
|
1002
|
-
_d.trys.push([14, 16, , 17]);
|
|
1003
|
-
return [4 /*yield*/, options.postUpdate(doc, body, req, prevDoc)];
|
|
1004
|
-
case 15:
|
|
1005
|
-
_d.sent();
|
|
1006
|
-
return [3 /*break*/, 17];
|
|
1007
|
-
case 16:
|
|
1008
|
-
error_10 = _d.sent();
|
|
1009
|
-
throw (0, errors_1.passthroughOrWrap)(error_10, {
|
|
1010
|
-
code: "post-update-hook-error",
|
|
1011
|
-
detail: "PATCH Post Update error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_10)),
|
|
1012
|
-
status: 400,
|
|
1013
|
-
title: "PATCH Post Update error",
|
|
1014
|
-
});
|
|
1015
|
-
case 17: return [2 /*return*/, res.json({
|
|
1016
|
-
data: (0, transformers_1.serialize)(req, options, doc),
|
|
1017
|
-
})];
|
|
1018
|
-
}
|
|
1019
|
-
});
|
|
1020
|
-
}); };
|
|
1021
|
-
var arrayPost = function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
|
|
1022
|
-
return __generator(this, function (_a) {
|
|
1023
|
-
return [2 /*return*/, arrayOperation(req, res, "POST")];
|
|
651
|
+
void (0, record_1.maybeRecordModelRouterAudit)({
|
|
652
|
+
audit: options.audit,
|
|
653
|
+
before: previous,
|
|
654
|
+
modelName: model.modelName,
|
|
655
|
+
operation: "delete",
|
|
656
|
+
recordId: String(existingDoc._id),
|
|
657
|
+
req,
|
|
658
|
+
verb: "deleted",
|
|
1024
659
|
});
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
660
|
+
return res.status(204).json({});
|
|
661
|
+
}));
|
|
662
|
+
const arrayOperation = async (req, res, operation) => {
|
|
663
|
+
// TODO Combine array operations and .patch(), as they are very similar.
|
|
664
|
+
if (!(await (0, permissions_1.checkPermissions)("update", options.permissions.update, req.user))) {
|
|
665
|
+
throw new errors_1.APIError({
|
|
666
|
+
code: "array-update-not-allowed",
|
|
667
|
+
detail: `Access to PATCH on ${model.modelName} denied for ${req.user?.id}`,
|
|
668
|
+
meta: { method: "PATCH", model: model.modelName },
|
|
669
|
+
status: 405,
|
|
670
|
+
title: "Access denied",
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
const doc = await model.findById(req.params.id);
|
|
674
|
+
// Make a copy for passing pre-saved values to hooks.
|
|
675
|
+
const prevDoc = (0, cloneDeep_1.default)(doc);
|
|
676
|
+
if (!doc) {
|
|
677
|
+
throw new errors_1.NotFoundError({
|
|
678
|
+
code: "document-not-found",
|
|
679
|
+
detail: `Could not find document to PATCH: ${req.params.id}`,
|
|
680
|
+
meta: { model: model.modelName },
|
|
681
|
+
title: "Document not found",
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
if (!(await (0, permissions_1.checkPermissions)("update", options.permissions.update, req.user, doc))) {
|
|
685
|
+
throw new errors_1.ForbiddenError({
|
|
686
|
+
code: "update-not-allowed",
|
|
687
|
+
detail: `Patch not allowed for user ${req.user?.id} on doc ${doc._id}`,
|
|
688
|
+
meta: { model: model.modelName },
|
|
689
|
+
title: "Update not allowed",
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
const field = req.params.field;
|
|
693
|
+
const itemId = req.params.itemId;
|
|
694
|
+
// We apply the operation *before* the hooks. As far as the callers are concerned, this should
|
|
695
|
+
// be like PATCHing the field and replacing the whole thing.
|
|
696
|
+
if (operation !== "DELETE" && req.body[field] === undefined) {
|
|
697
|
+
throw new errors_1.BadRequestError({
|
|
698
|
+
code: "malformed-array-operation-body",
|
|
699
|
+
detail: `Malformed body, array operations should have a single, top level key, got: ${Object.keys(req.body).join(",")}`,
|
|
700
|
+
meta: { field },
|
|
701
|
+
title: "Malformed array operation body",
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
const array = [...doc[field]];
|
|
705
|
+
if (operation === "POST") {
|
|
706
|
+
array.push(req.body[field]);
|
|
707
|
+
}
|
|
708
|
+
else if (operation === "PATCH" || operation === "DELETE") {
|
|
709
|
+
// Check for subschema vs String array:
|
|
710
|
+
let index;
|
|
711
|
+
if ((0, utils_1.isValidObjectId)(itemId)) {
|
|
712
|
+
index = array.findIndex((x) => x?.id === itemId);
|
|
713
|
+
}
|
|
714
|
+
else {
|
|
715
|
+
index = array.indexOf(itemId);
|
|
716
|
+
}
|
|
717
|
+
if (index === -1) {
|
|
718
|
+
throw new errors_1.NotFoundError({
|
|
719
|
+
code: "array-item-not-found",
|
|
720
|
+
detail: `Could not find ${field}/${itemId}`,
|
|
721
|
+
meta: { field, itemId },
|
|
722
|
+
title: "Array item not found",
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
// For PATCHing an item by ID, we need to merge the objects so we don't override the _id or
|
|
726
|
+
// other parts of the subdocument.
|
|
727
|
+
if (operation === "PATCH" && (0, utils_1.isValidObjectId)(itemId)) {
|
|
728
|
+
Object.assign(array[index], req.body[field]);
|
|
729
|
+
}
|
|
730
|
+
else if (operation === "PATCH") {
|
|
731
|
+
// For PATCHing a string array, we can replace the whole object.
|
|
732
|
+
array[index] = req.body[field];
|
|
733
|
+
}
|
|
734
|
+
else {
|
|
735
|
+
array.splice(index, 1);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
else {
|
|
739
|
+
throw new errors_1.BadRequestError({
|
|
740
|
+
code: "invalid-array-operation",
|
|
741
|
+
detail: `Invalid array operation: ${operation}`,
|
|
742
|
+
meta: { operation },
|
|
743
|
+
title: "Invalid array operation",
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
let body = { [field]: array };
|
|
747
|
+
try {
|
|
748
|
+
body = (0, transformers_1.transform)(options, body, "update", req.user);
|
|
749
|
+
}
|
|
750
|
+
catch (error) {
|
|
751
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
752
|
+
code: "transform-error",
|
|
753
|
+
status: 403,
|
|
754
|
+
title: "Transform error",
|
|
755
|
+
});
|
|
756
|
+
}
|
|
757
|
+
if (options.preUpdate) {
|
|
758
|
+
try {
|
|
759
|
+
body = await options.preUpdate(body, req);
|
|
760
|
+
}
|
|
761
|
+
catch (error) {
|
|
762
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
763
|
+
code: "pre-update-hook-error",
|
|
764
|
+
detail: `preUpdate hook error on ${req.params.id}: ${(0, errors_1.errorDetail)(error)}`,
|
|
765
|
+
status: 400,
|
|
766
|
+
title: "preUpdate hook error",
|
|
767
|
+
});
|
|
768
|
+
}
|
|
769
|
+
if (body === undefined) {
|
|
770
|
+
throw new errors_1.ForbiddenError({
|
|
771
|
+
code: "update-not-allowed",
|
|
772
|
+
detail: "A body must be returned from preUpdate",
|
|
773
|
+
title: "Update not allowed",
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
if (body === null) {
|
|
777
|
+
throw new errors_1.ForbiddenError({
|
|
778
|
+
code: "update-not-allowed",
|
|
779
|
+
detail: `preUpdate hook on ${req.params.id} returned null`,
|
|
780
|
+
title: "Update not allowed",
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
body = (0, auth_1.omitUserRolesFromWriteBody)(model.modelName, options.accessControl, body, req.terrenoAllowUserAdminWrite === true);
|
|
785
|
+
if (options.access && options.accessControl && body && typeof body === "object") {
|
|
786
|
+
await (0, modelRouterAccess_1.validateAccessWriteBody)({
|
|
787
|
+
access: options.access,
|
|
788
|
+
accessControl: options.accessControl,
|
|
789
|
+
body: body,
|
|
790
|
+
doc,
|
|
791
|
+
phase: "write",
|
|
792
|
+
user: req.user,
|
|
793
|
+
});
|
|
794
|
+
}
|
|
795
|
+
// Using .save here runs the risk of a versioning error if you try to make two simultaneous
|
|
796
|
+
// updates. We won't wind up with corrupted data, just an API error.
|
|
797
|
+
try {
|
|
798
|
+
Object.assign(doc, body);
|
|
799
|
+
await doc.save();
|
|
800
|
+
}
|
|
801
|
+
catch (error) {
|
|
802
|
+
throw (0, errors_1.passthroughOrWrapWrite)(error, {
|
|
803
|
+
code: "update-save-error",
|
|
804
|
+
detail: `PATCH Pre Update error on ${req.params.id}: ${(0, errors_1.errorDetail)(error)}`,
|
|
805
|
+
status: 400,
|
|
806
|
+
title: "PATCH Pre Update error",
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
if (options.postUpdate) {
|
|
810
|
+
try {
|
|
811
|
+
await options.postUpdate(doc, body, req, prevDoc);
|
|
812
|
+
}
|
|
813
|
+
catch (error) {
|
|
814
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
815
|
+
code: "post-update-hook-error",
|
|
816
|
+
detail: `PATCH Post Update error on ${req.params.id}: ${(0, errors_1.errorDetail)(error)}`,
|
|
817
|
+
status: 400,
|
|
818
|
+
title: "PATCH Post Update error",
|
|
819
|
+
});
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
const arrayAuditOperation = operation === "POST" ? "arrayPush" : operation === "PATCH" ? "arrayUpdate" : "arrayRemove";
|
|
823
|
+
void (0, record_1.maybeRecordModelRouterAudit)({
|
|
824
|
+
after: doc,
|
|
825
|
+
audit: options.audit,
|
|
826
|
+
before: prevDoc,
|
|
827
|
+
modelName: model.modelName,
|
|
828
|
+
operation: arrayAuditOperation,
|
|
829
|
+
recordId: String(doc._id),
|
|
830
|
+
req,
|
|
831
|
+
verb: "updated",
|
|
1029
832
|
});
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
return __generator(this, function (_a) {
|
|
1033
|
-
return [2 /*return*/, arrayOperation(req, res, "DELETE")];
|
|
833
|
+
return res.json({
|
|
834
|
+
data: (0, transformers_1.serialize)(req, options, doc),
|
|
1034
835
|
});
|
|
1035
|
-
}
|
|
836
|
+
};
|
|
837
|
+
const arrayPost = async (req, res) => {
|
|
838
|
+
return arrayOperation(req, res, "POST");
|
|
839
|
+
};
|
|
840
|
+
const arrayPatch = async (req, res) => {
|
|
841
|
+
return arrayOperation(req, res, "PATCH");
|
|
842
|
+
};
|
|
843
|
+
const arrayDelete = async (req, res) => {
|
|
844
|
+
return arrayOperation(req, res, "DELETE");
|
|
845
|
+
};
|
|
1036
846
|
// Set up routes for managing array fields. Check if there any array fields to add this for.
|
|
1037
|
-
if (Object.values(model.schema.paths).find(
|
|
847
|
+
if (Object.values(model.schema.paths).find((config) => config.instance === "Array")) {
|
|
1038
848
|
router.post("/:id/:field", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(arrayPost));
|
|
1039
849
|
router.patch("/:id/:field/:itemId", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(arrayPatch));
|
|
1040
850
|
router.delete("/:id/:field/:itemId", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(arrayDelete));
|
|
@@ -1042,20 +852,19 @@ var _buildModelRouter = function (model, options, routePath) {
|
|
|
1042
852
|
router.use(errors_1.apiErrorMiddleware);
|
|
1043
853
|
return router;
|
|
1044
854
|
};
|
|
1045
|
-
|
|
1046
|
-
var _a, _b;
|
|
855
|
+
const asyncHandler = (fn, options) => {
|
|
1047
856
|
// If no validation options, return simple handler
|
|
1048
|
-
if (!
|
|
1049
|
-
return
|
|
857
|
+
if (!options?.bodySchema && !options?.querySchema) {
|
|
858
|
+
return (req, res, next) => {
|
|
1050
859
|
return Promise.resolve(fn(req, res, next)).catch(next);
|
|
1051
860
|
};
|
|
1052
861
|
}
|
|
1053
862
|
// Import validation functions dynamically to avoid circular deps at module load
|
|
1054
|
-
|
|
863
|
+
const { validateRequestBody, validateQueryParams, getOpenApiValidatorConfig, } = require("./openApiValidator");
|
|
1055
864
|
// Build validation middleware
|
|
1056
|
-
|
|
865
|
+
const validators = [];
|
|
1057
866
|
// Determine if validation should be enabled
|
|
1058
|
-
|
|
867
|
+
const shouldValidate = options.validate ?? getOpenApiValidatorConfig().validateRequests ?? false;
|
|
1059
868
|
if (shouldValidate) {
|
|
1060
869
|
if (options.bodySchema) {
|
|
1061
870
|
validators.push(validateRequestBody(options.bodySchema, { enabled: true }));
|
|
@@ -1064,16 +873,16 @@ var asyncHandler = function (fn, options) {
|
|
|
1064
873
|
validators.push(validateQueryParams(options.querySchema, { enabled: true }));
|
|
1065
874
|
}
|
|
1066
875
|
}
|
|
1067
|
-
return
|
|
876
|
+
return (req, res, next) => {
|
|
1068
877
|
// Run validators sequentially, then the handler
|
|
1069
|
-
|
|
878
|
+
const runValidators = (index) => {
|
|
1070
879
|
if (index >= validators.length) {
|
|
1071
880
|
// All validators passed, run the actual handler
|
|
1072
881
|
Promise.resolve(fn(req, res, next)).catch(next);
|
|
1073
882
|
return;
|
|
1074
883
|
}
|
|
1075
884
|
try {
|
|
1076
|
-
validators[index](req, res, (
|
|
885
|
+
validators[index](req, res, ((err) => {
|
|
1077
886
|
if (err) {
|
|
1078
887
|
next(err);
|
|
1079
888
|
return;
|