@sanity-labs/client-fake-for-test 0.17.2 → 0.18.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 +47 -2
- package/dist/index.cjs +157 -102
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +76 -39
- package/dist/index.d.ts +76 -39
- package/dist/index.js +153 -97
- package/dist/index.js.map +1 -1
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -7,6 +7,8 @@
|
|
|
7
7
|
npm install -D @sanity-labs/client-fake-for-test
|
|
8
8
|
```
|
|
9
9
|
|
|
10
|
+
`@sanity/client` (7.21 or later, or 8) is a peer dependency: the fake's HTTP errors extend its `ClientError`, so they need the copy your code imports. See [Errors are `ClientError`s](#errors-are-clienterrors).
|
|
11
|
+
|
|
10
12
|
## What this is for
|
|
11
13
|
|
|
12
14
|
Any code typed against `SanityClient` (or a narrow subset of its methods) that you want to test without:
|
|
@@ -77,7 +79,7 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
|
|
|
77
79
|
| Transaction | `transaction()` chain → `.commit()` | Mutations: `.create`, `.createOrReplace`, `.createIfNotExists`, `.delete`, `.patch(id, recipe)`. Atomic — any throw rolls back the whole batch. Default result is a `MultipleMutationResult` (`{ transactionId, documentIds, results }`) |
|
|
78
80
|
| Actions | `action(action \| action[])` | Content Lake release / version actions, applied atomically |
|
|
79
81
|
| Releases | `releases.*`, `createVersion`, `unpublishVersion` | Content Releases lifecycle — create / edit / schedule / publish / archive / delete, plus version create / replace / discard / unpublish. `createVersion({ baseId, publishedId, releaseId })` (or `version.create` with `baseId` + `versionId`) copies the base document, `_type` included, into the version and records it in `_system.base` (`{ id, rev }`); a missing base fails. With access control, `version.create` in either form needs `create` on the resulting version, or `update` on the version it replaces (as `createOrReplace` does), as the Content Lake does; the base is not access-checked. A failed revision precondition (`ifDraftRevisionId`, `ifPublishedRevisionId`, `ifBaseRevisionId`) carries `statusCode: 409`, as the Actions API answers |
|
|
80
|
-
| Config | `config()` | Returns `{ projectId
|
|
82
|
+
| Config | `config()` | Returns `{ projectId?, dataset, resource?, perspective, token?, useProjectHostname }`. `projectId` defaults to `"test"`, and is absent on a client created with `useProjectHostname: false` and no `projectId`, as `@sanity/client` leaves it unset there (its siblings too, until one names a project) |
|
|
81
83
|
| Config | `getDataUrl(operation, path?)` | The same URL `@sanity/client` builds: `<resource base>/<operation>/<path>` on a `resource` handle, `/data/<operation>/<dataset>/<path>` otherwise |
|
|
82
84
|
| Config | `withConfig({ projectId?, dataset?, resource?, perspective?, accessControl?, token?, useProjectHostname? })` | Sibling handle into the same multi-resource registry; `resource` points it at a Media Library, Canvas, dashboard or dataset (see [Resource types](#resource-types-media-library-canvas-dashboard)); `token` binds a registered identity (see the token→identity registry below), `accessControl` rebinds it inline — the two are mutually exclusive; `useProjectHostname: false` mints a global-hosted sibling |
|
|
83
85
|
| Perspectives | `raw` / `published` / `drafts` / release stacks / a single release name or comma-joined stack (`"rA"`, `"drafts,rA"`), as `@sanity/client` sends them | Per-client default or per-`fetch` override; draft/version layering with `_originalId` projection |
|
|
@@ -101,7 +103,7 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
|
|
|
101
103
|
|
|
102
104
|
`createTestClient({ mutationGuard })` installs a pluggable write interceptor. It runs once for each document's net change in a commit through the document mutation API — `create` / `createOrReplace` / `createIfNotExists` / `patch` / `delete` and the equivalent `transaction()` / `mutate()` operations. Document publish and unpublish actions are expanded into their published and draft mutations. Release and version actions (`releases.*`, `createVersion`, and `unpublishVersion`) are not intercepted.
|
|
103
105
|
|
|
104
|
-
The client owns the _seam_; the caller owns the _policy_. This is the hook a workflow test bench uses to enforce Content Lake **mutation guards** at the write path without re-implementing guard evaluation. Each call receives the original/final image (`before` is `null` on create, `after` is `null` on delete), the `action`, and the acting `identity`. Return every denying guard as `{ guardID, name? }`; the fake evaluates every net document mutation, aggregates the returned denials, deduplicates them by `guardID` in first-observed order, rolls back the commit, and throws
|
|
106
|
+
The client owns the _seam_; the caller owns the _policy_. This is the hook a workflow test bench uses to enforce Content Lake **mutation guards** at the write path without re-implementing guard evaluation. Each call receives the original/final image (`before` is `null` on create, `after` is `null` on delete), the `action`, and the acting `identity`. Return every denying guard as `{ guardID, name? }`; the fake evaluates every net document mutation, aggregates the returned denials, deduplicates them by `guardID` in first-observed order, rolls back the commit, and throws `GuardDeniedError`: the Content Lake's 403, a `ClientError` (see [Errors are `ClientError`s](#errors-are-clienterrors)), with `type: "guardDeniedError"` and `denials` on it. Other thrown callback errors propagate unchanged.
|
|
105
107
|
|
|
106
108
|
```ts
|
|
107
109
|
const client = createTestClient({
|
|
@@ -144,6 +146,34 @@ const bob = alice.withConfig({ token: "t-bob" });
|
|
|
144
146
|
|
|
145
147
|
Register more identities after creation with `client.addIdentity(token, { user, grants })` — an upsert into the family-shared registry; already-bound siblings resolve lazily and pick the change up immediately. For a one-off identity without a registry, `withConfig({ accessControl })` still works (mutually exclusive with `token` in the same call).
|
|
146
148
|
|
|
149
|
+
#### Unknown tokens and revoked tokens
|
|
150
|
+
|
|
151
|
+
The fake tells apart two kinds of bad token:
|
|
152
|
+
|
|
153
|
+
- **Unknown** (never registered): binding it (`createTestClient({ token })`, `withConfig({ token })`) throws at once. That is a mistake in the test setup, not something production answers.
|
|
154
|
+
- **Revoked** (`client.revokeIdentity(token)`): models a token the platform has no session for any more, because it was revoked, expired or deleted. The token stays registered and still binds, as production clients accept any string. From the next request on, every request made with it on any handle in the family is refused: `fetch`, `getDocument(s)`, every mutation, transaction and action (release and version actions included), `releases.get` / `releases.fetchDocuments`, and `request()` (`/users/me`, the ACL, the project and Access APIs, the History API). Nothing is written, and a write already queued is refused when its turn comes. Requests made before the call keep their answers, so "the first read succeeds, then the token is refused" is `await read(); client.revokeIdentity(token);`. Revocation is permanent; `addIdentity` does not restore the token.
|
|
155
|
+
|
|
156
|
+
The refusal is the platform's answer, probed on staging and production, raised as a `PlatformHttpError`, a `ClientError` (see [Errors are `ClientError`s](#errors-are-clienterrors)):
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
{
|
|
160
|
+
statusCode: 401,
|
|
161
|
+
message: "Unauthorized - Session not found",
|
|
162
|
+
details: undefined, // @sanity/client sets details only for `{ error: { … } }` bodies
|
|
163
|
+
responseBody: '{\n "error": "Unauthorized", …}', // the body, JSON.stringify(body, null, 2)
|
|
164
|
+
response: {
|
|
165
|
+
statusCode: 401,
|
|
166
|
+
statusMessage: "Unauthorized",
|
|
167
|
+
method: "GET", // or "POST" for mutations and actions
|
|
168
|
+
url: "/data/query/test", // the API path, without host or version
|
|
169
|
+
headers: { "content-type": "application/json; charset=utf-8" },
|
|
170
|
+
body: { error: "Unauthorized", errorCode: "SIO-401-ANF", message: "Session not found", statusCode: 401 },
|
|
171
|
+
},
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
The platform checks the session before it routes, so the 401 comes before a resource's 404 for a route it does not mount.
|
|
176
|
+
|
|
147
177
|
#### Token grants: filters and paths
|
|
148
178
|
|
|
149
179
|
A grant is either a GROQ `filter`, as a project's ACL serves it, or a `path` glob, as a token carries it (an internal token's `{ s, p }` grant is `{ path: s, permissions: p }`). The Content Lake holds a grant as one or the other and evaluates a path grant as `_id in path("<path>")` (gradient `pkg/security/models.go`): the id's dot-separated elements compare literally, `*` matches one element and a trailing `**` one or more. The fake matches `{ path }` grants the same way. A `path()` call inside a GROQ query or a `{ filter }` grant still runs through groq-js, which matches `.` there as any character:
|
|
@@ -182,6 +212,8 @@ Filter grants come from the ACL, not the token, and are not checked. `/users/me`
|
|
|
182
212
|
|
|
183
213
|
The fake checks every written document the way the Content Lake does (gradient `pkg/security/document_permission_checker.go`): a create needs `create` on the new document; an update, replace or patch needs `update` on the document before the write **and** on the document after it; a delete needs `update` on the document before. So a patch or `createOrReplace` that moves a document out of the identity's `update` grant (a filter it stops matching) is refused with `WriteAccessDeniedError`, and nothing is written. The same holds for `version.create` replacing a version and for the documents `document.publish` / `document.unpublish` write and delete. A transaction, `mutate` or action batch is checked per document on its net change once every mutation is staged, so a document patched out of the grant and back again in one transaction passes, and one created and deleted in it is not checked. Reads inside a write are not checked.
|
|
184
214
|
|
|
215
|
+
The refusal is the Content Lake's 403, a `ClientError` with the `insufficientPermissionsError` wrapped in a `mutationError`, as gradient writes it; `message` is `transaction failed: Insufficient permissions; permission "update" required` followed by the item. The error also carries `documentId`, `permission` and `matchingGrants`, which the platform's answer does not name.
|
|
216
|
+
|
|
185
217
|
#### System-document grants
|
|
186
218
|
|
|
187
219
|
User-issued writes to system document IDs beginning with `_.` require the `manage` permission **in addition to** the `create` or `update` the write needs, each checked on the same documents (before and after the write), as the Content Lake's permission checker does. `create` and `update` alone do not authorize these writes, and neither does `manage` alone; grant `manage` alongside `create` / `update` to identities whose tests intentionally create, replace, patch, delete, transact, mutate, publish, or unpublish system documents. The fake's internal release/version bookkeeping remains outside access-control interception.
|
|
@@ -252,6 +284,18 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
|
|
|
252
284
|
- **Project features.** `GET /projects/<projectId>/features` answers the project's feature names as a bare array, sorted and once each, as the project API does. Seed them with `createTestClient({ projectFeatures: { "<projectId>": ["advancedRolesManagement"] } })`; a project without an entry has no features and answers `[]`. Like `/projects/<projectId>`, it answers any project id to any acting identity: the platform lets any project member read it, and every identity is a member of every project.
|
|
253
285
|
- **Identity.** `@sanity/client` sends a `resource` client's requests to the global host, so `/users/me` answers `globalUser`.
|
|
254
286
|
|
|
287
|
+
### Errors are `ClientError`s
|
|
288
|
+
|
|
289
|
+
Every error the fake throws for an HTTP answer of the platform is an instance of `@sanity/client`'s `ClientError`, so code that branches on `error instanceof ClientError` handles it as it handles production's:
|
|
290
|
+
|
|
291
|
+
| Class | Answer |
|
|
292
|
+
| --- | --- |
|
|
293
|
+
| `PlatformHttpError` | the platform's refusals: a revoked token's 401, a token grant the Content Lake cannot parse (400), the Access API's 400/403/404, a route a resource does not mount (404), a Media Library release (403), an action's failed `if…RevisionId` precondition (409 `documentRevisionIDDoesNotMatchError`, or 404 `documentNotFoundError` when the document is missing) |
|
|
294
|
+
| `WriteAccessDeniedError` | a write the grants do not permit (403) |
|
|
295
|
+
| `GuardDeniedError` | a write a mutation guard denies (403) |
|
|
296
|
+
|
|
297
|
+
The fake hands `ClientError` the response the platform sends, and `ClientError` derives `statusCode`, `message`, `responseBody` and `details` from it, exactly as for a real response. `instanceof` needs the fake and your code to share one `@sanity/client`, so it is a peer dependency (7.21 or later, or 8); with several copies installed, dedupe them. Mistakes in a test's setup (an unknown token, a document without `_id`, an unimplemented member) stay plain `Error`s prefixed `[client-fake-for-test]`, as do refusals whose platform answer the fake does not model yet (a mutation's existing id, missing target or `ifRevisionId` mismatch, an unknown id at `/projects/<projectId>/users/<id>`, which carries `statusCode: 404`).
|
|
298
|
+
|
|
255
299
|
### Test-only helpers (not on real `SanityClient`)
|
|
256
300
|
|
|
257
301
|
Useful in test bodies, but a giveaway that the code under test isn't using the real client. Keep them in the test file, not in the code being tested.
|
|
@@ -275,6 +319,7 @@ Useful in test bodies, but a giveaway that the code under test isn't using the r
|
|
|
275
319
|
| `client.stubs()` | The currently-registered stubs |
|
|
276
320
|
| `client.addIdentity(token, identity)` | Register (upsert) a token→identity entry in the family-shared registry |
|
|
277
321
|
| `client.identities()` | Snapshot of the registered token→identity entries |
|
|
322
|
+
| `client.revokeIdentity(token)` | Make every later request on a registered token answer 401 `Session not found` (see [Unknown tokens and revoked tokens](#unknown-tokens-and-revoked-tokens)) |
|
|
278
323
|
| `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
|
|
279
324
|
| `createTestClient({ resources: { "media-library:ml1": [...] } })` | Seed any resource type up front; keys are `"<type>:<id>"` |
|
|
280
325
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,36 +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
|
-
|
|
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
|
+
};
|
|
22
23
|
}
|
|
23
|
-
function
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
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
|
+
});
|
|
32
37
|
}
|
|
33
|
-
const notMounted = ({ method, path }) => new PlatformHttpError({
|
|
38
|
+
const DEFAULT_WRITE = { method: "POST", path: "/data/mutate" }, notMounted = ({ method, path }) => new PlatformHttpError({
|
|
34
39
|
method,
|
|
35
40
|
path,
|
|
36
41
|
statusCode: 404,
|
|
@@ -46,7 +51,17 @@ function accessApiError(args) {
|
|
|
46
51
|
body: { statusCode, error: statusMessage, message }
|
|
47
52
|
});
|
|
48
53
|
}
|
|
49
|
-
const
|
|
54
|
+
const sessionNotFound = (request) => new PlatformHttpError({
|
|
55
|
+
...request,
|
|
56
|
+
statusCode: 401,
|
|
57
|
+
statusMessage: "Unauthorized",
|
|
58
|
+
body: {
|
|
59
|
+
error: "Unauthorized",
|
|
60
|
+
errorCode: "SIO-401-ANF",
|
|
61
|
+
message: "Session not found",
|
|
62
|
+
statusCode: 401
|
|
63
|
+
}
|
|
64
|
+
}), noPermission = (request) => accessApiError({
|
|
50
65
|
request,
|
|
51
66
|
statusCode: 403,
|
|
52
67
|
statusMessage: "Forbidden",
|
|
@@ -681,13 +696,17 @@ function attributeRecord(attribute) {
|
|
|
681
696
|
);
|
|
682
697
|
return { type, key, values: { ...values }, activeSource, activeValue };
|
|
683
698
|
}
|
|
684
|
-
class WriteAccessDeniedError extends
|
|
699
|
+
class WriteAccessDeniedError extends client.ClientError {
|
|
685
700
|
documentId;
|
|
686
701
|
permission;
|
|
687
702
|
matchingGrants;
|
|
688
703
|
constructor(args) {
|
|
689
704
|
super(
|
|
690
|
-
|
|
705
|
+
transactionRefused(args.request ?? DEFAULT_WRITE, {
|
|
706
|
+
description: `Insufficient permissions; permission "${args.permission}" required`,
|
|
707
|
+
permission: args.permission,
|
|
708
|
+
type: "insufficientPermissionsError"
|
|
709
|
+
})
|
|
691
710
|
), this.name = "WriteAccessDeniedError", this.documentId = args.documentId, this.permission = args.permission, this.matchingGrants = args.matchingGrants;
|
|
692
711
|
}
|
|
693
712
|
}
|
|
@@ -717,7 +736,7 @@ async function evaluateWriteAccess(args) {
|
|
|
717
736
|
return { allowed: !1, matchingGrants: matching };
|
|
718
737
|
}
|
|
719
738
|
async function enforceWriteAccess(args) {
|
|
720
|
-
const { document, grants, permission, userId } = args, { allowed, matchingGrants } = await evaluateWriteAccess({
|
|
739
|
+
const { document, grants, permission, userId, request } = args, { allowed, matchingGrants } = await evaluateWriteAccess({
|
|
721
740
|
document,
|
|
722
741
|
grants,
|
|
723
742
|
permission,
|
|
@@ -727,11 +746,13 @@ async function enforceWriteAccess(args) {
|
|
|
727
746
|
throw typeof document._id != "string" ? new WriteAccessDeniedError({
|
|
728
747
|
documentId: "(unknown)",
|
|
729
748
|
permission,
|
|
730
|
-
matchingGrants
|
|
749
|
+
matchingGrants,
|
|
750
|
+
request
|
|
731
751
|
}) : new WriteAccessDeniedError({
|
|
732
752
|
documentId: document._id,
|
|
733
753
|
permission,
|
|
734
|
-
matchingGrants
|
|
754
|
+
matchingGrants,
|
|
755
|
+
request
|
|
735
756
|
});
|
|
736
757
|
}
|
|
737
758
|
function defaultAclPath(projectId, dataset) {
|
|
@@ -841,24 +862,24 @@ function makeRequestImpl(ctx) {
|
|
|
841
862
|
);
|
|
842
863
|
};
|
|
843
864
|
}
|
|
844
|
-
class GuardDeniedError extends
|
|
845
|
-
statusCode = 403;
|
|
865
|
+
class GuardDeniedError extends client.ClientError {
|
|
846
866
|
type = "guardDeniedError";
|
|
847
867
|
denials;
|
|
848
|
-
|
|
849
|
-
response;
|
|
850
|
-
constructor(denials) {
|
|
868
|
+
constructor(denials, request = DEFAULT_WRITE) {
|
|
851
869
|
const unique = uniqueDenials(denials);
|
|
852
|
-
super(
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
};
|
|
870
|
+
super(
|
|
871
|
+
transactionRefused(request, {
|
|
872
|
+
description: guardDeniedDescription(unique),
|
|
873
|
+
denials: unique,
|
|
874
|
+
type: "guardDeniedError"
|
|
875
|
+
})
|
|
876
|
+
), this.name = "GuardDeniedError", this.denials = unique;
|
|
860
877
|
}
|
|
861
878
|
}
|
|
879
|
+
function guardDeniedDescription(denials) {
|
|
880
|
+
const named = denials.map(({ guardID, name }) => name ? `${guardID} (${name})` : guardID);
|
|
881
|
+
return `mutation denied by ${denials.length} guard(s): ${named.join(" ")}`;
|
|
882
|
+
}
|
|
862
883
|
function uniqueDenials(denials) {
|
|
863
884
|
const seen = /* @__PURE__ */ new Set();
|
|
864
885
|
return denials.filter((denial) => seen.has(denial.guardID) ? !1 : (seen.add(denial.guardID), !0));
|
|
@@ -874,14 +895,14 @@ function mutationContexts(images) {
|
|
|
874
895
|
return context === void 0 ? [] : [context];
|
|
875
896
|
});
|
|
876
897
|
}
|
|
877
|
-
async function enforceMutationGuards(guard, contexts) {
|
|
898
|
+
async function enforceMutationGuards(guard, contexts, request) {
|
|
878
899
|
if (guard === void 0) return;
|
|
879
900
|
const denials = [];
|
|
880
901
|
for (const context of contexts) {
|
|
881
902
|
const denied = await guard(context);
|
|
882
903
|
denied !== void 0 && denials.push(...denied);
|
|
883
904
|
}
|
|
884
|
-
if (denials.length > 0) throw new GuardDeniedError(denials);
|
|
905
|
+
if (denials.length > 0) throw new GuardDeniedError(denials, request);
|
|
885
906
|
}
|
|
886
907
|
function describeType(value) {
|
|
887
908
|
return value === null ? "null" : Array.isArray(value) ? "an array" : `a ${typeof value}`;
|
|
@@ -1279,7 +1300,7 @@ function requireActive(release) {
|
|
|
1279
1300
|
`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.`
|
|
1280
1301
|
);
|
|
1281
1302
|
}
|
|
1282
|
-
async function applyAction(store, action) {
|
|
1303
|
+
async function applyAction(store, action, request = ACTIONS_REQUEST) {
|
|
1283
1304
|
switch (action.actionType) {
|
|
1284
1305
|
case "sanity.action.release.create": {
|
|
1285
1306
|
if (maybeRelease(store, action.releaseId) !== void 0)
|
|
@@ -1383,7 +1404,7 @@ async function applyAction(store, action) {
|
|
|
1383
1404
|
return store.remove(release._id), { transactionId: cryptoRandomKey() };
|
|
1384
1405
|
}
|
|
1385
1406
|
case "sanity.action.document.version.create": {
|
|
1386
|
-
if ("baseId" in action) return createVersionFromBase(store, action);
|
|
1407
|
+
if ("baseId" in action) return createVersionFromBase(store, action, request);
|
|
1387
1408
|
const releaseId = action.releaseId ?? (action.document._id !== void 0 ? parseVersionId(action.document._id).releaseId : void 0);
|
|
1388
1409
|
if (releaseId === void 0)
|
|
1389
1410
|
throw fakeError(
|
|
@@ -1430,7 +1451,12 @@ async function applyAction(store, action) {
|
|
|
1430
1451
|
`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}", ... })).`
|
|
1431
1452
|
);
|
|
1432
1453
|
const published = store.get(action.publishedId);
|
|
1433
|
-
requireRevisionMatch(action.draftId, draft._rev, action.ifDraftRevisionId), requireRevisionMatch(
|
|
1454
|
+
requireRevisionMatch(request, action.draftId, draft._rev, action.ifDraftRevisionId), requireRevisionMatch(
|
|
1455
|
+
request,
|
|
1456
|
+
action.publishedId,
|
|
1457
|
+
published?._rev,
|
|
1458
|
+
action.ifPublishedRevisionId
|
|
1459
|
+
);
|
|
1434
1460
|
const promoted = promote({ ...draft, _id: action.publishedId });
|
|
1435
1461
|
return published !== void 0 && (promoted._createdAt = published._createdAt), store.put(promoted), store.remove(action.draftId), { transactionId: cryptoRandomKey() };
|
|
1436
1462
|
}
|
|
@@ -1455,7 +1481,7 @@ function requireDraftOf(action) {
|
|
|
1455
1481
|
`${action.actionType}: draftId "${action.draftId}" is not the draft of publishedId "${action.publishedId}" \u2014 expected draftId "drafts.${action.publishedId}".`
|
|
1456
1482
|
);
|
|
1457
1483
|
}
|
|
1458
|
-
async function createVersionFromBase(store, action) {
|
|
1484
|
+
async function createVersionFromBase(store, action, request) {
|
|
1459
1485
|
const { releaseId, publishedId } = parseVersionId(action.versionId);
|
|
1460
1486
|
if (publishedId !== action.publishedId)
|
|
1461
1487
|
throw fakeError(
|
|
@@ -1467,7 +1493,7 @@ async function createVersionFromBase(store, action) {
|
|
|
1467
1493
|
throw fakeError(
|
|
1468
1494
|
`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.`
|
|
1469
1495
|
);
|
|
1470
|
-
requireRevisionMatch(action.baseId, base._rev, action.ifBaseRevisionId);
|
|
1496
|
+
requireRevisionMatch(request, action.baseId, base._rev, action.ifBaseRevisionId);
|
|
1471
1497
|
const existing = store.get(action.versionId), copy = {
|
|
1472
1498
|
...base,
|
|
1473
1499
|
_id: action.versionId,
|
|
@@ -1476,14 +1502,33 @@ async function createVersionFromBase(store, action) {
|
|
|
1476
1502
|
}, promoted = promote(copy);
|
|
1477
1503
|
return store.put(promoted), { transactionId: cryptoRandomKey() };
|
|
1478
1504
|
}
|
|
1479
|
-
|
|
1505
|
+
const ACTIONS_REQUEST = { method: "POST", path: "/data/actions" };
|
|
1506
|
+
function requireRevisionMatch(request, documentId, actualRev, expectedRev) {
|
|
1480
1507
|
if (!(expectedRev === void 0 || actualRev === expectedRev))
|
|
1481
|
-
throw
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1508
|
+
throw actualRev === void 0 ? new PlatformHttpError({
|
|
1509
|
+
...request,
|
|
1510
|
+
statusCode: 404,
|
|
1511
|
+
statusMessage: "Not Found",
|
|
1512
|
+
body: {
|
|
1513
|
+
error: {
|
|
1514
|
+
description: `The document with the ID ${JSON.stringify(documentId)} was not found`,
|
|
1515
|
+
id: documentId,
|
|
1516
|
+
type: "documentNotFoundError"
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
}) : new PlatformHttpError({
|
|
1520
|
+
...request,
|
|
1521
|
+
statusCode: 409,
|
|
1522
|
+
statusMessage: "Conflict",
|
|
1523
|
+
body: {
|
|
1524
|
+
error: {
|
|
1525
|
+
currentRevisionID: actualRev,
|
|
1526
|
+
description: `Document ${JSON.stringify(documentId)} has unexpected revision ID (${JSON.stringify(actualRev)}), expected ${JSON.stringify(expectedRev)}`,
|
|
1527
|
+
expectedRevisionID: expectedRev,
|
|
1528
|
+
type: "documentRevisionIDDoesNotMatchError"
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
});
|
|
1487
1532
|
}
|
|
1488
1533
|
async function applyActions(store, actions, hooks) {
|
|
1489
1534
|
const list = Array.isArray(actions) ? actions : [actions], snapshot = /* @__PURE__ */ new Map(), guardedIds = /* @__PURE__ */ new Set(), gatedIds = /* @__PURE__ */ new Set(), remember = (id) => {
|
|
@@ -1538,7 +1583,7 @@ async function applyActions(store, actions, hooks) {
|
|
|
1538
1583
|
remember(a.draftId), remember(a.publishedId), guardedIds.add(a.draftId), guardedIds.add(a.publishedId), gatedIds.add(a.publishedId), gatedIds.add(a.draftId);
|
|
1539
1584
|
break;
|
|
1540
1585
|
}
|
|
1541
|
-
last = await applyAction(store, a);
|
|
1586
|
+
last = await applyAction(store, a, hooks?.request);
|
|
1542
1587
|
}
|
|
1543
1588
|
for (const id of gatedIds) {
|
|
1544
1589
|
const before = snapshot.get(id), after = store.get(id);
|
|
@@ -1713,9 +1758,9 @@ function wrapNamespace(ns, prefix, onCall) {
|
|
|
1713
1758
|
}
|
|
1714
1759
|
});
|
|
1715
1760
|
}
|
|
1716
|
-
function wrapWithGuards(
|
|
1761
|
+
function wrapWithGuards(client2, config) {
|
|
1717
1762
|
const { getStub, onCall, recorded } = config;
|
|
1718
|
-
return new Proxy(
|
|
1763
|
+
return new Proxy(client2, {
|
|
1719
1764
|
get(target, prop, receiver) {
|
|
1720
1765
|
if (typeof prop == "symbol") return Reflect.get(target, prop, receiver);
|
|
1721
1766
|
if (prop in target) {
|
|
@@ -1836,6 +1881,7 @@ function createTestClient(options = {}) {
|
|
|
1836
1881
|
calls: [],
|
|
1837
1882
|
concurrentEdits: /* @__PURE__ */ new Map(),
|
|
1838
1883
|
identities: new Map(Object.entries(options.identities ?? {})),
|
|
1884
|
+
revoked: /* @__PURE__ */ new Set(),
|
|
1839
1885
|
writeChain: Promise.resolve()
|
|
1840
1886
|
}, registry = backend.registry;
|
|
1841
1887
|
if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
|
|
@@ -1860,7 +1906,8 @@ function createTestClient(options = {}) {
|
|
|
1860
1906
|
requestTagPrefix: options.requestTagPrefix,
|
|
1861
1907
|
mutationGuard: options.mutationGuard,
|
|
1862
1908
|
token: options.token,
|
|
1863
|
-
useProjectHostname: options.useProjectHostname ?? !0
|
|
1909
|
+
useProjectHostname: options.useProjectHostname ?? !0,
|
|
1910
|
+
hasProjectId: options.projectId !== void 0
|
|
1864
1911
|
});
|
|
1865
1912
|
}
|
|
1866
1913
|
function dedupeIds(results) {
|
|
@@ -1923,7 +1970,7 @@ function makeHandle(handleArgs) {
|
|
|
1923
1970
|
mutationGuard,
|
|
1924
1971
|
token,
|
|
1925
1972
|
useProjectHostname
|
|
1926
|
-
} = handleArgs, { registry } = backend, { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = resource ?? datasetResource(projectId, dataset), activeAccess = () => {
|
|
1973
|
+
} = handleArgs, { registry } = backend, hasProjectId = handleArgs.hasProjectId || useProjectHostname && resource === void 0 || resource?.type === "dataset", { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = resource ?? datasetResource(projectId, dataset), activeAccess = () => {
|
|
1927
1974
|
if (token === void 0) return accessControl;
|
|
1928
1975
|
const identity = backend.identities.get(token);
|
|
1929
1976
|
if (identity === void 0)
|
|
@@ -1940,7 +1987,10 @@ function makeHandle(handleArgs) {
|
|
|
1940
1987
|
if (access === void 0)
|
|
1941
1988
|
throw fakeError("this handle has no acting identity (no token or accessControl bound).");
|
|
1942
1989
|
return access;
|
|
1943
|
-
},
|
|
1990
|
+
}, refuseRevoked = (request) => {
|
|
1991
|
+
if (token !== void 0 && backend.revoked.has(token)) throw sessionNotFound(request);
|
|
1992
|
+
}, withSession = (request) => async (opts) => (refuseRevoked({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
|
|
1993
|
+
refuseRevoked(request);
|
|
1944
1994
|
const access = activeAccess();
|
|
1945
1995
|
if (access === void 0) return;
|
|
1946
1996
|
const refusal = refusedToken(request, access.grants);
|
|
@@ -1960,13 +2010,13 @@ function makeHandle(handleArgs) {
|
|
|
1960
2010
|
if (access !== void 0)
|
|
1961
2011
|
return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
|
|
1962
2012
|
};
|
|
1963
|
-
let beforeWrite;
|
|
2013
|
+
let beforeWrite, writeRequest = DEFAULT_WRITE;
|
|
1964
2014
|
const write = (run, request = lakeRequest("POST", "mutate")) => serializeWrite(backend, async () => {
|
|
1965
|
-
admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
|
|
2015
|
+
admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc])), writeRequest = request;
|
|
1966
2016
|
try {
|
|
1967
2017
|
return await run();
|
|
1968
2018
|
} finally {
|
|
1969
|
-
beforeWrite = void 0;
|
|
2019
|
+
beforeWrite = void 0, writeRequest = DEFAULT_WRITE;
|
|
1970
2020
|
}
|
|
1971
2021
|
}), commitHistory = (transactionId) => {
|
|
1972
2022
|
beforeWrite !== void 0 && history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() });
|
|
@@ -2033,13 +2083,15 @@ function makeHandle(handleArgs) {
|
|
|
2033
2083
|
document,
|
|
2034
2084
|
grants: access.grants,
|
|
2035
2085
|
permission,
|
|
2036
|
-
userId: actorId()
|
|
2086
|
+
userId: actorId(),
|
|
2087
|
+
request: writeRequest
|
|
2037
2088
|
});
|
|
2038
2089
|
}, guardGate = async (contexts) => {
|
|
2039
2090
|
const identity = actorId();
|
|
2040
2091
|
await enforceMutationGuards(
|
|
2041
2092
|
mutationGuard,
|
|
2042
|
-
contexts.map((context) => ({ ...context, identity }))
|
|
2093
|
+
contexts.map((context) => ({ ...context, identity })),
|
|
2094
|
+
writeRequest
|
|
2043
2095
|
);
|
|
2044
2096
|
}, guardOne = async (action, before, after) => {
|
|
2045
2097
|
await guardGate([{ action, before, after }]);
|
|
@@ -2122,17 +2174,14 @@ function makeHandle(handleArgs) {
|
|
|
2122
2174
|
txnOptions?.returnFirst ?? !1
|
|
2123
2175
|
);
|
|
2124
2176
|
}, runAction = async (actions) => {
|
|
2125
|
-
const request =
|
|
2126
|
-
|
|
2127
|
-
path: `${capabilities.dataBase(target.id)}/actions`
|
|
2128
|
-
};
|
|
2129
|
-
if (capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2177
|
+
const request = lakeRequest("POST", "actions");
|
|
2178
|
+
if (refuseRevoked(request), capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2130
2179
|
return write(async () => {
|
|
2131
2180
|
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
2132
2181
|
const refused = capabilities.refusedActions[action.actionType];
|
|
2133
2182
|
if (refused !== void 0) throw refused(request);
|
|
2134
2183
|
}
|
|
2135
|
-
const result = await applyActions(store, actions, { gate, guard: guardGate });
|
|
2184
|
+
const result = await applyActions(store, actions, { gate, guard: guardGate, request });
|
|
2136
2185
|
return commitHistory(result.transactionId), result;
|
|
2137
2186
|
}, request);
|
|
2138
2187
|
}, accessVisibleDocs = async () => {
|
|
@@ -2145,7 +2194,7 @@ function makeHandle(handleArgs) {
|
|
|
2145
2194
|
}, visibleDocs = async (override) => {
|
|
2146
2195
|
const accessible = await accessVisibleDocs();
|
|
2147
2196
|
return applyPerspective(accessible, override ?? perspective);
|
|
2148
|
-
},
|
|
2197
|
+
}, client2 = {
|
|
2149
2198
|
fetch: async (query, params, opts) => {
|
|
2150
2199
|
admitToLake(lakeRequest("GET", "query"));
|
|
2151
2200
|
const start = Date.now(), tree = groqJs.parse(query, params ? { params } : void 0), result = await (await groqJs.evaluate(tree, {
|
|
@@ -2330,36 +2379,38 @@ function makeHandle(handleArgs) {
|
|
|
2330
2379
|
publishedId
|
|
2331
2380
|
}),
|
|
2332
2381
|
...token !== void 0 || accessControl !== void 0 ? {
|
|
2333
|
-
request:
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
listIdentities: members,
|
|
2340
|
-
platform: {
|
|
2341
|
-
projectId,
|
|
2382
|
+
request: withSession(
|
|
2383
|
+
makeRequestImpl({
|
|
2384
|
+
getAccess: requireActiveAccess,
|
|
2385
|
+
// `@sanity/client` sends every request of a `resource`-configured
|
|
2386
|
+
// client to the global API host.
|
|
2387
|
+
useProjectHostname: useProjectHostname && resource === void 0,
|
|
2342
2388
|
organizationId: backend.organizationId,
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2389
|
+
listIdentities: members,
|
|
2390
|
+
platform: {
|
|
2391
|
+
projectId,
|
|
2392
|
+
organizationId: backend.organizationId,
|
|
2393
|
+
projectFeatures: backend.projectFeatures,
|
|
2394
|
+
own: (asked) => registryKey(asked) === registryKey(target) ? {
|
|
2395
|
+
grants: requireActiveAccess().grants,
|
|
2396
|
+
documents: () => store.all(),
|
|
2397
|
+
history,
|
|
2398
|
+
canRead,
|
|
2399
|
+
admitToLake
|
|
2400
|
+
} : void 0,
|
|
2401
|
+
actorUser: () => {
|
|
2402
|
+
const access = requireActiveAccess();
|
|
2403
|
+
return access.globalUser ?? access.currentUser;
|
|
2404
|
+
},
|
|
2405
|
+
actorAccess: () => requireActiveAccess().access,
|
|
2406
|
+
identities: members,
|
|
2407
|
+
resources: () => [...registry.values()].map((entry) => entry.resource)
|
|
2408
|
+
}
|
|
2409
|
+
})
|
|
2410
|
+
)
|
|
2360
2411
|
} : {},
|
|
2361
2412
|
config: () => ({
|
|
2362
|
-
projectId,
|
|
2413
|
+
...hasProjectId || resource !== void 0 ? { projectId } : {},
|
|
2363
2414
|
dataset,
|
|
2364
2415
|
...resource !== void 0 ? { resource } : {},
|
|
2365
2416
|
perspective,
|
|
@@ -2380,7 +2431,8 @@ function makeHandle(handleArgs) {
|
|
|
2380
2431
|
requestTagPrefix: config.requestTagPrefix ?? requestTagPrefix,
|
|
2381
2432
|
mutationGuard,
|
|
2382
2433
|
token: rebinds ? config.token : token,
|
|
2383
|
-
useProjectHostname: config.useProjectHostname ?? useProjectHostname
|
|
2434
|
+
useProjectHostname: config.useProjectHostname ?? useProjectHostname,
|
|
2435
|
+
hasProjectId: hasProjectId || config.projectId !== void 0
|
|
2384
2436
|
});
|
|
2385
2437
|
},
|
|
2386
2438
|
seed: (documents) => store.seed(documents),
|
|
@@ -2402,6 +2454,9 @@ function makeHandle(handleArgs) {
|
|
|
2402
2454
|
backend.identities.set(identityToken, identity);
|
|
2403
2455
|
},
|
|
2404
2456
|
identities: () => Object.fromEntries(backend.identities),
|
|
2457
|
+
revokeIdentity: (revokedToken) => {
|
|
2458
|
+
requireIdentity(backend, revokedToken, "revokeIdentity()"), backend.revoked.add(revokedToken);
|
|
2459
|
+
},
|
|
2405
2460
|
mutations: () => backend.log.flatMap((entry) => entry.mutations),
|
|
2406
2461
|
transactions: () => [...backend.log],
|
|
2407
2462
|
clearLog: () => {
|
|
@@ -2413,7 +2468,7 @@ function makeHandle(handleArgs) {
|
|
|
2413
2468
|
backend.calls.length = 0;
|
|
2414
2469
|
}
|
|
2415
2470
|
};
|
|
2416
|
-
return wrapWithGuards(
|
|
2471
|
+
return wrapWithGuards(client2, {
|
|
2417
2472
|
getStub: (name) => backend.stubs.get(name),
|
|
2418
2473
|
onCall: (method, args) => {
|
|
2419
2474
|
const rec = {
|