@sanity-labs/client-fake-for-test 0.30.0 → 0.31.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/dist/index.d.cts CHANGED
@@ -654,6 +654,15 @@ export declare interface MutationLogEntry {
654
654
  dataset: string;
655
655
  /** The resource the transaction targeted, on a `resource`-configured handle. */
656
656
  resource?: TestClientResource;
657
+ /**
658
+ * The organization store the transaction targeted, for a write over the
659
+ * Workflows store routes; `projectId` and `dataset` are then the calling
660
+ * handle's, not where the write landed.
661
+ */
662
+ organizationStore?: {
663
+ id: string;
664
+ organizationId: string;
665
+ };
657
666
  mutations: TxnMutation[];
658
667
  /** Request tag the commit carried, when one was passed (`null` = explicit suppression). */
659
668
  tag?: string | null;
@@ -1326,6 +1335,14 @@ export declare interface TestClient {
1326
1335
  * store whose provisioning never completes stays `provisioning`.
1327
1336
  */
1328
1337
  completeOrganizationStoreProvisioning: (organizationId: string) => void;
1338
+ /**
1339
+ * The documents of the organization's store, the Workflows store, which
1340
+ * the Workflows store routes of {@link TestClient.request} read and write:
1341
+ * seed it, or read what a test wrote. Throws unless the organization has a
1342
+ * store (seed `organizationStores`, or look it up first). Seeding does not
1343
+ * change the store's status; the routes serve it once it is `active`.
1344
+ */
1345
+ organizationStore: (organizationId: string) => TestStore;
1329
1346
  /**
1330
1347
  * Deploy a function, or replace the one with its id, for every handle of
1331
1348
  * the family. Throws for an id shorter than 10 characters, an unknown
package/dist/index.d.ts CHANGED
@@ -654,6 +654,15 @@ export declare interface MutationLogEntry {
654
654
  dataset: string;
655
655
  /** The resource the transaction targeted, on a `resource`-configured handle. */
656
656
  resource?: TestClientResource;
657
+ /**
658
+ * The organization store the transaction targeted, for a write over the
659
+ * Workflows store routes; `projectId` and `dataset` are then the calling
660
+ * handle's, not where the write landed.
661
+ */
662
+ organizationStore?: {
663
+ id: string;
664
+ organizationId: string;
665
+ };
657
666
  mutations: TxnMutation[];
658
667
  /** Request tag the commit carried, when one was passed (`null` = explicit suppression). */
659
668
  tag?: string | null;
@@ -1326,6 +1335,14 @@ export declare interface TestClient {
1326
1335
  * store whose provisioning never completes stays `provisioning`.
1327
1336
  */
1328
1337
  completeOrganizationStoreProvisioning: (organizationId: string) => void;
1338
+ /**
1339
+ * The documents of the organization's store, the Workflows store, which
1340
+ * the Workflows store routes of {@link TestClient.request} read and write:
1341
+ * seed it, or read what a test wrote. Throws unless the organization has a
1342
+ * store (seed `organizationStores`, or look it up first). Seeding does not
1343
+ * change the store's status; the routes serve it once it is `active`.
1344
+ */
1345
+ organizationStore: (organizationId: string) => TestStore;
1329
1346
  /**
1330
1347
  * Deploy a function, or replace the one with its id, for every handle of
1331
1348
  * the family. Throws for an id shorter than 10 characters, an unknown
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { parse, evaluate } from "groq-js";
2
1
  import { ClientError, ServerError } from "@sanity/client";
2
+ import { parse, evaluate, GroqSyntaxError } from "groq-js";
3
3
  import { createHash, createPublicKey, verify } from "node:crypto";
4
4
  const ERR_PREFIX = "[client-fake-for-test]";
5
5
  function fakeError(message) {
@@ -260,7 +260,22 @@ const RESOURCE_CAPABILITIES = {
260
260
  refusedActions: {},
261
261
  access: { type: "dashboard", id: (id) => id }
262
262
  }
263
+ }, ORGANIZATION_STORE_CAPABILITIES = {
264
+ label: (id) => `organization store "${id}"`,
265
+ dataBase: (id) => `/organization-stores/${id}`,
266
+ matchBase: () => {
267
+ },
268
+ lookupAtBase: !1,
269
+ identity: "global",
270
+ acl: notMounted,
271
+ history: notMounted,
272
+ actions: notMounted,
273
+ refusedActions: {},
274
+ access: { type: "organization", id: (id) => id }
263
275
  };
276
+ function storeCapabilitiesOf(type) {
277
+ return type === "organization-store" ? ORGANIZATION_STORE_CAPABILITIES : capabilitiesOf(type);
278
+ }
264
279
  function capabilitiesOf(type) {
265
280
  const row = Object.hasOwn(RESOURCE_CAPABILITIES, type) ? RESOURCE_CAPABILITIES[type] : void 0;
266
281
  if (row === void 0)
@@ -558,7 +573,7 @@ function bodyIssue(body) {
558
573
  const [path, value] = failed;
559
574
  return issueAt(path, `Invalid input: expected object, received ${typeName(value)}`);
560
575
  }
561
- function parseQuery(request) {
576
+ function parseQuery$1(request) {
562
577
  const queryStart = request.url.indexOf("?"), query = new URLSearchParams(queryStart === -1 ? "" : request.url.slice(queryStart + 1)), repeated = ["blueprintStackId", "sync"].find((key) => query.getAll(key).length > 1);
563
578
  if (repeated !== void 0)
564
579
  throw fakeError(
@@ -639,7 +654,7 @@ function admitScope(ctx, args) {
639
654
  return { type, id };
640
655
  }
641
656
  function validate(request, parts) {
642
- const query = parseQuery(request);
657
+ const query = parseQuery$1(request);
643
658
  if (Array.isArray(query)) throw invalidInput(request, query);
644
659
  const issue = [
645
660
  tooShort({ key: "functionId", min: 3, value: parts.segment }),
@@ -2466,6 +2481,107 @@ function internalTokenRefusal(request, check) {
2466
2481
  }
2467
2482
  });
2468
2483
  }
2484
+ const IDENT = /[A-Za-z_][A-Za-z0-9_]*/y, SIMPLE_ESCAPES = /* @__PURE__ */ new Set(['"', "'", "\\", "/", "b", "f", "n", "r", "t"]), UNICODE_ESCAPE = /u([0-9A-Fa-f]{4})/y;
2485
+ function refuseUnsentParams(args) {
2486
+ const { request, query, params = {}, syntaxErrorAt } = args, { references, invalidStringAt } = scanQuery(query), errorAt = Math.min(syntaxErrorAt ?? 1 / 0, invalidStringAt ?? 1 / 0), unsent = references.find(
2487
+ (reference) => reference.index < errorAt && !isSent(params, reference.name)
2488
+ );
2489
+ if (unsent === void 0) return;
2490
+ const start = codePoints(query.slice(0, unsent.index));
2491
+ throw new PlatformHttpError({
2492
+ ...request,
2493
+ statusCode: 400,
2494
+ statusMessage: "Bad Request",
2495
+ body: {
2496
+ error: {
2497
+ description: `param $${unsent.name} referenced, but not provided`,
2498
+ end: start + unsent.name.length,
2499
+ query,
2500
+ ...start !== 0 ? { start } : {},
2501
+ type: "queryParseError"
2502
+ }
2503
+ }
2504
+ });
2505
+ }
2506
+ function isSent(params, name) {
2507
+ return Object.hasOwn(params, name) && params[name] !== void 0;
2508
+ }
2509
+ function scanQuery(query) {
2510
+ const references = [];
2511
+ let declaration, atStatementStart = !0, index = 0;
2512
+ for (; index < query.length; ) {
2513
+ const char = query[index];
2514
+ if (char === '"' || char === "'") {
2515
+ const end = stringEnd(query, index);
2516
+ if (end === void 0) return { references, invalidStringAt: index };
2517
+ index = end, atStatementStart = !1;
2518
+ continue;
2519
+ }
2520
+ if (query.startsWith("//", index)) {
2521
+ const newline = query.indexOf(`
2522
+ `, index);
2523
+ index = newline === -1 ? query.length : newline + 1;
2524
+ continue;
2525
+ }
2526
+ if (/\s/.test(char)) {
2527
+ index++;
2528
+ continue;
2529
+ }
2530
+ if (atStatementStart && isKeyword(query, index, "fn")) {
2531
+ declaration = { params: /* @__PURE__ */ new Set(), header: !0 }, atStatementStart = !1, index += 2;
2532
+ continue;
2533
+ }
2534
+ if (atStatementStart = !1, declaration?.header && char === ")" && (declaration.header = !1), declaration !== void 0 && char === ";") {
2535
+ declaration = void 0, atStatementStart = !0, index++;
2536
+ continue;
2537
+ }
2538
+ if (char === "$") {
2539
+ IDENT.lastIndex = index + 1;
2540
+ const name = IDENT.exec(query)?.[0];
2541
+ if (name !== void 0) {
2542
+ declaration?.header ? declaration.params.add(name) : declaration?.params.has(name) || references.push({ name, index }), index += 1 + name.length;
2543
+ continue;
2544
+ }
2545
+ }
2546
+ index++;
2547
+ }
2548
+ return { references, invalidStringAt: void 0 };
2549
+ }
2550
+ function isKeyword(query, index, word) {
2551
+ return query.startsWith(word, index) && !/[A-Za-z0-9_]/.test(query[index + word.length] ?? "");
2552
+ }
2553
+ function stringEnd(query, index) {
2554
+ const quote = query[index];
2555
+ let at = index + 1;
2556
+ for (; at < query.length && query[at] !== quote; ) {
2557
+ if (query[at] !== "\\") {
2558
+ at++;
2559
+ continue;
2560
+ }
2561
+ const escaped = escapeLength(query, at + 1);
2562
+ if (escaped === void 0) return;
2563
+ at += 1 + escaped;
2564
+ }
2565
+ return at + 1;
2566
+ }
2567
+ function escapeLength(query, index) {
2568
+ const char = query[index];
2569
+ if (char === void 0) return 0;
2570
+ if (SIMPLE_ESCAPES.has(char)) return 1;
2571
+ const unit = unicodeEscape(query, index);
2572
+ if (unit === void 0 || unit >= 56320 && unit <= 57343) return;
2573
+ if (unit < 55296 || unit > 56319) return 5;
2574
+ const low = query[index + 5] === "\\" ? unicodeEscape(query, index + 6) : void 0;
2575
+ return low !== void 0 && low >= 56320 && low <= 57343 ? 11 : void 0;
2576
+ }
2577
+ function unicodeEscape(query, index) {
2578
+ UNICODE_ESCAPE.lastIndex = index;
2579
+ const hex = UNICODE_ESCAPE.exec(query)?.[1];
2580
+ return hex === void 0 ? void 0 : Number.parseInt(hex, 16);
2581
+ }
2582
+ function codePoints(text) {
2583
+ return [...text].length;
2584
+ }
2469
2585
  const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
2470
2586
  "fetch",
2471
2587
  "getDocument",
@@ -2628,6 +2744,42 @@ function wrapWithGuards(client, config) {
2628
2744
  }
2629
2745
  });
2630
2746
  }
2747
+ const READ_ROUTE = /^\/workflows\/organizations\/([^/]+)\/(query|doc|listen)(?=\/|$)(.*)$/, STORE_ROUTE = /^\/organization-stores\/([^/]+)\/(query|mutate|doc|listen|export|references|actions|history)(?=\/|$)(.*)$/, SERVICE_ROUTE = /^\/workflows(?=\/|$)/;
2748
+ function matchWorkflowsStoreRoute(args) {
2749
+ const { path, apiVersion } = args, read = path.match(READ_ROUTE);
2750
+ if (read !== null) {
2751
+ if (apiVersion !== "X") return "unrouted";
2752
+ const [, organizationId, action, rest] = read;
2753
+ return { route: "read", organizationId: decodeURIComponent(organizationId), action, rest };
2754
+ }
2755
+ const store = path.match(STORE_ROUTE);
2756
+ if (store !== null) {
2757
+ if (apiVersion === "1") return "unrouted";
2758
+ const [, storeId, action, rest] = store;
2759
+ return { route: "store", storeId: decodeURIComponent(storeId), action, rest };
2760
+ }
2761
+ if (SERVICE_ROUTE.test(path)) return apiVersion === "X" ? "service" : "unrouted";
2762
+ }
2763
+ function noRouteMatched(request) {
2764
+ return new PlatformHttpError({
2765
+ ...request,
2766
+ statusCode: 404,
2767
+ statusMessage: "Not Found",
2768
+ body: { message: "no Route matched with those values" }
2769
+ });
2770
+ }
2771
+ function storeNotFound(request, identifier) {
2772
+ return new PlatformHttpError({
2773
+ ...request,
2774
+ statusCode: 404,
2775
+ statusMessage: "Not Found",
2776
+ body: {
2777
+ statusCode: 404,
2778
+ error: "Dataset not found",
2779
+ message: `Dataset for id "${identifier}" not found`
2780
+ }
2781
+ });
2782
+ }
2631
2783
  const OPTIONS_ARG_POSITION = {
2632
2784
  fetch: 2,
2633
2785
  getDocument: 1,
@@ -2708,6 +2860,79 @@ const registryKey = (resource) => `${resource.type}:${resource.id}`, datasetReso
2708
2860
  );
2709
2861
  return validateResource(resource), resource;
2710
2862
  };
2863
+ async function serveStoreAction(args) {
2864
+ const { client, history, action, rest, sent, opts } = args, search = new URL(sent.url).searchParams, tag = opts.tag !== void 0 ? { tag: opts.tag } : {};
2865
+ try {
2866
+ if (action === "doc") {
2867
+ if (sent.method !== "GET") throw notAllowed(sent);
2868
+ const ids = rest.slice(1).split(",").map(decodeURIComponent);
2869
+ if (rest === "" || ids.some((id) => id === ""))
2870
+ throw fakeError(`request(): "${sent.path}" names no document id; GET <store>/doc/<ids>.`);
2871
+ const found = await client.getDocuments(ids, tag), readable = new Set(found.flatMap((doc) => doc === null ? [] : [doc._id])), stored = new Set(
2872
+ client.store().all().map((doc) => doc._id)
2873
+ );
2874
+ return {
2875
+ documents: found.filter((doc) => doc !== null),
2876
+ omitted: ids.filter((id) => !readable.has(id)).map((id) => ({ id, reason: stored.has(id) ? "permission" : "existence" }))
2877
+ };
2878
+ }
2879
+ if (action === "query") {
2880
+ const { query, params } = storeQuery(sent, search, opts.body);
2881
+ return await client.fetch(query, params, {
2882
+ filterResponse: !1,
2883
+ returnQuery: search.get("returnQuery") !== "false",
2884
+ ...tag
2885
+ });
2886
+ }
2887
+ if (sent.method !== "POST") throw notAllowed(sent);
2888
+ const body = opts.body;
2889
+ if (!Array.isArray(body?.mutations))
2890
+ throw fakeError(`request(): POST "${sent.path}" needs a body \`{ mutations: [...] }\`.`);
2891
+ const committed = await client.mutate(body.mutations, {
2892
+ returnDocuments: !1,
2893
+ returnFirst: !1,
2894
+ ...tag
2895
+ }), images = /* @__PURE__ */ new Map();
2896
+ if (search.get("returnDocuments") === "true") {
2897
+ const ids = committed.results.map((result) => result.id), record = history.transactions(ids, () => !0).find((txn) => txn.id === committed.transactionId);
2898
+ for (const mutation of record?.mutations ?? []) {
2899
+ const document = "create" in mutation ? mutation.create : "createOrReplace" in mutation ? mutation.createOrReplace : void 0;
2900
+ document !== void 0 && images.set(document._id, document);
2901
+ }
2902
+ }
2903
+ return {
2904
+ transactionId: committed.transactionId,
2905
+ results: committed.results.map((result) => {
2906
+ const document = images.get(result.id) ?? (search.get("returnDocuments") === "true" ? client.store().get(result.id) : void 0);
2907
+ return document !== void 0 ? { ...result, document } : result;
2908
+ })
2909
+ };
2910
+ } catch (error) {
2911
+ throw (error instanceof ClientError || error instanceof ServerError) && Object.assign(error.response, { method: sent.method, url: sent.url }), error;
2912
+ }
2913
+ }
2914
+ function storeQuery(sent, search, body) {
2915
+ if (sent.method === "POST") {
2916
+ const posted = body;
2917
+ if (typeof posted?.query != "string")
2918
+ throw fakeError(`request(): POST "${sent.path}" needs a body \`{ query, params? }\`.`);
2919
+ return { query: posted.query, params: posted.params ?? {} };
2920
+ }
2921
+ const query = search.get("query");
2922
+ if (query === null) throw fakeError(`request(): GET "${sent.path}" needs a \`query\` parameter.`);
2923
+ const params = Object.fromEntries(
2924
+ [...search].filter(([name]) => name.startsWith("$")).map(([name, value]) => [name.slice(1), JSON.parse(value)])
2925
+ );
2926
+ return { query, params };
2927
+ }
2928
+ function notAllowed(sent) {
2929
+ return fakeError(`request(): ${sent.method} "${sent.path}" is not a method this route takes.`);
2930
+ }
2931
+ function clientResources(registry) {
2932
+ return [...registry.values()].filter(
2933
+ (entry) => entry.resource.type !== "organization-store"
2934
+ );
2935
+ }
2711
2936
  function ensureEntry(registry, resource) {
2712
2937
  const key = registryKey(resource);
2713
2938
  let entry = registry.get(key);
@@ -2808,6 +3033,19 @@ function createTestClient(options = {}) {
2808
3033
  configuredPerspective: options.perspective
2809
3034
  });
2810
3035
  }
3036
+ function parseQuery(request, query, params) {
3037
+ try {
3038
+ const tree = parse(query, params ? { params } : void 0);
3039
+ return refuseUnsentParams({ request, query, params }), tree;
3040
+ } catch (error) {
3041
+ throw refuseUnsentParams({
3042
+ request,
3043
+ query,
3044
+ params,
3045
+ ...error instanceof GroqSyntaxError ? { syntaxErrorAt: error.position } : {}
3046
+ }), error;
3047
+ }
3048
+ }
2811
3049
  function dedupeIds(results) {
2812
3050
  const seen = /* @__PURE__ */ new Set(), out = [];
2813
3051
  for (const r of results)
@@ -2872,7 +3110,7 @@ function makeHandle(handleArgs) {
2872
3110
  apiVersion,
2873
3111
  useCdn,
2874
3112
  configuredPerspective
2875
- } = handleArgs, { registry } = backend, hasProjectId = handleArgs.hasProjectId || useProjectHostname && resource === void 0 || resource?.type === "dataset", { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = resource ?? datasetResource(projectId, dataset), activeAccess = () => {
3113
+ } = handleArgs, { registry } = backend, hasProjectId = handleArgs.hasProjectId || useProjectHostname && resource === void 0 || resource?.type === "dataset", { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = handleArgs.internalStore?.resource ?? resource ?? datasetResource(projectId, dataset), activeAccess = () => {
2876
3114
  if (token === void 0) return accessControl;
2877
3115
  const verified = internalToken(backend, token), identity = verified !== void 0 && "identity" in verified ? verified.identity : backend.identities.get(token);
2878
3116
  if (verified !== void 0 && "refused" in verified)
@@ -2881,7 +3119,7 @@ function makeHandle(handleArgs) {
2881
3119
  throw fakeError(`no identity is registered for token "${token}" (was it removed?).`);
2882
3120
  return {
2883
3121
  // Per-project records apply only where the resource lives in a project.
2884
- currentUser: capabilitiesOf(target.type).identity === "project" ? projectUserOf(identity, projectId) : identity.user,
3122
+ currentUser: storeCapabilitiesOf(target.type).identity === "project" ? projectUserOf(identity, projectId) : identity.user,
2885
3123
  ...identity.globalUser !== void 0 ? { globalUser: identity.globalUser } : {},
2886
3124
  ...identity.robot ? { robot: !0 } : {},
2887
3125
  grants: identity.grants,
@@ -2911,7 +3149,50 @@ function makeHandle(handleArgs) {
2911
3149
  );
2912
3150
  if (refuseSession2(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
2913
3151
  throw projectApiDown(sent);
2914
- return request(opts);
3152
+ const routed = activeAccess()?.aclPath === (opts.uri ?? opts.url) ? void 0 : matchWorkflowsStoreRoute({ path: sent.path, apiVersion });
3153
+ return routed !== void 0 ? serveWorkflowsStore(routed, sent, opts) : request(opts);
3154
+ }, serveWorkflowsStore = (routed, sent, opts) => {
3155
+ if (routed === "unrouted") throw noRouteMatched(sent);
3156
+ if (routed === "service")
3157
+ throw fakeError(
3158
+ `request(): ${sent.method} "${sent.path}" goes to the Workflows service, which the fake does not serve. Mount a Workflows service double for it.`
3159
+ );
3160
+ const store2 = routed.route === "read" ? activeStoreOf(routed.organizationId) : [...backend.organizationStores.values()].find(
3161
+ (one) => one.id === routed.storeId && one.status === "active"
3162
+ );
3163
+ if (store2 === void 0)
3164
+ throw storeNotFound(
3165
+ sent,
3166
+ routed.route === "read" ? `org:${routed.organizationId}` : routed.storeId
3167
+ );
3168
+ const servedActions = routed.route === "read" ? ["query", "doc"] : ["query", "doc", "mutate"];
3169
+ if (!servedActions.includes(routed.action))
3170
+ throw fakeError(
3171
+ `request(): "${sent.path}" is ${routed.action} on the organization store; the fake serves ${servedActions.join(", ")} there.`
3172
+ );
3173
+ const onStore = makeHandle({
3174
+ ...handleArgs,
3175
+ resource: void 0,
3176
+ // Both routes are on the global API host, whatever host the caller's other requests go to.
3177
+ useProjectHostname: !1,
3178
+ perspective: "raw",
3179
+ configuredPerspective: void 0,
3180
+ internalStore: {
3181
+ resource: { type: "organization-store", id: store2.id },
3182
+ store: { id: store2.id, organizationId: store2.organizationId }
3183
+ }
3184
+ });
3185
+ return serveStoreAction({
3186
+ client: onStore,
3187
+ history: ensureEntry(registry, { type: "organization-store", id: store2.id }).history,
3188
+ action: routed.action,
3189
+ rest: routed.rest,
3190
+ sent,
3191
+ opts
3192
+ });
3193
+ }, activeStoreOf = (organizationId) => {
3194
+ const store2 = backend.organizationStores.get(organizationId);
3195
+ return store2?.status === "active" ? store2 : void 0;
2915
3196
  }, admitToLake = (request) => {
2916
3197
  if (refuseSession2(request), missingKey !== void 0) {
2917
3198
  const parts = datasetParts(target.id);
@@ -2991,7 +3272,7 @@ function makeHandle(handleArgs) {
2991
3272
  ...accessControl.access !== void 0 ? { access: accessControl.access } : {}
2992
3273
  }
2993
3274
  ] : []
2994
- ], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, missingKey = (() => {
3275
+ ], capabilities = storeCapabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, missingKey = (() => {
2995
3276
  if (target.type !== "dataset") return;
2996
3277
  const parts = datasetParts(target.id), key = `${parts.projectId}:${parts.dataset}`;
2997
3278
  return backend.missingDatasets.has(key) ? key : void 0;
@@ -3030,6 +3311,7 @@ function makeHandle(handleArgs) {
3030
3311
  projectId,
3031
3312
  dataset,
3032
3313
  ...resource !== void 0 ? { resource } : {},
3314
+ ...handleArgs.internalStore !== void 0 ? { organizationStore: { ...handleArgs.internalStore.store } } : {},
3033
3315
  mutations,
3034
3316
  ...effectiveTag !== void 0 ? { tag: effectiveTag } : {}
3035
3317
  });
@@ -3204,16 +3486,15 @@ function makeHandle(handleArgs) {
3204
3486
  return applyPerspective(accessible, override ?? perspective);
3205
3487
  }, client = {
3206
3488
  fetch: async (query, params, opts) => {
3207
- admitToLake(
3208
- queryRequest({
3209
- query,
3210
- params,
3211
- tag: opts?.tag,
3212
- perspective: opts?.perspective,
3213
- returnQuery: opts?.filterResponse === !1 && opts.returnQuery !== !1
3214
- })
3215
- );
3216
- const start = Date.now(), tree = parse(query, params ? { params } : void 0), result = await (await evaluate(tree, {
3489
+ const request = queryRequest({
3490
+ query,
3491
+ params,
3492
+ tag: opts?.tag,
3493
+ perspective: opts?.perspective,
3494
+ returnQuery: opts?.filterResponse === !1 && opts.returnQuery !== !1
3495
+ });
3496
+ admitToLake(request);
3497
+ const start = Date.now(), tree = parseQuery(request, query, params), result = await (await evaluate(tree, {
3217
3498
  dataset: await visibleDocs(opts?.perspective),
3218
3499
  ...params !== void 0 ? { params } : {}
3219
3500
  })).get();
@@ -3439,7 +3720,7 @@ function makeHandle(handleArgs) {
3439
3720
  identities: members,
3440
3721
  // A dataset stands for its project, and every project exists in
3441
3722
  // the fake, so a dataset handle still counts as before.
3442
- resources: () => [...registry.values()].filter((e) => e.exists || e.resource.type === "dataset").map((e) => e.resource)
3723
+ resources: () => clientResources(registry).filter((e) => e.exists || e.resource.type === "dataset").map((e) => e.resource)
3443
3724
  },
3444
3725
  functions: {
3445
3726
  apiVersion,
@@ -3504,7 +3785,7 @@ function makeHandle(handleArgs) {
3504
3785
  backend.concurrentEdits.set(editKey, (backend.concurrentEdits.get(editKey) ?? 0) + count);
3505
3786
  },
3506
3787
  datasets: () => [...registry.values()].filter((entry) => entry.resource.type === "dataset").map((entry) => datasetParts(entry.resource.id)),
3507
- resources: () => [...registry.values()].map((entry) => ({ ...entry.resource })),
3788
+ resources: () => clientResources(registry).map((entry) => ({ ...entry.resource })),
3508
3789
  stub: (name, handler) => {
3509
3790
  backend.stubs.set(name, handler);
3510
3791
  },
@@ -3524,6 +3805,14 @@ function makeHandle(handleArgs) {
3524
3805
  backend.outages.add(component);
3525
3806
  },
3526
3807
  completeOrganizationStoreProvisioning: (organizationId) => completeProvisioning(backend.organizationStores, organizationId),
3808
+ organizationStore: (organizationId) => {
3809
+ const organizationStore = backend.organizationStores.get(organizationId);
3810
+ if (organizationStore === void 0)
3811
+ throw fakeError(
3812
+ `organizationStore(): organization "${organizationId}" has no store. Seed createTestClient({ organizationStores }), or look it up with GET /internal/organization-stores first.`
3813
+ );
3814
+ return ensureEntry(registry, { type: "organization-store", id: organizationStore.id }).store;
3815
+ },
3527
3816
  addFunction: (fn) => registerFunction(backend.functions, { fn, site: "addFunction()" }),
3528
3817
  removeFunction: (id) => unregisterFunction(backend.functions, id),
3529
3818
  functionInvocations: () => structuredClone(backend.functions.invocations),
@@ -3554,7 +3843,7 @@ function makeHandle(handleArgs) {
3554
3843
  "error" in outcome ? rec.error = outcome.error : rec.result = outcome.result;
3555
3844
  };
3556
3845
  },
3557
- recorded: RECORDED_METHODS
3846
+ recorded: handleArgs.internalStore === void 0 ? RECORDED_METHODS : /* @__PURE__ */ new Set()
3558
3847
  });
3559
3848
  }
3560
3849
  export {