@terreno/api 0.31.0 → 56.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +122 -2
- package/LICENSE +202 -21
- package/dist/api.d.ts +12 -3
- package/dist/api.js +110 -361
- package/dist/auth.d.ts +26 -0
- package/dist/auth.js +100 -1
- package/dist/betterAuth.d.ts +5 -0
- package/dist/betterAuthSetup.d.ts +1 -15
- package/dist/betterAuthSetup.js +29 -8
- package/dist/configurationPlugin.js +2 -2
- package/dist/docLoader.js +12 -9
- package/dist/errors.d.ts +13 -0
- package/dist/errors.js +29 -1
- package/dist/expressServer.js +5 -11
- package/dist/githubAuth.js +4 -1
- package/dist/index.d.ts +17 -1
- package/dist/index.js +29 -1
- package/dist/middleware.d.ts +7 -0
- package/dist/middleware.js +16 -1
- package/dist/openApiCompat.d.ts +10 -1
- package/dist/openApiCompat.js +115 -47
- package/dist/permissions.d.ts +27 -0
- package/dist/permissions.js +42 -1
- package/dist/plugins.d.ts +15 -3
- package/dist/plugins.js +36 -6
- package/dist/realtime/changeStreamWatcher.d.ts +100 -3
- package/dist/realtime/changeStreamWatcher.js +542 -137
- package/dist/realtime/realtimeApp.d.ts +3 -1
- package/dist/realtime/realtimeApp.js +75 -27
- package/dist/realtime/sessionRevalidation.d.ts +90 -0
- package/dist/realtime/sessionRevalidation.js +438 -0
- package/dist/realtime/socketAuth.d.ts +97 -0
- package/dist/realtime/socketAuth.js +272 -0
- package/dist/realtime/socketUser.d.ts +54 -0
- package/dist/realtime/socketUser.js +75 -5
- package/dist/realtime/types.d.ts +40 -0
- package/dist/secretProviders.d.ts +23 -0
- package/dist/secretProviders.js +9 -3
- package/dist/sync/executors.d.ts +198 -0
- package/dist/sync/executors.js +670 -0
- package/dist/sync/loadHarness.js +807 -0
- package/dist/sync/models.d.ts +216 -0
- package/dist/sync/models.js +644 -0
- package/dist/sync/mutationHandler.d.ts +97 -0
- package/dist/sync/mutationHandler.js +886 -0
- package/dist/sync/registry.d.ts +73 -0
- package/dist/sync/registry.js +223 -0
- package/dist/sync/routes.d.ts +62 -0
- package/dist/sync/routes.js +936 -0
- package/dist/sync/scripts/compactTombstones.d.ts +47 -0
- package/dist/sync/scripts/compactTombstones.js +270 -0
- package/dist/sync/serialize.d.ts +20 -0
- package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
- package/dist/sync/socketHandlers.d.ts +54 -0
- package/dist/sync/socketHandlers.js +470 -0
- package/dist/sync/streams.d.ts +85 -0
- package/dist/sync/streams.js +221 -0
- package/dist/sync/syncApp.d.ts +29 -0
- package/dist/sync/syncApp.js +44 -0
- package/dist/sync/syncBatch.d.ts +71 -0
- package/dist/sync/syncBatch.js +252 -0
- package/dist/sync/syncSeqPlugin.d.ts +8 -0
- package/dist/sync/syncSeqPlugin.js +903 -0
- package/dist/sync/types.d.ts +254 -0
- package/dist/sync/types.js +9 -0
- package/dist/terrenoApp.js +90 -27
- package/dist/tests/models.d.ts +11 -27
- package/dist/tests/models.js +3 -5
- package/dist/tests/testHelper.d.ts +3 -9
- package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
- package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
- package/package.json +10 -8
- package/src/__tests__/openApiCompat.test.ts +20 -0
- package/src/actions.test.ts +12 -19
- package/src/actions.ts +2 -2
- package/src/api.coverage.test.ts +9 -7
- package/src/api.errorPaths.test.ts +1 -47
- package/src/api.test.ts +12 -0
- package/src/api.ts +98 -317
- package/src/auth.test.ts +128 -176
- package/src/auth.ts +109 -0
- package/src/betterAuth.ts +6 -0
- package/src/betterAuthSetup.test.ts +34 -0
- package/src/betterAuthSetup.ts +27 -8
- package/src/configurationPlugin.ts +2 -2
- package/src/consentApp.test.ts +12 -12
- package/src/docLoader.ts +3 -1
- package/src/errors.ts +33 -0
- package/src/expressServer.test.ts +7 -1
- package/src/expressServer.ts +5 -11
- package/src/githubAuth.ts +3 -1
- package/src/index.ts +42 -0
- package/src/middleware.test.ts +40 -1
- package/src/middleware.ts +15 -0
- package/src/models/versionConfig.ts +1 -1
- package/src/openApiBuilder.test.ts +9 -24
- package/src/openApiCompat.ts +99 -45
- package/src/openApiValidator.test.ts +0 -41
- package/src/permissions.test.ts +75 -1
- package/src/permissions.ts +49 -0
- package/src/plugins.test.ts +54 -14
- package/src/plugins.ts +47 -9
- package/src/populate.test.ts +16 -25
- package/src/realtime/changeStreamWatcher.ts +552 -114
- package/src/realtime/realtime.test.ts +157 -239
- package/src/realtime/realtimeApp.ts +80 -19
- package/src/realtime/sessionRevalidation.test.ts +423 -0
- package/src/realtime/sessionRevalidation.ts +273 -0
- package/src/realtime/socketAuth.test.ts +355 -0
- package/src/realtime/socketAuth.ts +228 -0
- package/src/realtime/socketUser.ts +69 -0
- package/src/realtime/types.ts +40 -0
- package/src/secretProviders.test.ts +7 -1
- package/src/secretProviders.ts +15 -3
- package/src/sync/ensureSyncIndexes.test.ts +144 -0
- package/src/sync/executors.test.ts +882 -0
- package/src/sync/executors.ts +703 -0
- package/src/sync/integration.test.ts +1160 -0
- package/src/sync/loadHarness.ts +618 -0
- package/src/sync/models.ts +640 -0
- package/src/sync/mutationHandler.test.ts +1252 -0
- package/src/sync/mutationHandler.ts +850 -0
- package/src/sync/registry.ts +232 -0
- package/src/sync/routes.ts +812 -0
- package/src/sync/scripts/compactTombstones.test.ts +249 -0
- package/src/sync/scripts/compactTombstones.ts +145 -0
- package/src/sync/serialize.ts +48 -0
- package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
- package/src/sync/socketHandlers.ts +320 -0
- package/src/sync/streams.ts +188 -0
- package/src/sync/sync.test.ts +582 -0
- package/src/sync/syncApp.ts +44 -0
- package/src/sync/syncBatch.ts +219 -0
- package/src/sync/syncFrontier.test.ts +494 -0
- package/src/sync/syncPhaseC.test.ts +718 -0
- package/src/sync/syncRoutes.test.ts +865 -0
- package/src/sync/syncSeqPlugin.ts +738 -0
- package/src/sync/syncSocket.test.ts +1440 -0
- package/src/sync/types.ts +270 -0
- package/src/terrenoApp.ts +37 -17
- package/src/tests/bunSetup.ts +8 -0
- package/src/tests/models.ts +6 -8
- package/tsconfig.json +4 -4
- package/tsconfig.typedoc.json +7 -1
- package/dist/__tests__/openApiCompat.test.js +0 -317
- package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
- package/dist/__tests__/versionCheckPlugin.test.js +0 -597
- package/dist/actions.openApi.test.d.ts +0 -1
- package/dist/actions.openApi.test.js +0 -253
- package/dist/actions.test.d.ts +0 -1
- package/dist/actions.test.js +0 -1087
- package/dist/api.arrayOperations.test.d.ts +0 -1
- package/dist/api.arrayOperations.test.js +0 -878
- package/dist/api.asyncHandler.test.d.ts +0 -1
- package/dist/api.asyncHandler.test.js +0 -236
- package/dist/api.coverage.test.d.ts +0 -1
- package/dist/api.coverage.test.js +0 -192
- package/dist/api.errorPaths.test.d.ts +0 -1
- package/dist/api.errorPaths.test.js +0 -887
- package/dist/api.errors.test.d.ts +0 -1
- package/dist/api.errors.test.js +0 -185
- package/dist/api.hooks.test.d.ts +0 -1
- package/dist/api.hooks.test.js +0 -950
- package/dist/api.query.test.d.ts +0 -1
- package/dist/api.query.test.js +0 -948
- package/dist/api.test.d.ts +0 -1
- package/dist/api.test.js +0 -2820
- package/dist/auth.compile.test.d.ts +0 -1
- package/dist/auth.compile.test.js +0 -201
- package/dist/auth.coverage.test.d.ts +0 -1
- package/dist/auth.coverage.test.js +0 -202
- package/dist/auth.test.d.ts +0 -1
- package/dist/auth.test.js +0 -2286
- package/dist/betterAuth.test.d.ts +0 -1
- package/dist/betterAuth.test.js +0 -181
- package/dist/betterAuthApp.test.d.ts +0 -1
- package/dist/betterAuthApp.test.js +0 -242
- package/dist/betterAuthSetup.test.d.ts +0 -1
- package/dist/betterAuthSetup.test.js +0 -762
- package/dist/config.test.d.ts +0 -1
- package/dist/config.test.js +0 -353
- package/dist/configuration.test.d.ts +0 -1
- package/dist/configuration.test.js +0 -980
- package/dist/configurationPlugin.test.d.ts +0 -1
- package/dist/configurationPlugin.test.js +0 -827
- package/dist/consentApp.test.d.ts +0 -1
- package/dist/consentApp.test.js +0 -1411
- package/dist/docLoader.test.d.ts +0 -1
- package/dist/docLoader.test.js +0 -137
- package/dist/envConfigurationPlugin.test.d.ts +0 -1
- package/dist/envConfigurationPlugin.test.js +0 -369
- package/dist/errors.test.d.ts +0 -1
- package/dist/errors.test.js +0 -607
- package/dist/expressServer.test.d.ts +0 -1
- package/dist/expressServer.test.js +0 -1249
- package/dist/githubAuth.test.d.ts +0 -1
- package/dist/githubAuth.test.js +0 -1142
- package/dist/httpClient.test.d.ts +0 -1
- package/dist/httpClient.test.js +0 -1471
- package/dist/logger.test.d.ts +0 -1
- package/dist/logger.test.js +0 -685
- package/dist/middleware.test.d.ts +0 -1
- package/dist/middleware.test.js +0 -241
- package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
- package/dist/notifiers/googleChatNotifier.test.js +0 -298
- package/dist/notifiers/slackNotifier.test.d.ts +0 -1
- package/dist/notifiers/slackNotifier.test.js +0 -297
- package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
- package/dist/notifiers/zoomNotifier.test.js +0 -373
- package/dist/openApi.test.d.ts +0 -1
- package/dist/openApi.test.js +0 -620
- package/dist/openApiBuilder.test.d.ts +0 -1
- package/dist/openApiBuilder.test.js +0 -599
- package/dist/openApiEtag.test.d.ts +0 -1
- package/dist/openApiEtag.test.js +0 -86
- package/dist/openApiValidator.test.d.ts +0 -1
- package/dist/openApiValidator.test.js +0 -795
- package/dist/permissions.middleware.test.d.ts +0 -1
- package/dist/permissions.middleware.test.js +0 -308
- package/dist/permissions.test.d.ts +0 -1
- package/dist/permissions.test.js +0 -439
- package/dist/plugins.test.d.ts +0 -1
- package/dist/plugins.test.js +0 -902
- package/dist/populate.test.d.ts +0 -1
- package/dist/populate.test.js +0 -370
- package/dist/realtime/realtime.test.d.ts +0 -10
- package/dist/realtime/realtime.test.js +0 -4213
- package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
- package/dist/realtime/realtimeAppSetup.test.js +0 -213
- package/dist/requestContext.test.d.ts +0 -1
- package/dist/requestContext.test.js +0 -412
- package/dist/scriptRunner.test.d.ts +0 -1
- package/dist/scriptRunner.test.js +0 -386
- package/dist/secretProviders.test.d.ts +0 -1
- package/dist/secretProviders.test.js +0 -726
- package/dist/syncConsents.test.d.ts +0 -1
- package/dist/syncConsents.test.js +0 -522
- package/dist/terrenoApp.test.d.ts +0 -1
- package/dist/terrenoApp.test.js +0 -489
- package/dist/tests/bunSetup.d.ts +0 -1
- package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
- package/dist/tests/fixtures/compileAuthEntry.js +0 -37
- package/dist/tests/testEnv.d.ts +0 -0
- package/dist/tests/testEnv.js +0 -6
- package/dist/transformers.test.d.ts +0 -1
- package/dist/transformers.test.js +0 -423
- package/dist/utils.test.d.ts +0 -1
- package/dist/utils.test.js +0 -242
- package/src/realtime/realtimeAppSetup.test.ts +0 -161
- /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
package/src/permissions.test.ts
CHANGED
|
@@ -7,7 +7,12 @@ import type TestAgent from "supertest/lib/agent";
|
|
|
7
7
|
|
|
8
8
|
import {modelRouter} from "./api";
|
|
9
9
|
import {addAuthRoutes, setupAuth} from "./auth";
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
getUserOrganizationIds,
|
|
12
|
+
OrganizationQueryFilter,
|
|
13
|
+
OwnerQueryFilter,
|
|
14
|
+
Permissions,
|
|
15
|
+
} from "./permissions";
|
|
11
16
|
import {
|
|
12
17
|
authAsUser,
|
|
13
18
|
type Food,
|
|
@@ -219,6 +224,75 @@ describe("permissions module", () => {
|
|
|
219
224
|
});
|
|
220
225
|
});
|
|
221
226
|
|
|
227
|
+
describe("getUserOrganizationIds", () => {
|
|
228
|
+
it("returns the user's organizationIds", () => {
|
|
229
|
+
const user = {id: "u1", organizationIds: ["org-1", "org-2"]} as any;
|
|
230
|
+
expect(getUserOrganizationIds(user)).toEqual(["org-1", "org-2"]);
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
it("returns an empty array when missing or undefined", () => {
|
|
234
|
+
expect(getUserOrganizationIds({id: "u1"} as any)).toEqual([]);
|
|
235
|
+
expect(getUserOrganizationIds(undefined)).toEqual([]);
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
describe("OrganizationQueryFilter", () => {
|
|
240
|
+
it("returns an $in filter over the user's organizationIds", () => {
|
|
241
|
+
const user = {id: "u1", organizationIds: ["org-1", "org-2"]} as any;
|
|
242
|
+
expect(OrganizationQueryFilter(user)).toEqual({
|
|
243
|
+
organizationId: {$in: ["org-1", "org-2"]},
|
|
244
|
+
});
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
it("returns an empty $in filter when the user has no organizations", () => {
|
|
248
|
+
const user = {id: "u1"} as any;
|
|
249
|
+
expect(OrganizationQueryFilter(user)).toEqual({organizationId: {$in: []}});
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it("returns null when user is undefined", () => {
|
|
253
|
+
expect(OrganizationQueryFilter(undefined)).toBeNull();
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
describe("Permissions.IsOrganizationMember", () => {
|
|
258
|
+
it("returns true when no object is provided", () => {
|
|
259
|
+
const user = {id: "u1", organizationIds: ["org-1"]} as any;
|
|
260
|
+
expect(Permissions.IsOrganizationMember("list", user, undefined)).toBe(true);
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
it("returns false when there is no user", () => {
|
|
264
|
+
expect(Permissions.IsOrganizationMember("read", undefined, {organizationId: "org-1"})).toBe(
|
|
265
|
+
false
|
|
266
|
+
);
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
it("returns true for admins regardless of membership", () => {
|
|
270
|
+
const user = {admin: true, id: "admin-1", organizationIds: []} as any;
|
|
271
|
+
expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-9"})).toBe(
|
|
272
|
+
true
|
|
273
|
+
);
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it("returns true when the user belongs to the document's organization", () => {
|
|
277
|
+
const user = {id: "u1", organizationIds: ["org-1", "org-2"]} as any;
|
|
278
|
+
expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-2"})).toBe(
|
|
279
|
+
true
|
|
280
|
+
);
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
it("returns false when the user does not belong to the document's organization", () => {
|
|
284
|
+
const user = {id: "u1", organizationIds: ["org-1"]} as any;
|
|
285
|
+
expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-9"})).toBe(
|
|
286
|
+
false
|
|
287
|
+
);
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
it("returns false when the document has no organizationId", () => {
|
|
291
|
+
const user = {id: "u1", organizationIds: ["org-1"]} as any;
|
|
292
|
+
expect(Permissions.IsOrganizationMember("read", user, {})).toBe(false);
|
|
293
|
+
});
|
|
294
|
+
});
|
|
295
|
+
|
|
222
296
|
describe("Permissions.IsAuthenticatedOrReadOnly", () => {
|
|
223
297
|
it("returns true for authenticated non-anonymous users", () => {
|
|
224
298
|
const user = {id: "user-123", isAnonymous: false} as any;
|
package/src/permissions.ts
CHANGED
|
@@ -28,6 +28,32 @@ export const OwnerQueryFilter = (user?: User) => {
|
|
|
28
28
|
return null;
|
|
29
29
|
};
|
|
30
30
|
|
|
31
|
+
/**
|
|
32
|
+
* A user that may belong to one or more organizations (tenants). Backends that use tenant-scoped
|
|
33
|
+
* models add an `organizationIds` array to their user model; this interface lets the shared
|
|
34
|
+
* permission/query-filter helpers read it without every consumer casting by hand.
|
|
35
|
+
*/
|
|
36
|
+
export interface OrganizationScopedUser extends User {
|
|
37
|
+
organizationIds?: string[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Reads the caller's organization ids, tolerating users without the `organizationIds` field. */
|
|
41
|
+
export const getUserOrganizationIds = (user?: User): string[] => {
|
|
42
|
+
return (user as OrganizationScopedUser | undefined)?.organizationIds ?? [];
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Restricts list queries to documents belonging to one of the caller's organizations. This is the
|
|
47
|
+
* tenant-scoped analog of {@link OwnerQueryFilter}: it filters on the document's `organizationId`
|
|
48
|
+
* field using the user's `organizationIds`. Returns `null` for anonymous callers (no user).
|
|
49
|
+
*/
|
|
50
|
+
export const OrganizationQueryFilter = (user?: User) => {
|
|
51
|
+
if (!user) {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
return {organizationId: {$in: getUserOrganizationIds(user)}};
|
|
55
|
+
};
|
|
56
|
+
|
|
31
57
|
export const Permissions = {
|
|
32
58
|
IsAdmin: (_method: RESTMethod, user?: User) => {
|
|
33
59
|
return Boolean(user?.admin);
|
|
@@ -47,6 +73,29 @@ export const Permissions = {
|
|
|
47
73
|
}
|
|
48
74
|
return method === "list" || method === "read";
|
|
49
75
|
},
|
|
76
|
+
/**
|
|
77
|
+
* Object-level permission for tenant-scoped documents: the caller must belong to the document's
|
|
78
|
+
* organization (admins always pass). With no object (list/create checks) it returns true and
|
|
79
|
+
* defers to the {@link OrganizationQueryFilter} / a `preCreate` hook to scope access. Expects the
|
|
80
|
+
* document to expose an `organizationId` and the user an `organizationIds` array.
|
|
81
|
+
*/
|
|
82
|
+
IsOrganizationMember: (_method: RESTMethod, user?: User, obj?: unknown) => {
|
|
83
|
+
// When checking if we can possibly perform the action, return true.
|
|
84
|
+
if (!obj) {
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
if (!user) {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
if (user?.admin) {
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
const organizationId = (obj as {organizationId?: string}).organizationId;
|
|
94
|
+
if (!organizationId) {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
return getUserOrganizationIds(user).includes(organizationId);
|
|
98
|
+
},
|
|
50
99
|
IsOwner: (_method: RESTMethod, user?: User, obj?: unknown) => {
|
|
51
100
|
// When checking if we can possibly perform the action, return true.
|
|
52
101
|
if (!obj) {
|
package/src/plugins.test.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
// noExplicitAny: test mock typing
|
|
2
2
|
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
3
|
import {beforeEach, describe, expect, it, setSystemTime} from "bun:test";
|
|
4
|
-
import {assert} from "chai";
|
|
5
4
|
import type express from "express";
|
|
6
5
|
import {type Document, type Model, model, Schema} from "mongoose";
|
|
7
6
|
import supertest from "supertest";
|
|
@@ -14,10 +13,12 @@ import {
|
|
|
14
13
|
baseUserPlugin,
|
|
15
14
|
createdUpdatedPlugin,
|
|
16
15
|
DateOnly,
|
|
16
|
+
excludeArchivedPlugin,
|
|
17
17
|
findExactlyOne,
|
|
18
18
|
findOneOrNone,
|
|
19
19
|
findOneOrNoneFor,
|
|
20
20
|
firebaseJWTPlugin,
|
|
21
|
+
type IsArchived,
|
|
21
22
|
type IsDeleted,
|
|
22
23
|
isDeletedPlugin,
|
|
23
24
|
upsertPlugin,
|
|
@@ -426,6 +427,58 @@ describe("upsertPlugin", () => {
|
|
|
426
427
|
});
|
|
427
428
|
});
|
|
428
429
|
|
|
430
|
+
interface ArchivableStuff extends IsArchived {
|
|
431
|
+
_id: string;
|
|
432
|
+
name: string;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const archivableSchema = new Schema<ArchivableStuff>({
|
|
436
|
+
name: {description: "The name of the item", type: String},
|
|
437
|
+
});
|
|
438
|
+
archivableSchema.plugin(excludeArchivedPlugin);
|
|
439
|
+
const ArchivableModel = model<ArchivableStuff>("ArchivableStuff", archivableSchema);
|
|
440
|
+
|
|
441
|
+
describe("excludeArchivedPlugin", () => {
|
|
442
|
+
beforeEach(async () => {
|
|
443
|
+
await ArchivableModel.deleteMany({});
|
|
444
|
+
await setupDb();
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
it("adds an archived field defaulting to false", () => {
|
|
448
|
+
const archivedPath = archivableSchema.path("archived");
|
|
449
|
+
expect(archivedPath).toBeDefined();
|
|
450
|
+
expect((archivedPath as unknown as {options: {default: boolean}}).options.default).toBe(false);
|
|
451
|
+
expect((archivedPath as unknown as {options: {index: boolean}}).options.index).toBe(true);
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
it("excludes archived documents from find() by default", async () => {
|
|
455
|
+
await ArchivableModel.create({archived: false, name: "Active"});
|
|
456
|
+
await ArchivableModel.create({archived: true, name: "Archived"});
|
|
457
|
+
|
|
458
|
+
const results = await ArchivableModel.find({});
|
|
459
|
+
expect(results).toHaveLength(1);
|
|
460
|
+
expect(results[0].name).toBe("Active");
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
it("includes archived documents when explicitly requested", async () => {
|
|
464
|
+
await ArchivableModel.create({archived: false, name: "Active"});
|
|
465
|
+
await ArchivableModel.create({archived: true, name: "Archived"});
|
|
466
|
+
|
|
467
|
+
const results = await ArchivableModel.find({archived: true});
|
|
468
|
+
expect(results).toHaveLength(1);
|
|
469
|
+
expect(results[0].name).toBe("Archived");
|
|
470
|
+
});
|
|
471
|
+
|
|
472
|
+
it("does not override an explicit archived filter of false", async () => {
|
|
473
|
+
await ArchivableModel.create({archived: false, name: "Active"});
|
|
474
|
+
await ArchivableModel.create({archived: true, name: "Archived"});
|
|
475
|
+
|
|
476
|
+
const results = await ArchivableModel.find({archived: false});
|
|
477
|
+
expect(results).toHaveLength(1);
|
|
478
|
+
expect(results[0].name).toBe("Active");
|
|
479
|
+
});
|
|
480
|
+
});
|
|
481
|
+
|
|
429
482
|
describe("TypeScript return types", () => {
|
|
430
483
|
let _things: any;
|
|
431
484
|
|
|
@@ -470,19 +523,6 @@ describe("TypeScript return types", () => {
|
|
|
470
523
|
});
|
|
471
524
|
});
|
|
472
525
|
describe("DateOnly", () => {
|
|
473
|
-
it("strips the time portion when getting a Date value", () => {
|
|
474
|
-
const dateOnly = new DateOnly("date", {});
|
|
475
|
-
const value = dateOnly.get(new Date("2005-10-10T17:17:17.017Z")) as unknown as Date;
|
|
476
|
-
assert.instanceOf(value, Date);
|
|
477
|
-
assert.equal(value.toISOString(), "2005-10-10T00:00:00.000Z");
|
|
478
|
-
});
|
|
479
|
-
|
|
480
|
-
it("returns non-Date values unchanged when getting a value", () => {
|
|
481
|
-
const dateOnly = new DateOnly("date", {});
|
|
482
|
-
assert.isNull(dateOnly.get(null));
|
|
483
|
-
assert.equal(dateOnly.get("2005-10-10") as unknown as string, "2005-10-10");
|
|
484
|
-
});
|
|
485
|
-
|
|
486
526
|
it("throws error with invalid date", async () => {
|
|
487
527
|
try {
|
|
488
528
|
await StuffModel.create({
|
package/src/plugins.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {DateTime} from "luxon";
|
|
2
2
|
import mongoose, {
|
|
3
3
|
type Document,
|
|
4
|
+
type FilterQuery,
|
|
4
5
|
Error as MongooseError,
|
|
5
6
|
type Query,
|
|
6
7
|
type Schema,
|
|
@@ -10,8 +11,6 @@ import mongoose, {
|
|
|
10
11
|
|
|
11
12
|
import {APIError, type APIErrorOptions, InternalServerError, NotFoundError} from "./errors";
|
|
12
13
|
|
|
13
|
-
export type ModelQuery<T> = Partial<Record<keyof T, unknown>> & Record<string, unknown>;
|
|
14
|
-
|
|
15
14
|
export interface BaseUser {
|
|
16
15
|
admin: boolean;
|
|
17
16
|
email: string;
|
|
@@ -173,14 +172,14 @@ export const findOneOrNone = <T>(schema: Schema<T>): void => {
|
|
|
173
172
|
*/
|
|
174
173
|
export const findOneOrNoneFor = async <T>(
|
|
175
174
|
model: mongoose.Model<T>,
|
|
176
|
-
query:
|
|
175
|
+
query: FilterQuery<T>,
|
|
177
176
|
errorArgs?: Partial<APIErrorOptions>
|
|
178
177
|
): Promise<(Document & T) | null> => {
|
|
179
178
|
const withStatic = model as mongoose.Model<T> & Partial<FindOneOrNonePlugin<T>>;
|
|
180
179
|
if (typeof withStatic.findOneOrNone === "function") {
|
|
181
180
|
return withStatic.findOneOrNone(query, errorArgs);
|
|
182
181
|
}
|
|
183
|
-
const results = await model.find(query
|
|
182
|
+
const results = await model.find(query);
|
|
184
183
|
if (results.length === 0) {
|
|
185
184
|
return null;
|
|
186
185
|
}
|
|
@@ -285,6 +284,49 @@ export interface HasUpsert<T> {
|
|
|
285
284
|
upsert(conditions: Record<string, unknown>, update: Record<string, unknown>): Promise<T>;
|
|
286
285
|
}
|
|
287
286
|
|
|
287
|
+
/** For models with the excludeArchivedPlugin, extend this interface to add the archived field. */
|
|
288
|
+
export interface IsArchived {
|
|
289
|
+
// Archived objects are excluded from find() queries unless {archived: true} is passed.
|
|
290
|
+
archived: boolean;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Adds an `archived` boolean field and excludes archived documents from `find()` queries by
|
|
295
|
+
* default. Pass `{archived: true}` explicitly to include them. This is a soft-archive analog to
|
|
296
|
+
* {@link isDeletedPlugin}: use it when documents should be hidden from normal listings but kept
|
|
297
|
+
* (and still directly queryable) rather than treated as deleted.
|
|
298
|
+
* @param schema Mongoose Schema
|
|
299
|
+
* @param defaultValue Default value for the `archived` field (defaults to `false`)
|
|
300
|
+
*/
|
|
301
|
+
export const excludeArchivedPlugin = (
|
|
302
|
+
// noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
|
|
303
|
+
// biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
|
|
304
|
+
schema: Schema<any, any, any, any>,
|
|
305
|
+
defaultValue = false
|
|
306
|
+
): void => {
|
|
307
|
+
schema.add({
|
|
308
|
+
archived: {
|
|
309
|
+
default: defaultValue,
|
|
310
|
+
description:
|
|
311
|
+
"Archived objects are not returned in any find() by default. " +
|
|
312
|
+
"Add {archived: true} to find them.",
|
|
313
|
+
index: true,
|
|
314
|
+
type: Boolean,
|
|
315
|
+
},
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
// noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
|
|
319
|
+
// biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
|
|
320
|
+
schema.pre<Query<any, any>>("find", function () {
|
|
321
|
+
const conditions = this.getFilter();
|
|
322
|
+
// Only apply the default filter when the query does not mention `archived` at all, so an
|
|
323
|
+
// explicit `{archived: true}` (or `false`) is always respected.
|
|
324
|
+
if (conditions.archived === undefined) {
|
|
325
|
+
this.setQuery({...conditions, archived: {$ne: true}});
|
|
326
|
+
}
|
|
327
|
+
});
|
|
328
|
+
};
|
|
329
|
+
|
|
288
330
|
export interface FindOneOrNonePlugin<T> {
|
|
289
331
|
findOneOrNone(
|
|
290
332
|
query: Record<string, unknown>,
|
|
@@ -330,11 +372,7 @@ export class DateOnly extends SchemaType {
|
|
|
330
372
|
const handler = this.$conditionalHandlers[$conditional];
|
|
331
373
|
|
|
332
374
|
if (!handler) {
|
|
333
|
-
throw new
|
|
334
|
-
detail: `Can't use ${$conditional} with DateOnly.`,
|
|
335
|
-
status: 400,
|
|
336
|
-
title: "Unsupported query conditional for DateOnly",
|
|
337
|
-
});
|
|
375
|
+
throw new Error(`Can't use ${$conditional} with DateOnly.`);
|
|
338
376
|
}
|
|
339
377
|
|
|
340
378
|
return handler.call(this, val);
|
package/src/populate.test.ts
CHANGED
|
@@ -1,24 +1,17 @@
|
|
|
1
|
+
// noExplicitAny: test mock typing
|
|
2
|
+
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
1
3
|
import {beforeEach, describe, expect, it} from "bun:test";
|
|
2
4
|
import mongoose, {type Document, type HydratedDocument, Schema} from "mongoose";
|
|
3
5
|
|
|
4
6
|
import {fixMixedFields, getOpenApiSpecForModel, unpopulate} from "./populate";
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* A Food document whose ObjectId references have been replaced by populated user
|
|
9
|
-
* documents. `unpopulate` swaps them back to ObjectIds in place, so both shapes
|
|
10
|
-
* are optional on the reference fields.
|
|
11
|
-
*/
|
|
12
|
-
type PopulatedFood = Omit<HydratedDocument<Food>, "eatenBy" | "likesIds" | "ownerId"> & {
|
|
13
|
-
ownerId: Partial<User> & {toString(): string};
|
|
14
|
-
eatenBy: (Partial<User> & {id?: string})[] & {toString(): string};
|
|
15
|
-
likesIds: {likes: boolean; userId: Partial<User> & {id?: string; toString(): string}}[];
|
|
16
|
-
};
|
|
7
|
+
import {FoodModel, setupTestData, type User, UserModel} from "./tests";
|
|
17
8
|
|
|
18
9
|
describe("populate functions", () => {
|
|
19
10
|
let admin: HydratedDocument<User>;
|
|
20
11
|
let notAdmin: HydratedDocument<User>;
|
|
21
|
-
|
|
12
|
+
|
|
13
|
+
// noExplicitAny: typing as HydratedDocument<Food> causes cascading errors on populated field access patterns (e.g. populated.ownerId.name)
|
|
14
|
+
let spinach: any;
|
|
22
15
|
|
|
23
16
|
beforeEach(async () => {
|
|
24
17
|
const testData = await setupTestData();
|
|
@@ -28,10 +21,9 @@ describe("populate functions", () => {
|
|
|
28
21
|
});
|
|
29
22
|
|
|
30
23
|
it("unpopulate", async () => {
|
|
31
|
-
await spinach.populate("ownerId");
|
|
32
|
-
await
|
|
33
|
-
await
|
|
34
|
-
const populated = spinach as unknown as PopulatedFood;
|
|
24
|
+
let populated = await spinach.populate("ownerId");
|
|
25
|
+
populated = await populated.populate("eatenBy");
|
|
26
|
+
populated = await populated.populate("likesIds.userId");
|
|
35
27
|
expect(populated.ownerId.name).toBe("Not Admin");
|
|
36
28
|
expect(populated.eatenBy[0].id).toBe(admin.id);
|
|
37
29
|
expect(populated.eatenBy[0].name).toBe("Admin");
|
|
@@ -40,11 +32,9 @@ describe("populate functions", () => {
|
|
|
40
32
|
expect(populated.likesIds[1].userId.id).toBe(notAdmin.id);
|
|
41
33
|
expect(populated.likesIds[1].userId.name).toBe("Not Admin");
|
|
42
34
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
) as unknown as PopulatedFood;
|
|
47
|
-
expect(populated.ownerId.name).toBeUndefined();
|
|
35
|
+
// noExplicitAny: unpopulate returns Document<T> which doesn't expose model properties; would require refactoring the return type
|
|
36
|
+
let unpopulated: any = unpopulate(populated, "ownerId");
|
|
37
|
+
expect(spinach.ownerId.name).toBeUndefined();
|
|
48
38
|
expect(unpopulated.ownerId.toString()).toBe(notAdmin.id);
|
|
49
39
|
// Ensure nothing else was touched.
|
|
50
40
|
expect(populated.likesIds[0].userId.id).toBe(admin.id);
|
|
@@ -52,11 +42,11 @@ describe("populate functions", () => {
|
|
|
52
42
|
expect(populated.likesIds[1].userId.id).toBe(notAdmin.id);
|
|
53
43
|
expect(populated.likesIds[1].userId.name).toBe("Not Admin");
|
|
54
44
|
|
|
55
|
-
unpopulate(populated
|
|
45
|
+
unpopulated = unpopulate(populated, "eatenBy");
|
|
56
46
|
expect(populated.eatenBy.toString()).toBe(admin.id);
|
|
57
47
|
expect(populated.eatenBy[0]?.name).toBeUndefined();
|
|
58
48
|
|
|
59
|
-
unpopulate(populated
|
|
49
|
+
unpopulated = unpopulate(populated, "likesIds.userId");
|
|
60
50
|
expect(populated.likesIds[0].userId.toString()).toBe(admin.id);
|
|
61
51
|
expect(populated.likesIds[0].userId?.name).toBeUndefined();
|
|
62
52
|
expect(populated.likesIds[1].userId.toString()).toBe(notAdmin.id);
|
|
@@ -336,7 +326,8 @@ describe("filterKeys (via getOpenApiSpecForModel populatePaths)", () => {
|
|
|
336
326
|
populatePaths: [{fields: ["__proto__.polluted"], path: "ownerId"}],
|
|
337
327
|
});
|
|
338
328
|
expect(result.properties).toBeDefined();
|
|
339
|
-
|
|
329
|
+
// noExplicitAny: testing that prototype pollution did not add a 'polluted' property to Object.prototype
|
|
330
|
+
expect((Object.prototype as any).polluted).toBeUndefined();
|
|
340
331
|
const ownerProps = (result.properties.ownerId as Record<string, unknown>).properties as Record<
|
|
341
332
|
string,
|
|
342
333
|
unknown
|