@sanity-labs/client-fake-for-test 0.17.3 → 0.18.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
@@ -1,3 +1,5 @@
1
+ import { ClientError } from "@sanity/client";
2
+
1
3
  export declare type Action = ReleaseAction | VersionAction | DocumentAction;
2
4
 
3
5
  /** Options for `action()`. Only `tag` is meaningful to the fake. */
@@ -449,25 +451,46 @@ export declare interface GuardConfig {
449
451
  recorded?: Set<string>;
450
452
  }
451
453
 
452
- /** HTTP-shaped guard rejection matching the error exposed by `@sanity/client`. */
453
- export declare class GuardDeniedError extends Error {
454
- readonly statusCode = 403;
454
+ /** The `guardDeniedError` gradient writes for a guard's denial (`proto.GuardDeniedError`). */
455
+ export declare interface GuardDeniedDetails {
456
+ description: string;
457
+ denials: MutationGuardDenial[];
458
+ type: "guardDeniedError";
459
+ }
460
+
461
+ /**
462
+ * The Content Lake's 403 when a mutation guard denies a write: a
463
+ * `ClientError` built from the response gradient sends, a
464
+ * `guardDeniedError` wrapped in a `mutationError`. `denials` and `type` lift
465
+ * the guard's answer to the top for callers that match on them.
466
+ */
467
+ export declare class GuardDeniedError extends ClientError {
455
468
  readonly type = "guardDeniedError";
456
469
  readonly denials: MutationGuardDenial[];
457
- readonly details: GuardDeniedResponse["body"]["error"];
470
+ readonly statusCode: 403;
458
471
  readonly response: GuardDeniedResponse;
459
- constructor(denials: readonly MutationGuardDenial[]);
472
+ constructor(
473
+ denials: readonly MutationGuardDenial[],
474
+ request?: PlatformRequest,
475
+ );
460
476
  }
461
477
 
478
+ /** The `response` of a {@link GuardDeniedError}: the Content Lake's 403 for a guarded write. */
462
479
  export declare interface GuardDeniedResponse {
463
480
  body: {
464
481
  error: {
465
- type: "guardDeniedError";
466
- denials: MutationGuardDenial[];
482
+ description: string;
483
+ items: [
484
+ {
485
+ error: GuardDeniedDetails;
486
+ index: 0;
487
+ },
488
+ ];
489
+ type: "mutationError";
467
490
  };
468
491
  };
469
492
  url: string;
470
- method: "POST";
493
+ method: string;
471
494
  headers: Record<string, string>;
472
495
  statusCode: 403;
473
496
  statusMessage: "Forbidden";
@@ -692,34 +715,30 @@ export declare type Perspective =
692
715
  | (string & {})
693
716
  | string[];
694
717
 
695
- /** The `response` of an HTTP error, shaped like `@sanity/client`'s `HttpError["response"]`. */
696
- declare interface PlatformErrorResponse {
697
- body: unknown;
698
- url: string;
718
+ /**
719
+ * The platform's refusal, as the `ClientError` `@sanity/client` throws for
720
+ * the same response: the fake hands `ClientError` the response the client
721
+ * would have received, and `ClientError` derives `statusCode`, `message`,
722
+ * `responseBody` and `details` from it. So `instanceof ClientError` holds for
723
+ * the `@sanity/client` the consumer has installed.
724
+ */
725
+ export declare class PlatformHttpError extends ClientError {
726
+ constructor(args: PlatformResponseArgs);
727
+ }
728
+
729
+ /** A request the platform answers. `path` is the API path, without host or API version. */
730
+ declare interface PlatformRequest {
731
+ method: "GET" | "POST";
732
+ path: string;
733
+ }
734
+
735
+ /** What the platform answered, and to which request. */
736
+ declare interface PlatformResponseArgs {
699
737
  method: string;
700
- headers: Record<string, string>;
738
+ path: string;
701
739
  statusCode: number;
702
740
  statusMessage: string;
703
- }
704
-
705
- /**
706
- * The platform's refusal, shaped like the `ClientError` `@sanity/client`
707
- * throws for the same response: `statusCode`, `response`, `responseBody`,
708
- * `details`, and a `message` derived from the body the way the client
709
- * derives it.
710
- */
711
- export declare class PlatformHttpError extends Error {
712
- readonly statusCode: number;
713
- readonly response: PlatformErrorResponse;
714
- readonly responseBody: string;
715
- readonly details: unknown;
716
- constructor(args: {
717
- method: string;
718
- path: string;
719
- statusCode: number;
720
- statusMessage: string;
721
- body: unknown;
722
- });
741
+ body: unknown;
723
742
  }
724
743
 
725
744
  /** One row of the `/projects/<projectId>` members response. */
@@ -1484,12 +1503,15 @@ export declare function wrapWithGuards<T extends object>(
1484
1503
  ): T;
1485
1504
 
1486
1505
  /**
1487
- * Sanity-style 403 raised when a configured-grants check rejects a
1488
- * write. The thrown object carries the doc id, the attempted
1489
- * permission, and the count of matching grants (for parity with the
1490
- * engine's `permission-denied` disabled-reason).
1506
+ * The Content Lake's 403 when a configured-grants check rejects a write: a
1507
+ * `ClientError` built from the response gradient sends, an
1508
+ * `insufficientPermissionsError` wrapped in a `mutationError`
1509
+ * (`pkg/security/errors.go` `InsufficientPermissionsError`). It also carries
1510
+ * the doc id, the attempted permission, and the count of matching grants
1511
+ * (for parity with the engine's `permission-denied` disabled-reason), which
1512
+ * the platform's answer does not name.
1491
1513
  */
1492
- export declare class WriteAccessDeniedError extends Error {
1514
+ export declare class WriteAccessDeniedError extends ClientError {
1493
1515
  readonly documentId: string;
1494
1516
  readonly permission: DocumentValuePermission;
1495
1517
  readonly matchingGrants: number;
@@ -1497,6 +1519,8 @@ export declare class WriteAccessDeniedError extends Error {
1497
1519
  documentId: string;
1498
1520
  permission: DocumentValuePermission;
1499
1521
  matchingGrants: number;
1522
+ /** The write the Content Lake refused; defaults to a `/data/mutate` request. */
1523
+ request?: PlatformRequest;
1500
1524
  });
1501
1525
  }
1502
1526
 
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { ClientError } from "@sanity/client";
2
+
1
3
  export declare type Action = ReleaseAction | VersionAction | DocumentAction;
2
4
 
3
5
  /** Options for `action()`. Only `tag` is meaningful to the fake. */
@@ -449,25 +451,46 @@ export declare interface GuardConfig {
449
451
  recorded?: Set<string>;
450
452
  }
451
453
 
452
- /** HTTP-shaped guard rejection matching the error exposed by `@sanity/client`. */
453
- export declare class GuardDeniedError extends Error {
454
- readonly statusCode = 403;
454
+ /** The `guardDeniedError` gradient writes for a guard's denial (`proto.GuardDeniedError`). */
455
+ export declare interface GuardDeniedDetails {
456
+ description: string;
457
+ denials: MutationGuardDenial[];
458
+ type: "guardDeniedError";
459
+ }
460
+
461
+ /**
462
+ * The Content Lake's 403 when a mutation guard denies a write: a
463
+ * `ClientError` built from the response gradient sends, a
464
+ * `guardDeniedError` wrapped in a `mutationError`. `denials` and `type` lift
465
+ * the guard's answer to the top for callers that match on them.
466
+ */
467
+ export declare class GuardDeniedError extends ClientError {
455
468
  readonly type = "guardDeniedError";
456
469
  readonly denials: MutationGuardDenial[];
457
- readonly details: GuardDeniedResponse["body"]["error"];
470
+ readonly statusCode: 403;
458
471
  readonly response: GuardDeniedResponse;
459
- constructor(denials: readonly MutationGuardDenial[]);
472
+ constructor(
473
+ denials: readonly MutationGuardDenial[],
474
+ request?: PlatformRequest,
475
+ );
460
476
  }
461
477
 
478
+ /** The `response` of a {@link GuardDeniedError}: the Content Lake's 403 for a guarded write. */
462
479
  export declare interface GuardDeniedResponse {
463
480
  body: {
464
481
  error: {
465
- type: "guardDeniedError";
466
- denials: MutationGuardDenial[];
482
+ description: string;
483
+ items: [
484
+ {
485
+ error: GuardDeniedDetails;
486
+ index: 0;
487
+ },
488
+ ];
489
+ type: "mutationError";
467
490
  };
468
491
  };
469
492
  url: string;
470
- method: "POST";
493
+ method: string;
471
494
  headers: Record<string, string>;
472
495
  statusCode: 403;
473
496
  statusMessage: "Forbidden";
@@ -692,34 +715,30 @@ export declare type Perspective =
692
715
  | (string & {})
693
716
  | string[];
694
717
 
695
- /** The `response` of an HTTP error, shaped like `@sanity/client`'s `HttpError["response"]`. */
696
- declare interface PlatformErrorResponse {
697
- body: unknown;
698
- url: string;
718
+ /**
719
+ * The platform's refusal, as the `ClientError` `@sanity/client` throws for
720
+ * the same response: the fake hands `ClientError` the response the client
721
+ * would have received, and `ClientError` derives `statusCode`, `message`,
722
+ * `responseBody` and `details` from it. So `instanceof ClientError` holds for
723
+ * the `@sanity/client` the consumer has installed.
724
+ */
725
+ export declare class PlatformHttpError extends ClientError {
726
+ constructor(args: PlatformResponseArgs);
727
+ }
728
+
729
+ /** A request the platform answers. `path` is the API path, without host or API version. */
730
+ declare interface PlatformRequest {
731
+ method: "GET" | "POST";
732
+ path: string;
733
+ }
734
+
735
+ /** What the platform answered, and to which request. */
736
+ declare interface PlatformResponseArgs {
699
737
  method: string;
700
- headers: Record<string, string>;
738
+ path: string;
701
739
  statusCode: number;
702
740
  statusMessage: string;
703
- }
704
-
705
- /**
706
- * The platform's refusal, shaped like the `ClientError` `@sanity/client`
707
- * throws for the same response: `statusCode`, `response`, `responseBody`,
708
- * `details`, and a `message` derived from the body the way the client
709
- * derives it.
710
- */
711
- export declare class PlatformHttpError extends Error {
712
- readonly statusCode: number;
713
- readonly response: PlatformErrorResponse;
714
- readonly responseBody: string;
715
- readonly details: unknown;
716
- constructor(args: {
717
- method: string;
718
- path: string;
719
- statusCode: number;
720
- statusMessage: string;
721
- body: unknown;
722
- });
741
+ body: unknown;
723
742
  }
724
743
 
725
744
  /** One row of the `/projects/<projectId>` members response. */
@@ -1484,12 +1503,15 @@ export declare function wrapWithGuards<T extends object>(
1484
1503
  ): T;
1485
1504
 
1486
1505
  /**
1487
- * Sanity-style 403 raised when a configured-grants check rejects a
1488
- * write. The thrown object carries the doc id, the attempted
1489
- * permission, and the count of matching grants (for parity with the
1490
- * engine's `permission-denied` disabled-reason).
1506
+ * The Content Lake's 403 when a configured-grants check rejects a write: a
1507
+ * `ClientError` built from the response gradient sends, an
1508
+ * `insufficientPermissionsError` wrapped in a `mutationError`
1509
+ * (`pkg/security/errors.go` `InsufficientPermissionsError`). It also carries
1510
+ * the doc id, the attempted permission, and the count of matching grants
1511
+ * (for parity with the engine's `permission-denied` disabled-reason), which
1512
+ * the platform's answer does not name.
1491
1513
  */
1492
- export declare class WriteAccessDeniedError extends Error {
1514
+ export declare class WriteAccessDeniedError extends ClientError {
1493
1515
  readonly documentId: string;
1494
1516
  readonly permission: DocumentValuePermission;
1495
1517
  readonly matchingGrants: number;
@@ -1497,6 +1519,8 @@ export declare class WriteAccessDeniedError extends Error {
1497
1519
  documentId: string;
1498
1520
  permission: DocumentValuePermission;
1499
1521
  matchingGrants: number;
1522
+ /** The write the Content Lake refused; defaults to a `/data/mutate` request. */
1523
+ request?: PlatformRequest;
1500
1524
  });
1501
1525
  }
1502
1526
 
package/dist/index.js CHANGED
@@ -1,38 +1,40 @@
1
1
  import { parse, evaluate } from "groq-js";
2
+ import { ClientError } from "@sanity/client";
2
3
  const ERR_PREFIX = "[client-fake-for-test]";
3
4
  function fakeError(message) {
4
5
  return new Error(`${ERR_PREFIX} ${message}`);
5
6
  }
6
- class PlatformHttpError extends Error {
7
- statusCode;
8
- response;
9
- responseBody;
10
- details;
7
+ class PlatformHttpError extends ClientError {
11
8
  constructor(args) {
12
- const { method, path, statusCode, statusMessage, body } = args;
13
- super(clientErrorMessage(args)), this.name = "PlatformHttpError", this.statusCode = statusCode, this.response = { body, url: path, method, headers: {}, statusCode, statusMessage }, this.responseBody = typeof body == "string" ? body : JSON.stringify(body, null, 2);
14
- const error = isRecord(body) ? body.error : void 0;
15
- this.details = isRecord(error) ? error : void 0;
9
+ super(platformResponse(args)), this.name = "PlatformHttpError";
16
10
  }
17
11
  }
18
- function isRecord(value) {
19
- return typeof value == "object" && value !== null;
20
- }
21
- function clientErrorMessage(args) {
22
- const { body } = args;
23
- if (isRecord(body)) {
24
- const { error, message } = body;
25
- if (typeof error == "string" && typeof message == "string") return `${error} - ${message}`;
26
- if (typeof error == "string") return error;
27
- if (isRecord(error)) {
28
- if (typeof error.description == "string") return error.description;
29
- } else if (typeof message == "string")
30
- return message;
31
- }
32
- const details = typeof body == "string" ? ` (${body.length > 100 ? `${body.slice(0, 100)}\u2026` : body})` : "";
33
- return `${args.method}-request to ${args.path} resulted in HTTP ${args.statusCode} ${args.statusMessage}${details}`;
12
+ function platformResponse(args) {
13
+ const { method, path, statusCode, statusMessage, body } = args;
14
+ return {
15
+ body,
16
+ url: path,
17
+ method,
18
+ headers: { "content-type": `${typeof body == "string" ? "text/html" : "application/json"}; charset=utf-8` },
19
+ statusCode,
20
+ statusMessage
21
+ };
22
+ }
23
+ function transactionRefused(request, cause) {
24
+ return platformResponse({
25
+ ...request,
26
+ statusCode: 403,
27
+ statusMessage: "Forbidden",
28
+ body: {
29
+ error: {
30
+ description: `transaction failed: ${cause.description}`,
31
+ items: [{ error: cause, index: 0 }],
32
+ type: "mutationError"
33
+ }
34
+ }
35
+ });
34
36
  }
35
- const notMounted = ({ method, path }) => new PlatformHttpError({
37
+ const DEFAULT_WRITE = { method: "POST", path: "/data/mutate" }, notMounted = ({ method, path }) => new PlatformHttpError({
36
38
  method,
37
39
  path,
38
40
  statusCode: 404,
@@ -693,13 +695,17 @@ function attributeRecord(attribute) {
693
695
  );
694
696
  return { type, key, values: { ...values }, activeSource, activeValue };
695
697
  }
696
- class WriteAccessDeniedError extends Error {
698
+ class WriteAccessDeniedError extends ClientError {
697
699
  documentId;
698
700
  permission;
699
701
  matchingGrants;
700
702
  constructor(args) {
701
703
  super(
702
- `Sanity (test): permission denied \u2014 actor lacks "${args.permission}" on document "${args.documentId}" (${args.matchingGrants} grant${args.matchingGrants === 1 ? "" : "s"} matched the document but none included "${args.permission}").`
704
+ transactionRefused(args.request ?? DEFAULT_WRITE, {
705
+ description: `Insufficient permissions; permission "${args.permission}" required`,
706
+ permission: args.permission,
707
+ type: "insufficientPermissionsError"
708
+ })
703
709
  ), this.name = "WriteAccessDeniedError", this.documentId = args.documentId, this.permission = args.permission, this.matchingGrants = args.matchingGrants;
704
710
  }
705
711
  }
@@ -729,7 +735,7 @@ async function evaluateWriteAccess(args) {
729
735
  return { allowed: !1, matchingGrants: matching };
730
736
  }
731
737
  async function enforceWriteAccess(args) {
732
- const { document, grants, permission, userId } = args, { allowed, matchingGrants } = await evaluateWriteAccess({
738
+ const { document, grants, permission, userId, request } = args, { allowed, matchingGrants } = await evaluateWriteAccess({
733
739
  document,
734
740
  grants,
735
741
  permission,
@@ -739,11 +745,13 @@ async function enforceWriteAccess(args) {
739
745
  throw typeof document._id != "string" ? new WriteAccessDeniedError({
740
746
  documentId: "(unknown)",
741
747
  permission,
742
- matchingGrants
748
+ matchingGrants,
749
+ request
743
750
  }) : new WriteAccessDeniedError({
744
751
  documentId: document._id,
745
752
  permission,
746
- matchingGrants
753
+ matchingGrants,
754
+ request
747
755
  });
748
756
  }
749
757
  function defaultAclPath(projectId, dataset) {
@@ -853,24 +861,24 @@ function makeRequestImpl(ctx) {
853
861
  );
854
862
  };
855
863
  }
856
- class GuardDeniedError extends Error {
857
- statusCode = 403;
864
+ class GuardDeniedError extends ClientError {
858
865
  type = "guardDeniedError";
859
866
  denials;
860
- details;
861
- response;
862
- constructor(denials) {
867
+ constructor(denials, request = DEFAULT_WRITE) {
863
868
  const unique = uniqueDenials(denials);
864
- super(`Mutation denied by guard(s) [${unique.map((denial) => denial.guardID).join(", ")}]`), this.name = "GuardDeniedError", this.denials = unique, this.details = { type: this.type, denials: unique }, this.response = {
865
- body: { error: this.details },
866
- url: "memory://client-fake-for-test/data/mutate",
867
- method: "POST",
868
- headers: {},
869
- statusCode: this.statusCode,
870
- statusMessage: "Forbidden"
871
- };
869
+ super(
870
+ transactionRefused(request, {
871
+ description: guardDeniedDescription(unique),
872
+ denials: unique,
873
+ type: "guardDeniedError"
874
+ })
875
+ ), this.name = "GuardDeniedError", this.denials = unique;
872
876
  }
873
877
  }
878
+ function guardDeniedDescription(denials) {
879
+ const named = denials.map(({ guardID, name }) => name ? `${guardID} (${name})` : guardID);
880
+ return `mutation denied by ${denials.length} guard(s): ${named.join(" ")}`;
881
+ }
874
882
  function uniqueDenials(denials) {
875
883
  const seen = /* @__PURE__ */ new Set();
876
884
  return denials.filter((denial) => seen.has(denial.guardID) ? !1 : (seen.add(denial.guardID), !0));
@@ -886,14 +894,14 @@ function mutationContexts(images) {
886
894
  return context === void 0 ? [] : [context];
887
895
  });
888
896
  }
889
- async function enforceMutationGuards(guard, contexts) {
897
+ async function enforceMutationGuards(guard, contexts, request) {
890
898
  if (guard === void 0) return;
891
899
  const denials = [];
892
900
  for (const context of contexts) {
893
901
  const denied = await guard(context);
894
902
  denied !== void 0 && denials.push(...denied);
895
903
  }
896
- if (denials.length > 0) throw new GuardDeniedError(denials);
904
+ if (denials.length > 0) throw new GuardDeniedError(denials, request);
897
905
  }
898
906
  function describeType(value) {
899
907
  return value === null ? "null" : Array.isArray(value) ? "an array" : `a ${typeof value}`;
@@ -1291,7 +1299,7 @@ function requireActive(release) {
1291
1299
  `Release "${release.name}" is "${release.state}", but only "active" releases accept version writes (create / replace / discard / unpublish). Unschedule or unarchive it back to "active" first, or target a different release.`
1292
1300
  );
1293
1301
  }
1294
- async function applyAction(store, action) {
1302
+ async function applyAction(store, action, request = ACTIONS_REQUEST) {
1295
1303
  switch (action.actionType) {
1296
1304
  case "sanity.action.release.create": {
1297
1305
  if (maybeRelease(store, action.releaseId) !== void 0)
@@ -1395,7 +1403,7 @@ async function applyAction(store, action) {
1395
1403
  return store.remove(release._id), { transactionId: cryptoRandomKey() };
1396
1404
  }
1397
1405
  case "sanity.action.document.version.create": {
1398
- if ("baseId" in action) return createVersionFromBase(store, action);
1406
+ if ("baseId" in action) return createVersionFromBase(store, action, request);
1399
1407
  const releaseId = action.releaseId ?? (action.document._id !== void 0 ? parseVersionId(action.document._id).releaseId : void 0);
1400
1408
  if (releaseId === void 0)
1401
1409
  throw fakeError(
@@ -1442,7 +1450,12 @@ async function applyAction(store, action) {
1442
1450
  `Cannot publish "${action.publishedId}": draft "${action.draftId}" not found. document.publish promotes an existing draft onto the published id \u2014 create the draft first (e.g. client.createOrReplace({ _id: "${action.draftId}", ... })).`
1443
1451
  );
1444
1452
  const published = store.get(action.publishedId);
1445
- requireRevisionMatch(action.draftId, draft._rev, action.ifDraftRevisionId), requireRevisionMatch(action.publishedId, published?._rev, action.ifPublishedRevisionId);
1453
+ requireRevisionMatch(request, action.draftId, draft._rev, action.ifDraftRevisionId), requireRevisionMatch(
1454
+ request,
1455
+ action.publishedId,
1456
+ published?._rev,
1457
+ action.ifPublishedRevisionId
1458
+ );
1446
1459
  const promoted = promote({ ...draft, _id: action.publishedId });
1447
1460
  return published !== void 0 && (promoted._createdAt = published._createdAt), store.put(promoted), store.remove(action.draftId), { transactionId: cryptoRandomKey() };
1448
1461
  }
@@ -1467,7 +1480,7 @@ function requireDraftOf(action) {
1467
1480
  `${action.actionType}: draftId "${action.draftId}" is not the draft of publishedId "${action.publishedId}" \u2014 expected draftId "drafts.${action.publishedId}".`
1468
1481
  );
1469
1482
  }
1470
- async function createVersionFromBase(store, action) {
1483
+ async function createVersionFromBase(store, action, request) {
1471
1484
  const { releaseId, publishedId } = parseVersionId(action.versionId);
1472
1485
  if (publishedId !== action.publishedId)
1473
1486
  throw fakeError(
@@ -1479,7 +1492,7 @@ async function createVersionFromBase(store, action) {
1479
1492
  throw fakeError(
1480
1493
  `Cannot create version "${action.versionId}": base document "${action.baseId}" not found. version.create with \`baseId\` copies an existing document; pass \`document\` instead when there is nothing to copy.`
1481
1494
  );
1482
- requireRevisionMatch(action.baseId, base._rev, action.ifBaseRevisionId);
1495
+ requireRevisionMatch(request, action.baseId, base._rev, action.ifBaseRevisionId);
1483
1496
  const existing = store.get(action.versionId), copy = {
1484
1497
  ...base,
1485
1498
  _id: action.versionId,
@@ -1488,14 +1501,33 @@ async function createVersionFromBase(store, action) {
1488
1501
  }, promoted = promote(copy);
1489
1502
  return store.put(promoted), { transactionId: cryptoRandomKey() };
1490
1503
  }
1491
- function requireRevisionMatch(documentId, actualRev, expectedRev) {
1504
+ const ACTIONS_REQUEST = { method: "POST", path: "/data/actions" };
1505
+ function requireRevisionMatch(request, documentId, actualRev, expectedRev) {
1492
1506
  if (!(expectedRev === void 0 || actualRev === expectedRev))
1493
- throw Object.assign(
1494
- fakeError(
1495
- `Revision precondition failed for "${documentId}": expected _rev "${expectedRev}" but the document is at ${actualRev === void 0 ? "no revision (missing)" : `"${actualRev}"`}.`
1496
- ),
1497
- { statusCode: 409 }
1498
- );
1507
+ throw actualRev === void 0 ? new PlatformHttpError({
1508
+ ...request,
1509
+ statusCode: 404,
1510
+ statusMessage: "Not Found",
1511
+ body: {
1512
+ error: {
1513
+ description: `The document with the ID ${JSON.stringify(documentId)} was not found`,
1514
+ id: documentId,
1515
+ type: "documentNotFoundError"
1516
+ }
1517
+ }
1518
+ }) : new PlatformHttpError({
1519
+ ...request,
1520
+ statusCode: 409,
1521
+ statusMessage: "Conflict",
1522
+ body: {
1523
+ error: {
1524
+ currentRevisionID: actualRev,
1525
+ description: `Document ${JSON.stringify(documentId)} has unexpected revision ID (${JSON.stringify(actualRev)}), expected ${JSON.stringify(expectedRev)}`,
1526
+ expectedRevisionID: expectedRev,
1527
+ type: "documentRevisionIDDoesNotMatchError"
1528
+ }
1529
+ }
1530
+ });
1499
1531
  }
1500
1532
  async function applyActions(store, actions, hooks) {
1501
1533
  const list = Array.isArray(actions) ? actions : [actions], snapshot = /* @__PURE__ */ new Map(), guardedIds = /* @__PURE__ */ new Set(), gatedIds = /* @__PURE__ */ new Set(), remember = (id) => {
@@ -1550,7 +1582,7 @@ async function applyActions(store, actions, hooks) {
1550
1582
  remember(a.draftId), remember(a.publishedId), guardedIds.add(a.draftId), guardedIds.add(a.publishedId), gatedIds.add(a.publishedId), gatedIds.add(a.draftId);
1551
1583
  break;
1552
1584
  }
1553
- last = await applyAction(store, a);
1585
+ last = await applyAction(store, a, hooks?.request);
1554
1586
  }
1555
1587
  for (const id of gatedIds) {
1556
1588
  const before = snapshot.get(id), after = store.get(id);
@@ -1977,13 +2009,13 @@ function makeHandle(handleArgs) {
1977
2009
  if (access !== void 0)
1978
2010
  return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
1979
2011
  };
1980
- let beforeWrite;
2012
+ let beforeWrite, writeRequest = DEFAULT_WRITE;
1981
2013
  const write = (run, request = lakeRequest("POST", "mutate")) => serializeWrite(backend, async () => {
1982
- admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
2014
+ admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc])), writeRequest = request;
1983
2015
  try {
1984
2016
  return await run();
1985
2017
  } finally {
1986
- beforeWrite = void 0;
2018
+ beforeWrite = void 0, writeRequest = DEFAULT_WRITE;
1987
2019
  }
1988
2020
  }), commitHistory = (transactionId) => {
1989
2021
  beforeWrite !== void 0 && history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() });
@@ -2050,13 +2082,15 @@ function makeHandle(handleArgs) {
2050
2082
  document,
2051
2083
  grants: access.grants,
2052
2084
  permission,
2053
- userId: actorId()
2085
+ userId: actorId(),
2086
+ request: writeRequest
2054
2087
  });
2055
2088
  }, guardGate = async (contexts) => {
2056
2089
  const identity = actorId();
2057
2090
  await enforceMutationGuards(
2058
2091
  mutationGuard,
2059
- contexts.map((context) => ({ ...context, identity }))
2092
+ contexts.map((context) => ({ ...context, identity })),
2093
+ writeRequest
2060
2094
  );
2061
2095
  }, guardOne = async (action, before, after) => {
2062
2096
  await guardGate([{ action, before, after }]);
@@ -2139,17 +2173,14 @@ function makeHandle(handleArgs) {
2139
2173
  txnOptions?.returnFirst ?? !1
2140
2174
  );
2141
2175
  }, runAction = async (actions) => {
2142
- const request = {
2143
- method: "POST",
2144
- path: `${capabilities.dataBase(target.id)}/actions`
2145
- };
2176
+ const request = lakeRequest("POST", "actions");
2146
2177
  if (refuseRevoked(request), capabilities.actions !== "served") throw capabilities.actions(request);
2147
2178
  return write(async () => {
2148
2179
  for (const action of Array.isArray(actions) ? actions : [actions]) {
2149
2180
  const refused = capabilities.refusedActions[action.actionType];
2150
2181
  if (refused !== void 0) throw refused(request);
2151
2182
  }
2152
- const result = await applyActions(store, actions, { gate, guard: guardGate });
2183
+ const result = await applyActions(store, actions, { gate, guard: guardGate, request });
2153
2184
  return commitHistory(result.transactionId), result;
2154
2185
  }, request);
2155
2186
  }, accessVisibleDocs = async () => {