@sanity-labs/client-fake-for-test 0.19.0 → 0.20.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
@@ -293,7 +293,7 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
293
293
  | Project role catalog `/projects/<projectId>/roles` | ✅ with `sanity.project.roles.read`, else 403 | n/a | n/a | n/a |
294
294
  | Org lookup | `/projects/<projectId>` | `GET /media-libraries/<id>` | `GET /canvases/<id>` | `GET /dashboards/<id>` |
295
295
 
296
- - **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 member of every project with its project roles, except a project-scoped one (`projectId`, see [Project-scoped tokens](#project-scoped-tokens-membership-and-refusals)), which is a member of its own project only. 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" }`.
296
+ - **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 member of every project with its project roles, except a project-scoped one (`projectId`, see [Project-scoped tokens](#project-scoped-tokens-membership-and-refusals)), which is a member of its own project only. 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 that does not exist answers 404 `Media library not found` / `Canvas not found` / `Dashboard not found`, except `…/me/check`, which answers `false` as staging does. A Media Library, Canvas or dashboard exists once it is seeded (`resources`, `documents`, or `seed()` / `add()` on its handle or its `store()`) or written to through the fake; pointing a client at it (`withConfig({ resource })`) does not create it, as on the platform. `…/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" }`.
297
297
  - **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.
298
298
  - **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.
299
299
  - **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.
@@ -302,7 +302,7 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
302
302
  - **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.
303
303
  - **Org lookup.** `createTestClient({ organizationId })` names the organization every resource of the client belongs to.
304
304
  - **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 `[]`. Only a project member may read it, as on the platform: an identity without `projectId` reads every project's features, and a project-scoped one only its own project's, with 401 `User must be a member of this project to perform this operation` for any other (see [Project-scoped tokens](#project-scoped-tokens-membership-and-refusals)).
305
- - **ACL refusals.** A Media Library's ACL needs `sanity.media-library.read` in the actor's `"media-library:<id>"` `permissions`, else 401 `{ statusCode: 401, error: "Unauthorized", message: "User must be able to read media libraries for this organization to perform this operation" }`. A Media Library or Canvas id the registry does not hold (never seeded, written or addressed by a handle) answers 404 `{ statusCode: 404, error: "Not Found", message: "Media library not found" }` / `{ …, message: "Resource not found" }`. That is the platform's answer for an unknown resource on a route it mounts, distinct from the `Cannot GET …` text body of a route it does not mount (a dashboard's ACL). An explicit `accessControl.aclPath` naming one of these ACLs is refused the same way.
305
+ - **ACL refusals.** A Media Library's ACL needs `sanity.media-library.read` in the actor's `"media-library:<id>"` `permissions`, else 401 `{ statusCode: 401, error: "Unauthorized", message: "User must be able to read media libraries for this organization to perform this operation" }`. A Media Library or Canvas that does not exist (never seeded or written to; a client pointed at it does not create it) answers 404 `{ statusCode: 404, error: "Not Found", message: "Media library not found" }` / `{ …, message: "Resource not found" }`. That is the platform's answer for an unknown resource on a route it mounts, distinct from the `Cannot GET …` text body of a route it does not mount (a dashboard's ACL). An explicit `accessControl.aclPath` naming one of these ACLs is refused the same way.
306
306
  - **Identity.** `@sanity/client` sends a `resource` client's requests to the global host, so `/users/me` answers `globalUser`.
307
307
 
308
308
  ### Errors are `ClientError`s
package/dist/index.cjs CHANGED
@@ -1915,7 +1915,16 @@ const registryKey = (resource) => `${resource.type}:${resource.id}`, datasetReso
1915
1915
  function ensureEntry(registry, resource) {
1916
1916
  const key = registryKey(resource);
1917
1917
  let entry = registry.get(key);
1918
- return entry === void 0 && (entry = { resource, store: createTestStore(), history: createDocumentHistory() }, registry.set(key, entry)), entry;
1918
+ return entry === void 0 && (entry = {
1919
+ resource,
1920
+ store: createTestStore(),
1921
+ history: createDocumentHistory(),
1922
+ exists: !1
1923
+ }, registry.set(key, entry)), entry;
1924
+ }
1925
+ function seedEntry(registry, resource, documents) {
1926
+ const entry = ensureEntry(registry, resource);
1927
+ entry.store.seed(documents), entry.exists = !0;
1919
1928
  }
1920
1929
  function createTestClient(options = {}) {
1921
1930
  const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = {
@@ -1932,16 +1941,16 @@ function createTestClient(options = {}) {
1932
1941
  }, registry = backend.registry;
1933
1942
  if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
1934
1943
  const root = options.resource ?? datasetResource(defaultProjectId, defaultDataset);
1935
- ensureEntry(registry, root).store.seed(options.documents);
1944
+ seedEntry(registry, root, options.documents);
1936
1945
  }
1937
1946
  if (options.datasets)
1938
1947
  for (const [key, docs] of Object.entries(options.datasets)) {
1939
1948
  const { projectId, dataset } = parseDatasetKey(key);
1940
- ensureEntry(registry, datasetResource(projectId, dataset)).store.seed(docs);
1949
+ seedEntry(registry, datasetResource(projectId, dataset), docs);
1941
1950
  }
1942
1951
  if (options.resources)
1943
1952
  for (const [key, docs] of Object.entries(options.resources))
1944
- ensureEntry(registry, parseResourceKey(key)).store.seed(docs);
1953
+ seedEntry(registry, parseResourceKey(key), docs);
1945
1954
  return makeHandle({
1946
1955
  backend,
1947
1956
  projectId: defaultProjectId,
@@ -2055,7 +2064,18 @@ function makeHandle(handleArgs) {
2055
2064
  ...accessControl.access !== void 0 ? { access: accessControl.access } : {}
2056
2065
  }
2057
2066
  ] : []
2058
- ], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), { store, history } = ensureEntry(registry, target), concurrentEditKey = (id) => registryKey(target) + " " + id, actorId = () => {
2067
+ ], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, publicStore = {
2068
+ ...store,
2069
+ seed: (documents) => {
2070
+ store.seed(documents), targetEntry.exists = !0;
2071
+ },
2072
+ add: (documents) => {
2073
+ store.add(documents), targetEntry.exists = !0;
2074
+ },
2075
+ put: (doc) => {
2076
+ store.put(doc), targetEntry.exists = !0;
2077
+ }
2078
+ }, concurrentEditKey = (id) => registryKey(target) + " " + id, actorId = () => {
2059
2079
  const access = activeAccess();
2060
2080
  if (access !== void 0)
2061
2081
  return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
@@ -2069,7 +2089,7 @@ function makeHandle(handleArgs) {
2069
2089
  beforeWrite = void 0, writeRequest = DEFAULT_WRITE;
2070
2090
  }
2071
2091
  }), commitHistory = (transactionId) => {
2072
- beforeWrite !== void 0 && history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() });
2092
+ beforeWrite !== void 0 && (targetEntry.exists = !0, history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() }));
2073
2093
  }, record = (transactionId, mutations, tag) => {
2074
2094
  const effectiveTag = effectiveRequestTag(tag);
2075
2095
  commitHistory(transactionId), backend.log.push({
@@ -2453,7 +2473,9 @@ function makeHandle(handleArgs) {
2453
2473
  actorAccess: () => requireActiveAccess().access,
2454
2474
  actorProjectId: () => token === void 0 ? void 0 : backend.identities.get(token)?.projectId,
2455
2475
  identities: members,
2456
- resources: () => [...registry.values()].map((entry) => entry.resource)
2476
+ // A dataset stands for its project, and every project exists in
2477
+ // the fake, so a dataset handle still counts as before.
2478
+ resources: () => [...registry.values()].filter((e) => e.exists || e.resource.type === "dataset").map((e) => e.resource)
2457
2479
  }
2458
2480
  })
2459
2481
  )
@@ -2484,11 +2506,11 @@ function makeHandle(handleArgs) {
2484
2506
  hasProjectId: hasProjectId || config.projectId !== void 0
2485
2507
  });
2486
2508
  },
2487
- seed: (documents) => store.seed(documents),
2488
- add: (documents) => store.add(documents),
2509
+ seed: (documents) => publicStore.seed(documents),
2510
+ add: (documents) => publicStore.add(documents),
2489
2511
  reset: () => store.reset(),
2490
2512
  snapshot: () => store.snapshot(),
2491
- store: () => store,
2513
+ store: () => publicStore,
2492
2514
  simulateConcurrentEdit: (id, count = 1) => {
2493
2515
  const editKey = concurrentEditKey(id);
2494
2516
  backend.concurrentEdits.set(editKey, (backend.concurrentEdits.get(editKey) ?? 0) + count);