@sanity-labs/client-fake-for-test 0.29.0 → 0.30.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
@@ -83,7 +83,7 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
83
83
  | Config | `getDataUrl(operation, path?)` | The same URL `@sanity/client` builds: `<resource base>/<operation>/<path>` on a `resource` handle, `/data/<operation>/<dataset>/<path>` otherwise |
84
84
  | Config | `withConfig({ projectId?, dataset?, resource?, perspective?, accessControl?, token?, useProjectHostname?, apiHost?, apiVersion?, useCdn? })` | 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 |
85
85
  | 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 |
86
- | 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. |
86
+ | HTTP | `request({ url? \| uri?, method?, body?, headers?, query? })` | 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)), and `POST /functions/<idOrName>/invoke` (see [Functions](#functions)). Calling it without one throws a guidance error. |
87
87
 
88
88
  #### Mutation return shapes
89
89
 
@@ -250,6 +250,68 @@ The first lookup for an organization without a store creates one `provisioning`,
250
250
 
251
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
252
 
253
+ #### Functions
254
+
255
+ `createTestClient({ functions })` deploys functions as the Functions API (sanity-io/functions) holds them, and `request()` invokes them as `POST /v<apiVersion>/functions/<idOrName>/invoke` does:
256
+
257
+ ```ts
258
+ const client = createTestClient({
259
+ projectId: "p1",
260
+ apiVersion: "2025-07-30", // the Functions API serves vX and dated versions only
261
+ organizationId: "oAbc",
262
+ identities: {
263
+ "t-editor": {
264
+ user: { id: "p-editor" },
265
+ globalUser: { id: "gEditor" },
266
+ grants: [],
267
+ access: { "project:p1": { roles: [], permissions: ["sanity.project.functions.invoke"] } },
268
+ },
269
+ },
270
+ token: "t-editor",
271
+ functions: [
272
+ {
273
+ id: "fn0123456789",
274
+ name: "advance",
275
+ type: "sanity.function.pubsub",
276
+ blueprintStackId: "ST-0123456789",
277
+ resourceType: "project",
278
+ resourceId: "p1",
279
+ },
280
+ ],
281
+ });
282
+ await client.request({
283
+ uri: "/functions/advance/invoke",
284
+ method: "POST",
285
+ query: { blueprintStackId: "ST-0123456789" }, // by name; omit to invoke by id
286
+ headers: { "X-Sanity-Scope-Type": "project", "X-Sanity-Scope-Id": "p1" },
287
+ body: { event: { data: { instanceId: "wf-1" } } },
288
+ });
289
+ // undefined: the API's 202 has an empty body
290
+ client.functionInvocations();
291
+ // [{ functionId: "fn0123456789", name: "advance", blueprintStackId: "ST-0123456789",
292
+ // scopeType: "project", scopeId: "p1", sync: false,
293
+ // event: { data: { instanceId: "wf-1" } }, invokedBy: { userId: "gEditor" } }]
294
+ ```
295
+
296
+ `client.addFunction(fn)` deploys (or replaces) one more and `client.removeFunction(id)` removes one, for every handle of the family. `functionInvocations()` lists every accepted invocation, in order; a refused one is not recorded. The caller's permissions are read from its `access["<scopeType>:<scopeId>"].permissions`. Header names are case-insensitive, and `blueprintStackId` may also be in the `uri`'s own query string. A `POST` to any other path throws the fake's no-handler error. Refusals are `PlatformHttpError`s whose `response.body` is the Functions API's `{ error, message, details: { errors } }`, checked in the service's order:
297
+
298
+ | Request | Answer |
299
+ | --- | --- |
300
+ | `apiVersion` `1` (the default) | 400 `BAD_REQUEST`, `Invalid API version in path`, `details.errors: { version: "v1" }` |
301
+ | An internal token (a service-minted JWT has no `guid` claim) | 401 `INVALID_TOKEN`, `Missing required claim: guid` |
302
+ | No `X-Sanity-Scope-Type` or `X-Sanity-Scope-Id` header | 400 `MISSING_SCOPE` |
303
+ | A scope type other than `project` or `organization` | 400 `INVALID_SCOPE_TYPE` |
304
+ | A caller holding none of `sanity.project.functions.invoke`, `sanity.project.blueprints.deploy`, `sanity.project.deployStudio` on a project scope (organization: `sanity.organization.functions.invoke`, `sanity.blueprints.deploy`, `sanity.organization.tokens.create`) | 403 `FORBIDDEN`, `You do not have invoke access to project p1`, `details.errors: { required: [...] }` |
305
+ | While `simulateOutage("project-api")` is in effect | 500 `ACCESS_ERROR`, `Failed to validate project access` |
306
+ | A body that is not `{ event: { data: {} } }`, a `blueprintStackId` under 10 characters, a `sync` other than `true` / `false` | 400 `INVALID_INPUT`, `Validation error: …` |
307
+ | Without `blueprintStackId`, an id under 10 characters | 400 `BAD_REQUEST`, `Invalid functionId` |
308
+ | With `blueprintStackId`, a name the stack does not hold | 404 `FUNCTION_NOT_FOUND`, `Function "<name>" was not found in Blueprint Stack <stackId>` |
309
+ | An unknown id, or a function outside the scope | 404 `FUNCTION_NOT_FOUND`, `function not found` |
310
+ | A document, media-library-asset, sync-tag-invalidate or schedule function; a queue or durable function with `sync: "true"` | 400 `INVOKE_NOT_SUPPORTED` |
311
+ | An asynchronous payload of 256 KiB or more | 413 `CONTENT_TOO_LARGE` |
312
+
313
+ A function is in scope when the scope owns it, or when an organization scope invokes a project's function and that organization is the client's `organizationId` (every project of the family belongs to it); a project scope never reaches an organization's function. Invocations are asynchronous only: a synchronous one that passes every check throws a fake error, as does an `x-sanity-lineage` header (the recursion limit is not modelled). The payload size is measured on `{ data, invokedBySanityUserId, lineage }`, slightly smaller than the Lambda payload the service measures. The service's quota check is not modelled.
314
+
253
315
  #### Missing datasets
254
316
 
255
317
  `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:
@@ -440,6 +502,8 @@ Useful in test bodies, but a giveaway that the code under test isn't using the r
440
502
  | `client.identities()` | Snapshot of the registered token→identity entries |
441
503
  | `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)) |
442
504
  | `createTestClient({ internalTokenKeys: [publicKeyPem] })` | Verify JWT bearers as the Content Lake does (see [Internal tokens](#internal-tokens)) |
505
+ | `client.addFunction(fn)` / `client.removeFunction(id)` | Deploy or remove a function the Functions API invoke route serves (see [Functions](#functions)) |
506
+ | `client.functionInvocations()` | Every invocation the Functions API accepted, in order (see [Functions](#functions)) |
443
507
  | `client.completeOrganizationStoreProvisioning(organizationId)` | Set the organization's `provisioning` store `active`, as populus's provisioning workflow does (see [Organization stores](#organization-stores)) |
444
508
  | `client.simulateOutage("project-api")` | Make every later project API request answer populus's 500 (see [Platform outages](#platform-outages)) |
445
509
  | `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
package/dist/index.cjs CHANGED
@@ -452,6 +452,316 @@ function badRequest(request, description) {
452
452
  body: { error: { description, type: "httpBadRequest" } }
453
453
  });
454
454
  }
455
+ const FUNCTION_INVOKE_PATH = /^\/functions\/([^/]+)\/invoke\/?$/, FUNCTION_TYPES = /* @__PURE__ */ new Set([
456
+ "sanity.function.pubsub",
457
+ "sanity.function.document",
458
+ "sanity.function.queue",
459
+ "sanity.function.durable",
460
+ "sanity.function.schedule",
461
+ "sanity.function.media-library-asset",
462
+ "sanity.function.sync-tag-invalidate"
463
+ ]), FUNCTION_ID_MIN_LENGTH = 10, INVOKE_PERMISSIONS = {
464
+ project: [
465
+ "sanity.project.functions.invoke",
466
+ "sanity.project.blueprints.deploy",
467
+ "sanity.project.deployStudio"
468
+ ],
469
+ organization: [
470
+ "sanity.organization.functions.invoke",
471
+ "sanity.blueprints.deploy",
472
+ "sanity.organization.tokens.create"
473
+ ]
474
+ }, MB_6 = 6291456, LAMBDA_ASYNC_LIMIT = 256 * 1024, CL_EVENTING_HINT = "Invoke the function by issuing a relevant Content Lake mutation operation instead.", STATUS_MESSAGES = {
475
+ 400: "Bad Request",
476
+ 401: "Unauthorized",
477
+ 403: "Forbidden",
478
+ 404: "Not Found",
479
+ 413: "Payload Too Large"
480
+ };
481
+ function registerFunction(registry, args) {
482
+ const { fn, site } = args;
483
+ if (typeof fn.id != "string" || fn.id.length < FUNCTION_ID_MIN_LENGTH)
484
+ throw fakeError(
485
+ `${site}: function id ${JSON.stringify(fn.id)} is shorter than ${FUNCTION_ID_MIN_LENGTH} characters; the Functions API's ids are at least that long.`
486
+ );
487
+ if (!FUNCTION_TYPES.has(fn.type))
488
+ throw fakeError(
489
+ `${site}: function "${fn.id}" has type ${JSON.stringify(fn.type)}; expected one of ${[...FUNCTION_TYPES].join(", ")}.`
490
+ );
491
+ if (fn.resourceType !== "project" && fn.resourceType !== "organization")
492
+ throw fakeError(
493
+ `${site}: function "${fn.id}" has resourceType ${JSON.stringify(fn.resourceType)}; expected "project" or "organization".`
494
+ );
495
+ const clash = [...registry.functions.values()].find(
496
+ (other) => other.id !== fn.id && other.blueprintStackId === fn.blueprintStackId && other.name === fn.name
497
+ );
498
+ if (clash !== void 0)
499
+ throw fakeError(
500
+ `${site}: functions "${clash.id}" and "${fn.id}" are both named "${fn.name}" in Blueprint stack ${fn.blueprintStackId}; a name is unique within its stack.`
501
+ );
502
+ registry.functions.set(fn.id, { ...fn });
503
+ }
504
+ function unregisterFunction(registry, id) {
505
+ if (!registry.functions.delete(id))
506
+ throw fakeError(
507
+ `removeFunction(): no function has id "${id}". Deployed ids: ${[...registry.functions.keys()].map((known) => `"${known}"`).join(", ") || "none"}.`
508
+ );
509
+ }
510
+ function refusal(request, args) {
511
+ const { statusCode } = args;
512
+ return new PlatformHttpError({
513
+ ...request,
514
+ statusCode,
515
+ statusMessage: STATUS_MESSAGES[statusCode],
516
+ body: { error: args.error, message: args.message, details: { errors: args.errors ?? [] } }
517
+ });
518
+ }
519
+ function invalidInput(request, issues) {
520
+ return new PlatformHttpError({
521
+ ...request,
522
+ statusCode: 400,
523
+ statusMessage: "Bad Request",
524
+ body: {
525
+ details: { errors: [{ message: issues.map((issue) => issue.pretty).join(`
526
+ `) }] },
527
+ error: "INVALID_INPUT",
528
+ message: `Validation error: ${issues.map((issue) => issue.summary).join("; ")}`
529
+ }
530
+ });
531
+ }
532
+ function prettyPath(path) {
533
+ return path.map((key, index) => /^[A-Za-z_$][\w$]*$/.test(key) ? index === 0 ? key : `.${key}` : `[${JSON.stringify(key)}]`).join("");
534
+ }
535
+ function issueAt(path, message) {
536
+ return path.length === 0 ? { summary: message, pretty: `\u2716 ${message}` } : {
537
+ summary: `${message} at "${path.join(".")}"`,
538
+ pretty: `\u2716 ${message}
539
+ \u2192 at ${prettyPath(path)}`
540
+ };
541
+ }
542
+ function tooShort(args) {
543
+ const { key, min, value } = args;
544
+ if (!(value.length >= min))
545
+ return issueAt([key], `Too small: expected string to have >=${min} characters`);
546
+ }
547
+ function typeName(value) {
548
+ return value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
549
+ }
550
+ function isRecord(value) {
551
+ return typeName(value) === "object";
552
+ }
553
+ function bodyIssue(body) {
554
+ const parts = [[[], body]];
555
+ isRecord(body) && (parts.push([["event"], body.event]), isRecord(body.event) && parts.push([["event", "data"], body.event.data]));
556
+ const failed = parts.find(([, value2]) => !isRecord(value2));
557
+ if (failed === void 0) return;
558
+ const [path, value] = failed;
559
+ return issueAt(path, `Invalid input: expected object, received ${typeName(value)}`);
560
+ }
561
+ function parseQuery(request) {
562
+ 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
+ if (repeated !== void 0)
564
+ throw fakeError(
565
+ `request(): ${request.path} got "${repeated}" more than once; Hono reads a repeated query key as an array, whose validation answer the fake does not model. Pass it once.`
566
+ );
567
+ const blueprintStackId = query.get("blueprintStackId") ?? void 0, sync = query.get("sync") ?? "false", issues = [
568
+ blueprintStackId === void 0 ? void 0 : tooShort({ key: "blueprintStackId", min: 10, value: blueprintStackId }),
569
+ sync === "true" || sync === "false" ? void 0 : {
570
+ summary: 'Invalid input: expected "true" at "sync" or Invalid input: expected "false" at "sync"',
571
+ pretty: `\u2716 Invalid input
572
+ \u2192 at sync`
573
+ }
574
+ ].filter((issue) => issue !== void 0);
575
+ return issues.length > 0 ? issues : { blueprintStackId, sync: sync === "true" };
576
+ }
577
+ function decodeSegment$1(segment) {
578
+ try {
579
+ return decodeURIComponent(segment);
580
+ } catch {
581
+ return segment;
582
+ }
583
+ }
584
+ function lowercaseHeaders(headers) {
585
+ return new Map(Object.entries(headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]));
586
+ }
587
+ function cannotInvoke(fn, sync) {
588
+ switch (fn.type) {
589
+ case "sanity.function.document":
590
+ case "sanity.function.media-library-asset":
591
+ case "sanity.function.sync-tag-invalidate":
592
+ return `Content Lake evented functions like ${fn.type} cannot be directly invoked. ${CL_EVENTING_HINT}`;
593
+ case "sanity.function.schedule":
594
+ return `${fn.type} functions cannot be directly invoked.`;
595
+ case "sanity.function.queue":
596
+ case "sanity.function.durable":
597
+ return sync ? `${fn.type} functions cannot be synchronously invoked.` : void 0;
598
+ case "sanity.function.pubsub":
599
+ return;
600
+ }
601
+ }
602
+ function inScope(organizationId, args) {
603
+ const { fn, scope } = args;
604
+ return fn.resourceType === scope.type && fn.resourceId === scope.id ? !0 : scope.type === "organization" && fn.resourceType === "project" && organizationId !== void 0 && organizationId === scope.id;
605
+ }
606
+ function admitScope(ctx, args) {
607
+ const { request, headers } = args, type = headers.get("x-sanity-scope-type"), id = headers.get("x-sanity-scope-id");
608
+ if (!type || !id)
609
+ throw refusal(request, {
610
+ statusCode: 400,
611
+ error: "MISSING_SCOPE",
612
+ message: "X-Sanity-Scope-Type and X-Sanity-Scope-Id headers are required"
613
+ });
614
+ if (type !== "project" && type !== "organization")
615
+ throw refusal(request, {
616
+ statusCode: 400,
617
+ error: "INVALID_SCOPE_TYPE",
618
+ message: "Only organization and project scopes are currently supported"
619
+ });
620
+ if (ctx.projectApiDown())
621
+ throw new PlatformServerError({
622
+ ...request,
623
+ statusCode: 500,
624
+ statusMessage: "Internal Server Error",
625
+ body: {
626
+ error: "ACCESS_ERROR",
627
+ message: "Failed to validate project access",
628
+ details: { errors: [] }
629
+ }
630
+ });
631
+ const required = INVOKE_PERMISSIONS[type], held = ctx.actorAccess()?.[accessKey(type, id)]?.permissions ?? [];
632
+ if (!required.some((permission) => held.includes(permission)))
633
+ throw refusal(request, {
634
+ statusCode: 403,
635
+ error: "FORBIDDEN",
636
+ message: `You do not have invoke access to ${type} ${id}`,
637
+ errors: { required: [...required] }
638
+ });
639
+ return { type, id };
640
+ }
641
+ function validate(request, parts) {
642
+ const query = parseQuery(request);
643
+ if (Array.isArray(query)) throw invalidInput(request, query);
644
+ const issue = [
645
+ tooShort({ key: "functionId", min: 3, value: parts.segment }),
646
+ tooShort({
647
+ key: "x-sanity-scope-id",
648
+ min: 8,
649
+ value: parts.headers.get("x-sanity-scope-id")
650
+ }),
651
+ bodyIssue(parts.body)
652
+ ].find((found) => found !== void 0);
653
+ if (issue !== void 0) throw invalidInput(request, [issue]);
654
+ const { event } = parts.body;
655
+ return { ...query, data: event.data };
656
+ }
657
+ function findFunction(registry, args) {
658
+ const { request, segment, blueprintStackId } = args;
659
+ if (blueprintStackId === void 0) {
660
+ if (segment.length < FUNCTION_ID_MIN_LENGTH)
661
+ throw refusal(request, {
662
+ statusCode: 400,
663
+ error: "BAD_REQUEST",
664
+ message: "Invalid functionId"
665
+ });
666
+ return registry.functions.get(segment);
667
+ }
668
+ const byName = [...registry.functions.values()].find(
669
+ (fn) => fn.blueprintStackId === blueprintStackId && fn.name === segment
670
+ );
671
+ if (byName === void 0)
672
+ throw refusal(request, {
673
+ statusCode: 404,
674
+ error: "FUNCTION_NOT_FOUND",
675
+ message: `Function "${segment}" was not found in Blueprint Stack ${blueprintStackId}`
676
+ });
677
+ return byName;
678
+ }
679
+ function refuseOversized(request, args) {
680
+ const size = Buffer.byteLength(
681
+ JSON.stringify({ data: args.data, invokedBySanityUserId: args.userId, lineage: "" }),
682
+ "utf8"
683
+ );
684
+ if (!args.sync && size >= LAMBDA_ASYNC_LIMIT)
685
+ throw refusal(request, {
686
+ statusCode: 413,
687
+ error: "CONTENT_TOO_LARGE",
688
+ message: `Invoke payload must be smaller than ${LAMBDA_ASYNC_LIMIT} bytes for asynchronous invocations; current size=${size} bytes. Reduce payload size or set sync=true (not recommended due to blocking network request).`
689
+ });
690
+ if (args.sync && size > MB_6)
691
+ throw refusal(request, {
692
+ statusCode: 413,
693
+ error: "CONTENT_TOO_LARGE",
694
+ message: `Invoke payload must be smaller than ${MB_6} bytes for synchronous invocations; current size=${size} bytes.`
695
+ });
696
+ }
697
+ function serveFunctionInvoke(ctx, invoke) {
698
+ const { request, ...parts } = invoke, pathVersion = `v${ctx.apiVersion}`;
699
+ if (!/^v\d{4}-\d{2}-\d{2}$/.test(pathVersion) && pathVersion !== "vX")
700
+ throw refusal(request, {
701
+ statusCode: 400,
702
+ error: "BAD_REQUEST",
703
+ message: "Invalid API version in path",
704
+ errors: { version: pathVersion }
705
+ });
706
+ if (ctx.internalToken())
707
+ throw refusal(request, {
708
+ statusCode: 401,
709
+ error: "INVALID_TOKEN",
710
+ message: "Missing required claim: guid"
711
+ });
712
+ const headers = lowercaseHeaders(parts.headers), scope = admitScope(ctx, { request, headers });
713
+ if (parts.body === void 0)
714
+ throw fakeError(
715
+ `request(): POST ${request.path} without a body. The Functions API answers it with a 500 once its pre-flight checks pass, which the fake does not model. Send \`body: { event: { data: {} } }\`.`
716
+ );
717
+ if (typeof parts.body != "object" || parts.body === null)
718
+ throw fakeError(
719
+ `request(): POST ${request.path} with a ${typeof parts.body} body; @sanity/client sends it without a JSON content type, which the fake does not model. Send an object.`
720
+ );
721
+ if (Buffer.byteLength(JSON.stringify(parts.body), "utf8") > MB_6)
722
+ throw refusal(request, {
723
+ statusCode: 413,
724
+ error: "CONTENT_TOO_LARGE",
725
+ message: `Request must be smaller than ${MB_6} bytes for the Invoke Function operation`
726
+ });
727
+ const segment = decodeSegment$1(request.path.match(FUNCTION_INVOKE_PATH)[1]), { blueprintStackId, sync, data } = validate(request, {
728
+ segment,
729
+ headers,
730
+ body: parts.body
731
+ }), fn = findFunction(ctx.registry, { request, segment, blueprintStackId });
732
+ if (fn === void 0 || !inScope(ctx.organizationId, { fn, scope }))
733
+ throw refusal(request, {
734
+ statusCode: 404,
735
+ error: "FUNCTION_NOT_FOUND",
736
+ message: "function not found"
737
+ });
738
+ const notInvokable = cannotInvoke(fn, sync);
739
+ if (notInvokable !== void 0)
740
+ throw refusal(request, {
741
+ statusCode: 400,
742
+ error: "INVOKE_NOT_SUPPORTED",
743
+ message: notInvokable
744
+ });
745
+ if (headers.has("x-sanity-lineage"))
746
+ throw fakeError(
747
+ `request(): POST ${request.path} with an x-sanity-lineage header; the Functions API's recursion limit is not modelled. Omit the header.`
748
+ );
749
+ const userId = ctx.actorUser().id;
750
+ if (refuseOversized(request, { data, userId, sync }), sync)
751
+ throw fakeError(
752
+ `request(): POST ${request.path}?sync=true passed every check the Functions API makes, but synchronous invocation (the function's return value) is not modelled. Invoke asynchronously: omit \`sync\` or pass \`sync: "false"\`.`
753
+ );
754
+ ctx.registry.invocations.push({
755
+ functionId: fn.id,
756
+ name: fn.name,
757
+ blueprintStackId: fn.blueprintStackId,
758
+ scopeType: scope.type,
759
+ scopeId: scope.id,
760
+ sync,
761
+ event: { data: structuredClone(data) },
762
+ invokedBy: { userId }
763
+ });
764
+ }
455
765
  function createDocumentHistory() {
456
766
  const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
457
767
  return {
@@ -1111,6 +1421,7 @@ function serveProject(args) {
1111
1421
  function makeRequestImpl(ctx) {
1112
1422
  const { getAccess, requestFor, useProjectHostname, listIdentities, organizationId, platform } = ctx;
1113
1423
  return async (opts) => {
1424
+ if ((opts.method ?? "GET").toUpperCase() !== "GET") return servePost(ctx, opts);
1114
1425
  const accessControl = getAccess(), path = opts.uri ?? opts.url;
1115
1426
  if (path === "/users/me") {
1116
1427
  const user = useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
@@ -1139,6 +1450,18 @@ function makeRequestImpl(ctx) {
1139
1450
  );
1140
1451
  };
1141
1452
  }
1453
+ function servePost(ctx, opts) {
1454
+ const request = ctx.requestFor(opts);
1455
+ if (request.method === "POST" && FUNCTION_INVOKE_PATH.test(request.path))
1456
+ return serveFunctionInvoke(ctx.functions, {
1457
+ request,
1458
+ body: opts.body,
1459
+ headers: opts.headers
1460
+ });
1461
+ throw fakeError(
1462
+ `request(): no handler for ${opts.method} "${opts.uri ?? opts.url}". The fake serves POST on "/functions/<idOrName>/invoke" (the Functions API) only. For any other endpoint, register a stub (client.stub("request", fn)) or intercept the HTTP call with a tool like MSW.`
1463
+ );
1464
+ }
1142
1465
  class GuardDeniedError extends client.ClientError {
1143
1466
  type = "guardDeniedError";
1144
1467
  denials;
@@ -2404,6 +2727,15 @@ function seedEntry(registry, resource, documents) {
2404
2727
  const entry = ensureEntry(registry, resource);
2405
2728
  entry.store.seed(documents), entry.exists = !0;
2406
2729
  }
2730
+ function seedFunctions(functions) {
2731
+ const registry = { functions: /* @__PURE__ */ new Map(), invocations: [] };
2732
+ for (const fn of functions) {
2733
+ if (registry.functions.has(fn.id))
2734
+ throw fakeError(`createTestClient(): \`functions\` lists id "${fn.id}" twice.`);
2735
+ registerFunction(registry, { fn, site: "createTestClient()" });
2736
+ }
2737
+ return registry;
2738
+ }
2407
2739
  function seedOrganizationStores(options) {
2408
2740
  const seeded = Object.entries(options.organizationStores ?? {}), unserved = seeded.find(([, status]) => status !== "provisioning" && status !== "active");
2409
2741
  if (unserved !== void 0)
@@ -2428,6 +2760,7 @@ function createTestClient(options = {}) {
2428
2760
  organizationId: options.organizationId,
2429
2761
  projectFeatures: options.projectFeatures ?? {},
2430
2762
  organizationStores: seedOrganizationStores(options),
2763
+ functions: seedFunctions(options.functions ?? []),
2431
2764
  log: [],
2432
2765
  stubs: /* @__PURE__ */ new Map(),
2433
2766
  calls: [],
@@ -2568,8 +2901,8 @@ function makeHandle(handleArgs) {
2568
2901
  }, internal = () => token === void 0 ? void 0 : internalToken(backend, token), refuseInternalToken = (request) => {
2569
2902
  const check = internal();
2570
2903
  if (check === void 0) return;
2571
- const refusal = internalTokenRefusal(request, check);
2572
- if (refusal !== void 0) throw refusal;
2904
+ const refusal2 = internalTokenRefusal(request, check);
2905
+ if (refusal2 !== void 0) throw refusal2;
2573
2906
  }, withSession = (request) => async (opts) => {
2574
2907
  const sent = rawRequest(opts);
2575
2908
  if (internal() !== void 0 && servedByProjectApi(sent.path) && sent.path !== ORGANIZATION_STORES_PATH)
@@ -2587,8 +2920,8 @@ function makeHandle(handleArgs) {
2587
2920
  refuseInternalToken(request);
2588
2921
  const access = activeAccess();
2589
2922
  if (access === void 0) return;
2590
- const refusal = refusedToken(request, access.grants);
2591
- if (refusal !== void 0) throw refusal;
2923
+ const refusal2 = refusedToken(request, access.grants);
2924
+ if (refusal2 !== void 0) throw refusal2;
2592
2925
  }, baseUrls = apiBaseUrls({
2593
2926
  apiHost,
2594
2927
  apiVersion,
@@ -2641,7 +2974,7 @@ function makeHandle(handleArgs) {
2641
2974
  if (opts.query !== void 0 && "tag" in opts.query)
2642
2975
  throw fakeError("request(): pass the request tag as `tag`, not in `query`.");
2643
2976
  return platformRequest({
2644
- method: "GET",
2977
+ method: opts.method?.toUpperCase() === "POST" ? "POST" : "GET",
2645
2978
  uri: opts.uri ?? opts.url ?? "",
2646
2979
  tag: opts.tag,
2647
2980
  query: Object.entries(opts.query ?? {}).flatMap(
@@ -3078,6 +3411,7 @@ function makeHandle(handleArgs) {
3078
3411
  makeRequestImpl({
3079
3412
  getAccess: requireActiveAccess,
3080
3413
  requestFor: rawRequest,
3414
+ projectId,
3081
3415
  useProjectHostname: projectHosted,
3082
3416
  organizationId: backend.organizationId,
3083
3417
  listIdentities: members,
@@ -3106,6 +3440,18 @@ function makeHandle(handleArgs) {
3106
3440
  // A dataset stands for its project, and every project exists in
3107
3441
  // the fake, so a dataset handle still counts as before.
3108
3442
  resources: () => [...registry.values()].filter((e) => e.exists || e.resource.type === "dataset").map((e) => e.resource)
3443
+ },
3444
+ functions: {
3445
+ apiVersion,
3446
+ organizationId: backend.organizationId,
3447
+ registry: backend.functions,
3448
+ internalToken: () => internal() !== void 0,
3449
+ projectApiDown: () => backend.outages.has("project-api"),
3450
+ actorUser: () => {
3451
+ const access = requireActiveAccess();
3452
+ return access.globalUser ?? access.currentUser;
3453
+ },
3454
+ actorAccess: () => requireActiveAccess().access
3109
3455
  }
3110
3456
  })
3111
3457
  )
@@ -3178,6 +3524,9 @@ function makeHandle(handleArgs) {
3178
3524
  backend.outages.add(component);
3179
3525
  },
3180
3526
  completeOrganizationStoreProvisioning: (organizationId) => completeProvisioning(backend.organizationStores, organizationId),
3527
+ addFunction: (fn) => registerFunction(backend.functions, { fn, site: "addFunction()" }),
3528
+ removeFunction: (id) => unregisterFunction(backend.functions, id),
3529
+ functionInvocations: () => structuredClone(backend.functions.invocations),
3181
3530
  mutations: () => backend.log.flatMap((entry) => entry.mutations),
3182
3531
  transactions: () => [...backend.log],
3183
3532
  clearLog: () => {