@sanity-labs/client-fake-for-test 0.17.3 → 0.19.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/README.md +43 -6
- package/dist/index.cjs +175 -96
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +72 -40
- package/dist/index.d.ts +72 -40
- package/dist/index.js +171 -91
- package/dist/index.js.map +1 -1
- package/package.json +5 -1
package/dist/index.cjs
CHANGED
|
@@ -1,40 +1,41 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: !0 });
|
|
3
|
-
var groqJs = require("groq-js");
|
|
3
|
+
var groqJs = require("groq-js"), client = require("@sanity/client");
|
|
4
4
|
const ERR_PREFIX = "[client-fake-for-test]";
|
|
5
5
|
function fakeError(message) {
|
|
6
6
|
return new Error(`${ERR_PREFIX} ${message}`);
|
|
7
7
|
}
|
|
8
|
-
class PlatformHttpError extends
|
|
9
|
-
statusCode;
|
|
10
|
-
response;
|
|
11
|
-
responseBody;
|
|
12
|
-
details;
|
|
8
|
+
class PlatformHttpError extends client.ClientError {
|
|
13
9
|
constructor(args) {
|
|
14
|
-
|
|
15
|
-
super(clientErrorMessage(args)), this.name = "PlatformHttpError", this.statusCode = statusCode, this.response = { body, url: path, method, headers: {}, statusCode, statusMessage }, this.responseBody = typeof body == "string" ? body : JSON.stringify(body, null, 2);
|
|
16
|
-
const error = isRecord(body) ? body.error : void 0;
|
|
17
|
-
this.details = isRecord(error) ? error : void 0;
|
|
10
|
+
super(platformResponse(args)), this.name = "PlatformHttpError";
|
|
18
11
|
}
|
|
19
12
|
}
|
|
20
|
-
function
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
13
|
+
function platformResponse(args) {
|
|
14
|
+
const { method, path, statusCode, statusMessage, body } = args;
|
|
15
|
+
return {
|
|
16
|
+
body,
|
|
17
|
+
url: path,
|
|
18
|
+
method,
|
|
19
|
+
headers: { "content-type": `${typeof body == "string" ? "text/html" : "application/json"}; charset=utf-8` },
|
|
20
|
+
statusCode,
|
|
21
|
+
statusMessage
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function transactionRefused(request, cause) {
|
|
25
|
+
return platformResponse({
|
|
26
|
+
...request,
|
|
27
|
+
statusCode: 403,
|
|
28
|
+
statusMessage: "Forbidden",
|
|
29
|
+
body: {
|
|
30
|
+
error: {
|
|
31
|
+
description: `transaction failed: ${cause.description}`,
|
|
32
|
+
items: [{ error: cause, index: 0 }],
|
|
33
|
+
type: "mutationError"
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
});
|
|
36
37
|
}
|
|
37
|
-
const notMounted = ({ method, path }) => new PlatformHttpError({
|
|
38
|
+
const DEFAULT_WRITE = { method: "POST", path: "/data/mutate" }, notMounted = ({ method, path }) => new PlatformHttpError({
|
|
38
39
|
method,
|
|
39
40
|
path,
|
|
40
41
|
statusCode: 404,
|
|
@@ -60,6 +61,26 @@ const sessionNotFound = (request) => new PlatformHttpError({
|
|
|
60
61
|
message: "Session not found",
|
|
61
62
|
statusCode: 401
|
|
62
63
|
}
|
|
64
|
+
}), sessionHostMismatch = (request) => new PlatformHttpError({
|
|
65
|
+
...request,
|
|
66
|
+
statusCode: 401,
|
|
67
|
+
statusMessage: "Unauthorized",
|
|
68
|
+
body: {
|
|
69
|
+
statusCode: 401,
|
|
70
|
+
errorCode: "SIO-401-AWH",
|
|
71
|
+
error: "Unauthorized",
|
|
72
|
+
message: "Session does not match project host"
|
|
73
|
+
}
|
|
74
|
+
}), projectMembershipRequired = (request) => accessApiError({
|
|
75
|
+
request,
|
|
76
|
+
statusCode: 401,
|
|
77
|
+
statusMessage: "Unauthorized",
|
|
78
|
+
message: "User must be a member of this project to perform this operation"
|
|
79
|
+
}), mediaLibraryReadRequired = (request) => accessApiError({
|
|
80
|
+
request,
|
|
81
|
+
statusCode: 401,
|
|
82
|
+
statusMessage: "Unauthorized",
|
|
83
|
+
message: "User must be able to read media libraries for this organization to perform this operation"
|
|
63
84
|
}), noPermission = (request) => accessApiError({
|
|
64
85
|
request,
|
|
65
86
|
statusCode: 403,
|
|
@@ -115,6 +136,9 @@ function datasetParts(id) {
|
|
|
115
136
|
const dot = id.indexOf(".");
|
|
116
137
|
return { projectId: id.slice(0, dot), dataset: id.slice(dot + 1) };
|
|
117
138
|
}
|
|
139
|
+
function isProjectMember(tokenProjectId, projectId) {
|
|
140
|
+
return tokenProjectId === void 0 || tokenProjectId === projectId;
|
|
141
|
+
}
|
|
118
142
|
function accessEntryRoles(type) {
|
|
119
143
|
return ({ identity, id }) => identity.access?.[accessKey(type, id)]?.roles;
|
|
120
144
|
}
|
|
@@ -149,6 +173,10 @@ const RESOURCE_CAPABILITIES = {
|
|
|
149
173
|
lookupAtBase: !0,
|
|
150
174
|
identity: "global",
|
|
151
175
|
acl: "served",
|
|
176
|
+
aclRefusals: {
|
|
177
|
+
unknown: notFound("Media library"),
|
|
178
|
+
read: { permission: "sanity.media-library.read", refusal: mediaLibraryReadRequired }
|
|
179
|
+
},
|
|
152
180
|
history: "served",
|
|
153
181
|
actions: "served",
|
|
154
182
|
refusedActions: { "sanity.action.release.create": releaseLimitExceeded },
|
|
@@ -161,6 +189,7 @@ const RESOURCE_CAPABILITIES = {
|
|
|
161
189
|
lookupAtBase: !0,
|
|
162
190
|
identity: "global",
|
|
163
191
|
acl: "served",
|
|
192
|
+
aclRefusals: { unknown: notFound("Resource") },
|
|
164
193
|
history: "served",
|
|
165
194
|
actions: notMounted,
|
|
166
195
|
refusedActions: {},
|
|
@@ -243,8 +272,8 @@ const ACCESS_CAPABILITIES = {
|
|
|
243
272
|
// Single-user reads are served only where the fake checks members read (the
|
|
244
273
|
// organization); elsewhere they refuse rather than answer unchecked.
|
|
245
274
|
user: noPermission,
|
|
246
|
-
//
|
|
247
|
-
memberRoles: ({ identity, id }) => (identity.usersByProject?.[id] ?? identity.user).roles ?? []
|
|
275
|
+
// A member holds its project roles; see `isProjectMember`.
|
|
276
|
+
memberRoles: ({ identity, id }) => isProjectMember(identity.projectId, id) ? (identity.usersByProject?.[id] ?? identity.user).roles ?? [] : void 0
|
|
248
277
|
},
|
|
249
278
|
"media-library": {
|
|
250
279
|
// Staging refuses it only because no probe token held roles read.
|
|
@@ -451,6 +480,8 @@ async function servePlatformRequest(ctx, url) {
|
|
|
451
480
|
const projectFeatures = path.match(PROJECT_FEATURES_PATH);
|
|
452
481
|
if (projectFeatures !== null) {
|
|
453
482
|
const projectId = decodeURIComponent(projectFeatures[1]);
|
|
483
|
+
if (!isProjectMember(ctx.actorProjectId(), projectId))
|
|
484
|
+
throw projectMembershipRequired(request);
|
|
454
485
|
return { value: featuresOf(ctx, projectId) };
|
|
455
486
|
}
|
|
456
487
|
const access = path.match(ACCESS_PATH);
|
|
@@ -469,12 +500,32 @@ async function servePlatformRequest(ctx, url) {
|
|
|
469
500
|
if (rest === "") return row.lookupAtBase ? serveLookup(ctx, resource) : void 0;
|
|
470
501
|
if (rest === "/acl")
|
|
471
502
|
return serveCapability(row.acl, request, () => {
|
|
503
|
+
refuseAcl({ ctx, request, resource, row });
|
|
472
504
|
const own = ctx.own(resource);
|
|
473
505
|
return own === void 0 ? void 0 : { value: own.grants };
|
|
474
506
|
});
|
|
475
507
|
if (rest.startsWith("/history/"))
|
|
476
508
|
return serveHistory({ ctx, request, resource, rest: rest.slice(8), query });
|
|
477
509
|
}
|
|
510
|
+
function refuseAclRequest(ctx, url) {
|
|
511
|
+
const queryStart = url.indexOf("?"), path = queryStart === -1 ? url : url.slice(0, queryStart), matched = matchResourcePath(path);
|
|
512
|
+
if (matched?.rest !== "/acl") return;
|
|
513
|
+
const row = capabilitiesOf(matched.resource.type), request = { method: "GET", path };
|
|
514
|
+
serveCapability(
|
|
515
|
+
row.acl,
|
|
516
|
+
request,
|
|
517
|
+
() => refuseAcl({ ctx, request, resource: matched.resource, row })
|
|
518
|
+
);
|
|
519
|
+
}
|
|
520
|
+
function refuseAcl(args) {
|
|
521
|
+
const { ctx, request, resource, row } = args;
|
|
522
|
+
if (row.aclRefusals === void 0) return;
|
|
523
|
+
const type = row.access.type, id = row.access.id(resource.id), registry = { organizationId: ctx.organizationId, resources: ctx.resources };
|
|
524
|
+
if (!holdsResource(type)(registry, id)) throw row.aclRefusals.unknown(request);
|
|
525
|
+
const { read } = row.aclRefusals;
|
|
526
|
+
if (read !== void 0 && !(ctx.actorAccess()?.[accessKey(type, id)]?.permissions ?? []).includes(read.permission))
|
|
527
|
+
throw read.refusal(request);
|
|
528
|
+
}
|
|
478
529
|
function featuresOf(ctx, projectId) {
|
|
479
530
|
const features = Object.hasOwn(ctx.projectFeatures, projectId) ? ctx.projectFeatures[projectId] : [];
|
|
480
531
|
return [...new Set(features)].toSorted();
|
|
@@ -695,13 +746,17 @@ function attributeRecord(attribute) {
|
|
|
695
746
|
);
|
|
696
747
|
return { type, key, values: { ...values }, activeSource, activeValue };
|
|
697
748
|
}
|
|
698
|
-
class WriteAccessDeniedError extends
|
|
749
|
+
class WriteAccessDeniedError extends client.ClientError {
|
|
699
750
|
documentId;
|
|
700
751
|
permission;
|
|
701
752
|
matchingGrants;
|
|
702
753
|
constructor(args) {
|
|
703
754
|
super(
|
|
704
|
-
|
|
755
|
+
transactionRefused(args.request ?? DEFAULT_WRITE, {
|
|
756
|
+
description: `Insufficient permissions; permission "${args.permission}" required`,
|
|
757
|
+
permission: args.permission,
|
|
758
|
+
type: "insufficientPermissionsError"
|
|
759
|
+
})
|
|
705
760
|
), this.name = "WriteAccessDeniedError", this.documentId = args.documentId, this.permission = args.permission, this.matchingGrants = args.matchingGrants;
|
|
706
761
|
}
|
|
707
762
|
}
|
|
@@ -731,7 +786,7 @@ async function evaluateWriteAccess(args) {
|
|
|
731
786
|
return { allowed: !1, matchingGrants: matching };
|
|
732
787
|
}
|
|
733
788
|
async function enforceWriteAccess(args) {
|
|
734
|
-
const { document, grants, permission, userId } = args, { allowed, matchingGrants } = await evaluateWriteAccess({
|
|
789
|
+
const { document, grants, permission, userId, request } = args, { allowed, matchingGrants } = await evaluateWriteAccess({
|
|
735
790
|
document,
|
|
736
791
|
grants,
|
|
737
792
|
permission,
|
|
@@ -741,22 +796,18 @@ async function enforceWriteAccess(args) {
|
|
|
741
796
|
throw typeof document._id != "string" ? new WriteAccessDeniedError({
|
|
742
797
|
documentId: "(unknown)",
|
|
743
798
|
permission,
|
|
744
|
-
matchingGrants
|
|
799
|
+
matchingGrants,
|
|
800
|
+
request
|
|
745
801
|
}) : new WriteAccessDeniedError({
|
|
746
802
|
documentId: document._id,
|
|
747
803
|
permission,
|
|
748
|
-
matchingGrants
|
|
804
|
+
matchingGrants,
|
|
805
|
+
request
|
|
749
806
|
});
|
|
750
807
|
}
|
|
751
808
|
function defaultAclPath(projectId, dataset) {
|
|
752
809
|
return `/projects/${projectId}/datasets/${dataset}/acl`;
|
|
753
810
|
}
|
|
754
|
-
function refusedAcl(path) {
|
|
755
|
-
const matched = matchResourcePath(path);
|
|
756
|
-
if (matched?.rest !== "/acl") return;
|
|
757
|
-
const { acl } = capabilitiesOf(matched.resource.type);
|
|
758
|
-
return acl === "served" ? void 0 : acl({ method: "GET", path });
|
|
759
|
-
}
|
|
760
811
|
function projectUserOf(identity, projectId) {
|
|
761
812
|
return identity.usersByProject?.[projectId] ?? identity.user;
|
|
762
813
|
}
|
|
@@ -793,7 +844,7 @@ function serveProjectUsers(args) {
|
|
|
793
844
|
};
|
|
794
845
|
}, byId = consistentProjectRecords({
|
|
795
846
|
projectId: pathProjectId,
|
|
796
|
-
records: identities.map(toRecord)
|
|
847
|
+
records: identities.filter((identity) => isProjectMember(identity.projectId, pathProjectId)).map(toRecord)
|
|
797
848
|
}), ids = requestedIds.split(","), [firstId] = ids;
|
|
798
849
|
if (ids.length === 1 && firstId !== void 0) {
|
|
799
850
|
const record = byId.get(firstId);
|
|
@@ -813,17 +864,19 @@ function serveProjectUsers(args) {
|
|
|
813
864
|
}
|
|
814
865
|
const PROJECT_USERS_PATH = /^\/projects\/([^/]+)\/users\/([^/]+)$/, PROJECT_PATH = /^\/projects\/([^/]+)$/;
|
|
815
866
|
function serveProject(args) {
|
|
816
|
-
const records = args.identities.
|
|
867
|
+
const records = args.identities.filter(
|
|
868
|
+
(identity) => isProjectMember(identity.projectId, args.pathProjectId)
|
|
869
|
+
).map((identity) => {
|
|
817
870
|
const projectUser = projectUserOf(identity, args.pathProjectId);
|
|
818
871
|
return {
|
|
819
872
|
id: projectUser.id,
|
|
820
873
|
...projectUser.id.startsWith("p-") ? { isRobot: !0 } : {},
|
|
821
874
|
...projectUser.roles !== void 0 ? { roles: canonicalProjectRoles(projectUser.roles) } : {}
|
|
822
875
|
};
|
|
823
|
-
}),
|
|
876
|
+
}), byId = consistentProjectRecords({ projectId: args.pathProjectId, records });
|
|
824
877
|
return {
|
|
825
878
|
...args.organizationId !== void 0 ? { organizationId: args.organizationId } : {},
|
|
826
|
-
members: [...
|
|
879
|
+
members: [...byId.values()]
|
|
827
880
|
};
|
|
828
881
|
}
|
|
829
882
|
function makeRequestImpl(ctx) {
|
|
@@ -832,8 +885,8 @@ function makeRequestImpl(ctx) {
|
|
|
832
885
|
const accessControl = getAccess(), path = opts.uri ?? opts.url;
|
|
833
886
|
if (path === "/users/me")
|
|
834
887
|
return useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
|
|
835
|
-
if (path !== void 0 && path === accessControl.aclPath
|
|
836
|
-
return accessControl.grants;
|
|
888
|
+
if (path !== void 0 && path === accessControl.aclPath)
|
|
889
|
+
return refuseAclRequest(platform, path), accessControl.grants;
|
|
837
890
|
const projectUsers = path?.match(PROJECT_USERS_PATH), [, pathProjectId, requestedIds] = projectUsers ?? [];
|
|
838
891
|
if (pathProjectId !== void 0 && requestedIds !== void 0)
|
|
839
892
|
return serveProjectUsers({
|
|
@@ -855,24 +908,24 @@ function makeRequestImpl(ctx) {
|
|
|
855
908
|
);
|
|
856
909
|
};
|
|
857
910
|
}
|
|
858
|
-
class GuardDeniedError extends
|
|
859
|
-
statusCode = 403;
|
|
911
|
+
class GuardDeniedError extends client.ClientError {
|
|
860
912
|
type = "guardDeniedError";
|
|
861
913
|
denials;
|
|
862
|
-
|
|
863
|
-
response;
|
|
864
|
-
constructor(denials) {
|
|
914
|
+
constructor(denials, request = DEFAULT_WRITE) {
|
|
865
915
|
const unique = uniqueDenials(denials);
|
|
866
|
-
super(
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
};
|
|
916
|
+
super(
|
|
917
|
+
transactionRefused(request, {
|
|
918
|
+
description: guardDeniedDescription(unique),
|
|
919
|
+
denials: unique,
|
|
920
|
+
type: "guardDeniedError"
|
|
921
|
+
})
|
|
922
|
+
), this.name = "GuardDeniedError", this.denials = unique;
|
|
874
923
|
}
|
|
875
924
|
}
|
|
925
|
+
function guardDeniedDescription(denials) {
|
|
926
|
+
const named = denials.map(({ guardID, name }) => name ? `${guardID} (${name})` : guardID);
|
|
927
|
+
return `mutation denied by ${denials.length} guard(s): ${named.join(" ")}`;
|
|
928
|
+
}
|
|
876
929
|
function uniqueDenials(denials) {
|
|
877
930
|
const seen = /* @__PURE__ */ new Set();
|
|
878
931
|
return denials.filter((denial) => seen.has(denial.guardID) ? !1 : (seen.add(denial.guardID), !0));
|
|
@@ -888,14 +941,14 @@ function mutationContexts(images) {
|
|
|
888
941
|
return context === void 0 ? [] : [context];
|
|
889
942
|
});
|
|
890
943
|
}
|
|
891
|
-
async function enforceMutationGuards(guard, contexts) {
|
|
944
|
+
async function enforceMutationGuards(guard, contexts, request) {
|
|
892
945
|
if (guard === void 0) return;
|
|
893
946
|
const denials = [];
|
|
894
947
|
for (const context of contexts) {
|
|
895
948
|
const denied = await guard(context);
|
|
896
949
|
denied !== void 0 && denials.push(...denied);
|
|
897
950
|
}
|
|
898
|
-
if (denials.length > 0) throw new GuardDeniedError(denials);
|
|
951
|
+
if (denials.length > 0) throw new GuardDeniedError(denials, request);
|
|
899
952
|
}
|
|
900
953
|
function describeType(value) {
|
|
901
954
|
return value === null ? "null" : Array.isArray(value) ? "an array" : `a ${typeof value}`;
|
|
@@ -1293,7 +1346,7 @@ function requireActive(release) {
|
|
|
1293
1346
|
`Release "${release.name}" is "${release.state}", but only "active" releases accept version writes (create / replace / discard / unpublish). Unschedule or unarchive it back to "active" first, or target a different release.`
|
|
1294
1347
|
);
|
|
1295
1348
|
}
|
|
1296
|
-
async function applyAction(store, action) {
|
|
1349
|
+
async function applyAction(store, action, request = ACTIONS_REQUEST) {
|
|
1297
1350
|
switch (action.actionType) {
|
|
1298
1351
|
case "sanity.action.release.create": {
|
|
1299
1352
|
if (maybeRelease(store, action.releaseId) !== void 0)
|
|
@@ -1397,7 +1450,7 @@ async function applyAction(store, action) {
|
|
|
1397
1450
|
return store.remove(release._id), { transactionId: cryptoRandomKey() };
|
|
1398
1451
|
}
|
|
1399
1452
|
case "sanity.action.document.version.create": {
|
|
1400
|
-
if ("baseId" in action) return createVersionFromBase(store, action);
|
|
1453
|
+
if ("baseId" in action) return createVersionFromBase(store, action, request);
|
|
1401
1454
|
const releaseId = action.releaseId ?? (action.document._id !== void 0 ? parseVersionId(action.document._id).releaseId : void 0);
|
|
1402
1455
|
if (releaseId === void 0)
|
|
1403
1456
|
throw fakeError(
|
|
@@ -1444,7 +1497,12 @@ async function applyAction(store, action) {
|
|
|
1444
1497
|
`Cannot publish "${action.publishedId}": draft "${action.draftId}" not found. document.publish promotes an existing draft onto the published id \u2014 create the draft first (e.g. client.createOrReplace({ _id: "${action.draftId}", ... })).`
|
|
1445
1498
|
);
|
|
1446
1499
|
const published = store.get(action.publishedId);
|
|
1447
|
-
requireRevisionMatch(action.draftId, draft._rev, action.ifDraftRevisionId), requireRevisionMatch(
|
|
1500
|
+
requireRevisionMatch(request, action.draftId, draft._rev, action.ifDraftRevisionId), requireRevisionMatch(
|
|
1501
|
+
request,
|
|
1502
|
+
action.publishedId,
|
|
1503
|
+
published?._rev,
|
|
1504
|
+
action.ifPublishedRevisionId
|
|
1505
|
+
);
|
|
1448
1506
|
const promoted = promote({ ...draft, _id: action.publishedId });
|
|
1449
1507
|
return published !== void 0 && (promoted._createdAt = published._createdAt), store.put(promoted), store.remove(action.draftId), { transactionId: cryptoRandomKey() };
|
|
1450
1508
|
}
|
|
@@ -1469,7 +1527,7 @@ function requireDraftOf(action) {
|
|
|
1469
1527
|
`${action.actionType}: draftId "${action.draftId}" is not the draft of publishedId "${action.publishedId}" \u2014 expected draftId "drafts.${action.publishedId}".`
|
|
1470
1528
|
);
|
|
1471
1529
|
}
|
|
1472
|
-
async function createVersionFromBase(store, action) {
|
|
1530
|
+
async function createVersionFromBase(store, action, request) {
|
|
1473
1531
|
const { releaseId, publishedId } = parseVersionId(action.versionId);
|
|
1474
1532
|
if (publishedId !== action.publishedId)
|
|
1475
1533
|
throw fakeError(
|
|
@@ -1481,7 +1539,7 @@ async function createVersionFromBase(store, action) {
|
|
|
1481
1539
|
throw fakeError(
|
|
1482
1540
|
`Cannot create version "${action.versionId}": base document "${action.baseId}" not found. version.create with \`baseId\` copies an existing document; pass \`document\` instead when there is nothing to copy.`
|
|
1483
1541
|
);
|
|
1484
|
-
requireRevisionMatch(action.baseId, base._rev, action.ifBaseRevisionId);
|
|
1542
|
+
requireRevisionMatch(request, action.baseId, base._rev, action.ifBaseRevisionId);
|
|
1485
1543
|
const existing = store.get(action.versionId), copy = {
|
|
1486
1544
|
...base,
|
|
1487
1545
|
_id: action.versionId,
|
|
@@ -1490,14 +1548,33 @@ async function createVersionFromBase(store, action) {
|
|
|
1490
1548
|
}, promoted = promote(copy);
|
|
1491
1549
|
return store.put(promoted), { transactionId: cryptoRandomKey() };
|
|
1492
1550
|
}
|
|
1493
|
-
|
|
1551
|
+
const ACTIONS_REQUEST = { method: "POST", path: "/data/actions" };
|
|
1552
|
+
function requireRevisionMatch(request, documentId, actualRev, expectedRev) {
|
|
1494
1553
|
if (!(expectedRev === void 0 || actualRev === expectedRev))
|
|
1495
|
-
throw
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1554
|
+
throw actualRev === void 0 ? new PlatformHttpError({
|
|
1555
|
+
...request,
|
|
1556
|
+
statusCode: 404,
|
|
1557
|
+
statusMessage: "Not Found",
|
|
1558
|
+
body: {
|
|
1559
|
+
error: {
|
|
1560
|
+
description: `The document with the ID ${JSON.stringify(documentId)} was not found`,
|
|
1561
|
+
id: documentId,
|
|
1562
|
+
type: "documentNotFoundError"
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
}) : new PlatformHttpError({
|
|
1566
|
+
...request,
|
|
1567
|
+
statusCode: 409,
|
|
1568
|
+
statusMessage: "Conflict",
|
|
1569
|
+
body: {
|
|
1570
|
+
error: {
|
|
1571
|
+
currentRevisionID: actualRev,
|
|
1572
|
+
description: `Document ${JSON.stringify(documentId)} has unexpected revision ID (${JSON.stringify(actualRev)}), expected ${JSON.stringify(expectedRev)}`,
|
|
1573
|
+
expectedRevisionID: expectedRev,
|
|
1574
|
+
type: "documentRevisionIDDoesNotMatchError"
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
});
|
|
1501
1578
|
}
|
|
1502
1579
|
async function applyActions(store, actions, hooks) {
|
|
1503
1580
|
const list = Array.isArray(actions) ? actions : [actions], snapshot = /* @__PURE__ */ new Map(), guardedIds = /* @__PURE__ */ new Set(), gatedIds = /* @__PURE__ */ new Set(), remember = (id) => {
|
|
@@ -1552,7 +1629,7 @@ async function applyActions(store, actions, hooks) {
|
|
|
1552
1629
|
remember(a.draftId), remember(a.publishedId), guardedIds.add(a.draftId), guardedIds.add(a.publishedId), gatedIds.add(a.publishedId), gatedIds.add(a.draftId);
|
|
1553
1630
|
break;
|
|
1554
1631
|
}
|
|
1555
|
-
last = await applyAction(store, a);
|
|
1632
|
+
last = await applyAction(store, a, hooks?.request);
|
|
1556
1633
|
}
|
|
1557
1634
|
for (const id of gatedIds) {
|
|
1558
1635
|
const before = snapshot.get(id), after = store.get(id);
|
|
@@ -1727,9 +1804,9 @@ function wrapNamespace(ns, prefix, onCall) {
|
|
|
1727
1804
|
}
|
|
1728
1805
|
});
|
|
1729
1806
|
}
|
|
1730
|
-
function wrapWithGuards(
|
|
1807
|
+
function wrapWithGuards(client2, config) {
|
|
1731
1808
|
const { getStub, onCall, recorded } = config;
|
|
1732
|
-
return new Proxy(
|
|
1809
|
+
return new Proxy(client2, {
|
|
1733
1810
|
get(target, prop, receiver) {
|
|
1734
1811
|
if (typeof prop == "symbol") return Reflect.get(target, prop, receiver);
|
|
1735
1812
|
if (prop in target) {
|
|
@@ -1956,10 +2033,14 @@ function makeHandle(handleArgs) {
|
|
|
1956
2033
|
if (access === void 0)
|
|
1957
2034
|
throw fakeError("this handle has no acting identity (no token or accessControl bound).");
|
|
1958
2035
|
return access;
|
|
1959
|
-
},
|
|
1960
|
-
if (token
|
|
1961
|
-
|
|
1962
|
-
|
|
2036
|
+
}, projectHosted = useProjectHostname && resource === void 0, refuseSession = (request) => {
|
|
2037
|
+
if (token === void 0) return;
|
|
2038
|
+
if (backend.revoked.has(token)) throw sessionNotFound(request);
|
|
2039
|
+
const tokenProjectId = backend.identities.get(token)?.projectId;
|
|
2040
|
+
if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
|
|
2041
|
+
throw sessionHostMismatch(request);
|
|
2042
|
+
}, withSession = (request) => async (opts) => (refuseSession({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
|
|
2043
|
+
refuseSession(request);
|
|
1963
2044
|
const access = activeAccess();
|
|
1964
2045
|
if (access === void 0) return;
|
|
1965
2046
|
const refusal = refusedToken(request, access.grants);
|
|
@@ -1979,13 +2060,13 @@ function makeHandle(handleArgs) {
|
|
|
1979
2060
|
if (access !== void 0)
|
|
1980
2061
|
return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
|
|
1981
2062
|
};
|
|
1982
|
-
let beforeWrite;
|
|
2063
|
+
let beforeWrite, writeRequest = DEFAULT_WRITE;
|
|
1983
2064
|
const write = (run, request = lakeRequest("POST", "mutate")) => serializeWrite(backend, async () => {
|
|
1984
|
-
admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
|
|
2065
|
+
admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc])), writeRequest = request;
|
|
1985
2066
|
try {
|
|
1986
2067
|
return await run();
|
|
1987
2068
|
} finally {
|
|
1988
|
-
beforeWrite = void 0;
|
|
2069
|
+
beforeWrite = void 0, writeRequest = DEFAULT_WRITE;
|
|
1989
2070
|
}
|
|
1990
2071
|
}), commitHistory = (transactionId) => {
|
|
1991
2072
|
beforeWrite !== void 0 && history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() });
|
|
@@ -2052,13 +2133,15 @@ function makeHandle(handleArgs) {
|
|
|
2052
2133
|
document,
|
|
2053
2134
|
grants: access.grants,
|
|
2054
2135
|
permission,
|
|
2055
|
-
userId: actorId()
|
|
2136
|
+
userId: actorId(),
|
|
2137
|
+
request: writeRequest
|
|
2056
2138
|
});
|
|
2057
2139
|
}, guardGate = async (contexts) => {
|
|
2058
2140
|
const identity = actorId();
|
|
2059
2141
|
await enforceMutationGuards(
|
|
2060
2142
|
mutationGuard,
|
|
2061
|
-
contexts.map((context) => ({ ...context, identity }))
|
|
2143
|
+
contexts.map((context) => ({ ...context, identity })),
|
|
2144
|
+
writeRequest
|
|
2062
2145
|
);
|
|
2063
2146
|
}, guardOne = async (action, before, after) => {
|
|
2064
2147
|
await guardGate([{ action, before, after }]);
|
|
@@ -2141,17 +2224,14 @@ function makeHandle(handleArgs) {
|
|
|
2141
2224
|
txnOptions?.returnFirst ?? !1
|
|
2142
2225
|
);
|
|
2143
2226
|
}, runAction = async (actions) => {
|
|
2144
|
-
const request =
|
|
2145
|
-
|
|
2146
|
-
path: `${capabilities.dataBase(target.id)}/actions`
|
|
2147
|
-
};
|
|
2148
|
-
if (refuseRevoked(request), capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2227
|
+
const request = lakeRequest("POST", "actions");
|
|
2228
|
+
if (refuseSession(request), capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2149
2229
|
return write(async () => {
|
|
2150
2230
|
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
2151
2231
|
const refused = capabilities.refusedActions[action.actionType];
|
|
2152
2232
|
if (refused !== void 0) throw refused(request);
|
|
2153
2233
|
}
|
|
2154
|
-
const result = await applyActions(store, actions, { gate, guard: guardGate });
|
|
2234
|
+
const result = await applyActions(store, actions, { gate, guard: guardGate, request });
|
|
2155
2235
|
return commitHistory(result.transactionId), result;
|
|
2156
2236
|
}, request);
|
|
2157
2237
|
}, accessVisibleDocs = async () => {
|
|
@@ -2164,7 +2244,7 @@ function makeHandle(handleArgs) {
|
|
|
2164
2244
|
}, visibleDocs = async (override) => {
|
|
2165
2245
|
const accessible = await accessVisibleDocs();
|
|
2166
2246
|
return applyPerspective(accessible, override ?? perspective);
|
|
2167
|
-
},
|
|
2247
|
+
}, client2 = {
|
|
2168
2248
|
fetch: async (query, params, opts) => {
|
|
2169
2249
|
admitToLake(lakeRequest("GET", "query"));
|
|
2170
2250
|
const start = Date.now(), tree = groqJs.parse(query, params ? { params } : void 0), result = await (await groqJs.evaluate(tree, {
|
|
@@ -2352,9 +2432,7 @@ function makeHandle(handleArgs) {
|
|
|
2352
2432
|
request: withSession(
|
|
2353
2433
|
makeRequestImpl({
|
|
2354
2434
|
getAccess: requireActiveAccess,
|
|
2355
|
-
|
|
2356
|
-
// client to the global API host.
|
|
2357
|
-
useProjectHostname: useProjectHostname && resource === void 0,
|
|
2435
|
+
useProjectHostname: projectHosted,
|
|
2358
2436
|
organizationId: backend.organizationId,
|
|
2359
2437
|
listIdentities: members,
|
|
2360
2438
|
platform: {
|
|
@@ -2373,6 +2451,7 @@ function makeHandle(handleArgs) {
|
|
|
2373
2451
|
return access.globalUser ?? access.currentUser;
|
|
2374
2452
|
},
|
|
2375
2453
|
actorAccess: () => requireActiveAccess().access,
|
|
2454
|
+
actorProjectId: () => token === void 0 ? void 0 : backend.identities.get(token)?.projectId,
|
|
2376
2455
|
identities: members,
|
|
2377
2456
|
resources: () => [...registry.values()].map((entry) => entry.resource)
|
|
2378
2457
|
}
|
|
@@ -2438,7 +2517,7 @@ function makeHandle(handleArgs) {
|
|
|
2438
2517
|
backend.calls.length = 0;
|
|
2439
2518
|
}
|
|
2440
2519
|
};
|
|
2441
|
-
return wrapWithGuards(
|
|
2520
|
+
return wrapWithGuards(client2, {
|
|
2442
2521
|
getStub: (name) => backend.stubs.get(name),
|
|
2443
2522
|
onCall: (method, args) => {
|
|
2444
2523
|
const rec = {
|