@sanity-labs/client-fake-for-test 0.27.0 → 0.29.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
@@ -200,11 +200,11 @@ The Content Lake refuses the token on every request it serves (queries, document
200
200
  | `i` that is not a string | 400, `token field "i" must be a string` |
201
201
  | `x` at or before now | 403 `{ error: { type: "permissionDeniedError", description: "Token has expired (at 2026-11-20 12:00:30 +0000 UTC)" } }` |
202
202
 
203
- A JWT that does not verify still binds, as production clients accept any string; the refusal comes on the first request. Without `internalTokenKeys` a JWT is an unknown token, as before. An internal token has no session, so `revokeIdentity` throws for one: mint one whose `x` has passed instead. The project API (populus) verifies internal tokens with its own key and answers differently; the fake does not model that, so `request()` of `/users/me`, `/projects/…`, the Access API or an ACL throws a fake error with an internal token. Claims the fake does not model (`tokenType`, `guid`, `s`, `z`, `audit`, `act`, `exp`, `iat`, `nbf`, or a claims segment that is not a JSON object) throw a fake error instead of a guessed answer. A missing `i`, or a `g…` global user id other than `god` (which gradient maps to a project user), throws its fake error on a request, after the 400 and 403 checks above.
203
+ A JWT that does not verify still binds, as production clients accept any string; the refusal comes on the first request. Without `internalTokenKeys` a JWT is an unknown token, as before. An internal token has no session, so `revokeIdentity` throws for one: mint one whose `x` has passed instead. The project API (populus) verifies internal tokens with its own key and answers differently; the fake models that only for the [organization store lookup](#organization-stores), so `request()` of `/users/me`, `/projects/…`, the Access API or an ACL throws a fake error with an internal token. A token with claims the Content Lake reads but the fake does not model (`tokenType`, `guid`, `s`, `z`, `audit`, `act`) binds, and throws a fake error on a Content Lake request instead of a guessed answer; `exp`, `iat`, `nbf` or a claims segment that is not a JSON object throw when the token binds. A missing `i`, or a `g…` global user id other than `god` (which gradient maps to a project user), throws its fake error on a request, after the 400 and 403 checks above.
204
204
 
205
205
  #### Platform outages
206
206
 
207
- `client.simulateOutage("project-api")` takes the project API (populus) down, as in an outage. From the next request on, every `request()` it serves throws a `PlatformServerError`, on every handle of the family, siblings made before and after the call alike: `/users/me`, `/projects/<projectId>` and everything under it (members, users, roles, features, the dataset ACL), `/organizations/<id>/users/me/attributes`, the Access API, resource lookup (`/canvases/<id>`, …) and a Media Library's or Canvas's ACL. `PlatformServerError` extends `@sanity/client`'s `ServerError`, which the client throws for a status of 500 or more, not `ClientError`, and the client does not retry it:
207
+ `client.simulateOutage("project-api")` takes the project API (populus) down, as in an outage. From the next request on, every `request()` it serves throws a `PlatformServerError`, on every handle of the family, siblings made before and after the call alike: `/users/me`, `/projects/<projectId>` and everything under it (members, users, roles, features, the dataset ACL), `/organizations/<id>/users/me/attributes`, the organization store lookup, the Access API, resource lookup (`/canvases/<id>`, …) and a Media Library's or Canvas's ACL. `PlatformServerError` extends `@sanity/client`'s `ServerError`, which the client throws for a status of 500 or more, not `ClientError`, and the client does not retry it:
208
208
 
209
209
  ```ts
210
210
  {
@@ -222,6 +222,52 @@ A JWT that does not verify still binds, as production clients accept any string;
222
222
 
223
223
  That is the body populus sends for an unexpected error: its error handler sends Boom's payload, and Boom hides the error's own message behind a fixed one. The Content Lake keeps answering (queries, documents, mutations, actions, the History API), as does a route a resource does not mount (Express's 404). A token without a session is still refused with its 401 first, as the gateway checks the session before it routes. The call is recorded in `client.calls()` with its error. `"project-api"` is the only component so far, and an outage lasts for the rest of the family's life; create a new client for a healthy platform.
224
224
 
225
+ #### Organization stores
226
+
227
+ Populus keeps one document store per organization, which a service looks up with `GET /internal/organization-stores?organizationId=<id>`. Give the client its organization, and `request()` answers the lookup as populus does (`src/controllers/internal/organizationStores.ts`):
228
+
229
+ ```ts
230
+ const client = createTestClient({
231
+ useProjectHostname: false,
232
+ organizationId: "oAbc",
233
+ internalTokenKeys: [publicKeyPem],
234
+ token: serviceToken, // an RS256 JWT with tokenType: "service"
235
+ organizationStores: { oAbc: "active" }, // optional: a store that already exists
236
+ });
237
+ await client.request({ uri: "/internal/organization-stores", query: { organizationId: "oAbc" } });
238
+ // { id: "os…", organizationId: "oAbc", status: "active" }
239
+ ```
240
+
241
+ The first lookup for an organization without a store creates one `provisioning`, as populus does, and every later lookup answers the same store. In populus a background workflow then sets it `active`; in the fake `client.completeOrganizationStoreProvisioning("oAbc")` stands for that workflow finishing, and the next lookup answers `active`. A store whose provisioning never completes stays `provisioning`. The id is `os` and ten characters, derived from the organization id, so the same organization always gets the same id. Stores are shared by the whole `withConfig` family.
242
+
243
+ | Request | Answer |
244
+ | --- | --- |
245
+ | A registered identity's token (a user or robot session), or an internal token that is not a service token | 401 `{ statusCode: 401, error: "Unauthorized", message: "A service session is required for this endpoint" }` |
246
+ | An internal token without a signature, signed by another key, or past its `x` | 401, `jwt signature is required` / `invalid signature` / `Session expired` |
247
+ | A missing, empty, repeated or unknown query parameter | 400 `{ statusCode: 400, error: "Bad Request", message: "Validation failed", validation: { query: { source: "query", keys: [<key>], message: '"organizationId" is required' } } }` |
248
+ | An organization other than `organizationId` | 404, `Organization <id> not found` |
249
+ | While `simulateOutage("project-api")` is in effect | 500 (see [Platform outages](#platform-outages)); no store is created |
250
+
251
+ Populus answers only `provisioning` and `active` stores, so the lookup never answers another status, and seeding another status throws. `request()` takes a `query` object as `@sanity/client` does, appended to the URL after the request tag; every route reads its parameters from that URL. A `tag` in `query`, and bracketed query keys such as `organizationId[]` (which Express parses into nested values), throw a fake error.
252
+
253
+ #### Missing datasets
254
+
255
+ `createTestClient({ missingDatasets: ["p1:staged"] })` names datasets the platform does not have, as `"<projectId>:<dataset>"` keys. Every Content Lake request on one (queries, documents, mutations, actions, the History API) throws the `PlatformHttpError` the Content Lake answers for a missing dataset, on every handle of the family:
256
+
257
+ ```ts
258
+ {
259
+ statusCode: 404,
260
+ message: 'Dataset not found - Dataset "staged" not found for project ID "p1"',
261
+ response: {
262
+ statusCode: 404,
263
+ body: { error: "Dataset not found", message: 'Dataset "staged" not found for project ID "p1"', statusCode: 404 },
264
+ // url, method, headers, statusMessage
265
+ },
266
+ }
267
+ ```
268
+
269
+ A token without a session is refused with its 401 first, as the gateway checks the session before it routes. The order is the session first, then the missing dataset: a listed dataset answers its 404 before an internal token's or a malformed grant's refusal. A dataset that is not listed answers as before: one the fake has never seen is an empty dataset. A key may not also be seeded, at construction or later through `client.seed()` / `client.add()` / `client.store()`'s `seed` / `add` / `put`.
270
+
225
271
  #### Project-scoped tokens: membership and refusals
226
272
 
227
273
  A robot token belongs to the project that issued it. Model one with `projectId` on the identity:
@@ -394,6 +440,7 @@ Useful in test bodies, but a giveaway that the code under test isn't using the r
394
440
  | `client.identities()` | Snapshot of the registered token→identity entries |
395
441
  | `client.revokeIdentity(token)` | Make every later request on a registered token answer 401 `Session not found` (see [Unknown tokens and revoked tokens](#unknown-tokens-and-revoked-tokens)) |
396
442
  | `createTestClient({ internalTokenKeys: [publicKeyPem] })` | Verify JWT bearers as the Content Lake does (see [Internal tokens](#internal-tokens)) |
443
+ | `client.completeOrganizationStoreProvisioning(organizationId)` | Set the organization's `provisioning` store `active`, as populus's provisioning workflow does (see [Organization stores](#organization-stores)) |
397
444
  | `client.simulateOutage("project-api")` | Make every later project API request answer populus's 500 (see [Platform outages](#platform-outages)) |
398
445
  | `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
399
446
  | `createTestClient({ resources: { "media-library:ml1": [...] } })` | Seed any resource type up front; keys are `"<type>:<id>"` |
package/dist/index.cjs CHANGED
@@ -98,6 +98,18 @@ function projectApiDown(request) {
98
98
  }
99
99
  });
100
100
  }
101
+ function datasetNotFound(request, projectId, dataset) {
102
+ return new PlatformHttpError({
103
+ ...request,
104
+ statusCode: 404,
105
+ statusMessage: "Not Found",
106
+ body: {
107
+ error: "Dataset not found",
108
+ message: `Dataset "${dataset}" not found for project ID "${projectId}"`,
109
+ statusCode: 404
110
+ }
111
+ });
112
+ }
101
113
  const mediaLibraryReadRequired = (request) => accessApiError({
102
114
  request,
103
115
  statusCode: 401,
@@ -501,6 +513,98 @@ function createDocumentHistory() {
501
513
  function historyIds(list) {
502
514
  return list.split(",").map((id) => decodeURIComponent(id));
503
515
  }
516
+ const ORGANIZATION_STORES_PATH = "/internal/organization-stores";
517
+ function serveOrganizationStore(args) {
518
+ const { stores, organizationIds, session, request, query } = args;
519
+ refuseSession(request, session);
520
+ const organizationId = organizationIdOf(request, query);
521
+ if (!organizationIds.includes(organizationId))
522
+ throw boom(request, 404, "Not Found", `Organization ${organizationId} not found`);
523
+ const existing = stores.get(organizationId);
524
+ if (existing !== void 0) return { ...existing };
525
+ const store = {
526
+ id: organizationStoreId(organizationId),
527
+ organizationId,
528
+ status: "provisioning"
529
+ };
530
+ return stores.set(organizationId, store), { ...store };
531
+ }
532
+ function completeProvisioning(stores, organizationId) {
533
+ const store = stores.get(organizationId);
534
+ if (store?.status !== "provisioning")
535
+ throw fakeError(
536
+ `completeOrganizationStoreProvisioning(): organization "${organizationId}" has ` + (store === void 0 ? "no store. Populus creates one on the first GET /internal/organization-stores." : "an active store already.")
537
+ );
538
+ store.status = "active";
539
+ }
540
+ function refuseSession(request, session) {
541
+ const refused = "refused" in session ? session.refused : session.tokenType !== "service" && "A service session is required for this endpoint";
542
+ if (refused) throw boom(request, 401, "Unauthorized", refused);
543
+ }
544
+ function organizationIdOf(request, query) {
545
+ const nested = [...query.keys()].find((key) => key.includes("["));
546
+ if (nested !== void 0)
547
+ throw fakeError(
548
+ `request(): ${request.path} got query key "${nested}"; Express parses bracketed keys into nested values, which the fake does not model. Pass flat query parameters.`
549
+ );
550
+ const unknown = [...new Set(query.keys())].filter((key) => key !== "tag").find((key) => key !== "organizationId"), values = query.getAll("organizationId"), failure = values.length === 0 && {
551
+ key: "organizationId",
552
+ message: '"organizationId" is required'
553
+ } || values.length > 1 && {
554
+ key: "organizationId",
555
+ message: '"organizationId" must be a string'
556
+ } || values[0] === "" && {
557
+ key: "organizationId",
558
+ message: '"organizationId" is not allowed to be empty'
559
+ } || unknown !== void 0 && {
560
+ key: unknown,
561
+ message: `"${unknown}" is not allowed`
562
+ };
563
+ if (failure)
564
+ throw new PlatformHttpError({
565
+ ...request,
566
+ statusCode: 400,
567
+ statusMessage: "Bad Request",
568
+ body: {
569
+ statusCode: 400,
570
+ error: "Bad Request",
571
+ message: "Validation failed",
572
+ validation: {
573
+ query: {
574
+ source: "query",
575
+ keys: [escapeHtml(failure.key)],
576
+ message: failure.message
577
+ }
578
+ }
579
+ }
580
+ });
581
+ return values[0];
582
+ }
583
+ const DISALLOWED_SEGMENTS = ["ad", "api", "xxx"];
584
+ function organizationStoreId(organizationId) {
585
+ for (let attempt = 0; ; attempt++) {
586
+ const id = `os${node_crypto.createHash("sha256").update(`${organizationId}:${attempt}`).digest("hex").slice(0, 10)}`;
587
+ if (!DISALLOWED_SEGMENTS.some((segment) => id.includes(segment))) return id;
588
+ }
589
+ }
590
+ function escapeHtml(text) {
591
+ const entities = {
592
+ '"': "&quot;",
593
+ "&": "&amp;",
594
+ "'": "&#39;",
595
+ "<": "&lt;",
596
+ ">": "&gt;"
597
+ };
598
+ return text.replace(/["&'<>]/g, (char) => entities[char]);
599
+ }
600
+ function boom(request, statusCode, statusMessage, message) {
601
+ return new PlatformHttpError({
602
+ ...request,
603
+ statusCode,
604
+ statusMessage,
605
+ body: { statusCode, error: statusMessage, message }
606
+ });
607
+ }
504
608
  const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, ACCESS_ROBOT_PATH = /^\/robots(?:\/([^/]+))?$/, PROJECT_ROLES_PATH = /^\/projects\/([^/]+)\/roles$/, PROJECT_FEATURES_PATH = /^\/projects\/([^/]+)\/features$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/, ACCESS_API_SINCE = "2025-07-11", PROJECT_API_PATHS = [
505
609
  /^\/users\/me$/,
506
610
  /^\/projects\/[^/]+$/,
@@ -508,7 +612,8 @@ const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^
508
612
  PROJECT_ROLES_PATH,
509
613
  PROJECT_FEATURES_PATH,
510
614
  MY_ATTRIBUTES_PATH,
511
- ACCESS_PATH
615
+ ACCESS_PATH,
616
+ new RegExp(`^${ORGANIZATION_STORES_PATH}$`)
512
617
  ];
513
618
  function servedByProjectApi(path) {
514
619
  if (PROJECT_API_PATHS.some((pattern) => pattern.test(path))) return !0;
@@ -524,8 +629,19 @@ function usersPage(data) {
524
629
  return { ...page(data), totalCount: data.length };
525
630
  }
526
631
  const UNMODELLED_PROFILE = { provider: "sanity", createdAt: (/* @__PURE__ */ new Date(0)).toISOString() };
527
- async function servePlatformRequest(ctx, uri, request) {
528
- const { path } = request, queryStart = uri.indexOf("?"), query = new URLSearchParams(queryStart === -1 ? "" : uri.slice(queryStart + 1)), myAttributes = path.match(MY_ATTRIBUTES_PATH);
632
+ async function servePlatformRequest(ctx, request) {
633
+ const { path } = request, queryStart = request.url.indexOf("?"), query = new URLSearchParams(queryStart === -1 ? "" : request.url.slice(queryStart + 1));
634
+ if (path === ORGANIZATION_STORES_PATH)
635
+ return {
636
+ value: serveOrganizationStore({
637
+ stores: ctx.organizationStores,
638
+ organizationIds: ctx.organizationId === void 0 ? [] : [ctx.organizationId],
639
+ session: ctx.populusSession(),
640
+ request,
641
+ query
642
+ })
643
+ };
644
+ const myAttributes = path.match(MY_ATTRIBUTES_PATH);
529
645
  if (myAttributes !== null) {
530
646
  const organizationId = decodeURIComponent(myAttributes[1]);
531
647
  return serveMyAttributes({ ctx, request, organizationId, query });
@@ -1016,7 +1132,7 @@ function makeRequestImpl(ctx) {
1016
1132
  identities: listIdentities(),
1017
1133
  organizationId
1018
1134
  });
1019
- const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path, requestFor(opts));
1135
+ const served = path === void 0 ? void 0 : await servePlatformRequest(platform, requestFor(opts));
1020
1136
  if (served !== void 0) return served.value;
1021
1137
  throw fakeError(
1022
1138
  `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>] | robots[/<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.`
@@ -1933,9 +2049,11 @@ function jwtError(token, keys) {
1933
2049
  function identityOf(claims) {
1934
2050
  const unmodelledClaims = UNMODELLED_CLAIMS.filter((key) => key in claims);
1935
2051
  if (unmodelledClaims.length > 0)
1936
- throw fakeError(
1937
- `internal token: the fake does not model the ${unmodelledClaims.map((key) => `"${key}"`).join(", ")} claim(s); it reads "i", "g" and "x".`
1938
- );
2052
+ return {
2053
+ identity: { user: { id: "" }, grants: [] },
2054
+ expiresAt: void 0,
2055
+ unmodelled: `internal token: the Content Lake reads the ${unmodelledClaims.map((key) => `"${key}"`).join(", ")} claim(s), which the fake does not model; it reads "i", "g" and "x".`
2056
+ };
1939
2057
  const { i: id, g: grantList = [], x: rawExpiry } = claims;
1940
2058
  let expiresAt;
1941
2059
  if (rawExpiry != null) {
@@ -1972,6 +2090,32 @@ function checkInternalToken(token, keys) {
1972
2090
  const parsed = jwtError(token, keys);
1973
2091
  return "error" in parsed ? { refused: `invalid JWT token ${quoted(token)}: ${parsed.error}` } : identityOf(parsed.claims);
1974
2092
  }
2093
+ function populusSession(token, keys) {
2094
+ const [headerSegment, claimsSegment, signatureSegment] = token.split(".");
2095
+ if (signatureSegment.trim() === "") {
2096
+ const decoded = [headerSegment, claimsSegment].map(decodeSegment);
2097
+ if (decoded.some((bytes) => typeof bytes == "string"))
2098
+ throw fakeError(
2099
+ "internal token: a segment is not base64url; jsonwebtoken's answer to it is not modelled."
2100
+ );
2101
+ return decoded.forEach(
2102
+ (bytes, index) => jsonObject(bytes, index === 0 ? "header" : "claims segment")
2103
+ ), { refused: "jwt signature is required" };
2104
+ }
2105
+ const parsed = jwtError(token, keys);
2106
+ if ("error" in parsed) {
2107
+ if (parsed.error === "crypto/rsa: verification error") return { refused: "invalid signature" };
2108
+ throw fakeError(
2109
+ `internal token: populus refuses it with jsonwebtoken's 401 (gradient's reason: ${parsed.error}), whose message the fake does not model.`
2110
+ );
2111
+ }
2112
+ const { tokenType, x } = parsed.claims;
2113
+ if (x != null && typeof x != "number")
2114
+ throw fakeError(
2115
+ `internal token: "x" must be a number of epoch seconds; got ${JSON.stringify(x)}.`
2116
+ );
2117
+ return x && x < Math.ceil(Date.now() / 1e3) ? { refused: "Session expired" } : { tokenType };
2118
+ }
1975
2119
  function goTime(epochSeconds) {
1976
2120
  const date = new Date(epochSeconds * 1e3);
1977
2121
  if (Number.isNaN(date.getTime()) || date.getUTCFullYear() < 1e3)
@@ -2251,15 +2395,39 @@ function ensureEntry(registry, resource) {
2251
2395
  exists: !1
2252
2396
  }, registry.set(key, entry)), entry;
2253
2397
  }
2398
+ function seededMissingDataset(caller, key) {
2399
+ return fakeError(
2400
+ `${caller}: dataset "${key}" is both seeded and in \`missingDatasets\`; a dataset the platform does not have holds no documents.`
2401
+ );
2402
+ }
2254
2403
  function seedEntry(registry, resource, documents) {
2255
2404
  const entry = ensureEntry(registry, resource);
2256
2405
  entry.store.seed(documents), entry.exists = !0;
2257
2406
  }
2407
+ function seedOrganizationStores(options) {
2408
+ const seeded = Object.entries(options.organizationStores ?? {}), unserved = seeded.find(([, status]) => status !== "provisioning" && status !== "active");
2409
+ if (unserved !== void 0)
2410
+ throw fakeError(
2411
+ `createTestClient(): \`organizationStores\` seeds "${unserved[0]}" as ${JSON.stringify(unserved[1])}; populus serves only "provisioning" and "active" stores.`
2412
+ );
2413
+ const stray = seeded.find(([organizationId]) => organizationId !== options.organizationId);
2414
+ if (stray !== void 0)
2415
+ throw fakeError(
2416
+ `createTestClient(): \`organizationStores\` has a store for "${stray[0]}", which is not the configured \`organizationId\`; populus creates stores only for organizations it has.`
2417
+ );
2418
+ return new Map(
2419
+ seeded.map(([organizationId, status]) => [
2420
+ organizationId,
2421
+ { id: organizationStoreId(organizationId), organizationId, status }
2422
+ ])
2423
+ );
2424
+ }
2258
2425
  function createTestClient(options = {}) {
2259
2426
  const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = {
2260
2427
  registry: /* @__PURE__ */ new Map(),
2261
2428
  organizationId: options.organizationId,
2262
2429
  projectFeatures: options.projectFeatures ?? {},
2430
+ organizationStores: seedOrganizationStores(options),
2263
2431
  log: [],
2264
2432
  stubs: /* @__PURE__ */ new Map(),
2265
2433
  calls: [],
@@ -2269,6 +2437,7 @@ function createTestClient(options = {}) {
2269
2437
  internalTokenKeys: parseInternalTokenKeys(options.internalTokenKeys ?? []),
2270
2438
  internalTokens: /* @__PURE__ */ new Map(),
2271
2439
  outages: /* @__PURE__ */ new Set(),
2440
+ missingDatasets: new Set(options.missingDatasets ?? []),
2272
2441
  writeChain: Promise.resolve()
2273
2442
  }, registry = backend.registry;
2274
2443
  if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
@@ -2283,6 +2452,11 @@ function createTestClient(options = {}) {
2283
2452
  if (options.resources)
2284
2453
  for (const [key, docs] of Object.entries(options.resources))
2285
2454
  seedEntry(registry, parseResourceKey(key), docs);
2455
+ for (const key of backend.missingDatasets) {
2456
+ const { projectId, dataset } = parseDatasetKey(key);
2457
+ if (registry.get(registryKey(datasetResource(projectId, dataset)))?.exists)
2458
+ throw seededMissingDataset("createTestClient()", key);
2459
+ }
2286
2460
  return makeHandle({
2287
2461
  backend,
2288
2462
  projectId: defaultProjectId,
@@ -2385,7 +2559,7 @@ function makeHandle(handleArgs) {
2385
2559
  if (access === void 0)
2386
2560
  throw fakeError("this handle has no acting identity (no token or accessControl bound).");
2387
2561
  return access;
2388
- }, projectHosted = useProjectHostname && resource === void 0, refuseSession = (request) => {
2562
+ }, projectHosted = useProjectHostname && resource === void 0, refuseSession2 = (request) => {
2389
2563
  if (token === void 0 || internal() !== void 0) return;
2390
2564
  if (backend.revoked.has(token)) throw sessionNotFound(request);
2391
2565
  const tokenProjectId = backend.identities.get(token)?.projectId;
@@ -2398,15 +2572,19 @@ function makeHandle(handleArgs) {
2398
2572
  if (refusal !== void 0) throw refusal;
2399
2573
  }, withSession = (request) => async (opts) => {
2400
2574
  const sent = rawRequest(opts);
2401
- if (internal() !== void 0 && servedByProjectApi(sent.path))
2575
+ if (internal() !== void 0 && servedByProjectApi(sent.path) && sent.path !== ORGANIZATION_STORES_PATH)
2402
2576
  throw fakeError(
2403
2577
  `request(): "${sent.path}" with an internal token. The project API (populus) verifies internal tokens with its own key and answers differently from the Content Lake; the fake does not model that. Use a registered identity's token there.`
2404
2578
  );
2405
- if (refuseSession(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
2579
+ if (refuseSession2(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
2406
2580
  throw projectApiDown(sent);
2407
2581
  return request(opts);
2408
2582
  }, admitToLake = (request) => {
2409
- refuseSession(request), refuseInternalToken(request);
2583
+ if (refuseSession2(request), missingKey !== void 0) {
2584
+ const parts = datasetParts(target.id);
2585
+ throw datasetNotFound(request, parts.projectId, parts.dataset);
2586
+ }
2587
+ refuseInternalToken(request);
2410
2588
  const access = activeAccess();
2411
2589
  if (access === void 0) return;
2412
2590
  const refusal = refusedToken(request, access.grants);
@@ -2459,7 +2637,18 @@ function makeHandle(handleArgs) {
2459
2637
  ["skipCrossDatasetReferenceValidation", options.skipCrossDatasetReferenceValidation]
2460
2638
  ]
2461
2639
  });
2462
- }, rawRequest = (opts) => platformRequest({ method: "GET", uri: opts.uri ?? opts.url ?? "", tag: opts.tag }), members = () => [
2640
+ }, rawRequest = (opts) => {
2641
+ if (opts.query !== void 0 && "tag" in opts.query)
2642
+ throw fakeError("request(): pass the request tag as `tag`, not in `query`.");
2643
+ return platformRequest({
2644
+ method: "GET",
2645
+ uri: opts.uri ?? opts.url ?? "",
2646
+ tag: opts.tag,
2647
+ query: Object.entries(opts.query ?? {}).flatMap(
2648
+ ([key, value]) => (Array.isArray(value) ? value : [value]).map((one) => [key, one])
2649
+ )
2650
+ });
2651
+ }, members = () => [
2463
2652
  ...backend.identities.values(),
2464
2653
  ...token === void 0 && accessControl !== void 0 ? [
2465
2654
  {
@@ -2469,16 +2658,22 @@ function makeHandle(handleArgs) {
2469
2658
  ...accessControl.access !== void 0 ? { access: accessControl.access } : {}
2470
2659
  }
2471
2660
  ] : []
2472
- ], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, publicStore = {
2661
+ ], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, missingKey = (() => {
2662
+ if (target.type !== "dataset") return;
2663
+ const parts = datasetParts(target.id), key = `${parts.projectId}:${parts.dataset}`;
2664
+ return backend.missingDatasets.has(key) ? key : void 0;
2665
+ })(), refuseSeedingMissing = (caller) => {
2666
+ if (missingKey !== void 0) throw seededMissingDataset(caller, missingKey);
2667
+ }, publicStore = {
2473
2668
  ...store,
2474
2669
  seed: (documents) => {
2475
- store.seed(documents), targetEntry.exists = !0;
2670
+ refuseSeedingMissing("seed()"), store.seed(documents), targetEntry.exists = !0;
2476
2671
  },
2477
2672
  add: (documents) => {
2478
- store.add(documents), targetEntry.exists = !0;
2673
+ refuseSeedingMissing("add()"), store.add(documents), targetEntry.exists = !0;
2479
2674
  },
2480
2675
  put: (doc) => {
2481
- store.put(doc), targetEntry.exists = !0;
2676
+ refuseSeedingMissing("put()"), store.put(doc), targetEntry.exists = !0;
2482
2677
  }
2483
2678
  }, concurrentEditKey = (id) => registryKey(target) + " " + id, actorId = () => {
2484
2679
  const access = activeAccess();
@@ -2655,7 +2850,7 @@ function makeHandle(handleArgs) {
2655
2850
  tag,
2656
2851
  canUseCdn: !1
2657
2852
  });
2658
- if (refuseSession(request), capabilities.actions !== "served") throw capabilities.actions(request);
2853
+ if (refuseSession2(request), capabilities.actions !== "served") throw capabilities.actions(request);
2659
2854
  return write(async () => {
2660
2855
  for (const action of Array.isArray(actions) ? actions : [actions]) {
2661
2856
  const refused = capabilities.refusedActions[action.actionType];
@@ -2891,6 +3086,9 @@ function makeHandle(handleArgs) {
2891
3086
  apiVersion,
2892
3087
  organizationId: backend.organizationId,
2893
3088
  projectFeatures: backend.projectFeatures,
3089
+ organizationStores: backend.organizationStores,
3090
+ // A registered identity's session is a user or robot session, never a service one.
3091
+ populusSession: () => token === void 0 || internal() === void 0 ? { tokenType: void 0 } : populusSession(token, backend.internalTokenKeys),
2894
3092
  own: (asked) => registryKey(asked) === registryKey(target) ? {
2895
3093
  grants: requireActiveAccess().grants,
2896
3094
  documents: () => store.all(),
@@ -2979,6 +3177,7 @@ function makeHandle(handleArgs) {
2979
3177
  simulateOutage: (component) => {
2980
3178
  backend.outages.add(component);
2981
3179
  },
3180
+ completeOrganizationStoreProvisioning: (organizationId) => completeProvisioning(backend.organizationStores, organizationId),
2982
3181
  mutations: () => backend.log.flatMap((entry) => entry.mutations),
2983
3182
  transactions: () => [...backend.log],
2984
3183
  clearLog: () => {