@sanity-labs/client-fake-for-test 0.17.1 → 0.17.3
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 +35 -2
- package/dist/index.cjs +113 -75
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -1
- package/dist/index.d.ts +14 -1
- package/dist/index.js +113 -75
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -77,7 +77,7 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
|
|
|
77
77
|
| 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
78
|
| Actions | `action(action \| action[])` | Content Lake release / version actions, applied atomically |
|
|
79
79
|
| 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
|
|
80
|
+
| 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
81
|
| Config | `getDataUrl(operation, path?)` | The same URL `@sanity/client` builds: `<resource base>/<operation>/<path>` on a `resource` handle, `/data/<operation>/<dataset>/<path>` otherwise |
|
|
82
82
|
| 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
83
|
| 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 |
|
|
@@ -144,6 +144,34 @@ const bob = alice.withConfig({ token: "t-bob" });
|
|
|
144
144
|
|
|
145
145
|
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
146
|
|
|
147
|
+
#### Unknown tokens and revoked tokens
|
|
148
|
+
|
|
149
|
+
The fake tells apart two kinds of bad token:
|
|
150
|
+
|
|
151
|
+
- **Unknown** (never registered): binding it (`createTestClient({ token })`, `withConfig({ token })`) throws at once. That is a mistake in the test setup, not something production answers.
|
|
152
|
+
- **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.
|
|
153
|
+
|
|
154
|
+
The refusal is the platform's answer, probed on staging and production, raised as a `PlatformHttpError` shaped like `@sanity/client`'s `ClientError`:
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
{
|
|
158
|
+
statusCode: 401,
|
|
159
|
+
message: "Unauthorized - Session not found",
|
|
160
|
+
details: undefined, // @sanity/client sets details only for `{ error: { … } }` bodies
|
|
161
|
+
responseBody: '{\n "error": "Unauthorized", …}', // the body, JSON.stringify(body, null, 2)
|
|
162
|
+
response: {
|
|
163
|
+
statusCode: 401,
|
|
164
|
+
statusMessage: "Unauthorized",
|
|
165
|
+
method: "GET", // or "POST" for mutations and actions
|
|
166
|
+
url: "/data/query/test", // the API path, without host or version
|
|
167
|
+
headers: {},
|
|
168
|
+
body: { error: "Unauthorized", errorCode: "SIO-401-ANF", message: "Session not found", statusCode: 401 },
|
|
169
|
+
},
|
|
170
|
+
}
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
The platform checks the session before it routes, so the 401 comes before a resource's 404 for a route it does not mount.
|
|
174
|
+
|
|
147
175
|
#### Token grants: filters and paths
|
|
148
176
|
|
|
149
177
|
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:
|
|
@@ -178,9 +206,13 @@ The Content Lake parses a token's path grants on every request it serves and ref
|
|
|
178
206
|
|
|
179
207
|
Filter grants come from the ACL, not the token, and are not checked. `/users/me`, the project API (`/projects/…`), the Access API and the ACL are not the Content Lake's and do not read a token's grants, so they keep answering.
|
|
180
208
|
|
|
209
|
+
#### Which permission a write needs
|
|
210
|
+
|
|
211
|
+
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.
|
|
212
|
+
|
|
181
213
|
#### System-document grants
|
|
182
214
|
|
|
183
|
-
User-issued writes to system document IDs beginning with `_.` require the `manage` permission
|
|
215
|
+
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.
|
|
184
216
|
|
|
185
217
|
#### Dual-namespace identities: global vs project user ids
|
|
186
218
|
|
|
@@ -271,6 +303,7 @@ Useful in test bodies, but a giveaway that the code under test isn't using the r
|
|
|
271
303
|
| `client.stubs()` | The currently-registered stubs |
|
|
272
304
|
| `client.addIdentity(token, identity)` | Register (upsert) a token→identity entry in the family-shared registry |
|
|
273
305
|
| `client.identities()` | Snapshot of the registered token→identity entries |
|
|
306
|
+
| `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)) |
|
|
274
307
|
| `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
|
|
275
308
|
| `createTestClient({ resources: { "media-library:ml1": [...] } })` | Seed any resource type up front; keys are `"<type>:<id>"` |
|
|
276
309
|
|
package/dist/index.cjs
CHANGED
|
@@ -24,8 +24,12 @@ function clientErrorMessage(args) {
|
|
|
24
24
|
const { body } = args;
|
|
25
25
|
if (isRecord(body)) {
|
|
26
26
|
const { error, message } = body;
|
|
27
|
-
if (
|
|
28
|
-
if (typeof
|
|
27
|
+
if (typeof error == "string" && typeof message == "string") return `${error} - ${message}`;
|
|
28
|
+
if (typeof error == "string") return error;
|
|
29
|
+
if (isRecord(error)) {
|
|
30
|
+
if (typeof error.description == "string") return error.description;
|
|
31
|
+
} else if (typeof message == "string")
|
|
32
|
+
return message;
|
|
29
33
|
}
|
|
30
34
|
const details = typeof body == "string" ? ` (${body.length > 100 ? `${body.slice(0, 100)}\u2026` : body})` : "";
|
|
31
35
|
return `${args.method}-request to ${args.path} resulted in HTTP ${args.statusCode} ${args.statusMessage}${details}`;
|
|
@@ -46,7 +50,17 @@ function accessApiError(args) {
|
|
|
46
50
|
body: { statusCode, error: statusMessage, message }
|
|
47
51
|
});
|
|
48
52
|
}
|
|
49
|
-
const
|
|
53
|
+
const sessionNotFound = (request) => new PlatformHttpError({
|
|
54
|
+
...request,
|
|
55
|
+
statusCode: 401,
|
|
56
|
+
statusMessage: "Unauthorized",
|
|
57
|
+
body: {
|
|
58
|
+
error: "Unauthorized",
|
|
59
|
+
errorCode: "SIO-401-ANF",
|
|
60
|
+
message: "Session not found",
|
|
61
|
+
statusCode: 401
|
|
62
|
+
}
|
|
63
|
+
}), noPermission = (request) => accessApiError({
|
|
50
64
|
request,
|
|
51
65
|
statusCode: 403,
|
|
52
66
|
statusMessage: "Forbidden",
|
|
@@ -1279,7 +1293,7 @@ function requireActive(release) {
|
|
|
1279
1293
|
`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
1294
|
);
|
|
1281
1295
|
}
|
|
1282
|
-
async function applyAction(store, action
|
|
1296
|
+
async function applyAction(store, action) {
|
|
1283
1297
|
switch (action.actionType) {
|
|
1284
1298
|
case "sanity.action.release.create": {
|
|
1285
1299
|
if (maybeRelease(store, action.releaseId) !== void 0)
|
|
@@ -1383,7 +1397,7 @@ async function applyAction(store, action, hooks) {
|
|
|
1383
1397
|
return store.remove(release._id), { transactionId: cryptoRandomKey() };
|
|
1384
1398
|
}
|
|
1385
1399
|
case "sanity.action.document.version.create": {
|
|
1386
|
-
if ("baseId" in action) return createVersionFromBase(store, action
|
|
1400
|
+
if ("baseId" in action) return createVersionFromBase(store, action);
|
|
1387
1401
|
const releaseId = action.releaseId ?? (action.document._id !== void 0 ? parseVersionId(action.document._id).releaseId : void 0);
|
|
1388
1402
|
if (releaseId === void 0)
|
|
1389
1403
|
throw fakeError(
|
|
@@ -1395,7 +1409,7 @@ async function applyAction(store, action, hooks) {
|
|
|
1395
1409
|
...action.document,
|
|
1396
1410
|
_id: vid
|
|
1397
1411
|
}, existing = store.get(vid), promoted = promote(doc);
|
|
1398
|
-
return existing !== void 0 && (promoted._createdAt = existing._createdAt),
|
|
1412
|
+
return existing !== void 0 && (promoted._createdAt = existing._createdAt), store.put(promoted), { transactionId: cryptoRandomKey() };
|
|
1399
1413
|
}
|
|
1400
1414
|
case "sanity.action.document.version.replace": {
|
|
1401
1415
|
const id = action.document._id;
|
|
@@ -1432,7 +1446,7 @@ async function applyAction(store, action, hooks) {
|
|
|
1432
1446
|
const published = store.get(action.publishedId);
|
|
1433
1447
|
requireRevisionMatch(action.draftId, draft._rev, action.ifDraftRevisionId), requireRevisionMatch(action.publishedId, published?._rev, action.ifPublishedRevisionId);
|
|
1434
1448
|
const promoted = promote({ ...draft, _id: action.publishedId });
|
|
1435
|
-
return published !== void 0 && (promoted._createdAt = published._createdAt),
|
|
1449
|
+
return published !== void 0 && (promoted._createdAt = published._createdAt), store.put(promoted), store.remove(action.draftId), { transactionId: cryptoRandomKey() };
|
|
1436
1450
|
}
|
|
1437
1451
|
case "sanity.action.document.unpublish": {
|
|
1438
1452
|
requireDraftOf(action);
|
|
@@ -1441,7 +1455,7 @@ async function applyAction(store, action, hooks) {
|
|
|
1441
1455
|
throw fakeError(
|
|
1442
1456
|
`Cannot unpublish "${action.publishedId}": no published document with that _id exists. document.unpublish retracts a live published document into "${action.draftId}".`
|
|
1443
1457
|
);
|
|
1444
|
-
if (
|
|
1458
|
+
if (store.get(action.draftId) === void 0) {
|
|
1445
1459
|
const draft = promote({ ...published, _id: action.draftId });
|
|
1446
1460
|
draft._createdAt = published._createdAt, store.put(draft);
|
|
1447
1461
|
}
|
|
@@ -1455,7 +1469,7 @@ function requireDraftOf(action) {
|
|
|
1455
1469
|
`${action.actionType}: draftId "${action.draftId}" is not the draft of publishedId "${action.publishedId}" \u2014 expected draftId "drafts.${action.publishedId}".`
|
|
1456
1470
|
);
|
|
1457
1471
|
}
|
|
1458
|
-
async function createVersionFromBase(store, action
|
|
1472
|
+
async function createVersionFromBase(store, action) {
|
|
1459
1473
|
const { releaseId, publishedId } = parseVersionId(action.versionId);
|
|
1460
1474
|
if (publishedId !== action.publishedId)
|
|
1461
1475
|
throw fakeError(
|
|
@@ -1474,7 +1488,7 @@ async function createVersionFromBase(store, action, hooks) {
|
|
|
1474
1488
|
_createdAt: existing?._createdAt ?? nowIso(),
|
|
1475
1489
|
_system: { base: { id: base._id, rev: base._rev } }
|
|
1476
1490
|
}, promoted = promote(copy);
|
|
1477
|
-
return
|
|
1491
|
+
return store.put(promoted), { transactionId: cryptoRandomKey() };
|
|
1478
1492
|
}
|
|
1479
1493
|
function requireRevisionMatch(documentId, actualRev, expectedRev) {
|
|
1480
1494
|
if (!(expectedRev === void 0 || actualRev === expectedRev))
|
|
@@ -1486,7 +1500,7 @@ function requireRevisionMatch(documentId, actualRev, expectedRev) {
|
|
|
1486
1500
|
);
|
|
1487
1501
|
}
|
|
1488
1502
|
async function applyActions(store, actions, hooks) {
|
|
1489
|
-
const list = Array.isArray(actions) ? actions : [actions], snapshot = /* @__PURE__ */ new Map(), guardedIds = /* @__PURE__ */ new Set(), remember = (id) => {
|
|
1503
|
+
const list = Array.isArray(actions) ? actions : [actions], snapshot = /* @__PURE__ */ new Map(), guardedIds = /* @__PURE__ */ new Set(), gatedIds = /* @__PURE__ */ new Set(), remember = (id) => {
|
|
1490
1504
|
snapshot.has(id) || snapshot.set(id, store.get(id));
|
|
1491
1505
|
};
|
|
1492
1506
|
try {
|
|
@@ -1499,9 +1513,15 @@ async function applyActions(store, actions, hooks) {
|
|
|
1499
1513
|
case "sanity.action.release.unschedule":
|
|
1500
1514
|
case "sanity.action.release.archive":
|
|
1501
1515
|
case "sanity.action.release.unarchive":
|
|
1502
|
-
case "sanity.action.release.delete":
|
|
1503
1516
|
remember(`${RELEASE_DOC_PREFIX}${a.releaseId}`);
|
|
1504
1517
|
break;
|
|
1518
|
+
case "sanity.action.release.delete": {
|
|
1519
|
+
remember(`${RELEASE_DOC_PREFIX}${a.releaseId}`);
|
|
1520
|
+
const prefix = `${VERSIONS_PREFIX}${a.releaseId}.`;
|
|
1521
|
+
for (const d of store.all())
|
|
1522
|
+
d._id.startsWith(prefix) && remember(d._id);
|
|
1523
|
+
break;
|
|
1524
|
+
}
|
|
1505
1525
|
case "sanity.action.release.publish": {
|
|
1506
1526
|
remember(`${RELEASE_DOC_PREFIX}${a.releaseId}`);
|
|
1507
1527
|
const prefix = `${VERSIONS_PREFIX}${a.releaseId}.`;
|
|
@@ -1511,11 +1531,11 @@ async function applyActions(store, actions, hooks) {
|
|
|
1511
1531
|
}
|
|
1512
1532
|
case "sanity.action.document.version.create": {
|
|
1513
1533
|
if ("baseId" in a) {
|
|
1514
|
-
remember(a.versionId);
|
|
1534
|
+
remember(a.versionId), gatedIds.add(a.versionId);
|
|
1515
1535
|
break;
|
|
1516
1536
|
}
|
|
1517
1537
|
const releaseId = a.releaseId ?? (typeof a.document._id == "string" ? parseVersionId(a.document._id).releaseId : void 0);
|
|
1518
|
-
releaseId !== void 0 && remember(versionDocId(releaseId, a.publishedId));
|
|
1538
|
+
releaseId !== void 0 && (remember(versionDocId(releaseId, a.publishedId)), gatedIds.add(versionDocId(releaseId, a.publishedId)));
|
|
1519
1539
|
break;
|
|
1520
1540
|
}
|
|
1521
1541
|
case "sanity.action.document.version.replace":
|
|
@@ -1526,13 +1546,17 @@ async function applyActions(store, actions, hooks) {
|
|
|
1526
1546
|
remember(a.versionId);
|
|
1527
1547
|
break;
|
|
1528
1548
|
case "sanity.action.document.publish":
|
|
1529
|
-
remember(a.draftId), remember(a.publishedId), guardedIds.add(a.publishedId), guardedIds.add(a.draftId);
|
|
1549
|
+
remember(a.draftId), remember(a.publishedId), guardedIds.add(a.publishedId), guardedIds.add(a.draftId), gatedIds.add(a.publishedId), gatedIds.add(a.draftId);
|
|
1530
1550
|
break;
|
|
1531
1551
|
case "sanity.action.document.unpublish":
|
|
1532
|
-
remember(a.draftId), remember(a.publishedId), guardedIds.add(a.draftId), guardedIds.add(a.publishedId);
|
|
1552
|
+
remember(a.draftId), remember(a.publishedId), guardedIds.add(a.draftId), guardedIds.add(a.publishedId), gatedIds.add(a.publishedId), gatedIds.add(a.draftId);
|
|
1533
1553
|
break;
|
|
1534
1554
|
}
|
|
1535
|
-
last = await applyAction(store, a
|
|
1555
|
+
last = await applyAction(store, a);
|
|
1556
|
+
}
|
|
1557
|
+
for (const id of gatedIds) {
|
|
1558
|
+
const before = snapshot.get(id), after = store.get(id);
|
|
1559
|
+
before !== after && await hooks?.gate?.(before, after);
|
|
1536
1560
|
}
|
|
1537
1561
|
const contexts = mutationContexts(
|
|
1538
1562
|
[...guardedIds].map((id) => ({ before: snapshot.get(id), after: store.get(id) }))
|
|
@@ -1826,6 +1850,7 @@ function createTestClient(options = {}) {
|
|
|
1826
1850
|
calls: [],
|
|
1827
1851
|
concurrentEdits: /* @__PURE__ */ new Map(),
|
|
1828
1852
|
identities: new Map(Object.entries(options.identities ?? {})),
|
|
1853
|
+
revoked: /* @__PURE__ */ new Set(),
|
|
1829
1854
|
writeChain: Promise.resolve()
|
|
1830
1855
|
}, registry = backend.registry;
|
|
1831
1856
|
if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
|
|
@@ -1850,7 +1875,8 @@ function createTestClient(options = {}) {
|
|
|
1850
1875
|
requestTagPrefix: options.requestTagPrefix,
|
|
1851
1876
|
mutationGuard: options.mutationGuard,
|
|
1852
1877
|
token: options.token,
|
|
1853
|
-
useProjectHostname: options.useProjectHostname ?? !0
|
|
1878
|
+
useProjectHostname: options.useProjectHostname ?? !0,
|
|
1879
|
+
hasProjectId: options.projectId !== void 0
|
|
1854
1880
|
});
|
|
1855
1881
|
}
|
|
1856
1882
|
function dedupeIds(results) {
|
|
@@ -1913,7 +1939,7 @@ function makeHandle(handleArgs) {
|
|
|
1913
1939
|
mutationGuard,
|
|
1914
1940
|
token,
|
|
1915
1941
|
useProjectHostname
|
|
1916
|
-
} = handleArgs, { registry } = backend, { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = resource ?? datasetResource(projectId, dataset), activeAccess = () => {
|
|
1942
|
+
} = 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 = () => {
|
|
1917
1943
|
if (token === void 0) return accessControl;
|
|
1918
1944
|
const identity = backend.identities.get(token);
|
|
1919
1945
|
if (identity === void 0)
|
|
@@ -1930,7 +1956,10 @@ function makeHandle(handleArgs) {
|
|
|
1930
1956
|
if (access === void 0)
|
|
1931
1957
|
throw fakeError("this handle has no acting identity (no token or accessControl bound).");
|
|
1932
1958
|
return access;
|
|
1933
|
-
},
|
|
1959
|
+
}, refuseRevoked = (request) => {
|
|
1960
|
+
if (token !== void 0 && backend.revoked.has(token)) throw sessionNotFound(request);
|
|
1961
|
+
}, withSession = (request) => async (opts) => (refuseRevoked({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
|
|
1962
|
+
refuseRevoked(request);
|
|
1934
1963
|
const access = activeAccess();
|
|
1935
1964
|
if (access === void 0) return;
|
|
1936
1965
|
const refusal = refusedToken(request, access.grants);
|
|
@@ -2010,14 +2039,21 @@ function makeHandle(handleArgs) {
|
|
|
2010
2039
|
throw fakeError(
|
|
2011
2040
|
`ifRevisionId check failed: document "${id}" is at _rev="${existing._rev}" but the mutation required _rev="${ifRevisionId}". The document changed since you read it \u2014 re-read it and retry. (This mirrors Sanity's optimistic-locking 409.)`
|
|
2012
2041
|
);
|
|
2013
|
-
}, gate = async (
|
|
2042
|
+
}, gate = async (prev, next) => {
|
|
2014
2043
|
const access = activeAccess();
|
|
2015
|
-
access
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2044
|
+
if (access === void 0) return;
|
|
2045
|
+
const id = (prev ?? next)?._id;
|
|
2046
|
+
if (id === void 0) return;
|
|
2047
|
+
const required = isSystemId(id) ? ["manage"] : [];
|
|
2048
|
+
required.push(prev === void 0 ? "create" : "update");
|
|
2049
|
+
for (const permission of required)
|
|
2050
|
+
for (const document of [prev, next])
|
|
2051
|
+
document !== void 0 && await enforceWriteAccess({
|
|
2052
|
+
document,
|
|
2053
|
+
grants: access.grants,
|
|
2054
|
+
permission,
|
|
2055
|
+
userId: actorId()
|
|
2056
|
+
});
|
|
2021
2057
|
}, guardGate = async (contexts) => {
|
|
2022
2058
|
const identity = actorId();
|
|
2023
2059
|
await enforceMutationGuards(
|
|
@@ -2040,13 +2076,13 @@ function makeHandle(handleArgs) {
|
|
|
2040
2076
|
throw fakeError(
|
|
2041
2077
|
`Cannot patch document "${documentId}": not found \u2014 no document with that _id exists in ${targetLabel}. patch() requires the target to already exist; use createOrReplace() / createIfNotExists() to upsert, or seed the document first.`
|
|
2042
2078
|
);
|
|
2043
|
-
checkRevision(documentId, ifRev)
|
|
2079
|
+
checkRevision(documentId, ifRev);
|
|
2044
2080
|
const patched = applyPatchOps(existing, ops), now = (/* @__PURE__ */ new Date()).toISOString(), next = {
|
|
2045
2081
|
...patched,
|
|
2046
2082
|
_rev: cryptoRandomKey(),
|
|
2047
2083
|
_updatedAt: now
|
|
2048
2084
|
};
|
|
2049
|
-
return options.
|
|
2085
|
+
return options.inTransaction !== !0 && (await gate(existing, next), await guardOne("update", existing, next)), store.put(next), next;
|
|
2050
2086
|
}, applyTransaction = async (mutations, txnOptions) => {
|
|
2051
2087
|
const transactionId = txnOptions?.transactionId ?? cryptoRandomKey(), snapshot = /* @__PURE__ */ new Map(), touchedIds = [], operations = [], remember = (id) => {
|
|
2052
2088
|
snapshot.has(id) || snapshot.set(id, store.get(id));
|
|
@@ -2061,39 +2097,35 @@ function makeHandle(handleArgs) {
|
|
|
2061
2097
|
throw fakeError(
|
|
2062
2098
|
`create() failed: a document with _id "${promoted._id}" already exists in ${targetLabel}. Use createOrReplace() to overwrite it, or createIfNotExists() to leave the existing one untouched.`
|
|
2063
2099
|
);
|
|
2064
|
-
|
|
2100
|
+
store.put(promoted), touchedIds.push(promoted._id), operations.push({ id: promoted._id, operation: "create" });
|
|
2065
2101
|
break;
|
|
2066
2102
|
}
|
|
2067
2103
|
case "createOrReplace": {
|
|
2068
2104
|
remember(mut.doc._id);
|
|
2069
|
-
const promoted = promote2(mut.doc),
|
|
2070
|
-
await gate(existing ?? promoted, existing !== void 0 ? "update" : "create");
|
|
2071
|
-
const wasPresent = existing !== void 0;
|
|
2105
|
+
const promoted = promote2(mut.doc), wasPresent = store.get(promoted._id) !== void 0;
|
|
2072
2106
|
store.put(promoted), touchedIds.push(promoted._id), operations.push({ id: promoted._id, operation: wasPresent ? "update" : "create" });
|
|
2073
2107
|
break;
|
|
2074
2108
|
}
|
|
2075
2109
|
case "createIfNotExists": {
|
|
2076
2110
|
if (remember(mut.doc._id), store.get(mut.doc._id) === void 0) {
|
|
2077
2111
|
const promoted = promote2(mut.doc);
|
|
2078
|
-
|
|
2112
|
+
store.put(promoted), touchedIds.push(promoted._id), operations.push({ id: promoted._id, operation: "create" });
|
|
2079
2113
|
}
|
|
2080
2114
|
break;
|
|
2081
2115
|
}
|
|
2082
2116
|
case "delete": {
|
|
2083
|
-
remember(mut.id);
|
|
2084
|
-
const existing = store.get(mut.id);
|
|
2085
|
-
existing !== void 0 && await gate(existing, "update"), store.remove(mut.id) && (touchedIds.push(mut.id), operations.push({ id: mut.id, operation: "delete" }));
|
|
2117
|
+
remember(mut.id), store.remove(mut.id) && (touchedIds.push(mut.id), operations.push({ id: mut.id, operation: "delete" }));
|
|
2086
2118
|
break;
|
|
2087
2119
|
}
|
|
2088
2120
|
case "patch": {
|
|
2089
|
-
remember(mut.documentId), await applyPatch(mut.documentId, mut.ops, mut.ifRev, {
|
|
2121
|
+
remember(mut.documentId), await applyPatch(mut.documentId, mut.ops, mut.ifRev, { inTransaction: !0 }), touchedIds.push(mut.documentId), operations.push({ id: mut.documentId, operation: "update" });
|
|
2090
2122
|
break;
|
|
2091
2123
|
}
|
|
2092
2124
|
}
|
|
2093
|
-
const
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
await guardGate(
|
|
2125
|
+
const images = [...snapshot].map(([id, before]) => ({ before, after: store.get(id) }));
|
|
2126
|
+
for (const { before, after } of images)
|
|
2127
|
+
before !== after && await gate(before, after);
|
|
2128
|
+
await guardGate(mutationContexts(images));
|
|
2097
2129
|
} catch (error) {
|
|
2098
2130
|
for (const [id, doc] of snapshot)
|
|
2099
2131
|
doc === void 0 ? store.remove(id) : store.put(doc);
|
|
@@ -2113,7 +2145,7 @@ function makeHandle(handleArgs) {
|
|
|
2113
2145
|
method: "POST",
|
|
2114
2146
|
path: `${capabilities.dataBase(target.id)}/actions`
|
|
2115
2147
|
};
|
|
2116
|
-
if (capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2148
|
+
if (refuseRevoked(request), capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2117
2149
|
return write(async () => {
|
|
2118
2150
|
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
2119
2151
|
const refused = capabilities.refusedActions[action.actionType];
|
|
@@ -2176,7 +2208,7 @@ function makeHandle(handleArgs) {
|
|
|
2176
2208
|
`create() failed: a document with _id "${doc._id}" already exists in ${targetLabel}. Use createOrReplace() to overwrite it, or createIfNotExists() to leave the existing one untouched.`
|
|
2177
2209
|
);
|
|
2178
2210
|
const promoted = promote2(doc);
|
|
2179
|
-
await gate(
|
|
2211
|
+
await gate(void 0, promoted), await guardOne("create", null, promoted);
|
|
2180
2212
|
const transactionId = opts?.transactionId ?? cryptoRandomKey();
|
|
2181
2213
|
return opts?.dryRun !== !0 && (store.put(promoted), record(transactionId, [{ kind: "create", doc }], opts?.tag)), writeResult(
|
|
2182
2214
|
[promoted],
|
|
@@ -2188,7 +2220,7 @@ function makeHandle(handleArgs) {
|
|
|
2188
2220
|
createOrReplace: (doc, opts) => write(async () => {
|
|
2189
2221
|
checkRevision(doc._id, opts?.ifRevisionId);
|
|
2190
2222
|
const promoted = promote2(doc), existing = store.get(doc._id);
|
|
2191
|
-
await gate(existing
|
|
2223
|
+
await gate(existing, promoted), await guardOne(existing !== void 0 ? "update" : "create", existing ?? null, promoted);
|
|
2192
2224
|
const transactionId = opts?.transactionId ?? cryptoRandomKey();
|
|
2193
2225
|
opts?.dryRun !== !0 && (store.put(promoted), record(transactionId, [{ kind: "createOrReplace", doc }], opts?.tag));
|
|
2194
2226
|
const operation = existing !== void 0 ? "update" : "create";
|
|
@@ -2210,7 +2242,7 @@ function makeHandle(handleArgs) {
|
|
|
2210
2242
|
opts
|
|
2211
2243
|
);
|
|
2212
2244
|
const promoted = promote2(doc);
|
|
2213
|
-
return await gate(
|
|
2245
|
+
return await gate(void 0, promoted), await guardOne("create", null, promoted), opts?.dryRun !== !0 && (store.put(promoted), record(transactionId, [{ kind: "createIfNotExists", doc }], opts?.tag)), writeResult(
|
|
2214
2246
|
[promoted],
|
|
2215
2247
|
[{ id: promoted._id, operation: "create" }],
|
|
2216
2248
|
transactionId,
|
|
@@ -2220,7 +2252,7 @@ function makeHandle(handleArgs) {
|
|
|
2220
2252
|
delete: (id, opts) => write(async () => {
|
|
2221
2253
|
checkRevision(id, opts?.ifRevisionId);
|
|
2222
2254
|
const existing = store.get(id);
|
|
2223
|
-
existing !== void 0 && await gate(existing,
|
|
2255
|
+
existing !== void 0 && await gate(existing, void 0), existing !== void 0 && await guardOne("delete", existing, null);
|
|
2224
2256
|
const transactionId = opts?.transactionId ?? cryptoRandomKey();
|
|
2225
2257
|
let removed = existing;
|
|
2226
2258
|
return opts?.dryRun !== !0 && (removed = store.remove(id), removed !== void 0 && record(transactionId, [{ kind: "delete", id }], opts?.tag)), opts?.returnDocuments === void 0 && opts?.returnFirst === void 0 ? removed !== void 0 ? { _id: id } : null : formatMutationResult(
|
|
@@ -2317,36 +2349,38 @@ function makeHandle(handleArgs) {
|
|
|
2317
2349
|
publishedId
|
|
2318
2350
|
}),
|
|
2319
2351
|
...token !== void 0 || accessControl !== void 0 ? {
|
|
2320
|
-
request:
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
listIdentities: members,
|
|
2327
|
-
platform: {
|
|
2328
|
-
projectId,
|
|
2352
|
+
request: withSession(
|
|
2353
|
+
makeRequestImpl({
|
|
2354
|
+
getAccess: requireActiveAccess,
|
|
2355
|
+
// `@sanity/client` sends every request of a `resource`-configured
|
|
2356
|
+
// client to the global API host.
|
|
2357
|
+
useProjectHostname: useProjectHostname && resource === void 0,
|
|
2329
2358
|
organizationId: backend.organizationId,
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2359
|
+
listIdentities: members,
|
|
2360
|
+
platform: {
|
|
2361
|
+
projectId,
|
|
2362
|
+
organizationId: backend.organizationId,
|
|
2363
|
+
projectFeatures: backend.projectFeatures,
|
|
2364
|
+
own: (asked) => registryKey(asked) === registryKey(target) ? {
|
|
2365
|
+
grants: requireActiveAccess().grants,
|
|
2366
|
+
documents: () => store.all(),
|
|
2367
|
+
history,
|
|
2368
|
+
canRead,
|
|
2369
|
+
admitToLake
|
|
2370
|
+
} : void 0,
|
|
2371
|
+
actorUser: () => {
|
|
2372
|
+
const access = requireActiveAccess();
|
|
2373
|
+
return access.globalUser ?? access.currentUser;
|
|
2374
|
+
},
|
|
2375
|
+
actorAccess: () => requireActiveAccess().access,
|
|
2376
|
+
identities: members,
|
|
2377
|
+
resources: () => [...registry.values()].map((entry) => entry.resource)
|
|
2378
|
+
}
|
|
2379
|
+
})
|
|
2380
|
+
)
|
|
2347
2381
|
} : {},
|
|
2348
2382
|
config: () => ({
|
|
2349
|
-
projectId,
|
|
2383
|
+
...hasProjectId || resource !== void 0 ? { projectId } : {},
|
|
2350
2384
|
dataset,
|
|
2351
2385
|
...resource !== void 0 ? { resource } : {},
|
|
2352
2386
|
perspective,
|
|
@@ -2367,7 +2401,8 @@ function makeHandle(handleArgs) {
|
|
|
2367
2401
|
requestTagPrefix: config.requestTagPrefix ?? requestTagPrefix,
|
|
2368
2402
|
mutationGuard,
|
|
2369
2403
|
token: rebinds ? config.token : token,
|
|
2370
|
-
useProjectHostname: config.useProjectHostname ?? useProjectHostname
|
|
2404
|
+
useProjectHostname: config.useProjectHostname ?? useProjectHostname,
|
|
2405
|
+
hasProjectId: hasProjectId || config.projectId !== void 0
|
|
2371
2406
|
});
|
|
2372
2407
|
},
|
|
2373
2408
|
seed: (documents) => store.seed(documents),
|
|
@@ -2389,6 +2424,9 @@ function makeHandle(handleArgs) {
|
|
|
2389
2424
|
backend.identities.set(identityToken, identity);
|
|
2390
2425
|
},
|
|
2391
2426
|
identities: () => Object.fromEntries(backend.identities),
|
|
2427
|
+
revokeIdentity: (revokedToken) => {
|
|
2428
|
+
requireIdentity(backend, revokedToken, "revokeIdentity()"), backend.revoked.add(revokedToken);
|
|
2429
|
+
},
|
|
2392
2430
|
mutations: () => backend.log.flatMap((entry) => entry.mutations),
|
|
2393
2431
|
transactions: () => [...backend.log],
|
|
2394
2432
|
clearLog: () => {
|