@sanity-labs/client-fake-for-test 0.16.0 → 0.17.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 +36 -1
- package/dist/index.cjs +188 -81
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +28 -6
- package/dist/index.d.ts +28 -6
- package/dist/index.js +188 -81
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -81,7 +81,7 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
|
|
|
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 |
|
|
84
|
-
| HTTP | `request({ url? \| uri? })` | Present **only** when the handle has an acting identity (`accessControl`, or a bound `token`). Serves `/users/me` (host-aware: project-scoped record on the project host, `globalUser` on a global-hosted or `resource` handle), the handle's ACL (`<data base>/acl`, or an explicit `aclPath`), `/projects/<projectId>` (the project's members: `{ id, isRobot?, roles? }` rows, one per distinct resolved project user, plus `organizationId` when configured), `/projects/<projectId>/users/<ids>` (project-user records with `id` + `sanityUserId`), `/projects/<projectId>/roles` (the project role catalog), the History API, resource lookup and the Access API (see [Resource types](#resource-types-media-library-canvas-dashboard)). Calling it without one throws a guidance error. |
|
|
84
|
+
| HTTP | `request({ url? \| uri? })` | Present **only** when the handle has an acting identity (`accessControl`, or a bound `token`). Serves `/users/me` (host-aware: project-scoped record on the project host, `globalUser` on a global-hosted or `resource` handle), the handle's ACL (`<data base>/acl`, or an explicit `aclPath`), `/projects/<projectId>` (the project's members: `{ id, isRobot?, roles? }` rows, one per distinct resolved project user, plus `organizationId` when configured), `/projects/<projectId>/users/<ids>` (project-user records with `id` + `sanityUserId`), `/projects/<projectId>/roles` (the project role catalog), `/projects/<projectId>/features` (the project's feature names, seeded with `projectFeatures`), the History API, resource lookup and the Access API (see [Resource types](#resource-types-media-library-canvas-dashboard)). Calling it without one throws a guidance error. |
|
|
85
85
|
|
|
86
86
|
#### Mutation return shapes
|
|
87
87
|
|
|
@@ -144,6 +144,40 @@ 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
|
+
#### Token grants: filters and paths
|
|
148
|
+
|
|
149
|
+
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:
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
const client = createTestClient({
|
|
153
|
+
identities: {
|
|
154
|
+
"t-service": {
|
|
155
|
+
user: { id: "p-service" },
|
|
156
|
+
grants: [
|
|
157
|
+
{ path: "prod.wf-instance.*", permissions: ["read", "create", "update"] },
|
|
158
|
+
{ path: "temp.system.guard.prod.wf-instance.**", permissions: ["read", "create", "update"] },
|
|
159
|
+
],
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
token: "t-service",
|
|
163
|
+
});
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
The Content Lake parses a token's path grants on every request it serves and refuses the whole request when one does not parse — whatever the request asks. The fake does the same for every handle acting as that identity, token-bound or inline `accessControl`: `fetch`, `getDocument(s)`, `releases.get` / `releases.fetchDocuments`, every mutation and action, and the History API throw a `PlatformHttpError` with `statusCode: 400` and body `{ error: { description, type: "httpBadRequest" } }`, where `description` is the Content Lake's message for the first grant it cannot parse. A route the resource does not mount still answers its 404 first (a Canvas's `/actions`), as the request never reaches the Content Lake.
|
|
167
|
+
|
|
168
|
+
| Grant | `description` |
|
|
169
|
+
| --- | --- |
|
|
170
|
+
| `path: ""` | `path must contain at least one element` |
|
|
171
|
+
| `path` starting with `.` | `path cannot begin with delimiter "."` |
|
|
172
|
+
| `path` with an empty element (`a..b`, `a.`) | `path contains empty element` |
|
|
173
|
+
| `path` over 128 UTF-8 bytes | `path exceeds maximum length of 128` |
|
|
174
|
+
| `*` before the last element (`*.wf-instance.*`) | `wildcard must be last component` |
|
|
175
|
+
| `**` before the last element | `descendant wildcard must be last component` |
|
|
176
|
+
| an element outside `[A-Za-z0-9_-]`, or starting with `-` (an element with several lines passes when any one line is valid, a quirk the Content Lake keeps for old ids) | `invalid element "<element>"`, Go-quoted |
|
|
177
|
+
| a permission other than `read`, `update`, `create`, `manage`, `history`, `editHistory` (e.g. `delete`) | `invalid permission "<permission>"`, Go-quoted |
|
|
178
|
+
|
|
179
|
+
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
|
+
|
|
147
181
|
#### System-document grants
|
|
148
182
|
|
|
149
183
|
User-issued writes to system document IDs beginning with `_.` require the `manage` permission. Ordinary `create` and `update` grants do not authorize these writes; add `manage` 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.
|
|
@@ -211,6 +245,7 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
|
|
|
211
245
|
- **User attributes.** `GET /organizations/<organizationId>/users/me/attributes` answers the caller's own attributes there: `{ sanityUserId, organizationId, attributes: [{ type, key, values: { saml?, sanity? }, activeSource, activeValue }] }`, ordered by key. Seed them as `attributes: [{ key, type, values }]` on the identity's `"organization:<id>"` entry; the Sanity value takes precedence over the SAML one for `activeSource` and `activeValue`, as on the platform. No permission is needed. `limit` (default 50) and `cursor` (the last key of the previous page) page the list. A member with no seeded attributes gets `attributes: []`; a caller without roles in the organization gets 404 `User not found`, and another organization id 404 `Organization not found`.
|
|
212
246
|
- **History.** Every committed write since the client was created is recorded per resource, authored by the acting identity; seeded documents can be read at their seeded `_rev`. A handle answers for its own resource, and hides documents its grants cannot read, as reads do (a transaction that also touched such a document is served without it). Events model `createLiveDocument` / `updateLiveDocument` only.
|
|
213
247
|
- **Org lookup.** `createTestClient({ organizationId })` names the organization every resource of the client belongs to.
|
|
248
|
+
- **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.
|
|
214
249
|
- **Identity.** `@sanity/client` sends a `resource` client's requests to the global host, so `/users/me` answers `globalUser`.
|
|
215
250
|
|
|
216
251
|
### Test-only helpers (not on real `SanityClient`)
|
package/dist/index.cjs
CHANGED
|
@@ -5,67 +5,6 @@ const ERR_PREFIX = "[client-fake-for-test]";
|
|
|
5
5
|
function fakeError(message) {
|
|
6
6
|
return new Error(`${ERR_PREFIX} ${message}`);
|
|
7
7
|
}
|
|
8
|
-
function createDocumentHistory() {
|
|
9
|
-
const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
|
|
10
|
-
return {
|
|
11
|
-
commit: ({ transactionId, author, before, after }) => {
|
|
12
|
-
const afterById = new Map(after.map((doc) => [doc._id, doc])), ids = /* @__PURE__ */ new Set([...before.keys(), ...afterById.keys()]), effects = [];
|
|
13
|
-
for (const id of ids) {
|
|
14
|
-
const previous = before.get(id), next = afterById.get(id);
|
|
15
|
-
previous !== next && (previous !== void 0 && keep(previous), next !== void 0 && keep(next), next === void 0 && previous !== void 0 ? deleted.set(id, structuredClone(previous)) : deleted.delete(id), effects.push({
|
|
16
|
-
documentId: id,
|
|
17
|
-
after: next === void 0 ? void 0 : structuredClone(next),
|
|
18
|
-
existed: previous !== void 0
|
|
19
|
-
}));
|
|
20
|
-
}
|
|
21
|
-
effects.length !== 0 && transactions.push({
|
|
22
|
-
id: transactionId,
|
|
23
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
24
|
-
author,
|
|
25
|
-
effects
|
|
26
|
-
});
|
|
27
|
-
},
|
|
28
|
-
documentsAt: ({ ids, revision, current }) => ids.flatMap((id) => {
|
|
29
|
-
const image = revisions.get(`${id} ${revision}`) ?? current.find((doc) => doc._id === id && doc._rev === revision);
|
|
30
|
-
return image === void 0 ? [] : [structuredClone(image)];
|
|
31
|
-
}),
|
|
32
|
-
lastImage: (id) => deleted.get(id),
|
|
33
|
-
documentIds: () => [
|
|
34
|
-
...new Set(transactions.flatMap((txn) => txn.effects.map((effect) => effect.documentId)))
|
|
35
|
-
],
|
|
36
|
-
transactions: (ids, visible) => transactions.filter((txn) => txn.effects.some((effect) => ids.includes(effect.documentId))).map((txn) => ({ ...txn, effects: txn.effects.filter((e) => visible(e.documentId)) })).map((txn) => ({
|
|
37
|
-
id: txn.id,
|
|
38
|
-
timestamp: txn.timestamp,
|
|
39
|
-
...txn.author !== void 0 ? { author: txn.author } : {},
|
|
40
|
-
mutations: txn.effects.map((effect) => {
|
|
41
|
-
if (effect.after === void 0) return { delete: { id: effect.documentId } };
|
|
42
|
-
const after = structuredClone(effect.after);
|
|
43
|
-
return effect.existed ? { createOrReplace: after } : { create: after };
|
|
44
|
-
}),
|
|
45
|
-
documentIDs: txn.effects.map((effect) => effect.documentId)
|
|
46
|
-
})),
|
|
47
|
-
events: (ids) => Object.fromEntries(
|
|
48
|
-
ids.map((id) => [
|
|
49
|
-
id,
|
|
50
|
-
transactions.flatMap(
|
|
51
|
-
(txn) => txn.effects.filter((effect) => effect.documentId === id && effect.after !== void 0).map(
|
|
52
|
-
(effect) => ({
|
|
53
|
-
type: effect.existed ? "updateLiveDocument" : "createLiveDocument",
|
|
54
|
-
id: txn.id,
|
|
55
|
-
documentId: id,
|
|
56
|
-
revisionId: effect.after._rev,
|
|
57
|
-
timestamp: txn.timestamp,
|
|
58
|
-
...txn.author !== void 0 ? { author: txn.author } : {}
|
|
59
|
-
})
|
|
60
|
-
)
|
|
61
|
-
).toReversed()
|
|
62
|
-
])
|
|
63
|
-
)
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
function historyIds(list) {
|
|
67
|
-
return list.split(",").map((id) => decodeURIComponent(id));
|
|
68
|
-
}
|
|
69
8
|
class PlatformHttpError extends Error {
|
|
70
9
|
statusCode;
|
|
71
10
|
response;
|
|
@@ -335,7 +274,148 @@ function dataUrl(args) {
|
|
|
335
274
|
const base = `/${operation}/${dataset}`;
|
|
336
275
|
return `/data${path !== void 0 ? `${base}/${path}` : base}`.replace(/\/($|\?)/, "$1");
|
|
337
276
|
}
|
|
338
|
-
const
|
|
277
|
+
const MAX_PATH_BYTES = 128, PERMISSIONS = /* @__PURE__ */ new Set(["read", "update", "create", "manage", "history", "editHistory"]), MISPLACED_WILDCARD = /* @__PURE__ */ new Map([
|
|
278
|
+
["*", "wildcard must be last component"],
|
|
279
|
+
["**", "descendant wildcard must be last component"]
|
|
280
|
+
]), ELEMENT_LINE = /^[A-Za-z0-9_][A-Za-z0-9_-]*$/;
|
|
281
|
+
function validElement(element) {
|
|
282
|
+
return element.split(`
|
|
283
|
+
`).some((line) => ELEMENT_LINE.test(line));
|
|
284
|
+
}
|
|
285
|
+
const GO_ESCAPES = {
|
|
286
|
+
"\x07": "\\a",
|
|
287
|
+
"\b": "\\b",
|
|
288
|
+
"\f": "\\f",
|
|
289
|
+
"\n": "\\n",
|
|
290
|
+
"\r": "\\r",
|
|
291
|
+
" ": "\\t",
|
|
292
|
+
"\v": "\\v",
|
|
293
|
+
'"': '\\"',
|
|
294
|
+
"\\": "\\\\"
|
|
295
|
+
}, GO_PRINTABLE = /^[\p{L}\p{M}\p{N}\p{P}\p{S} ]$/u;
|
|
296
|
+
function quoted(value) {
|
|
297
|
+
let out = '"';
|
|
298
|
+
for (const char of value) {
|
|
299
|
+
const escape = GO_ESCAPES[char];
|
|
300
|
+
if (escape !== void 0) {
|
|
301
|
+
out += escape;
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
if (GO_PRINTABLE.test(char)) {
|
|
305
|
+
out += char;
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
const code = char.codePointAt(0);
|
|
309
|
+
out += code < 128 ? `\\x${code.toString(16).padStart(2, "0")}` : code <= 65535 ? `\\u${code.toString(16).padStart(4, "0")}` : `\\U${code.toString(16).padStart(8, "0")}`;
|
|
310
|
+
}
|
|
311
|
+
return `${out}"`;
|
|
312
|
+
}
|
|
313
|
+
function pathError(path) {
|
|
314
|
+
if (path === "") return "path must contain at least one element";
|
|
315
|
+
if (path.startsWith(".")) return 'path cannot begin with delimiter "."';
|
|
316
|
+
const elements = path.split(".");
|
|
317
|
+
if (elements.includes("")) return "path contains empty element";
|
|
318
|
+
if (new TextEncoder().encode(path).length > MAX_PATH_BYTES)
|
|
319
|
+
return `path exceeds maximum length of ${MAX_PATH_BYTES}`;
|
|
320
|
+
const last = elements.length - 1;
|
|
321
|
+
for (const [index, element] of elements.entries()) {
|
|
322
|
+
const misplaced = MISPLACED_WILDCARD.get(element);
|
|
323
|
+
if (misplaced !== void 0) {
|
|
324
|
+
if (index < last) return misplaced;
|
|
325
|
+
} else if (!validElement(element))
|
|
326
|
+
return `invalid element ${quoted(element)}`;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
function pathIncludes(path, id) {
|
|
330
|
+
const pattern = path.split("."), elements = id.split(".");
|
|
331
|
+
for (const [index, element] of pattern.entries()) {
|
|
332
|
+
if (index >= elements.length) return !1;
|
|
333
|
+
if (element === "**") return !0;
|
|
334
|
+
if (element === "*" ? elements[index] === "**" : element !== elements[index]) return !1;
|
|
335
|
+
}
|
|
336
|
+
return pattern.length === elements.length;
|
|
337
|
+
}
|
|
338
|
+
function grantsError(grants) {
|
|
339
|
+
for (const grant of grants) {
|
|
340
|
+
if (!("path" in grant)) continue;
|
|
341
|
+
const error = pathError(grant.path);
|
|
342
|
+
if (error !== void 0) return error;
|
|
343
|
+
const invalid = grant.permissions.find((permission) => !PERMISSIONS.has(permission));
|
|
344
|
+
if (invalid !== void 0) return `invalid permission ${quoted(invalid)}`;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
function refusedToken(request, grants) {
|
|
348
|
+
const description = grantsError(grants);
|
|
349
|
+
if (description !== void 0)
|
|
350
|
+
return new PlatformHttpError({
|
|
351
|
+
...request,
|
|
352
|
+
statusCode: 400,
|
|
353
|
+
statusMessage: "Bad Request",
|
|
354
|
+
body: { error: { description, type: "httpBadRequest" } }
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
function createDocumentHistory() {
|
|
358
|
+
const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
|
|
359
|
+
return {
|
|
360
|
+
commit: ({ transactionId, author, before, after }) => {
|
|
361
|
+
const afterById = new Map(after.map((doc) => [doc._id, doc])), ids = /* @__PURE__ */ new Set([...before.keys(), ...afterById.keys()]), effects = [];
|
|
362
|
+
for (const id of ids) {
|
|
363
|
+
const previous = before.get(id), next = afterById.get(id);
|
|
364
|
+
previous !== next && (previous !== void 0 && keep(previous), next !== void 0 && keep(next), next === void 0 && previous !== void 0 ? deleted.set(id, structuredClone(previous)) : deleted.delete(id), effects.push({
|
|
365
|
+
documentId: id,
|
|
366
|
+
after: next === void 0 ? void 0 : structuredClone(next),
|
|
367
|
+
existed: previous !== void 0
|
|
368
|
+
}));
|
|
369
|
+
}
|
|
370
|
+
effects.length !== 0 && transactions.push({
|
|
371
|
+
id: transactionId,
|
|
372
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
373
|
+
author,
|
|
374
|
+
effects
|
|
375
|
+
});
|
|
376
|
+
},
|
|
377
|
+
documentsAt: ({ ids, revision, current }) => ids.flatMap((id) => {
|
|
378
|
+
const image = revisions.get(`${id} ${revision}`) ?? current.find((doc) => doc._id === id && doc._rev === revision);
|
|
379
|
+
return image === void 0 ? [] : [structuredClone(image)];
|
|
380
|
+
}),
|
|
381
|
+
lastImage: (id) => deleted.get(id),
|
|
382
|
+
documentIds: () => [
|
|
383
|
+
...new Set(transactions.flatMap((txn) => txn.effects.map((effect) => effect.documentId)))
|
|
384
|
+
],
|
|
385
|
+
transactions: (ids, visible) => transactions.filter((txn) => txn.effects.some((effect) => ids.includes(effect.documentId))).map((txn) => ({ ...txn, effects: txn.effects.filter((e) => visible(e.documentId)) })).map((txn) => ({
|
|
386
|
+
id: txn.id,
|
|
387
|
+
timestamp: txn.timestamp,
|
|
388
|
+
...txn.author !== void 0 ? { author: txn.author } : {},
|
|
389
|
+
mutations: txn.effects.map((effect) => {
|
|
390
|
+
if (effect.after === void 0) return { delete: { id: effect.documentId } };
|
|
391
|
+
const after = structuredClone(effect.after);
|
|
392
|
+
return effect.existed ? { createOrReplace: after } : { create: after };
|
|
393
|
+
}),
|
|
394
|
+
documentIDs: txn.effects.map((effect) => effect.documentId)
|
|
395
|
+
})),
|
|
396
|
+
events: (ids) => Object.fromEntries(
|
|
397
|
+
ids.map((id) => [
|
|
398
|
+
id,
|
|
399
|
+
transactions.flatMap(
|
|
400
|
+
(txn) => txn.effects.filter((effect) => effect.documentId === id && effect.after !== void 0).map(
|
|
401
|
+
(effect) => ({
|
|
402
|
+
type: effect.existed ? "updateLiveDocument" : "createLiveDocument",
|
|
403
|
+
id: txn.id,
|
|
404
|
+
documentId: id,
|
|
405
|
+
revisionId: effect.after._rev,
|
|
406
|
+
timestamp: txn.timestamp,
|
|
407
|
+
...txn.author !== void 0 ? { author: txn.author } : {}
|
|
408
|
+
})
|
|
409
|
+
)
|
|
410
|
+
).toReversed()
|
|
411
|
+
])
|
|
412
|
+
)
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
function historyIds(list) {
|
|
416
|
+
return list.split(",").map((id) => decodeURIComponent(id));
|
|
417
|
+
}
|
|
418
|
+
const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, PROJECT_ROLES_PATH = /^\/projects\/([^/]+)\/roles$/, PROJECT_FEATURES_PATH = /^\/projects\/([^/]+)\/features$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/;
|
|
339
419
|
function page(data) {
|
|
340
420
|
return { data, nextCursor: null };
|
|
341
421
|
}
|
|
@@ -354,6 +434,11 @@ async function servePlatformRequest(ctx, url) {
|
|
|
354
434
|
const projectId = decodeURIComponent(projectRoles[1]);
|
|
355
435
|
return serveProjectRoles({ ctx, request, projectId });
|
|
356
436
|
}
|
|
437
|
+
const projectFeatures = path.match(PROJECT_FEATURES_PATH);
|
|
438
|
+
if (projectFeatures !== null) {
|
|
439
|
+
const projectId = decodeURIComponent(projectFeatures[1]);
|
|
440
|
+
return { value: featuresOf(ctx, projectId) };
|
|
441
|
+
}
|
|
357
442
|
const access = path.match(ACCESS_PATH);
|
|
358
443
|
if (access !== null) {
|
|
359
444
|
const [, type, id, rest2] = access;
|
|
@@ -376,6 +461,10 @@ async function servePlatformRequest(ctx, url) {
|
|
|
376
461
|
if (rest.startsWith("/history/"))
|
|
377
462
|
return serveHistory({ ctx, request, resource, rest: rest.slice(8), query });
|
|
378
463
|
}
|
|
464
|
+
function featuresOf(ctx, projectId) {
|
|
465
|
+
const features = Object.hasOwn(ctx.projectFeatures, projectId) ? ctx.projectFeatures[projectId] : [];
|
|
466
|
+
return [...new Set(features)].toSorted();
|
|
467
|
+
}
|
|
379
468
|
function serveLookup(ctx, resource) {
|
|
380
469
|
if (ctx.organizationId === void 0)
|
|
381
470
|
throw fakeError(
|
|
@@ -387,7 +476,8 @@ function serveHistory(args) {
|
|
|
387
476
|
const { ctx, request, resource, rest, query } = args;
|
|
388
477
|
return serveCapability(capabilitiesOf(resource.type).history, request, () => {
|
|
389
478
|
const own = ctx.own(resource);
|
|
390
|
-
|
|
479
|
+
if (own !== void 0)
|
|
480
|
+
return own.admitToLake(request), readHistory({ own, request, rest, query });
|
|
391
481
|
});
|
|
392
482
|
}
|
|
393
483
|
async function readHistory(args) {
|
|
@@ -614,15 +704,15 @@ async function matchesFilter(args) {
|
|
|
614
704
|
})).get();
|
|
615
705
|
return Array.isArray(data) && data.length === 1;
|
|
616
706
|
}
|
|
707
|
+
async function grantMatches(args) {
|
|
708
|
+
const { document, grant, userId } = args;
|
|
709
|
+
return "path" in grant ? typeof document._id == "string" && pathIncludes(grant.path, document._id) : matchesFilter({ document, filter: grant.filter, userId });
|
|
710
|
+
}
|
|
617
711
|
async function evaluateWriteAccess(args) {
|
|
618
712
|
const { document, grants, permission, userId } = args;
|
|
619
713
|
let matching = 0;
|
|
620
714
|
for (const grant of grants)
|
|
621
|
-
if (await
|
|
622
|
-
document,
|
|
623
|
-
filter: grant.filter,
|
|
624
|
-
userId
|
|
625
|
-
}) && (matching++, grant.permissions.includes(permission)))
|
|
715
|
+
if (await grantMatches({ document, grant, userId }) && (matching++, grant.permissions.includes(permission)))
|
|
626
716
|
return { allowed: !0, matchingGrants: matching };
|
|
627
717
|
return { allowed: !1, matchingGrants: matching };
|
|
628
718
|
}
|
|
@@ -747,7 +837,7 @@ function makeRequestImpl(ctx) {
|
|
|
747
837
|
const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path);
|
|
748
838
|
if (served !== void 0) return served.value;
|
|
749
839
|
throw fakeError(
|
|
750
|
-
`request(): no handler for path "${path}". With access control configured, the fake serves "/users/me", the handle's ACL ("<data base>/acl"), "/projects/<projectId>" (members), "/projects/<projectId>/users/<ids>", "/projects/<projectId>/roles", the History API (client.getDataUrl("history", \u2026)), resource lookup ("/media-libraries/<id>", "/canvases/<id>", "/dashboards/<id>") and the Access API ("/access/<type>/<id>/roles[/<name>] | users[/<id>] | user-permissions/me[/check]") and the caller's attributes ("/organizations/<id>/users/me/attributes"). For any other endpoint, register a stub (client.stub("request", fn)) or intercept the HTTP call with a tool like MSW.`
|
|
840
|
+
`request(): no handler for path "${path}". With access control configured, the fake serves "/users/me", the handle's ACL ("<data base>/acl"), "/projects/<projectId>" (members), "/projects/<projectId>/users/<ids>", "/projects/<projectId>/roles", "/projects/<projectId>/features", the History API (client.getDataUrl("history", \u2026)), resource lookup ("/media-libraries/<id>", "/canvases/<id>", "/dashboards/<id>") and the Access API ("/access/<type>/<id>/roles[/<name>] | users[/<id>] | user-permissions/me[/check]") and the caller's attributes ("/organizations/<id>/users/me/attributes"). For any other endpoint, register a stub (client.stub("request", fn)) or intercept the HTTP call with a tool like MSW.`
|
|
751
841
|
);
|
|
752
842
|
};
|
|
753
843
|
}
|
|
@@ -1545,7 +1635,7 @@ const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues",
|
|
|
1545
1635
|
},
|
|
1546
1636
|
request: {
|
|
1547
1637
|
what: "generic HTTP request hook \u2014 only wired up when the handle has an acting identity",
|
|
1548
|
-
workaround: "Create the client with `accessControl`, or bind a registered token (`identities` + `token` / `withConfig({ token })`), to enable request() (it serves /users/me, the ACL path, /projects/<projectId>, /projects/<projectId>/users/<ids>, the History API, resource lookup and the Access API). Or register a stub."
|
|
1638
|
+
workaround: "Create the client with `accessControl`, or bind a registered token (`identities` + `token` / `withConfig({ token })`), to enable request() (it serves /users/me, the ACL path, /projects/<projectId>, /projects/<projectId>/users/<ids>, /projects/<projectId>/features, the History API, resource lookup and the Access API). Or register a stub."
|
|
1549
1639
|
},
|
|
1550
1640
|
dryRun: {
|
|
1551
1641
|
what: "not a method \u2014 did you mean the `{ dryRun }` mutation option?",
|
|
@@ -1729,6 +1819,7 @@ function createTestClient(options = {}) {
|
|
|
1729
1819
|
const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = {
|
|
1730
1820
|
registry: /* @__PURE__ */ new Map(),
|
|
1731
1821
|
organizationId: options.organizationId,
|
|
1822
|
+
projectFeatures: options.projectFeatures ?? {},
|
|
1732
1823
|
log: [],
|
|
1733
1824
|
stubs: /* @__PURE__ */ new Map(),
|
|
1734
1825
|
calls: [],
|
|
@@ -1838,7 +1929,12 @@ function makeHandle(handleArgs) {
|
|
|
1838
1929
|
if (access === void 0)
|
|
1839
1930
|
throw fakeError("this handle has no acting identity (no token or accessControl bound).");
|
|
1840
1931
|
return access;
|
|
1841
|
-
},
|
|
1932
|
+
}, admitToLake = (request) => {
|
|
1933
|
+
const access = activeAccess();
|
|
1934
|
+
if (access === void 0) return;
|
|
1935
|
+
const refusal = refusedToken(request, access.grants);
|
|
1936
|
+
if (refusal !== void 0) throw refusal;
|
|
1937
|
+
}, lakeRequest = (method, operation, path) => ({ method, path: dataUrl({ resource, dataset, operation, path }) }), members = () => [
|
|
1842
1938
|
...backend.identities.values(),
|
|
1843
1939
|
...token === void 0 && accessControl !== void 0 ? [
|
|
1844
1940
|
{
|
|
@@ -1854,8 +1950,8 @@ function makeHandle(handleArgs) {
|
|
|
1854
1950
|
return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
|
|
1855
1951
|
};
|
|
1856
1952
|
let beforeWrite;
|
|
1857
|
-
const write = (run) => serializeWrite(backend, async () => {
|
|
1858
|
-
beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
|
|
1953
|
+
const write = (run, request = lakeRequest("POST", "mutate")) => serializeWrite(backend, async () => {
|
|
1954
|
+
admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
|
|
1859
1955
|
try {
|
|
1860
1956
|
return await run();
|
|
1861
1957
|
} finally {
|
|
@@ -2017,14 +2113,14 @@ function makeHandle(handleArgs) {
|
|
|
2017
2113
|
path: `${capabilities.dataBase(target.id)}/actions`
|
|
2018
2114
|
};
|
|
2019
2115
|
if (capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2020
|
-
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
2021
|
-
const refused = capabilities.refusedActions[action.actionType];
|
|
2022
|
-
if (refused !== void 0) throw refused(request);
|
|
2023
|
-
}
|
|
2024
2116
|
return write(async () => {
|
|
2117
|
+
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
2118
|
+
const refused = capabilities.refusedActions[action.actionType];
|
|
2119
|
+
if (refused !== void 0) throw refused(request);
|
|
2120
|
+
}
|
|
2025
2121
|
const result = await applyActions(store, actions, { gate, guard: guardGate });
|
|
2026
2122
|
return commitHistory(result.transactionId), result;
|
|
2027
|
-
});
|
|
2123
|
+
}, request);
|
|
2028
2124
|
}, accessVisibleDocs = async () => {
|
|
2029
2125
|
const all = store.all();
|
|
2030
2126
|
if (activeAccess() === void 0) return all;
|
|
@@ -2037,6 +2133,7 @@ function makeHandle(handleArgs) {
|
|
|
2037
2133
|
return applyPerspective(accessible, override ?? perspective);
|
|
2038
2134
|
}, client = {
|
|
2039
2135
|
fetch: async (query, params, opts) => {
|
|
2136
|
+
admitToLake(lakeRequest("GET", "query"));
|
|
2040
2137
|
const start = Date.now(), tree = groqJs.parse(query, params ? { params } : void 0), result = await (await groqJs.evaluate(tree, {
|
|
2041
2138
|
dataset: await visibleDocs(opts?.perspective),
|
|
2042
2139
|
...params !== void 0 ? { params } : {}
|
|
@@ -2048,6 +2145,7 @@ function makeHandle(handleArgs) {
|
|
|
2048
2145
|
return result;
|
|
2049
2146
|
},
|
|
2050
2147
|
getDocument: async (id, opts) => {
|
|
2148
|
+
admitToLake(lakeRequest("GET", "doc", id));
|
|
2051
2149
|
const effective = opts?.perspective ?? perspective;
|
|
2052
2150
|
if (effective === "raw") {
|
|
2053
2151
|
const doc = store.get(id);
|
|
@@ -2057,6 +2155,7 @@ function makeHandle(handleArgs) {
|
|
|
2057
2155
|
return resolveDocument(view, id, effective) ?? void 0;
|
|
2058
2156
|
},
|
|
2059
2157
|
getDocuments: async (ids, opts) => {
|
|
2158
|
+
admitToLake(lakeRequest("GET", "doc", ids.join(",")));
|
|
2060
2159
|
const effective = opts?.perspective ?? perspective;
|
|
2061
2160
|
if (effective === "raw") {
|
|
2062
2161
|
const result = [];
|
|
@@ -2170,10 +2269,16 @@ function makeHandle(handleArgs) {
|
|
|
2170
2269
|
};
|
|
2171
2270
|
},
|
|
2172
2271
|
edit: ({ releaseId, patch }) => runAction({ actionType: "sanity.action.release.edit", releaseId, patch }),
|
|
2173
|
-
|
|
2272
|
+
// `@sanity/client` reads a release by id and its documents by query.
|
|
2273
|
+
get: async ({ releaseId }) => {
|
|
2274
|
+
admitToLake(lakeRequest("GET", "doc", `_.releases.${releaseId}`));
|
|
2275
|
+
const doc = store.get(`_.releases.${releaseId}`);
|
|
2276
|
+
return doc !== void 0 && await canRead(doc) ? doc : void 0;
|
|
2277
|
+
},
|
|
2174
2278
|
fetchDocuments: async ({ releaseId }) => {
|
|
2279
|
+
admitToLake(lakeRequest("GET", "query"));
|
|
2175
2280
|
const prefix = `versions.${releaseId}.`;
|
|
2176
|
-
return
|
|
2281
|
+
return (await accessVisibleDocs()).filter((d) => d._id.startsWith(prefix));
|
|
2177
2282
|
},
|
|
2178
2283
|
schedule: ({ releaseId, publishAt }) => runAction({
|
|
2179
2284
|
actionType: "sanity.action.release.schedule",
|
|
@@ -2221,11 +2326,13 @@ function makeHandle(handleArgs) {
|
|
|
2221
2326
|
platform: {
|
|
2222
2327
|
projectId,
|
|
2223
2328
|
organizationId: backend.organizationId,
|
|
2329
|
+
projectFeatures: backend.projectFeatures,
|
|
2224
2330
|
own: (asked) => registryKey(asked) === registryKey(target) ? {
|
|
2225
2331
|
grants: requireActiveAccess().grants,
|
|
2226
2332
|
documents: () => store.all(),
|
|
2227
2333
|
history,
|
|
2228
|
-
canRead
|
|
2334
|
+
canRead,
|
|
2335
|
+
admitToLake
|
|
2229
2336
|
} : void 0,
|
|
2230
2337
|
actorUser: () => {
|
|
2231
2338
|
const access = requireActiveAccess();
|