@sanity-labs/client-fake-for-test 0.15.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 CHANGED
@@ -76,12 +76,12 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
76
76
  | Patch | `patch(id)` chain → `.commit()` | Ops: `.set`, `.setIfMissing`, `.unset`, `.inc`, `.dec`, `.insert(position, anchor, items)`, `.ifRevisionId` |
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
- | Releases | `releases.*`, `createVersion`, `unpublishVersion` | Content Releases lifecycle — create / edit / schedule / publish / archive / delete, plus version create / replace / discard / unpublish |
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; a missing base fails. A failed revision precondition (`ifDraftRevisionId`, `ifPublishedRevisionId`, `ifBaseRevisionId`) carries `statusCode: 409`, as the Actions API answers |
80
80
  | Config | `config()` | Returns `{ projectId, dataset, resource?, perspective, token?, useProjectHostname }` |
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`), 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.
@@ -199,16 +233,19 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
199
233
  | Access API `…/user-permissions/me`, `…/me/check` | ✅ | ✅ | ✅ | ✅ |
200
234
  | Access API `…/users` | ✅ | ✅ | 403 | 403 |
201
235
  | Access API `…/users/<sanityUserId>` (served on `organization`, below) | 403 | 403 | 403 | 403 |
202
- | Access API `…/roles`, `…/roles/<roleName>` | ✅ | ✅ with `sanity.media-library.roles.read`, else 403 | 403 | 403 |
236
+ | Access API `…/roles`, `…/roles/<roleName>` | ✅ with `sanity.project.roles.read`, else 403 | ✅ with `sanity.media-library.roles.read`, else 403 | 403 | 403 |
237
+ | Project role catalog `/projects/<projectId>/roles` | ✅ with `sanity.project.roles.read`, else 403 | n/a | n/a | n/a |
203
238
  | Org lookup | `/projects/<projectId>` | `GET /media-libraries/<id>` | `GET /canvases/<id>` | `GET /dashboards/<id>` |
204
239
 
205
240
  - **Access API.** Paths are `/access/<type>/<id>/…` with type `organization`, `project`, `media-library`, `canvas` or `dashboard`. An identity's `access` entries, keyed `"<type>:<id>"`, hold its `roles` there (membership) and the `permissions` the `user-permissions` endpoints report. Every identity is a project member with its project roles. A user row is `{ sanityUserId, profile: { id, displayName, email, provider, createdAt }, memberships: [{ resourceType, resourceId, roleNames }] }`; the fake does not model `provider` or `createdAt`, so they are always `"sanity"` and the epoch, and `email` is `""` where the identity seeds none. Listings come back on one page (`nextCursor: null`); users listings add `totalCount`. `includeImpliedRoles` is accepted and ignored: rows carry the seeded roles only, so seed an implied role explicitly when a test needs it. An unknown type answers 400 `Invalid resource type <type>`. An id the registry does not hold (never seeded, written or addressed) answers 404 `Media library not found` / `Canvas not found` / `Dashboard not found`, except `…/me/check`, which answers `false` as staging does. `…/users/<sanityUserId>` is served only on the organization, where the fake checks members read; elsewhere it answers 403 (the reference requires `sanity.<type>.members.read` for it; no type's single-user read was probed on staging, only the media-library listing). The other 403 cells were not proven on staging (no token could list them), so they answer the way the platform refuses a missing permission: `{ statusCode: 403, error: "Forbidden", message: "You do not have permission to access this resource" }`.
206
241
  - **Members.** Every member listing (`/projects/<projectId>`, `…/users`, `…/roles`) sees the registered identities plus, on a handle created with inline `accessControl`, that handle's own actor. Inline config belongs to its handle: a token sibling does not see it.
207
- - **Roles.** `…/roles` answers `{ data: [role], nextCursor: null }` and `…/roles/<roleName>` one role (404 `Role not found` for a name no member holds). A role is `{ name, title, description?, resourceType, resourceId, appliesToUsers, appliesToRobots, permissions }`, collected from the roles the members hold on the resource. The fake does not model role definitions, so `title` is the name where the seed gives none, both `appliesTo…` flags are `true` and `permissions` is `[]`. A media library serves its roles only to an actor whose `"media-library:<id>"` entry holds `sanity.media-library.roles.read` in `permissions`, else 403, as the reference requires.
242
+ - **Roles.** `…/roles` answers `{ data: [role], nextCursor: null }` and `…/roles/<roleName>` one role (404 `Role not found` for a name no member holds). A role is `{ name, title, description?, resourceType, resourceId, appliesToUsers, appliesToRobots, permissions }`, collected from the roles the members hold on the resource. The fake does not model role definitions, so `title` is the name where the seed gives none, both `appliesTo…` flags are `true` and `permissions` is `[]`. A media library serves its roles only to an actor whose `"media-library:<id>"` entry holds `sanity.media-library.roles.read` in `permissions`, else 403, as the reference requires. Likewise a project serves its roles only to an actor whose `"project:<id>"` entry holds `sanity.project.roles.read` (on staging every stock user role holds it), else 403.
243
+ - **Project role catalog.** `GET /projects/<projectId>/roles` answers the older projects API's bare array, one row per role the project's members hold: `{ name, title, description?, projectId, appliesToUsers, appliesToRobots }`, with the same unmodelled defaults as the Access API rows. The platform also sends `isCustom` and a `grants` tree per role; the fake does not model role definitions, so it omits both. It needs `sanity.project.roles.read` on the actor's `"project:<projectId>"` entry, else 403 with the Access API's permission body.
208
244
  - **Organization.** `/access/organization/<organizationId>/users` and `…/users/<sanityUserId>` (one row, or 404 `User not found` for a non-member) serve the members of the client's `organizationId`: identities with roles in their `"organization:<id>"` entry. Each row lists the organization membership, then the member's roles on every resource the client holds (its libraries, canvases, dashboards and projects), as the platform's organization row does. Like the platform, it needs `sanity.organization.members.read` in the actor's `"organization:<id>"` `permissions` (the built-in `member` role grants it), else 403. Another organization id answers 404 `Organization not found`; `…/roles` answers 403.
209
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`.
210
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.
211
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.
212
249
  - **Identity.** `@sanity/client` sends a `resource` client's requests to the global host, so `/users/me` answers `globalUser`.
213
250
 
214
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;
@@ -284,6 +223,8 @@ const ACCESS_CAPABILITIES = {
284
223
  },
285
224
  project: {
286
225
  roles: "served",
226
+ // Also gates `GET /projects/<id>/roles`; the stock user roles all hold it on staging.
227
+ rolesPermission: "sanity.project.roles.read",
287
228
  users: "served",
288
229
  // Single-user reads are served only where the fake checks members read (the
289
230
  // organization); elsewhere they refuse rather than answer unchecked.
@@ -333,7 +274,148 @@ function dataUrl(args) {
333
274
  const base = `/${operation}/${dataset}`;
334
275
  return `/data${path !== void 0 ? `${base}/${path}` : base}`.replace(/\/($|\?)/, "$1");
335
276
  }
336
- const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/;
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\/([^/]+)(\/.*)$/;
337
419
  function page(data) {
338
420
  return { data, nextCursor: null };
339
421
  }
@@ -347,6 +429,16 @@ async function servePlatformRequest(ctx, url) {
347
429
  const organizationId = decodeURIComponent(myAttributes[1]);
348
430
  return serveMyAttributes({ ctx, request, organizationId, query });
349
431
  }
432
+ const projectRoles = path.match(PROJECT_ROLES_PATH);
433
+ if (projectRoles !== null) {
434
+ const projectId = decodeURIComponent(projectRoles[1]);
435
+ return serveProjectRoles({ ctx, request, projectId });
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
+ }
350
442
  const access = path.match(ACCESS_PATH);
351
443
  if (access !== null) {
352
444
  const [, type, id, rest2] = access;
@@ -369,6 +461,10 @@ async function servePlatformRequest(ctx, url) {
369
461
  if (rest.startsWith("/history/"))
370
462
  return serveHistory({ ctx, request, resource, rest: rest.slice(8), query });
371
463
  }
464
+ function featuresOf(ctx, projectId) {
465
+ const features = Object.hasOwn(ctx.projectFeatures, projectId) ? ctx.projectFeatures[projectId] : [];
466
+ return [...new Set(features)].toSorted();
467
+ }
372
468
  function serveLookup(ctx, resource) {
373
469
  if (ctx.organizationId === void 0)
374
470
  throw fakeError(
@@ -380,7 +476,8 @@ function serveHistory(args) {
380
476
  const { ctx, request, resource, rest, query } = args;
381
477
  return serveCapability(capabilitiesOf(resource.type).history, request, () => {
382
478
  const own = ctx.own(resource);
383
- return own === void 0 ? void 0 : readHistory({ own, request, rest, query });
479
+ if (own !== void 0)
480
+ return own.admitToLake(request), readHistory({ own, request, rest, query });
384
481
  });
385
482
  }
386
483
  async function readHistory(args) {
@@ -414,6 +511,35 @@ async function readHistory(args) {
414
511
  }
415
512
  };
416
513
  }
514
+ function serveGated(args) {
515
+ const { capability, permission, held, request, serve } = args;
516
+ return serveCapability(capability, request, () => {
517
+ if (permission !== void 0 && !held.includes(permission)) throw noPermission(request);
518
+ return serve();
519
+ });
520
+ }
521
+ function serveProjectRoles(args) {
522
+ const { ctx, request, projectId } = args, row = ACCESS_CAPABILITIES.project;
523
+ return serveGated({
524
+ capability: row.roles,
525
+ permission: row.rolesPermission,
526
+ held: ctx.actorAccess()?.[accessKey("project", projectId)]?.permissions ?? [],
527
+ request,
528
+ serve: () => ({
529
+ value: rolesOn({
530
+ resource: { type: "project", id: projectId },
531
+ identities: ctx.identities()
532
+ }).map((role) => ({
533
+ name: role.name,
534
+ title: role.title,
535
+ ...role.description !== void 0 ? { description: role.description } : {},
536
+ projectId,
537
+ appliesToUsers: role.appliesToUsers,
538
+ appliesToRobots: role.appliesToRobots
539
+ }))
540
+ })
541
+ });
542
+ }
417
543
  function serveAccess(args) {
418
544
  const { ctx, request, type, id, rest, query } = args, row = accessCapabilitiesOf(type);
419
545
  if (row === void 0) throw invalidAccessType(request, type);
@@ -429,11 +555,7 @@ function serveAccess(args) {
429
555
  }
430
556
  if (row.unknown !== void 0 && !row.unknown.holds(registry, id))
431
557
  throw row.unknown.refusal(request);
432
- const gated = (capability, permission, serve) => serveCapability(capability, request, () => {
433
- if (permission !== void 0 && !permissions.includes(permission))
434
- throw noPermission(request);
435
- return serve();
436
- }), users = (capability, serve) => gated(capability, row.usersPermission, serve), roles = () => rolesOn({ resource, identities: ctx.identities() }), user = rest.match(ACCESS_USER_PATH);
558
+ const gated = (capability, permission, serve) => serveGated({ capability, permission, held: permissions, request, serve }), users = (capability, serve) => gated(capability, row.usersPermission, serve), roles = () => rolesOn({ resource, identities: ctx.identities() }), user = rest.match(ACCESS_USER_PATH);
437
559
  if (user !== null)
438
560
  return users(row.user, () => {
439
561
  const sanityUserId = decodeURIComponent(user[1]), record = usersOn({ resource, registry, identities: ctx.identities() }).find(
@@ -582,15 +704,15 @@ async function matchesFilter(args) {
582
704
  })).get();
583
705
  return Array.isArray(data) && data.length === 1;
584
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
+ }
585
711
  async function evaluateWriteAccess(args) {
586
712
  const { document, grants, permission, userId } = args;
587
713
  let matching = 0;
588
714
  for (const grant of grants)
589
- if (await matchesFilter({
590
- document,
591
- filter: grant.filter,
592
- userId
593
- }) && (matching++, grant.permissions.includes(permission)))
715
+ if (await grantMatches({ document, grant, userId }) && (matching++, grant.permissions.includes(permission)))
594
716
  return { allowed: !0, matchingGrants: matching };
595
717
  return { allowed: !1, matchingGrants: matching };
596
718
  }
@@ -715,7 +837,7 @@ function makeRequestImpl(ctx) {
715
837
  const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path);
716
838
  if (served !== void 0) return served.value;
717
839
  throw fakeError(
718
- `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>", 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.`
719
841
  );
720
842
  };
721
843
  }
@@ -1261,6 +1383,7 @@ async function applyAction(store, action, hooks) {
1261
1383
  return store.remove(release._id), { transactionId: cryptoRandomKey() };
1262
1384
  }
1263
1385
  case "sanity.action.document.version.create": {
1386
+ if ("baseId" in action) return createVersionFromBase(store, action);
1264
1387
  const releaseId = action.releaseId ?? (action.document._id !== void 0 ? parseVersionId(action.document._id).releaseId : void 0);
1265
1388
  if (releaseId === void 0)
1266
1389
  throw fakeError(
@@ -1332,10 +1455,33 @@ function requireDraftOf(action) {
1332
1455
  `${action.actionType}: draftId "${action.draftId}" is not the draft of publishedId "${action.publishedId}" \u2014 expected draftId "drafts.${action.publishedId}".`
1333
1456
  );
1334
1457
  }
1458
+ function createVersionFromBase(store, action) {
1459
+ const { releaseId, publishedId } = parseVersionId(action.versionId);
1460
+ if (publishedId !== action.publishedId)
1461
+ throw fakeError(
1462
+ `version.create: versionId "${action.versionId}" is not a version of publishedId "${action.publishedId}" (expected "${versionDocId(releaseId, action.publishedId)}").`
1463
+ );
1464
+ requireActive(getRelease(store, releaseId));
1465
+ const base = store.get(action.baseId);
1466
+ if (base === void 0)
1467
+ throw fakeError(
1468
+ `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
+ );
1470
+ requireRevisionMatch(action.baseId, base._rev, action.ifBaseRevisionId);
1471
+ const existing = store.get(action.versionId), promoted = promote({
1472
+ ...base,
1473
+ _id: action.versionId,
1474
+ _createdAt: existing?._createdAt ?? nowIso()
1475
+ });
1476
+ return store.put(promoted), { transactionId: cryptoRandomKey() };
1477
+ }
1335
1478
  function requireRevisionMatch(documentId, actualRev, expectedRev) {
1336
1479
  if (!(expectedRev === void 0 || actualRev === expectedRev))
1337
- throw fakeError(
1338
- `Revision precondition failed for "${documentId}": expected _rev "${expectedRev}" but the document is at ${actualRev === void 0 ? "no revision (missing)" : `"${actualRev}"`}.`
1480
+ throw Object.assign(
1481
+ fakeError(
1482
+ `Revision precondition failed for "${documentId}": expected _rev "${expectedRev}" but the document is at ${actualRev === void 0 ? "no revision (missing)" : `"${actualRev}"`}.`
1483
+ ),
1484
+ { statusCode: 409 }
1339
1485
  );
1340
1486
  }
1341
1487
  async function applyActions(store, actions, hooks) {
@@ -1363,6 +1509,10 @@ async function applyActions(store, actions, hooks) {
1363
1509
  break;
1364
1510
  }
1365
1511
  case "sanity.action.document.version.create": {
1512
+ if ("baseId" in a) {
1513
+ remember(a.versionId);
1514
+ break;
1515
+ }
1366
1516
  const releaseId = a.releaseId ?? (typeof a.document._id == "string" ? parseVersionId(a.document._id).releaseId : void 0);
1367
1517
  releaseId !== void 0 && remember(versionDocId(releaseId, a.publishedId));
1368
1518
  break;
@@ -1485,7 +1635,7 @@ const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues",
1485
1635
  },
1486
1636
  request: {
1487
1637
  what: "generic HTTP request hook \u2014 only wired up when the handle has an acting identity",
1488
- 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."
1489
1639
  },
1490
1640
  dryRun: {
1491
1641
  what: "not a method \u2014 did you mean the `{ dryRun }` mutation option?",
@@ -1669,6 +1819,7 @@ function createTestClient(options = {}) {
1669
1819
  const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = {
1670
1820
  registry: /* @__PURE__ */ new Map(),
1671
1821
  organizationId: options.organizationId,
1822
+ projectFeatures: options.projectFeatures ?? {},
1672
1823
  log: [],
1673
1824
  stubs: /* @__PURE__ */ new Map(),
1674
1825
  calls: [],
@@ -1778,7 +1929,12 @@ function makeHandle(handleArgs) {
1778
1929
  if (access === void 0)
1779
1930
  throw fakeError("this handle has no acting identity (no token or accessControl bound).");
1780
1931
  return access;
1781
- }, members = () => [
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 = () => [
1782
1938
  ...backend.identities.values(),
1783
1939
  ...token === void 0 && accessControl !== void 0 ? [
1784
1940
  {
@@ -1794,8 +1950,8 @@ function makeHandle(handleArgs) {
1794
1950
  return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
1795
1951
  };
1796
1952
  let beforeWrite;
1797
- const write = (run) => serializeWrite(backend, async () => {
1798
- 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]));
1799
1955
  try {
1800
1956
  return await run();
1801
1957
  } finally {
@@ -1957,14 +2113,14 @@ function makeHandle(handleArgs) {
1957
2113
  path: `${capabilities.dataBase(target.id)}/actions`
1958
2114
  };
1959
2115
  if (capabilities.actions !== "served") throw capabilities.actions(request);
1960
- for (const action of Array.isArray(actions) ? actions : [actions]) {
1961
- const refused = capabilities.refusedActions[action.actionType];
1962
- if (refused !== void 0) throw refused(request);
1963
- }
1964
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
+ }
1965
2121
  const result = await applyActions(store, actions, { gate, guard: guardGate });
1966
2122
  return commitHistory(result.transactionId), result;
1967
- });
2123
+ }, request);
1968
2124
  }, accessVisibleDocs = async () => {
1969
2125
  const all = store.all();
1970
2126
  if (activeAccess() === void 0) return all;
@@ -1977,6 +2133,7 @@ function makeHandle(handleArgs) {
1977
2133
  return applyPerspective(accessible, override ?? perspective);
1978
2134
  }, client = {
1979
2135
  fetch: async (query, params, opts) => {
2136
+ admitToLake(lakeRequest("GET", "query"));
1980
2137
  const start = Date.now(), tree = groqJs.parse(query, params ? { params } : void 0), result = await (await groqJs.evaluate(tree, {
1981
2138
  dataset: await visibleDocs(opts?.perspective),
1982
2139
  ...params !== void 0 ? { params } : {}
@@ -1988,6 +2145,7 @@ function makeHandle(handleArgs) {
1988
2145
  return result;
1989
2146
  },
1990
2147
  getDocument: async (id, opts) => {
2148
+ admitToLake(lakeRequest("GET", "doc", id));
1991
2149
  const effective = opts?.perspective ?? perspective;
1992
2150
  if (effective === "raw") {
1993
2151
  const doc = store.get(id);
@@ -1997,6 +2155,7 @@ function makeHandle(handleArgs) {
1997
2155
  return resolveDocument(view, id, effective) ?? void 0;
1998
2156
  },
1999
2157
  getDocuments: async (ids, opts) => {
2158
+ admitToLake(lakeRequest("GET", "doc", ids.join(",")));
2000
2159
  const effective = opts?.perspective ?? perspective;
2001
2160
  if (effective === "raw") {
2002
2161
  const result = [];
@@ -2110,10 +2269,16 @@ function makeHandle(handleArgs) {
2110
2269
  };
2111
2270
  },
2112
2271
  edit: ({ releaseId, patch }) => runAction({ actionType: "sanity.action.release.edit", releaseId, patch }),
2113
- get: async ({ releaseId }) => store.get(`_.releases.${releaseId}`),
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
+ },
2114
2278
  fetchDocuments: async ({ releaseId }) => {
2279
+ admitToLake(lakeRequest("GET", "query"));
2115
2280
  const prefix = `versions.${releaseId}.`;
2116
- return store.all().filter((d) => d._id.startsWith(prefix));
2281
+ return (await accessVisibleDocs()).filter((d) => d._id.startsWith(prefix));
2117
2282
  },
2118
2283
  schedule: ({ releaseId, publishAt }) => runAction({
2119
2284
  actionType: "sanity.action.release.schedule",
@@ -2126,12 +2291,25 @@ function makeHandle(handleArgs) {
2126
2291
  unarchive: ({ releaseId }) => runAction({ actionType: "sanity.action.release.unarchive", releaseId }),
2127
2292
  delete: ({ releaseId }) => runAction({ actionType: "sanity.action.release.delete", releaseId })
2128
2293
  },
2129
- createVersion: ({ releaseId, publishedId, document }) => runAction({
2130
- actionType: "sanity.action.document.version.create",
2131
- releaseId,
2132
- publishedId,
2133
- document
2134
- }),
2294
+ createVersion: (params) => {
2295
+ const { releaseId, publishedId, document, baseId, ifBaseRevisionId } = params;
2296
+ if (document)
2297
+ return runAction({
2298
+ actionType: "sanity.action.document.version.create",
2299
+ releaseId,
2300
+ publishedId,
2301
+ document
2302
+ });
2303
+ if (baseId === void 0)
2304
+ throw fakeError("createVersion() requires `baseId` when no `document` is provided.");
2305
+ return runAction({
2306
+ actionType: "sanity.action.document.version.create",
2307
+ publishedId,
2308
+ baseId,
2309
+ versionId: `versions.${releaseId}.${publishedId}`,
2310
+ ...ifBaseRevisionId !== void 0 ? { ifBaseRevisionId } : {}
2311
+ });
2312
+ },
2135
2313
  unpublishVersion: ({ releaseId, publishedId }) => runAction({
2136
2314
  actionType: "sanity.action.document.version.unpublish",
2137
2315
  versionId: `versions.${releaseId}.${publishedId}`,
@@ -2148,11 +2326,13 @@ function makeHandle(handleArgs) {
2148
2326
  platform: {
2149
2327
  projectId,
2150
2328
  organizationId: backend.organizationId,
2329
+ projectFeatures: backend.projectFeatures,
2151
2330
  own: (asked) => registryKey(asked) === registryKey(target) ? {
2152
2331
  grants: requireActiveAccess().grants,
2153
2332
  documents: () => store.all(),
2154
2333
  history,
2155
- canRead
2334
+ canRead,
2335
+ admitToLake
2156
2336
  } : void 0,
2157
2337
  actorUser: () => {
2158
2338
  const access = requireActiveAccess();