@powerhousedao/shared 6.2.3-dev.85 → 6.2.3-dev.87

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.
Files changed (69) hide show
  1. package/dist/clis/args/{help-CmnOv3z3.d.mts → help-Cgh3krcq.d.mts} +14 -2
  2. package/dist/clis/args/help-Cgh3krcq.d.mts.map +1 -0
  3. package/dist/clis/args/{help-Cb66IK-J.mjs → help-DnOa5Gr-.mjs} +9 -1
  4. package/dist/clis/args/help-DnOa5Gr-.mjs.map +1 -0
  5. package/dist/clis/args/help.d.mts +1 -1
  6. package/dist/clis/args/help.mjs +2 -1
  7. package/dist/clis/args/index.d.mts +3 -2
  8. package/dist/clis/args/index.mjs +3 -2
  9. package/dist/clis/args/keyframes.d.mts +25 -0
  10. package/dist/clis/args/keyframes.d.mts.map +1 -0
  11. package/dist/clis/args/keyframes.mjs +42 -0
  12. package/dist/clis/args/keyframes.mjs.map +1 -0
  13. package/dist/clis/build-pieces.d.mts +1 -1
  14. package/dist/clis/command-names.d.mts +1 -1
  15. package/dist/clis/command-names.d.mts.map +1 -1
  16. package/dist/clis/command-names.mjs +1 -0
  17. package/dist/clis/command-names.mjs.map +1 -1
  18. package/dist/clis/constants.d.mts +1 -1
  19. package/dist/clis/index.d.mts +126 -3
  20. package/dist/clis/index.d.mts.map +1 -1
  21. package/dist/clis/index.mjs +92 -3
  22. package/dist/clis/index.mjs.map +1 -1
  23. package/dist/clis/{types-0G3o7wZE.d.mts → types-ByIjNbGg.d.mts} +45 -2
  24. package/dist/clis/{types-0G3o7wZE.d.mts.map → types-ByIjNbGg.d.mts.map} +1 -1
  25. package/dist/connect/config-loader.d.ts +1 -1
  26. package/dist/connect/connect-config-schema.d.ts +2 -2
  27. package/dist/connect/connect-config-schema.js +16 -3
  28. package/dist/connect/connect-config-schema.js.map +1 -1
  29. package/dist/connect/index.d.ts +3 -3
  30. package/dist/connect/index.js +2 -2
  31. package/dist/{connect-config-schema-c39dvEne.d.ts → connect-config-schema-LzQbfZHm.d.ts} +37 -3
  32. package/dist/{connect-config-schema-c39dvEne.d.ts.map → connect-config-schema-LzQbfZHm.d.ts.map} +1 -1
  33. package/dist/document-drive/index.d.ts +3 -3
  34. package/dist/document-drive/index.js +1 -1
  35. package/dist/document-model/dispatch.d.ts +1 -1
  36. package/dist/document-model/errors.d.ts +2 -2
  37. package/dist/document-model/errors.js +49 -1
  38. package/dist/document-model/errors.js.map +1 -1
  39. package/dist/document-model/index.d.ts +2 -3
  40. package/dist/document-model/index.js +5 -5
  41. package/dist/document-model/utils.d.ts +2 -2
  42. package/dist/document-model/utils.js +2 -2
  43. package/dist/{document-model-CMyP_XZ8.js → document-model-B98EymhI.js} +927 -402
  44. package/dist/document-model-B98EymhI.js.map +1 -0
  45. package/dist/{index-CR7EJfyR.d.ts → index-59YGevDz.d.ts} +2 -2
  46. package/dist/{index-CR7EJfyR.d.ts.map → index-59YGevDz.d.ts.map} +1 -1
  47. package/dist/index.d.ts +4 -4
  48. package/dist/processors/index.d.ts +2 -2
  49. package/dist/processors/index.js +1 -1
  50. package/dist/processors/testing.d.ts +1 -1
  51. package/dist/{purge-YMJM0Vl7.js → purge-BOqSpe4O.js} +224 -6
  52. package/dist/purge-BOqSpe4O.js.map +1 -0
  53. package/dist/registry/index.d.ts +2 -2
  54. package/dist/registry/manifest-slim.d.ts +2 -2
  55. package/dist/{types-DR4mZKAj.d.ts → types-D1ToC1mB.d.ts} +651 -126
  56. package/dist/types-D1ToC1mB.d.ts.map +1 -0
  57. package/dist/{types-DPBZvxkk.d.ts → types-DRj0sF2w.d.ts} +2 -2
  58. package/dist/{types-DPBZvxkk.d.ts.map → types-DRj0sF2w.d.ts.map} +1 -1
  59. package/dist/{utils-CSF716ux.js → utils-DiV32YIj.js} +45 -2
  60. package/dist/utils-DiV32YIj.js.map +1 -0
  61. package/package.json +1 -1
  62. package/dist/clis/args/help-Cb66IK-J.mjs.map +0 -1
  63. package/dist/clis/args/help-CmnOv3z3.d.mts.map +0 -1
  64. package/dist/document-model-CMyP_XZ8.js.map +0 -1
  65. package/dist/purge-YMJM0Vl7.js.map +0 -1
  66. package/dist/types-DR4mZKAj.d.ts.map +0 -1
  67. package/dist/utils-BrKxCmKx.d.ts +0 -18
  68. package/dist/utils-BrKxCmKx.d.ts.map +0 -1
  69. package/dist/utils-CSF716ux.js.map +0 -1
@@ -1,13 +1,13 @@
1
- import { a as base58Decode, c as buildOperationSignatureParams, d as hashBrowser, f as hex2ab, i as ab2hex, l as bytesToBase64Url, n as generateId, o as base64UrlToBytes, s as buildOperationSignatureMessage, t as deriveOperationId } from "./utils-CSF716ux.js";
2
- import { O as canonicalJson, n as isPurgeMarker } from "./purge-YMJM0Vl7.js";
3
- import { AuthActionNotAllowedError, AuthAlreadyInitializedError, AuthInitializerNotCreatorError, AuthPolicyNotPreservedError, DowngradeNotSupportedError, FileSystemError, GrantNotFoundError, HashMismatchError, InvalidActionInputError, InvalidActionInputZodError, InvalidAuthVersionError, UnsupportedDocumentModelVersionError } from "./document-model/errors.js";
1
+ import { _ as buildOperationSignatureParams, b as hashBrowser, g as buildOperationSignatureMessage, h as base64UrlToBytes, m as base58Decode, n as generateId, p as ab2hex, t as deriveOperationId, v as bytesToBase64Url, x as hex2ab } from "./utils-DiV32YIj.js";
2
+ import { A as assertNever, B as isBaseReducerVersion, C as BASE_REDUCER_VERSIONS, E as RULE_EXEMPT_SCOPES, F as capabilitiesOf, H as needsTaggedModel, J as usesRetractionRule, L as createdCapabilities, M as baseReducerVersion, R as derivesByRule, U as optionalBaseReducerCapabilities, V as modelRunsBaseReducer, X as tagStateReducer, Y as stateReducerOf, j as baseReducerCapabilities, k as appliesRewind, n as isPurgeMarker, rt as canonicalJson, s as FLAGLESS_BASE_REDUCER_VERSION } from "./purge-BOqSpe4O.js";
3
+ import { AuthActionNotAllowedError, AuthAlreadyInitializedError, AuthInitializerNotCreatorError, AuthPolicyNotPreservedError, DowngradeNotSupportedError, FileSystemError, GrantNotFoundError, HashMismatchError, InvalidActionInputError, InvalidActionInputZodError, InvalidAuthVersionError, MissingStateReducerError, NoUndoRedoTargetError, SubmittedUndoRefusedError, UnsupportedDocumentModelVersionError } from "./document-model/errors.js";
4
4
  import { generateActionId, nextAuthTimestamp } from "./document-model/action-id.js";
5
5
  import { normalizeDocumentModelVersion } from "./document-model/version.js";
6
6
  import { ZodError, z } from "zod";
7
7
  import { stringify } from "safe-stable-stringify";
8
8
  import { sha256 } from "@noble/hashes/sha2.js";
9
- import { strFromU8, strToU8, unzip, zip } from "fflate";
10
9
  import { castDraft, create, isDraft, original, unsafe } from "mutative";
10
+ import { strFromU8, strToU8, unzip, zip } from "fflate";
11
11
  import { constantCase, pascalCase } from "change-case";
12
12
  //#region document-model/signatures.ts
13
13
  /**
@@ -167,6 +167,9 @@ function SetPreferredEditorActionSchema() {
167
167
  function UndoActionInputSchema() {
168
168
  return z.object({ count: z.number() });
169
169
  }
170
+ function RetractActionInputSchema() {
171
+ return z.object({ target: z.string() });
172
+ }
170
173
  function UndoActionSchema() {
171
174
  return z.object({
172
175
  id: z.string(),
@@ -682,6 +685,12 @@ const undo = (count = 1, scope = "global") => createAction("UNDO", { count }, vo
682
685
  const redo = (count = 1, scope = "global") => createAction("REDO", { count }, void 0, RedoActionInputSchema, scope);
683
686
  const noop = (scope = "global") => createAction("NOOP", {}, void 0, void 0, scope);
684
687
  /**
688
+ * Retracts the action with id `target` on base-reducer 3.
689
+ *
690
+ * @category Actions
691
+ */
692
+ const retract = (target, scope = "global") => createAction("RETRACT", { target }, void 0, RetractActionInputSchema, scope);
693
+ /**
685
694
  * Helper function to be used by action creators.
686
695
  *
687
696
  * @remarks
@@ -2416,6 +2425,34 @@ function mentionedGroupIds(action) {
2416
2425
  return ids;
2417
2426
  }
2418
2427
  //#endregion
2428
+ //#region document-model/create-base-reducer.ts
2429
+ const warnedUntaggedTypes = /* @__PURE__ */ new Set();
2430
+ /**
2431
+ * Steps a selected base-reducer down to the highest version the model runs.
2432
+ * An unregistered type cannot be checked, so it takes the highest version
2433
+ * that needs no tagged reducer.
2434
+ */
2435
+ function fitCreateBaseReducer(selected, documentType, modules, logger) {
2436
+ const version = selected["base-reducer"];
2437
+ if (documentType === void 0 || !isBaseReducerVersion(version)) return selected;
2438
+ const runs = modelRunsBaseReducer(capabilitiesOf(version), documentType, modules);
2439
+ if (runs === true || runs === void 0 && !needsTag(version)) return selected;
2440
+ const fitted = BASE_REDUCER_VERSIONS.filter((lower) => lower < version && !needsTag(lower)).at(-1);
2441
+ if (fitted === void 0) return selected;
2442
+ if (runs === void 0) logger.debug(`@documentType is not registered; its new documents take base-reducer ${fitted}`, documentType);
2443
+ else if (!warnedUntaggedTypes.has(documentType)) {
2444
+ warnedUntaggedTypes.add(documentType);
2445
+ logger.warn(`@documentType has a reducer not built by createReducer; its new documents take base-reducer ${fitted}`, documentType);
2446
+ }
2447
+ return {
2448
+ ...selected,
2449
+ "base-reducer": fitted
2450
+ };
2451
+ }
2452
+ function needsTag(version) {
2453
+ return needsTaggedModel(capabilitiesOf(version));
2454
+ }
2455
+ //#endregion
2419
2456
  //#region document-model/signature-policy.ts
2420
2457
  /** The `protocolVersions` key that fixes a document's signature requirement. */
2421
2458
  const SIGNATURE_PROTOCOL = "signature";
@@ -2432,10 +2469,10 @@ function signaturePolicyOf(source) {
2432
2469
  const version = (source && "protocolVersions" in source ? source.protocolVersions : source)?.[SIGNATURE_PROTOCOL];
2433
2470
  return typeof version === "number" && version >= 2 ? "v2-required" : "legacy";
2434
2471
  }
2435
- /** `protocolVersions` for a new v2-required document. */
2472
+ /** `protocolVersions` for a new v2-required document, over `base`. */
2436
2473
  function v2RequiredProtocolVersions(base = {}) {
2437
2474
  return {
2438
- "base-reducer": 2,
2475
+ "base-reducer": FLAGLESS_BASE_REDUCER_VERSION,
2439
2476
  ...base,
2440
2477
  [SIGNATURE_PROTOCOL]: 2
2441
2478
  };
@@ -2454,7 +2491,7 @@ function protocolVersionsFor(policy, base = {}) {
2454
2491
  if (policy === "v2-required") return v2RequiredProtocolVersions(base);
2455
2492
  const { [SIGNATURE_PROTOCOL]: _signature, ...rest } = base;
2456
2493
  return {
2457
- "base-reducer": 2,
2494
+ "base-reducer": FLAGLESS_BASE_REDUCER_VERSION,
2458
2495
  ...rest
2459
2496
  };
2460
2497
  }
@@ -2808,16 +2845,7 @@ function assertIsDocumentModelDocument(document) {
2808
2845
  DocumentModelSchema.parse(document);
2809
2846
  }
2810
2847
  //#endregion
2811
- //#region document-model/documents.ts
2812
- function isNoopOperation(op) {
2813
- return op.type === "NOOP" && op.skip !== void 0 && op.skip > 0 && op.hash !== void 0;
2814
- }
2815
- function isUndoRedo(action) {
2816
- return ["UNDO", "REDO"].includes(action.type);
2817
- }
2818
- function isUndo(action) {
2819
- return action.type === "UNDO";
2820
- }
2848
+ //#region document-model/operation-order.ts
2821
2849
  function isDocumentAction(action) {
2822
2850
  return [
2823
2851
  "SET_NAME",
@@ -2826,172 +2854,614 @@ function isDocumentAction(action) {
2826
2854
  "REDO"
2827
2855
  ].includes(action.type);
2828
2856
  }
2829
- /**
2830
- * The document-scope operations a reactor mints on `create`, so a standalone
2831
- * document carries its initial state when exported outside a reactor.
2832
- */
2833
- function createDocumentScopeOperations(header, state) {
2834
- const createInput = {
2835
- model: header.documentType,
2836
- version: 0,
2837
- documentId: header.id,
2838
- signing: {
2839
- signature: header.id,
2840
- publicKey: header.sig.publicKey,
2841
- nonce: header.sig.nonce,
2842
- createdAtUtcIso: header.createdAtUtcIso,
2843
- documentType: header.documentType
2844
- },
2845
- slug: header.slug,
2846
- name: header.name,
2847
- branch: header.branch,
2848
- meta: header.meta,
2849
- protocolVersions: header.protocolVersions ?? { "base-reducer": 2 }
2850
- };
2851
- const upgradeInput = {
2852
- model: header.documentType,
2853
- fromVersion: 0,
2854
- toVersion: state.document.version,
2855
- documentId: header.id,
2856
- initialState: state
2857
- };
2858
- return [{
2859
- id: generateActionId(),
2860
- type: "CREATE_DOCUMENT",
2861
- scope: "document",
2862
- timestampUtcMs: header.createdAtUtcIso,
2863
- input: createInput
2864
- }, {
2865
- id: generateActionId(),
2866
- type: "UPGRADE_DOCUMENT",
2867
- scope: "document",
2868
- timestampUtcMs: header.createdAtUtcIso,
2869
- input: upgradeInput
2870
- }].map((action, index) => ({
2871
- ...action,
2872
- action,
2873
- id: deriveOperationId(header.id, "document", header.branch, action.id),
2874
- hash: "",
2875
- error: void 0,
2876
- index,
2877
- skip: 0
2878
- }));
2857
+ function garbageCollect(sortedOperations) {
2858
+ const result = [];
2859
+ let i = sortedOperations.length - 1;
2860
+ while (i > -1) {
2861
+ result.unshift(sortedOperations[i]);
2862
+ const skipUntil = (sortedOperations[i]?.index || 0) - (sortedOperations[i]?.skip || 0) - 1;
2863
+ let j = i - 1;
2864
+ while (j > -1 && (sortedOperations[j]?.index || 0) > skipUntil) j--;
2865
+ i = j;
2866
+ }
2867
+ return result;
2868
+ }
2869
+ function sortOperations(operations) {
2870
+ return operations.slice().sort((a, b) => a.skip - b.skip).sort((a, b) => a.index - b.index);
2879
2871
  }
2872
+ function nextSkipNumber(sortedOperations) {
2873
+ if (sortedOperations.length < 1) return -1;
2874
+ const cleanedOperations = garbageCollect(sortedOperations);
2875
+ let nextSkip = (cleanedOperations[cleanedOperations.length - 1]?.skip || 0) + 1;
2876
+ if (cleanedOperations.length > 1) nextSkip += cleanedOperations[cleanedOperations.length - 2]?.skip || 0;
2877
+ return (cleanedOperations[cleanedOperations.length - 1]?.index || -1) < nextSkip ? -1 : nextSkip;
2878
+ }
2879
+ //#endregion
2880
+ //#region document-model/operations.ts
2880
2881
  /**
2881
- * Creates a new document. When `documentType` is given the header is stamped
2882
- * with it and the document-scope operations are seeded. Without
2883
- * `protocolVersions` the document is v2-required and takes a derived id; with
2884
- * them it is v2-required only if they say so (see {@link protocolVersionsFor}).
2882
+ * The NOOP base-reducers 1 and 2 synthesize for an undo. It takes the wall
2883
+ * clock in every scope, never the auth clock.
2885
2884
  */
2886
- function baseCreateDocument(createState, initialState, documentType = "", protocolVersions) {
2887
- const state = createState(initialState);
2888
- const header = createPresignedHeader(void 0, documentType, protocolVersions === void 0 ? protocolVersionsFor("v2-required") : {
2889
- "base-reducer": 2,
2890
- ...protocolVersions
2891
- });
2892
- header.revision = withScopeRevisions(header.revision, state);
2885
+ function undoMarker(scope) {
2893
2886
  return {
2894
- header,
2895
- state,
2896
- initialState: state,
2897
- operations: documentType ? {
2898
- global: [],
2899
- local: [],
2900
- document: createDocumentScopeOperations(header, state)
2901
- } : {
2902
- global: [],
2903
- local: []
2904
- },
2905
- clipboard: []
2887
+ id: generateActionId(),
2888
+ timestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),
2889
+ type: "NOOP",
2890
+ input: {},
2891
+ scope
2906
2892
  };
2907
2893
  }
2908
- /**
2909
- * `document`, not yet created, under a fresh header for `policy`. A legacy
2910
- * header takes `id` when given; a v2-required one ignores `id` and derives its
2911
- * own, so a caller that needs a fixed id must ask for legacy.
2912
- * `protocolVersions` are merged over the document's. Name, slug, branch and
2913
- * meta carry over. A document already under `policy` is returned as is unless
2914
- * a legacy `id` or `protocolVersions` are given.
2915
- */
2916
- function withSignaturePolicy(document, policy, options = {}) {
2917
- const id = policy === "legacy" ? options.id : void 0;
2918
- if (id === void 0 && options.protocolVersions === void 0 && signaturePolicyOf(document.header) === policy) return document;
2919
- const source = document.header;
2920
- const header = createPresignedHeader(id, source.documentType, protocolVersionsFor(policy, {
2921
- ...source.protocolVersions,
2922
- ...options.protocolVersions
2923
- }));
2924
- header.name = source.name;
2925
- header.slug = source.slug;
2926
- header.branch = source.branch;
2927
- header.meta = source.meta;
2928
- const operations = document.operations.document ? {
2929
- ...document.operations,
2930
- document: createDocumentScopeOperations(header, document.state)
2931
- } : document.operations;
2894
+ function setNameOperation(document, input) {
2932
2895
  return {
2933
2896
  ...document,
2934
- header,
2935
- operations
2897
+ header: {
2898
+ ...document.header,
2899
+ name: input.name
2900
+ }
2936
2901
  };
2937
2902
  }
2938
- function hashDocumentStateForScope(document, scope = "global") {
2939
- const stateString = stringify(document.state[scope] || "");
2940
- return hashBrowser(stateString);
2941
- }
2942
- function readOnly(value) {
2943
- return Object.freeze(value);
2944
- }
2945
- /**
2946
- * Maps skipped operations in an array of operations.
2947
- * Skipped operations are operations that are ignored during processing.
2948
- * @param operations - The array of operations to map.
2949
- * @param skippedHeadOperations - The number of operations to skip at the head of the array of operations.
2950
- * @returns An array of mapped operations with ignore flag indicating if the operation is skipped.
2951
- * @throws Error if the operation index is invalid and there are missing operations.
2952
- */
2953
- function mapSkippedOperations(operations, skippedHeadOperations) {
2954
- const ops = [...operations];
2955
- let skipped = skippedHeadOperations || 0;
2956
- let latestOpIndex = ops.length > 0 ? ops[ops.length - 1].index : 0;
2957
- const scopeOpsWithIgnore = [];
2958
- for (const operation of ops.reverse()) {
2959
- if (skipped > 0) {
2960
- const operationsDiff = latestOpIndex - operation.index;
2961
- skipped -= operationsDiff;
2903
+ function setPreferredEditorOperation(document, input) {
2904
+ const existingMeta = document.header.meta ?? {};
2905
+ if (input.preferredEditor) return {
2906
+ ...document,
2907
+ header: {
2908
+ ...document.header,
2909
+ meta: {
2910
+ ...existingMeta,
2911
+ preferredEditor: input.preferredEditor
2912
+ }
2962
2913
  }
2963
- if (skipped < 0) throw new Error("Invalid operation index, missing operations");
2964
- const mappedOp = {
2965
- ignore: skipped > 0,
2966
- operation
2967
- };
2968
- const operationSkip = operation.skip > 0 ? operation.skip + 1 : 0;
2969
- if (operationSkip > 0 && operationSkip > skipped) {
2970
- const skipDiff = operationSkip - skipped;
2971
- skipped = skipped + skipDiff;
2914
+ };
2915
+ const { preferredEditor: _removed, ...rest } = existingMeta;
2916
+ return {
2917
+ ...document,
2918
+ header: {
2919
+ ...document.header,
2920
+ meta: rest
2972
2921
  }
2973
- latestOpIndex = operation.index;
2974
- scopeOpsWithIgnore.push(mappedOp);
2975
- }
2976
- return scopeOpsWithIgnore.reverse();
2922
+ };
2923
+ }
2924
+ function undoOperation(document, action, skip) {
2925
+ const { scope } = action;
2926
+ return create({
2927
+ document,
2928
+ action,
2929
+ skip,
2930
+ reuseLastOperationIndex: false
2931
+ }, (draft) => {
2932
+ const sortedOperations = sortOperations([...document.operations[scope]]);
2933
+ draft.action = undoMarker(scope);
2934
+ const lastOperation = sortedOperations.at(-1);
2935
+ let nextIndex = lastOperation?.index ?? -1;
2936
+ const isNewNoop = lastOperation?.action.type !== "NOOP";
2937
+ if (isNewNoop) nextIndex = nextIndex + 1;
2938
+ else draft.reuseLastOperationIndex = true;
2939
+ draft.skip = nextSkipNumber(isNewNoop ? [...sortedOperations, {
2940
+ index: nextIndex,
2941
+ skip: 0
2942
+ }] : sortedOperations);
2943
+ if (lastOperation && draft.skip > lastOperation.skip + 1) draft.skip = draft.skip + 1;
2944
+ if (draft.skip < 0) throw new Error(`Cannot undo: you can't undo more operations than the ones in the scope history`);
2945
+ });
2977
2946
  }
2978
2947
  /**
2979
- * V2 version of mapSkippedOperations for protocol version 2+.
2980
- * In V2, all NOOPs have skip=1 and consecutive NOOPs form chains.
2981
- * N consecutive NOOPs at any point skip N preceding content operations.
2982
- *
2983
- * Algorithm: Process from end to start
2984
- * - When hitting a NOOP: increment chain length, mark as ignored
2985
- * - When hitting a non-NOOP:
2986
- * - If chain > 0: decrement chain, mark as ignored (this op was undone)
2987
- * - If chain == 0: mark as not ignored (apply this op)
2948
+ * V2 of undoOperation for protocol version 2+.
2949
+ * Key differences from undoOperation:
2950
+ * - Never reuses operation index (always increments)
2951
+ * - Always sets skip=1 (consecutive NOOPs are handled during rebuild/GC)
2952
+ * - No complex skip calculation - simpler model where each UNDO is independent
2988
2953
  */
2989
- function mapSkippedOperationsV2(operations) {
2990
- const ops = [...operations];
2991
- const result = [];
2992
- let noopChainLength = 0;
2993
- for (let i = ops.length - 1; i >= 0; i--) {
2994
- const operation = ops[i];
2954
+ function undoOperationV2(document, action, skip) {
2955
+ const { scope } = action;
2956
+ return create({
2957
+ document,
2958
+ action,
2959
+ skip,
2960
+ reuseLastOperationIndex: false
2961
+ }, (draft) => {
2962
+ const sortedOperations = sortOperations([...document.operations[scope] || []]);
2963
+ const nonNoopOps = sortedOperations.filter((op) => op.action.type !== "NOOP");
2964
+ let noopChainLength = 0;
2965
+ for (let i = sortedOperations.length - 1; i >= 0; i--) if (sortedOperations[i].action.type === "NOOP") noopChainLength++;
2966
+ else break;
2967
+ if (nonNoopOps.length <= noopChainLength) throw new Error(`Cannot undo: no more operations to undo in scope history`);
2968
+ draft.action = undoMarker(scope);
2969
+ draft.skip = 1;
2970
+ });
2971
+ }
2972
+ function redoOperation(document, action, skip) {
2973
+ const { scope, input } = action;
2974
+ return create({
2975
+ document,
2976
+ action,
2977
+ skip,
2978
+ reuseLastOperationIndex: false
2979
+ }, (draft) => {
2980
+ if (draft.skip > 0) throw new Error(`Cannot redo: skip value from reducer cannot be used with REDO action`);
2981
+ const count = typeof input === "object" && input !== null && "count" in input ? input.count : input;
2982
+ if (typeof count !== "number" || count > 1) throw new Error(`Cannot redo: you can only redo one operation at a time`);
2983
+ if (typeof count !== "number" || count < 1) throw new Error(`Invalid REDO action: invalid redo input value`);
2984
+ if (draft.document.clipboard.length < 1) throw new Error(`Cannot redo: no operations in the clipboard`);
2985
+ const operationIndex = draft.document.clipboard.findLastIndex((op) => op.action.scope === scope);
2986
+ if (operationIndex < 0) throw new Error(`Cannot redo: no operations in clipboard for scope "${scope}"`);
2987
+ const operation = draft.document.clipboard.splice(operationIndex, 1)[0];
2988
+ draft.action = castDraft({
2989
+ type: operation.action.type,
2990
+ scope: operation.action.scope,
2991
+ input: operation.action.input
2992
+ });
2993
+ });
2994
+ }
2995
+ /**
2996
+ * Reads an operation's outcome. A denial takes precedence over a reducer
2997
+ * error, since a denied operation never reaches its reducer.
2998
+ */
2999
+ function operationOutcome(operation) {
3000
+ if (operation.deniedReason !== void 0) return {
3001
+ kind: "denied",
3002
+ reason: operation.deniedReason
3003
+ };
3004
+ if (operation.error !== void 0) return {
3005
+ kind: "reducer-error",
3006
+ message: operation.error,
3007
+ ...operation.errorName !== void 0 && { name: operation.errorName },
3008
+ ...operation.errorCode !== void 0 && { code: operation.errorCode }
3009
+ };
3010
+ return { kind: "applied" };
3011
+ }
3012
+ //#endregion
3013
+ //#region document-model/base-action-reducer.ts
3014
+ /**
3015
+ * Applies a base document action (SET_NAME, SET_PREFERRED_EDITOR) to the
3016
+ * document. UNDO and REDO apply nothing here.
3017
+ */
3018
+ function baseActionReducer(document, action) {
3019
+ const parsedAction = DocumentActionSchema().parse(action);
3020
+ switch (parsedAction.type) {
3021
+ case "SET_NAME": return setNameOperation(document, parsedAction.input);
3022
+ case "SET_PREFERRED_EDITOR": return setPreferredEditorOperation(document, parsedAction.input);
3023
+ default: return document;
3024
+ }
3025
+ }
3026
+ //#endregion
3027
+ //#region document-model/retraction.ts
3028
+ /** Base-reducer 3: the rows left once each reshuffle rewind removes what it covers. */
3029
+ function positionalOperations(stream) {
3030
+ return garbageCollect(sortOperations([...stream]));
3031
+ }
3032
+ /** A stored row that changes which earlier rows apply: a RETRACT, or one a retraction names. */
3033
+ function retractionRewrites(row, named) {
3034
+ return row.action.type === "RETRACT" || named(row.action.id);
3035
+ }
3036
+ /** Under the rule, appending `row` re-derives its scope from every row. */
3037
+ function rewritesScope(row, named) {
3038
+ return row.skip > 0 || retractionRewrites(row, named);
3039
+ }
3040
+ function retractionTarget(operation) {
3041
+ return targetOf(operation.action);
3042
+ }
3043
+ /** The action ids `action` names; stores index exactly these for findReferencing. */
3044
+ function actionReferences(action) {
3045
+ const target = targetOf(action);
3046
+ return target === void 0 ? [] : [target];
3047
+ }
3048
+ function targetOf(action) {
3049
+ if (action.type !== "RETRACT") return void 0;
3050
+ const input = action.input;
3051
+ return typeof input?.target === "string" ? input.target : void 0;
3052
+ }
3053
+ /** Ids a live retraction names; a retraction is live iff no live retraction names it. */
3054
+ function retractedActionIds(rows) {
3055
+ const present = /* @__PURE__ */ new Map();
3056
+ const duplicated = /* @__PURE__ */ new Set();
3057
+ for (const operation of rows) {
3058
+ const id = operation.action.id;
3059
+ if (present.has(id)) duplicated.add(id);
3060
+ present.set(id, operation);
3061
+ }
3062
+ const targetOf = /* @__PURE__ */ new Map();
3063
+ for (const operation of rows) {
3064
+ if (isDenied(operation) || duplicated.has(operation.action.id)) continue;
3065
+ const target = retractionTarget(operation);
3066
+ if (target !== void 0 && target !== operation.action.id && present.has(target) && !isDocumentAction(present.get(target).action)) targetOf.set(operation.action.id, target);
3067
+ }
3068
+ for (const id of onCycles(targetOf)) targetOf.delete(id);
3069
+ const pending = /* @__PURE__ */ new Map();
3070
+ for (const target of targetOf.values()) pending.set(target, (pending.get(target) ?? 0) + 1);
3071
+ const retracted = /* @__PURE__ */ new Set();
3072
+ const ready = [...present.keys()].filter((id) => !pending.has(id));
3073
+ while (ready.length > 0) {
3074
+ const id = ready.pop();
3075
+ const target = targetOf.get(id);
3076
+ if (target === void 0) continue;
3077
+ if (!retracted.has(id)) retracted.add(target);
3078
+ const left = pending.get(target) - 1;
3079
+ pending.set(target, left);
3080
+ if (left === 0) ready.push(target);
3081
+ }
3082
+ return retracted;
3083
+ }
3084
+ /** The ids on a cycle of `targetOf`, where each id has at most one target. */
3085
+ function onCycles(targetOf) {
3086
+ const onCycle = /* @__PURE__ */ new Set();
3087
+ const settled = /* @__PURE__ */ new Set();
3088
+ for (const start of targetOf.keys()) {
3089
+ if (settled.has(start)) continue;
3090
+ const path = [];
3091
+ const onPath = /* @__PURE__ */ new Set();
3092
+ let id = start;
3093
+ while (id !== void 0 && !settled.has(id) && !onPath.has(id)) {
3094
+ path.push(id);
3095
+ onPath.add(id);
3096
+ id = targetOf.get(id);
3097
+ }
3098
+ if (id !== void 0 && onPath.has(id)) for (let i = path.indexOf(id); i < path.length; i++) onCycle.add(path[i]);
3099
+ for (const visited of path) settled.add(visited);
3100
+ }
3101
+ return onCycle;
3102
+ }
3103
+ /** The rows whose actions apply to state, in stream order. */
3104
+ function appliedOperations(stream) {
3105
+ const rows = positionalOperations(stream);
3106
+ const retracted = retractedActionIds(rows);
3107
+ return rows.filter((operation) => !retracted.has(operation.action.id) && operation.action.type !== "RETRACT" && !isDenied(operation));
3108
+ }
3109
+ /** Applies one row's action to the scope state; throws when the action throws. */
3110
+ function reduceOne(document, operation, reducerFor) {
3111
+ assertDerivedScope(operation.action.scope);
3112
+ return applyRow(document, operation, rowReducer(operation, reducerFor));
3113
+ }
3114
+ /**
3115
+ * Base-reducer 3 derivation of one scope, advanced a run of rows at a time.
3116
+ * Which rows apply is decided once, over the whole stream; `applied` collects
3117
+ * the ids whose action did not throw.
3118
+ */
3119
+ function scopeDeriver(stream, onThrow) {
3120
+ const live = new Set(appliedOperations(stream));
3121
+ const applied = /* @__PURE__ */ new Set();
3122
+ return {
3123
+ applied,
3124
+ advance(document, rows, reducerFor) {
3125
+ let next = document;
3126
+ for (const operation of rows) {
3127
+ if (!live.has(operation)) continue;
3128
+ assertDerivedScope(operation.action.scope);
3129
+ const reducer = rowReducer(operation, reducerFor);
3130
+ try {
3131
+ next = applyRow(next, operation, reducer);
3132
+ applied.add(operation.action.id);
3133
+ } catch (error) {
3134
+ onThrow?.(operation, error);
3135
+ }
3136
+ }
3137
+ return next;
3138
+ }
3139
+ };
3140
+ }
3141
+ function resetScope(document, scope) {
3142
+ assertDerivedScope(scope);
3143
+ const initial = document.initialState[scope];
3144
+ return {
3145
+ ...document,
3146
+ state: {
3147
+ ...document.state,
3148
+ [scope]: initial
3149
+ }
3150
+ };
3151
+ }
3152
+ /** Derives `scope` from initial state; `applied` holds the ids whose action did not throw. */
3153
+ function deriveScope(document, stream, reducerFor, scope = stream.at(0)?.action.scope, onThrow) {
3154
+ if (scope === void 0) return {
3155
+ document,
3156
+ applied: /* @__PURE__ */ new Set()
3157
+ };
3158
+ const deriver = scopeDeriver(stream, onThrow);
3159
+ return {
3160
+ document: deriver.advance(resetScope(document, scope), positionalOperations(stream), reducerFor),
3161
+ applied: deriver.applied
3162
+ };
3163
+ }
3164
+ /**
3165
+ * Derives `scope` from initial state across model versions: each row applies
3166
+ * with its own version's reducer, and each upgrade applies where its boundary
3167
+ * falls. Every row is visited, applied or not, so an upgrade a skipped row
3168
+ * crosses still applies there.
3169
+ */
3170
+ function deriveScopeVersioned(document, stream, versions, scope = stream.at(0)?.action.scope, onThrow) {
3171
+ if (scope === void 0) return {
3172
+ document,
3173
+ applied: /* @__PURE__ */ new Set()
3174
+ };
3175
+ const deriver = scopeDeriver(stream, onThrow);
3176
+ let next = resetScope(document, scope);
3177
+ for (const operation of sortOperations([...stream])) {
3178
+ const version = versions.versionOf(operation);
3179
+ next = versions.upgradeTo(next, version);
3180
+ next = deriver.advance(next, [operation], () => versions.reducerOf(version));
3181
+ }
3182
+ return {
3183
+ document: next,
3184
+ applied: deriver.applied
3185
+ };
3186
+ }
3187
+ function assertDerivedScope(scope) {
3188
+ if (RULE_EXEMPT_SCOPES.has(scope)) throw new Error(`Base-reducer 3 does not derive the ${scope} scope`);
3189
+ }
3190
+ function rowReducer(operation, reducerFor) {
3191
+ const action = operation.action;
3192
+ if (action.type === "NOOP" || action.type === "RETRACT" || isDocumentAction(action)) return;
3193
+ return reducerFor(operation);
3194
+ }
3195
+ function applyRow(document, operation, reducer) {
3196
+ const action = operation.action;
3197
+ if (isDocumentAction(action)) return baseActionReducer(document, action);
3198
+ if (reducer === void 0) return document;
3199
+ return create(document, (draft) => {
3200
+ const next = reducer(draft.state, action);
3201
+ if (next) unsafe(() => {
3202
+ draft.state = castDraft(next);
3203
+ });
3204
+ });
3205
+ }
3206
+ function isContent(operation) {
3207
+ return operation !== void 0 && operation.action.type !== "RETRACT" && operation.action.type !== "NOOP" && !isDocumentAction(operation.action) && !isDenied(operation);
3208
+ }
3209
+ /** The action UNDO retracts: the last applied content row. */
3210
+ function undoTarget(stream, applied) {
3211
+ const rows = positionalOperations(stream);
3212
+ for (let i = rows.length - 1; i >= 0; i--) {
3213
+ const operation = rows[i];
3214
+ if (applied.has(operation.action.id) && isContent(operation)) return operation.action.id;
3215
+ }
3216
+ }
3217
+ /** The last live retraction of content, unless applied content follows it. */
3218
+ function redoTarget(stream, applied) {
3219
+ const rows = positionalOperations(stream);
3220
+ const retracted = retractedActionIds(rows);
3221
+ const byId = new Map(rows.map((operation) => [operation.action.id, operation]));
3222
+ for (let i = rows.length - 1; i >= 0; i--) {
3223
+ const operation = rows[i];
3224
+ if (retracted.has(operation.action.id) || isDenied(operation)) continue;
3225
+ const target = retractionTarget(operation);
3226
+ if (target === void 0) {
3227
+ if (applied.has(operation.action.id) && isContent(operation)) return;
3228
+ continue;
3229
+ }
3230
+ if (isContent(byId.get(target))) return operation.action.id;
3231
+ }
3232
+ }
3233
+ /**
3234
+ * The targets of `scope` derived from the rows `document` holds; for a client
3235
+ * holding the whole log. None where the rule does not derive `scope`.
3236
+ */
3237
+ function undoRedoTargetsOf(document, caps, scope, reducer) {
3238
+ if (!derivesByRule(caps, scope)) return {};
3239
+ const rows = document.operations[scope] ?? [];
3240
+ const { applied } = deriveScope(document, rows, () => reducer, scope);
3241
+ return {
3242
+ undoTarget: undoTarget(rows, applied),
3243
+ redoTarget: redoTarget(rows, applied)
3244
+ };
3245
+ }
3246
+ /** The targets of a fully derived stream, with what advancing them needs. */
3247
+ function undoTargetsBase(stream, applied) {
3248
+ const named = /* @__PURE__ */ new Set();
3249
+ for (const operation of stream) {
3250
+ const target = retractionTarget(operation);
3251
+ if (target !== void 0) named.add(target);
3252
+ }
3253
+ return {
3254
+ targets: {
3255
+ undoTarget: undoTarget(stream, applied),
3256
+ redoTarget: redoTarget(stream, applied)
3257
+ },
3258
+ named
3259
+ };
3260
+ }
3261
+ /**
3262
+ * Whether `tail`, rows appended in index order after a derived base, applies
3263
+ * row by row. Not when a row rewinds, retracts, or is named by a retraction.
3264
+ * It assumes no tail row repeats a stored action id, as a reactor's admission
3265
+ * guarantees on a rule scope; a stream that holds such a repeat must be
3266
+ * derived whole.
3267
+ */
3268
+ function tailAppliesIncrementally(tail, base) {
3269
+ return !tail.some((row) => rewritesScope(row, base.named));
3270
+ }
3271
+ /**
3272
+ * The targets after `appended`, rows past the end of `base`'s stream in index
3273
+ * order; "rederive" unless the tail applies incrementally. A row's stored
3274
+ * `error` says whether it applied.
3275
+ */
3276
+ function advanceUndoTargets(base, appended) {
3277
+ if (!tailAppliesIncrementally(appended, { named: (id) => base.named.has(id) })) return "rederive";
3278
+ let { undoTarget: undo, redoTarget: redo } = base.targets;
3279
+ for (const operation of appended) if (isContent(operation) && operation.error === void 0) {
3280
+ undo = operation.action.id;
3281
+ redo = void 0;
3282
+ }
3283
+ return {
3284
+ undoTarget: undo,
3285
+ redoTarget: redo
3286
+ };
3287
+ }
3288
+ //#endregion
3289
+ //#region document-model/documents.ts
3290
+ function isNoopOperation(op) {
3291
+ return op.type === "NOOP" && op.skip !== void 0 && op.skip > 0 && op.hash !== void 0;
3292
+ }
3293
+ function isUndoRedo(action) {
3294
+ return ["UNDO", "REDO"].includes(action.type);
3295
+ }
3296
+ function isUndo(action) {
3297
+ return action.type === "UNDO";
3298
+ }
3299
+ /**
3300
+ * The document-scope operations a reactor mints on `create`, so a standalone
3301
+ * document carries its initial state when exported outside a reactor.
3302
+ */
3303
+ function createDocumentScopeOperations(header, state) {
3304
+ const createInput = {
3305
+ model: header.documentType,
3306
+ version: 0,
3307
+ documentId: header.id,
3308
+ signing: {
3309
+ signature: header.id,
3310
+ publicKey: header.sig.publicKey,
3311
+ nonce: header.sig.nonce,
3312
+ createdAtUtcIso: header.createdAtUtcIso,
3313
+ documentType: header.documentType
3314
+ },
3315
+ slug: header.slug,
3316
+ name: header.name,
3317
+ branch: header.branch,
3318
+ meta: header.meta,
3319
+ protocolVersions: header.protocolVersions ?? { "base-reducer": FLAGLESS_BASE_REDUCER_VERSION }
3320
+ };
3321
+ const upgradeInput = {
3322
+ model: header.documentType,
3323
+ fromVersion: 0,
3324
+ toVersion: state.document.version,
3325
+ documentId: header.id,
3326
+ initialState: state
3327
+ };
3328
+ return [{
3329
+ id: generateActionId(),
3330
+ type: "CREATE_DOCUMENT",
3331
+ scope: "document",
3332
+ timestampUtcMs: header.createdAtUtcIso,
3333
+ input: createInput
3334
+ }, {
3335
+ id: generateActionId(),
3336
+ type: "UPGRADE_DOCUMENT",
3337
+ scope: "document",
3338
+ timestampUtcMs: header.createdAtUtcIso,
3339
+ input: upgradeInput
3340
+ }].map((action, index) => ({
3341
+ ...action,
3342
+ action,
3343
+ id: deriveOperationId(header.id, "document", header.branch, action.id),
3344
+ hash: "",
3345
+ error: void 0,
3346
+ index,
3347
+ skip: 0
3348
+ }));
3349
+ }
3350
+ /**
3351
+ * Creates a new document. When `documentType` is given the header is stamped
3352
+ * with it and the document-scope operations are seeded. Without
3353
+ * `protocolVersions` the document is v2-required and takes a derived id; with
3354
+ * them it is v2-required only if they say so (see {@link protocolVersionsFor}).
3355
+ */
3356
+ function baseCreateDocument(createState, initialState, documentType = "", protocolVersions) {
3357
+ const state = createState(initialState);
3358
+ const header = createPresignedHeader(void 0, documentType, protocolVersions === void 0 ? protocolVersionsFor("v2-required") : {
3359
+ "base-reducer": FLAGLESS_BASE_REDUCER_VERSION,
3360
+ ...protocolVersions
3361
+ });
3362
+ header.revision = withScopeRevisions(header.revision, state);
3363
+ return {
3364
+ header,
3365
+ state,
3366
+ initialState: state,
3367
+ operations: documentType ? {
3368
+ global: [],
3369
+ local: [],
3370
+ document: createDocumentScopeOperations(header, state)
3371
+ } : {
3372
+ global: [],
3373
+ local: []
3374
+ },
3375
+ clipboard: []
3376
+ };
3377
+ }
3378
+ /**
3379
+ * `document`, not yet created, under a fresh header for `policy`. A legacy
3380
+ * header takes `id` when given; a v2-required one ignores `id` and derives its
3381
+ * own, so a caller that needs a fixed id must ask for legacy.
3382
+ * `protocolVersions` are merged over the document's. Name, slug, branch and
3383
+ * meta carry over. A document already under `policy` is returned as is unless
3384
+ * a legacy `id` or `protocolVersions` are given.
3385
+ */
3386
+ function withSignaturePolicy(document, policy, options = {}) {
3387
+ const id = policy === "legacy" ? options.id : void 0;
3388
+ if (id === void 0 && options.protocolVersions === void 0 && signaturePolicyOf(document.header) === policy) return document;
3389
+ const source = document.header;
3390
+ const header = createPresignedHeader(id, source.documentType, protocolVersionsFor(policy, {
3391
+ ...source.protocolVersions,
3392
+ ...options.protocolVersions
3393
+ }));
3394
+ header.name = source.name;
3395
+ header.slug = source.slug;
3396
+ header.branch = source.branch;
3397
+ header.meta = source.meta;
3398
+ const operations = document.operations.document ? {
3399
+ ...document.operations,
3400
+ document: createDocumentScopeOperations(header, document.state)
3401
+ } : document.operations;
3402
+ return {
3403
+ ...document,
3404
+ header,
3405
+ operations
3406
+ };
3407
+ }
3408
+ function hashDocumentStateForScope(document, scope = "global") {
3409
+ const stateString = stringify(document.state[scope] || "");
3410
+ return hashBrowser(stateString);
3411
+ }
3412
+ function readOnly(value) {
3413
+ return Object.freeze(value);
3414
+ }
3415
+ /**
3416
+ * Maps skipped operations in an array of operations.
3417
+ * Skipped operations are operations that are ignored during processing.
3418
+ * @param operations - The array of operations to map.
3419
+ * @param skippedHeadOperations - The number of operations to skip at the head of the array of operations.
3420
+ * @returns An array of mapped operations with ignore flag indicating if the operation is skipped.
3421
+ * @throws Error if the operation index is invalid and there are missing operations.
3422
+ */
3423
+ function mapSkippedOperations(operations, skippedHeadOperations) {
3424
+ const ops = [...operations];
3425
+ let skipped = skippedHeadOperations || 0;
3426
+ let latestOpIndex = ops.length > 0 ? ops[ops.length - 1].index : 0;
3427
+ const scopeOpsWithIgnore = [];
3428
+ for (const operation of ops.reverse()) {
3429
+ if (skipped > 0) {
3430
+ const operationsDiff = latestOpIndex - operation.index;
3431
+ skipped -= operationsDiff;
3432
+ }
3433
+ if (skipped < 0) throw new Error("Invalid operation index, missing operations");
3434
+ const mappedOp = {
3435
+ ignore: skipped > 0,
3436
+ operation
3437
+ };
3438
+ const operationSkip = operation.skip > 0 ? operation.skip + 1 : 0;
3439
+ if (operationSkip > 0 && operationSkip > skipped) {
3440
+ const skipDiff = operationSkip - skipped;
3441
+ skipped = skipped + skipDiff;
3442
+ }
3443
+ latestOpIndex = operation.index;
3444
+ scopeOpsWithIgnore.push(mappedOp);
3445
+ }
3446
+ return scopeOpsWithIgnore.reverse();
3447
+ }
3448
+ /**
3449
+ * V2 version of mapSkippedOperations for protocol version 2+.
3450
+ * In V2, all NOOPs have skip=1 and consecutive NOOPs form chains.
3451
+ * N consecutive NOOPs at any point skip N preceding content operations.
3452
+ *
3453
+ * Algorithm: Process from end to start
3454
+ * - When hitting a NOOP: increment chain length, mark as ignored
3455
+ * - When hitting a non-NOOP:
3456
+ * - If chain > 0: decrement chain, mark as ignored (this op was undone)
3457
+ * - If chain == 0: mark as not ignored (apply this op)
3458
+ */
3459
+ function mapSkippedOperationsV2(operations) {
3460
+ const ops = [...operations];
3461
+ const result = [];
3462
+ let noopChainLength = 0;
3463
+ for (let i = ops.length - 1; i >= 0; i--) {
3464
+ const operation = ops[i];
2995
3465
  if (operation.action.type === "NOOP") {
2996
3466
  noopChainLength++;
2997
3467
  result.unshift({
@@ -3016,18 +3486,6 @@ function mapSkippedOperationsV2(operations) {
3016
3486
  * Uses the V2 model where consecutive NOOPs form chains.
3017
3487
  * Unlike V1 garbageCollect, this preserves ALL operations but marks which to apply.
3018
3488
  */
3019
- /**
3020
- * The base-reducer protocol version a document is written against. Every
3021
- * document carries one, set from the CREATE_DOCUMENT input. A header without
3022
- * one was built outside that path, and choosing a version on its behalf would
3023
- * replay the document through a reducer it was not written for, so it is an
3024
- * error rather than a default.
3025
- */
3026
- function baseReducerVersion(header) {
3027
- const version = header.protocolVersions?.["base-reducer"];
3028
- if (typeof version !== "number") throw new Error(`Document ${header.id} carries no base-reducer protocol version`);
3029
- return version;
3030
- }
3031
3489
  function garbageCollectV2(sortedOperations) {
3032
3490
  const result = [];
3033
3491
  let noopChainLength = 0;
@@ -3063,8 +3521,65 @@ function appendWithoutApplying(document, operation, scope = operation.action.sco
3063
3521
  }
3064
3522
  };
3065
3523
  }
3524
+ /** The state reducer base-reducer 3 derives with; throws when `reducer` wraps none. */
3525
+ function requireStateReducer(reducer, documentType, version) {
3526
+ const stateReducer = stateReducerOf(reducer);
3527
+ if (stateReducer === void 0) throw new MissingStateReducerError(documentType, version);
3528
+ return stateReducer;
3529
+ }
3530
+ function replayOperation(document, operation, reducer, dispatch, checkHashes, skipIndexValidation, protocolVersion) {
3531
+ if (isDenied(operation)) return updateHeaderRevision(appendWithoutApplying(document, operation), operation.action.scope, operation.timestampUtcMs);
3532
+ return reducer(document, operation.action, dispatch, {
3533
+ ignoreSkipOperations: true,
3534
+ checkHashes,
3535
+ skipIndexValidation,
3536
+ protocolVersion,
3537
+ replayOptions: { operation }
3538
+ });
3539
+ }
3540
+ /** Rejects the index gaps the reducer rejects when it appends a replayed row. */
3541
+ function assertReplayIndices(operations) {
3542
+ let lastIndex = -1;
3543
+ for (const operation of operations) {
3544
+ if (operation.index - operation.skip > lastIndex + 1) throw new Error(`Missing operations: expected ${lastIndex + 1} with skip 0 or equivalent, got index ${operation.index} with skip ${operation.skip}`);
3545
+ lastIndex = operation.index;
3546
+ }
3547
+ }
3548
+ /** Base-reducer 3: rows stored as given, one derivation per ruled scope. */
3549
+ function replayRetractionScopes(caps, document, operations, reducer, dispatch, checkHashes, skipIndexValidation, protocolVersion) {
3550
+ let reducerFor;
3551
+ let result = document;
3552
+ for (const [scope, rows = []] of Object.entries(operations)) {
3553
+ if (rows.length === 0) continue;
3554
+ if (!derivesByRule(caps, scope)) {
3555
+ for (const operation of rows) result = replayOperation(result, operation, reducer, dispatch, checkHashes, skipIndexValidation, protocolVersion);
3556
+ continue;
3557
+ }
3558
+ if (!skipIndexValidation) assertReplayIndices(rows);
3559
+ result = updateHeaderRevision(appendRows(result, scope, rows), scope, rows.at(-1).timestampUtcMs);
3560
+ if (reducerFor === void 0) {
3561
+ const stateReducer = requireStateReducer(reducer, document.header.documentType);
3562
+ reducerFor = () => stateReducer;
3563
+ }
3564
+ result = deriveScope(result, rows, reducerFor, scope).document;
3565
+ }
3566
+ return result;
3567
+ }
3568
+ function appendRows(document, scope, rows) {
3569
+ return {
3570
+ ...document,
3571
+ operations: {
3572
+ ...document.operations,
3573
+ [scope]: [...document.operations[scope] ?? [], ...rows]
3574
+ }
3575
+ };
3576
+ }
3066
3577
  function replayDocument(initialState, operations, reducer, header, dispatch, skipHeaderOperations = {}, options) {
3067
- const { checkHashes = true, reuseOperationResultingState, operationResultingStateParser = parseResultingState, skipIndexValidation } = options || {};
3578
+ const { checkHashes = true, reuseOperationResultingState, operationResultingStateParser = parseResultingState, skipIndexValidation, protocolVersion: requestedVersion } = options || {};
3579
+ const headerVersion = header.protocolVersions?.["base-reducer"];
3580
+ const protocolVersion = typeof headerVersion === "number" && !isBaseReducerVersion(headerVersion) ? requestedVersion : void 0;
3581
+ const caps = protocolVersion === void 0 ? optionalBaseReducerCapabilities(header) : capabilitiesOf(protocolVersion);
3582
+ const retraction = usesRetractionRule(caps);
3068
3583
  const backfilledInitialState = backfillAuthState(initialState);
3069
3584
  let documentState = backfilledInitialState;
3070
3585
  const operationsToReplay = [];
@@ -3075,7 +3590,7 @@ function replayDocument(initialState, operations, reducer, header, dispatch, ski
3075
3590
  ]);
3076
3591
  const initialOperations = {};
3077
3592
  for (const scope of allScopes) initialOperations[scope] = [];
3078
- if (reuseOperationResultingState) for (const [scope, scopeOperations] of Object.entries(operations)) {
3593
+ if (reuseOperationResultingState && !retraction) for (const [scope, scopeOperations] of Object.entries(operations)) {
3079
3594
  if (!scopeOperations) continue;
3080
3595
  const index = scopeOperations.findLastIndex((s) => !!s.resultingState);
3081
3596
  if (index < 0) {
@@ -3106,21 +3621,18 @@ function replayDocument(initialState, operations, reducer, header, dispatch, ski
3106
3621
  clipboard: []
3107
3622
  };
3108
3623
  let result = document;
3109
- if (operationsToReplay.length) result = operationsToReplay.reduce((document, operation) => {
3110
- if (isDenied(operation)) return updateHeaderRevision(appendWithoutApplying(document, operation), operation.action.scope, operation.timestampUtcMs);
3111
- return reducer(document, operation.action, dispatch, {
3112
- ignoreSkipOperations: true,
3113
- checkHashes,
3114
- skipIndexValidation,
3115
- replayOptions: { operation }
3116
- });
3117
- }, document);
3624
+ if (operationsToReplay.length && caps && usesRetractionRule(caps)) result = replayRetractionScopes(caps, document, operations, reducer, dispatch, checkHashes, skipIndexValidation, protocolVersion);
3625
+ else if (operationsToReplay.length) result = operationsToReplay.reduce((document, operation) => replayOperation(document, operation, reducer, dispatch, checkHashes, skipIndexValidation, protocolVersion), document);
3118
3626
  else for (const scopeOperations of Object.values(initialOperations)) {
3119
3627
  if (!scopeOperations) continue;
3120
3628
  const lastOperation = scopeOperations.at(-1);
3121
3629
  if (lastOperation) result = updateHeaderRevision(result, lastOperation.action.scope, lastOperation.timestampUtcMs);
3122
3630
  }
3123
- if (!checkHashes) for (const scope of Object.keys(result.state)) for (let i = operationsToReplay.length - 1; i >= 0; i--) {
3631
+ if (!checkHashes && retraction) for (const scope of Object.keys(result.state)) {
3632
+ const operation = positionalOperations(operations[scope] ?? []).at(-1);
3633
+ if (operation && operation.hash !== hashDocumentStateForScope(result, scope)) throw new HashMismatchError(scope, result, operation);
3634
+ }
3635
+ else if (!checkHashes) for (const scope of Object.keys(result.state)) for (let i = operationsToReplay.length - 1; i >= 0; i--) {
3124
3636
  const operation = operationsToReplay[i];
3125
3637
  if (operation.action.scope !== scope) continue;
3126
3638
  if (operation.hash !== hashDocumentStateForScope(result, scope)) throw new HashMismatchError(scope, result, operation);
@@ -3197,18 +3709,6 @@ function checkCleanedOperationsIntegrity(sortedOperations) {
3197
3709
  }
3198
3710
  return result;
3199
3711
  }
3200
- function garbageCollect(sortedOperations) {
3201
- const result = [];
3202
- let i = sortedOperations.length - 1;
3203
- while (i > -1) {
3204
- result.unshift(sortedOperations[i]);
3205
- const skipUntil = (sortedOperations[i]?.index || 0) - (sortedOperations[i]?.skip || 0) - 1;
3206
- let j = i - 1;
3207
- while (j > -1 && (sortedOperations[j]?.index || 0) > skipUntil) j--;
3208
- i = j;
3209
- }
3210
- return result;
3211
- }
3212
3712
  function addUndo(sortedOperations) {
3213
3713
  const operationsCopy = [...sortedOperations];
3214
3714
  const latestOperation = operationsCopy[operationsCopy.length - 1];
@@ -3240,9 +3740,6 @@ function addUndo(sortedOperations) {
3240
3740
  });
3241
3741
  return operationsCopy;
3242
3742
  }
3243
- function sortOperations(operations) {
3244
- return operations.slice().sort((a, b) => a.skip - b.skip).sort((a, b) => a.index - b.index);
3245
- }
3246
3743
  function reshuffleByTimestamp(startIndex, opsA, opsB) {
3247
3744
  return [...opsA, ...opsB].sort((a, b) => {
3248
3745
  const timestampDiff = new Date(a.timestampUtcMs || "").getTime() - new Date(b.timestampUtcMs || "").getTime();
@@ -3370,13 +3867,6 @@ function getMaxIndex(sortedOperations) {
3370
3867
  if (!lastElement) return -1;
3371
3868
  return lastElement.index;
3372
3869
  }
3373
- function nextSkipNumber(sortedOperations) {
3374
- if (sortedOperations.length < 1) return -1;
3375
- const cleanedOperations = garbageCollect(sortedOperations);
3376
- let nextSkip = (cleanedOperations[cleanedOperations.length - 1]?.skip || 0) + 1;
3377
- if (cleanedOperations.length > 1) nextSkip += cleanedOperations[cleanedOperations.length - 2]?.skip || 0;
3378
- return (cleanedOperations[cleanedOperations.length - 1]?.index || -1) < nextSkip ? -1 : nextSkip;
3379
- }
3380
3870
  function checkOperationsIntegrity(operations) {
3381
3871
  return checkCleanedOperationsIntegrity(garbageCollect(sortOperations(operations)));
3382
3872
  }
@@ -3540,139 +4030,6 @@ function updateHeaderRevision(document, scope, lastModifiedTimestamp) {
3540
4030
  };
3541
4031
  }
3542
4032
  //#endregion
3543
- //#region document-model/operations.ts
3544
- /**
3545
- * The NOOP base-reducers 1 and 2 synthesize for an undo. It takes the wall
3546
- * clock in every scope, never the auth clock.
3547
- */
3548
- function undoMarker(scope) {
3549
- return {
3550
- id: generateActionId(),
3551
- timestampUtcMs: (/* @__PURE__ */ new Date()).toISOString(),
3552
- type: "NOOP",
3553
- input: {},
3554
- scope
3555
- };
3556
- }
3557
- function setNameOperation(document, input) {
3558
- return {
3559
- ...document,
3560
- header: {
3561
- ...document.header,
3562
- name: input.name
3563
- }
3564
- };
3565
- }
3566
- function setPreferredEditorOperation(document, input) {
3567
- const existingMeta = document.header.meta ?? {};
3568
- if (input.preferredEditor) return {
3569
- ...document,
3570
- header: {
3571
- ...document.header,
3572
- meta: {
3573
- ...existingMeta,
3574
- preferredEditor: input.preferredEditor
3575
- }
3576
- }
3577
- };
3578
- const { preferredEditor: _removed, ...rest } = existingMeta;
3579
- return {
3580
- ...document,
3581
- header: {
3582
- ...document.header,
3583
- meta: rest
3584
- }
3585
- };
3586
- }
3587
- function undoOperation(document, action, skip) {
3588
- const { scope } = action;
3589
- return create({
3590
- document,
3591
- action,
3592
- skip,
3593
- reuseLastOperationIndex: false
3594
- }, (draft) => {
3595
- const sortedOperations = sortOperations([...document.operations[scope]]);
3596
- draft.action = undoMarker(scope);
3597
- const lastOperation = sortedOperations.at(-1);
3598
- let nextIndex = lastOperation?.index ?? -1;
3599
- const isNewNoop = lastOperation?.action.type !== "NOOP";
3600
- if (isNewNoop) nextIndex = nextIndex + 1;
3601
- else draft.reuseLastOperationIndex = true;
3602
- draft.skip = nextSkipNumber(isNewNoop ? [...sortedOperations, {
3603
- index: nextIndex,
3604
- skip: 0
3605
- }] : sortedOperations);
3606
- if (lastOperation && draft.skip > lastOperation.skip + 1) draft.skip = draft.skip + 1;
3607
- if (draft.skip < 0) throw new Error(`Cannot undo: you can't undo more operations than the ones in the scope history`);
3608
- });
3609
- }
3610
- /**
3611
- * V2 of undoOperation for protocol version 2+.
3612
- * Key differences from undoOperation:
3613
- * - Never reuses operation index (always increments)
3614
- * - Always sets skip=1 (consecutive NOOPs are handled during rebuild/GC)
3615
- * - No complex skip calculation - simpler model where each UNDO is independent
3616
- */
3617
- function undoOperationV2(document, action, skip) {
3618
- const { scope } = action;
3619
- return create({
3620
- document,
3621
- action,
3622
- skip,
3623
- reuseLastOperationIndex: false
3624
- }, (draft) => {
3625
- const sortedOperations = sortOperations([...document.operations[scope] || []]);
3626
- const nonNoopOps = sortedOperations.filter((op) => op.action.type !== "NOOP");
3627
- let noopChainLength = 0;
3628
- for (let i = sortedOperations.length - 1; i >= 0; i--) if (sortedOperations[i].action.type === "NOOP") noopChainLength++;
3629
- else break;
3630
- if (nonNoopOps.length <= noopChainLength) throw new Error(`Cannot undo: no more operations to undo in scope history`);
3631
- draft.action = undoMarker(scope);
3632
- draft.skip = 1;
3633
- });
3634
- }
3635
- function redoOperation(document, action, skip) {
3636
- const { scope, input } = action;
3637
- return create({
3638
- document,
3639
- action,
3640
- skip,
3641
- reuseLastOperationIndex: false
3642
- }, (draft) => {
3643
- if (draft.skip > 0) throw new Error(`Cannot redo: skip value from reducer cannot be used with REDO action`);
3644
- const count = typeof input === "object" && input !== null && "count" in input ? input.count : input;
3645
- if (typeof count !== "number" || count > 1) throw new Error(`Cannot redo: you can only redo one operation at a time`);
3646
- if (typeof count !== "number" || count < 1) throw new Error(`Invalid REDO action: invalid redo input value`);
3647
- if (draft.document.clipboard.length < 1) throw new Error(`Cannot redo: no operations in the clipboard`);
3648
- const operationIndex = draft.document.clipboard.findLastIndex((op) => op.action.scope === scope);
3649
- if (operationIndex < 0) throw new Error(`Cannot redo: no operations in clipboard for scope "${scope}"`);
3650
- const operation = draft.document.clipboard.splice(operationIndex, 1)[0];
3651
- draft.action = castDraft({
3652
- type: operation.action.type,
3653
- scope: operation.action.scope,
3654
- input: operation.action.input
3655
- });
3656
- });
3657
- }
3658
- /**
3659
- * Reads an operation's outcome. A denial takes precedence over a reducer
3660
- * error, since a denied operation never reaches its reducer.
3661
- */
3662
- function operationOutcome(operation) {
3663
- if (operation.deniedReason !== void 0) return {
3664
- kind: "denied",
3665
- reason: operation.deniedReason
3666
- };
3667
- if (operation.error !== void 0) return {
3668
- kind: "reducer-error",
3669
- message: operation.error,
3670
- ...operation.errorName !== void 0 && { name: operation.errorName },
3671
- ...operation.errorCode !== void 0 && { code: operation.errorCode }
3672
- };
3673
- return { kind: "applied" };
3674
- }
3675
- //#endregion
3676
4033
  //#region document-model/reducer.ts
3677
4034
  function replayOperations(initialState, clearedOperations, stateReducer, header, dispatch, documentReducer = baseReducer, skipHeaderOperations = {}, options) {
3678
4035
  return replayDocument(initialState, clearedOperations, createReducer(stateReducer, documentReducer), header, dispatch, skipHeaderOperations, options);
@@ -3738,43 +4095,30 @@ function updateDocument(document, action, reuseLastOperationIndex, skip, context
3738
4095
  return newDocument;
3739
4096
  }
3740
4097
  /**
3741
- * The base document reducer function.
3742
- *
3743
- * @param state The current state of the document.
3744
- * @param action The action being applied to the document.
3745
- * @returns The updated document state.
3746
- */
3747
- function _baseReducer(document, action) {
3748
- const parsedAction = DocumentActionSchema().parse(action);
3749
- switch (parsedAction.type) {
3750
- case "SET_NAME": return setNameOperation(document, parsedAction.input);
3751
- case "SET_PREFERRED_EDITOR": return setPreferredEditorOperation(document, parsedAction.input);
3752
- default: return document;
3753
- }
3754
- }
3755
- /**
3756
4098
  * Processes an UNDO or REDO action.
3757
4099
  *
3758
4100
  * @param document The current state of the document.
3759
4101
  * @param action The action being applied to the document.
3760
4102
  * @param skip The number of operations to skip before applying the action.
4103
+ * @param protocolVersion The document's base-reducer version.
3761
4104
  * @returns The updated document, calculated skip value and transformed action (if applied).
3762
4105
  */
3763
4106
  function processUndoRedo(document, action, skip, protocolVersion = 1) {
3764
- switch (action.type) {
3765
- case "UNDO":
3766
- if (protocolVersion >= 2) return undoOperationV2(document, action, skip);
3767
- return undoOperation(document, action, skip);
3768
- case "REDO": return redoOperation(document, action, skip);
3769
- default: return {
3770
- document,
3771
- action,
3772
- skip,
3773
- reuseLastOperationIndex: false
3774
- };
4107
+ if (action.type !== "UNDO" && action.type !== "REDO") return {
4108
+ document,
4109
+ action,
4110
+ skip,
4111
+ reuseLastOperationIndex: false
4112
+ };
4113
+ const { undo: model } = capabilitiesOf(protocolVersion);
4114
+ switch (model) {
4115
+ case "skip": return action.type === "UNDO" ? undoOperation(document, action, skip) : redoOperation(document, action, skip);
4116
+ case "noop-chain": return action.type === "UNDO" ? undoOperationV2(document, action, skip) : redoOperation(document, action, skip);
4117
+ case "retraction": throw new SubmittedUndoRefusedError(document.header.id, action.type);
4118
+ default: return assertNever(model, "undo model");
3775
4119
  }
3776
4120
  }
3777
- function processSkipOperation(document, action, customReducer, skipValue, reuseOperationResultingState = false, resultingStateParser = parseResultingState) {
4121
+ function processSkipOperation(document, action, customReducer, skipValue, protocolVersion, reuseOperationResultingState = false, resultingStateParser = parseResultingState) {
3778
4122
  const scope = action.scope;
3779
4123
  const scopeOperations = document.operations[scope];
3780
4124
  if (!scopeOperations) return document;
@@ -3791,7 +4135,8 @@ function processSkipOperation(document, action, customReducer, skipValue, reuseO
3791
4135
  const { state } = replayOperations(document.initialState, documentOperations, customReducer, document.header, void 0, void 0, void 0, {
3792
4136
  reuseOperationResultingState,
3793
4137
  operationResultingStateParser: resultingStateParser,
3794
- skipIndexValidation: true
4138
+ skipIndexValidation: true,
4139
+ protocolVersion
3795
4140
  });
3796
4141
  scopeState = state[scope];
3797
4142
  }
@@ -3804,7 +4149,7 @@ function processSkipOperation(document, action, customReducer, skipValue, reuseO
3804
4149
  operations: garbageCollectDocumentOperations({ ...document.operations })
3805
4150
  };
3806
4151
  }
3807
- function processUndoOperation(document, scope, customReducer, reuseOperationResultingState = false, resultingStateParser = parseResultingState) {
4152
+ function processUndoOperation(document, scope, customReducer, protocolVersion, reuseOperationResultingState = false, resultingStateParser = parseResultingState) {
3808
4153
  const scopeOperations = document.operations[scope];
3809
4154
  if (!scopeOperations) return document;
3810
4155
  const sortedOperations = sortOperations([...scopeOperations]);
@@ -3816,7 +4161,8 @@ function processUndoOperation(document, scope, customReducer, reuseOperationResu
3816
4161
  const diff = diffOperations(garbageCollect(sortedOperations), clearedOperations);
3817
4162
  const doc = replayOperations(document.initialState, documentOperations, customReducer, document.header, void 0, void 0, void 0, {
3818
4163
  reuseOperationResultingState,
3819
- operationResultingStateParser: resultingStateParser
4164
+ operationResultingStateParser: resultingStateParser,
4165
+ protocolVersion
3820
4166
  });
3821
4167
  const clipboard = sortOperations([...document.clipboard, ...diff].filter((op) => op.action.type !== "NOOP")).reverse();
3822
4168
  return {
@@ -3840,12 +4186,15 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
3840
4186
  const { skip, ignoreSkipOperations = false, reuseOperationResultingState = false, operationResultingStateParser, pruneOnSkip = true, branch = "main" } = options;
3841
4187
  let _action = actionFromAction(action);
3842
4188
  assertAuthScopeActionAllowed(_action);
4189
+ const protocolVersion = options.protocolVersion ?? baseReducerVersion(document.header);
4190
+ const caps = capabilitiesOf(protocolVersion);
4191
+ const byRule = derivesByRule(caps, _action.scope);
3843
4192
  let skipValue = skip ?? options.replayOptions?.operation.skip ?? 0;
3844
4193
  let newDocument = { ...document };
3845
4194
  let reuseLastOperationIndex = false;
3846
- const shouldProcessSkipOperation = !ignoreSkipOperations && skipValue > 0;
4195
+ const shouldProcessSkipOperation = appliesRewind(caps, _action.scope) && !ignoreSkipOperations && skipValue > 0;
3847
4196
  if (isUndoRedo(_action)) {
3848
- const { skip: calculatedSkip, action: transformedAction, document: processedDocument, reuseLastOperationIndex: reuseIndex } = processUndoRedo(document, _action, skipValue, options.protocolVersion ?? baseReducerVersion(document.header));
4197
+ const { skip: calculatedSkip, action: transformedAction, document: processedDocument, reuseLastOperationIndex: reuseIndex } = processUndoRedo(document, _action, skipValue, protocolVersion);
3849
4198
  _action = transformedAction;
3850
4199
  skipValue = calculatedSkip;
3851
4200
  newDocument = processedDocument;
@@ -3854,31 +4203,43 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
3854
4203
  ...newDocument,
3855
4204
  clipboard: []
3856
4205
  };
3857
- if (isDocumentAction(_action)) newDocument = _baseReducer(newDocument, _action);
4206
+ if (!byRule && isDocumentAction(_action)) newDocument = baseActionReducer(newDocument, _action);
3858
4207
  const operationContext = {
3859
4208
  documentId: document.header.id,
3860
4209
  scope: _action.scope,
3861
4210
  branch
3862
4211
  };
3863
4212
  newDocument = updateDocument(newDocument, _action, reuseLastOperationIndex, skipValue, operationContext, options.replayOptions?.operation, options.skipIndexValidation);
3864
- const protocolVersion = options.protocolVersion ?? baseReducerVersion(document.header);
3865
- if (isUndo(action) && protocolVersion < 2) return processUndoOperation(newDocument, action.scope, customReducer);
4213
+ if (byRule) return applyByRule(newDocument, _action.scope, customReducer, dispatch, skipValue, options);
3866
4214
  const isNoopWithSkip = _action.type === "NOOP" && skipValue > 0;
3867
- if ((isUndo(action) || isNoopWithSkip) && protocolVersion >= 2) {
3868
- const scope = _action.scope;
3869
- const opsToReplay = garbageCollectV2(sortOperations([...newDocument.operations[scope] || []])).filter((op) => op.action.type !== "NOOP");
3870
- const replayOps = {
3871
- ...newDocument.operations,
3872
- [scope]: opsToReplay
3873
- };
3874
- return {
3875
- ...replayOperations(newDocument.initialState, replayOps, customReducer, newDocument.header, dispatch, baseReducer, {}, { skipIndexValidation: true }),
3876
- operations: newDocument.operations,
3877
- clipboard: []
3878
- };
4215
+ const undoModel = caps.undo;
4216
+ switch (undoModel) {
4217
+ case "skip":
4218
+ if (isUndo(action)) return processUndoOperation(newDocument, action.scope, customReducer, protocolVersion);
4219
+ break;
4220
+ case "noop-chain":
4221
+ if (isUndo(action) || isNoopWithSkip) {
4222
+ const scope = _action.scope;
4223
+ const opsToReplay = garbageCollectV2(sortOperations([...newDocument.operations[scope] || []])).filter((op) => op.action.type !== "NOOP");
4224
+ const replayOps = {
4225
+ ...newDocument.operations,
4226
+ [scope]: opsToReplay
4227
+ };
4228
+ return {
4229
+ ...replayOperations(newDocument.initialState, replayOps, customReducer, newDocument.header, dispatch, baseReducer, {}, {
4230
+ skipIndexValidation: true,
4231
+ protocolVersion
4232
+ }),
4233
+ operations: newDocument.operations,
4234
+ clipboard: []
4235
+ };
4236
+ }
4237
+ break;
4238
+ case "retraction": break;
4239
+ default: assertNever(undoModel, "undo model");
3879
4240
  }
3880
4241
  if (shouldProcessSkipOperation) {
3881
- const processed = processSkipOperation(newDocument, _action, customReducer, skipValue, reuseOperationResultingState, operationResultingStateParser);
4242
+ const processed = processSkipOperation(newDocument, _action, customReducer, skipValue, protocolVersion, reuseOperationResultingState, operationResultingStateParser);
3882
4243
  if (!pruneOnSkip) newDocument = {
3883
4244
  ...processed,
3884
4245
  operations: newDocument.operations
@@ -3925,6 +4286,57 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
3925
4286
  return newDocument;
3926
4287
  }
3927
4288
  /**
4289
+ * Base-reducer 3: applies the appended row, or re-derives the scope when the
4290
+ * row rewinds, retracts, or is named by a retraction. A stored `error` is
4291
+ * diagnostic: it is written only on the appended row.
4292
+ */
4293
+ function applyByRule(document, scope, customReducer, dispatch, skip, options) {
4294
+ const operations = document.operations[scope] ?? [];
4295
+ const appended = operations.at(-1);
4296
+ if (!appended) throw new Error(`No operations found for scope: ${scope}`);
4297
+ const appendedId = appended.action.id;
4298
+ const appendedReducer = (state, action) => customReducer(state, action, dispatch);
4299
+ const reducerFor = (operation) => operation.action.id === appendedId ? appendedReducer : customReducer;
4300
+ const targeted = options.targeted ?? retractedActionIds(positionalOperations(operations));
4301
+ const rebuild = !tailAppliesIncrementally([{
4302
+ skip,
4303
+ action: appended.action
4304
+ }], { named: (id) => targeted.has(id) });
4305
+ let next = document;
4306
+ let error;
4307
+ if (rebuild) {
4308
+ let thrown;
4309
+ const onThrow = (operation, caught) => {
4310
+ if (operation.action.id === appendedId) thrown = caught;
4311
+ };
4312
+ const derived = options.deriveScope ? options.deriveScope(document, operations, scope, onThrow) : deriveScope(document, operations, reducerFor, scope, onThrow);
4313
+ next = derived.document;
4314
+ if (!derived.applied.has(appendedId) && appliedOperations(operations).some((operation) => operation.action.id === appendedId)) error = errorMessage(thrown);
4315
+ } else if (!isDenied(appended)) try {
4316
+ next = reduceOne(document, appended, reducerFor);
4317
+ } catch (caught) {
4318
+ error = errorMessage(caught);
4319
+ }
4320
+ const replayHash = options.replayOptions?.operation.hash;
4321
+ const row = {
4322
+ ...appended,
4323
+ hash: replayHash ? replayHash : hashDocumentStateForScope(next, scope),
4324
+ ...error === void 0 ? {} : { error },
4325
+ ...options.reuseOperationResultingState ? { resultingState: JSON.stringify(next.state[scope]) } : {}
4326
+ };
4327
+ return {
4328
+ ...next,
4329
+ operations: {
4330
+ ...next.operations,
4331
+ [scope]: [...operations.slice(0, -1), row]
4332
+ }
4333
+ };
4334
+ }
4335
+ function errorMessage(error) {
4336
+ if (error instanceof Error) return error.message;
4337
+ return typeof error === "string" ? error : "Action failed";
4338
+ }
4339
+ /**
3928
4340
  * Helper function to create a document model reducer.
3929
4341
  *
3930
4342
  * @remarks
@@ -3945,7 +4357,7 @@ function createReducer(stateReducer, documentReducer = baseReducer) {
3945
4357
  const reducer = (document, action, dispatch, options) => {
3946
4358
  return documentReducer(document, action, stateReducer, dispatch, options);
3947
4359
  };
3948
- return reducer;
4360
+ return tagStateReducer(reducer, stateReducer);
3949
4361
  }
3950
4362
  /** A thrown error's class name and generated `errorCode`, where it has them. */
3951
4363
  function reducerErrorIdentity(error) {
@@ -3969,7 +4381,8 @@ const RESERVED_OPERATION_NAMES = [
3969
4381
  "SET_NAME",
3970
4382
  "SET_PREFERRED_EDITOR",
3971
4383
  "NOOP",
3972
- "PURGE_DOCUMENT"
4384
+ "PURGE_DOCUMENT",
4385
+ "RETRACT"
3973
4386
  ];
3974
4387
  /**
3975
4388
  * Operation names become the literal action `type` string at runtime and the
@@ -4782,7 +5195,7 @@ function highestReducerVersion(reducers) {
4782
5195
  */
4783
5196
  function replayDocumentVersioned(initialState, operations, config, header, dispatch, options) {
4784
5197
  const { checkHashes = true, skipIndexValidation } = options || {};
4785
- const protocolVersion = baseReducerVersion(header);
5198
+ const caps = baseReducerCapabilities(header);
4786
5199
  const spine = (operations["document"] ?? []).slice().sort((a, b) => a.index - b.index);
4787
5200
  const upgrades = spine.filter((op) => op.action.type === "UPGRADE_DOCUMENT");
4788
5201
  const legacyFallback = () => {
@@ -4861,6 +5274,13 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
4861
5274
  };
4862
5275
  let currentVersion = startVersion;
4863
5276
  const segmentEndHashPerScope = /* @__PURE__ */ new Map();
5277
+ const derivers = /* @__PURE__ */ new Map();
5278
+ if (usesRetractionRule(caps)) for (const s of replayScopes) {
5279
+ if (!derivesByRule(caps, s)) continue;
5280
+ const ops = scopeOps[s] ?? [];
5281
+ if (!skipIndexValidation) assertReplayIndices(ops);
5282
+ derivers.set(s, scopeDeriver(ops));
5283
+ }
4864
5284
  for (let k = 0; k <= validatedUpgrades.length; k++) {
4865
5285
  const reducer = config.reducers[currentVersion];
4866
5286
  if (!reducer) throw new UnsupportedDocumentModelVersionError(header.documentType, currentVersion, Object.keys(config.reducers).map(Number).sort((a, b) => a - b));
@@ -4869,6 +5289,16 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
4869
5289
  const segStart = k === 0 ? 0 : boundaries[k - 1]?.[s] ?? 0;
4870
5290
  const segEnd = k < validatedUpgrades.length ? boundaries[k]?.[s] ?? ops.length : ops.length;
4871
5291
  const segOps = ops.slice(segStart, segEnd);
5292
+ const deriver = derivers.get(s);
5293
+ if (deriver) {
5294
+ if (segOps.length === 0) continue;
5295
+ const stateReducer = requireStateReducer(reducer, header.documentType, currentVersion);
5296
+ const reducerFor = () => stateReducer;
5297
+ document = updateHeaderRevision(appendRows(document, s, segOps), s, segOps.at(-1).timestampUtcMs);
5298
+ document = deriver.advance(document, segOps, reducerFor);
5299
+ segmentEndHashPerScope.set(s, hashDocumentStateForScope(document, s));
5300
+ continue;
5301
+ }
4872
5302
  for (const op of segOps) {
4873
5303
  if (isDenied(op)) document = updateHeaderRevision(appendWithoutApplying(document, op, s), s, op.timestampUtcMs);
4874
5304
  else document = reducer(document, op.action, dispatch, {
@@ -4876,7 +5306,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
4876
5306
  checkHashes,
4877
5307
  skipIndexValidation,
4878
5308
  replayOptions: { operation: op },
4879
- protocolVersion
5309
+ protocolVersion: caps.version
4880
5310
  });
4881
5311
  segmentEndHashPerScope.set(s, hashDocumentStateForScope(document, s));
4882
5312
  }
@@ -4895,7 +5325,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
4895
5325
  checkHashes,
4896
5326
  skipIndexValidation,
4897
5327
  replayOptions: { operation: spineOp },
4898
- protocolVersion
5328
+ protocolVersion: caps.version
4899
5329
  });
4900
5330
  }
4901
5331
  if (k < validatedUpgrades.length) {
@@ -5201,6 +5631,101 @@ function selectDocumentModelModule(modules, documentModelType, documentModelVers
5201
5631
  return latest;
5202
5632
  }
5203
5633
  //#endregion
5204
- export { baseReducer as $, SetModuleNameInputSchema as $a, updateChangeLogItem as $i, isDocumentCreator as $n, addChangeLogItem as $r, BaseDocumentStateSchema as $t, documentModelStateReducer as A, PieceModulesSchema as Aa, setAuthorName as Ai, isDerivedDocumentId as An, GroupPrincipalNotAllowedError as Ar, isUndo as At, findOperationErrorOrThrow as B, ReorderModulesInputSchema as Ba, setOperationDescription as Bi, RemoveGrantActionInputSchema as Bn, evaluateCondition as Br, readOnly as Bt, withProtocolVersions as C, ManifestSchema as Ca, releaseNewVersion as Ci, sign as Cn, UpdateStateExampleInputSchema as Co, documentModelFileExtension as Cr, garbageCollectDocumentOperations as Ct, documentModelOperationExampleReducer as D, OperationScopeSchema as Da, reorderOperationErrors as Di, SIGNATURE_PROTOCOL as Dn, deserializeSignature as Do, AuthAdministrationLockoutError as Dr, hashDocumentStateForScope as Dt, documentModelOperationErrorReducer as E, OperationErrorSchema as Ea, reorderModules as Ei, DEFAULT_SIGNATURE_POLICY as En, toTransportAction as Eo, documentModelInitialLocalState as Er, groupOperationsByScope as Et, assertModuleIdUnique as F, RedoActionInputSchema as Fa, setModelId as Fi, v2RequiredProtocolVersions as Fn, MAX_CONDITION_NODES as Fr, nextSkipNumber as Ft, isValidOperationNameFormat as G, SetAuthorNameInputSchema as Ga, setOperationName as Gi, applyRemoveGrantAction as Gn, referencedGroupIds as Gr, skipHeaderOperations as Gt, findOperationOrThrow as H, ReorderOperationExamplesInputSchema as Ha, setOperationErrorDescription as Hi, applyAuthAction as Hn, evaluateGrants as Hr, replayDocument as Ht, assertOperationErrorIdUnique as I, RedoActionSchema as Ia, setModelName as Ii, AUTH_ACTION_TYPES as In, assertAuthAdministrationRetained as Ir, operationsAreEqual as It, validateModuleOperation as J, SetModelDescriptionInputSchema as Ja, setOperationScope as Ji, assertAuthScopeActionAllowed as Jn, groupMembershipActionTypes as Jr, split as Jt, validateInitialState as K, SetAuthorWebsiteInputSchema as Ka, setOperationReducer as Ki, applySetGrantAction as Kn, documentModelDocumentType as Kr, sortMappedOperations as Kt, assertOperationExampleIdUnique as L, RedoSchema as La, setModuleDescription as Li, InitializeAuthActionInputSchema as Ln, assertValidGrant as Lr, parseResultingState as Lt, documentModelVersioningReducer as M, PowerhouseModulesSchema as Ma, setInitialState as Mi, protocolVersionsFor as Mn, MAX_AUTH_GRANTS as Mr, mapSkippedOperations as Mt, OPERATION_NAME_PATTERN as N, PublisherSchema as Na, setModelDescription as Ni, requestedSignaturePolicy as Nn, MAX_CAPABILITY_OPERATIONS as Nr, mapSkippedOperationsV2 as Nt, documentModelOperationReducer as O, OperationSpecificationSchema as Oa, reorderOperationExamples as Oi, SIGNATURE_PROTOCOL_V2 as On, serializeSignature as Oo, AuthAdministrationMissingError as Or, isDocumentAction as Ot, RESERVED_OPERATION_NAMES as P, PwaConfigSchema as Pa, setModelExtension as Pi, signaturePolicyOf as Pn, MAX_CONDITION_DEPTH as Pr, merge as Pt, validateStateSchemaName as Q, SetModuleDescriptionInputSchema as Qa, undo as Qi, isAuthAction as Qn, actions as Qr, BaseDocumentHeaderSchema as Qt, assertOperationIdUnique as R, ReorderChangeLogItemsInputSchema as Ra, setModuleName as Ri, MAX_SUPPORTED_AUTH_VERSION as Rn, assertValidGrantUpsert as Rr, precedes as Rt, latestVersionOf as S, DocumentSpecificationSchema as Sa, redo as Si, hasDerivedDocumentId as Sn, UpdateOperationExampleInputSchema as So, HASH_ENCODING_HEX as Sr, garbageCollect as St, documentModelModuleReducer as T, MoveOperationInputSchema as Ta, reorderModuleOperations as Ti, verify as Tn, isDefinedNonNullAny as To, documentModelInitialGlobalState as Tr, getDocumentLastModified as Tt, getAllOperationNames as U, ReorderStateExamplesInputSchema as Ua, setOperationErrorName as Ui, applyInitializeAuthAction as Un, grantProblem as Ur, reshuffleByTimestamp as Ut, findOperationExampleOrThrow as V, ReorderOperationErrorsInputSchema as Va, setOperationErrorCode as Vi, SetGrantActionInputSchema as Vn, evaluateGrantStack as Vr, removeExistingOperations as Vt, isReservedOperationName as W, ScopeStateSchema as Wa, setOperationErrorTemplate as Wi, applyMoveGrantAction as Wn, isPlainValue as Wr, reshuffleByTimestampAndIndex as Wt, validateOperationName as X, SetModelIdInputSchema as Xa, setPreferredEditor as Xi, evaluate as Xn, actionFromAction as Xr, withScopeRevisions as Xt, validateModules as Y, SetModelExtensionInputSchema as Ya, setOperationTemplate as Yi, decide as Yn, actionContext as Yr, updateHeaderRevision as Yt, validateOperations as Z, SetModelNameInputSchema as Za, setStateSchema as Zi, initializeAuth as Zn, actionSigner as Zr, withSignaturePolicy as Zt, zipEntries as _, DeleteOperationInputSchema as _a, noop as _i, createCopyHeader as _n, StateSchema as _o, defaultPHState as _r, checkCleanedOperationsIntegrity as _t, baseLoadFromInputVersioned as a, AddOperationErrorInputSchema as aa, baseActions as ai, isDocumentModelDocument as an, SetOperationErrorNameInputSchema as ao, backfillAuthState as ar, redoOperation as at, applyUpgradeDocumentAction as b, DocumentModelGlobalStateSchema as ba, operationFromOperation as bi, createSignedHeaderForSigner as bn, UndoSchema as bo, HASH_ALGORITHM_SHA512 as br, filterDocumentOperationsResultingState as bt, createZip as c, AddStateExampleInputSchema as ca, createAction as ci, AUTH_NO_GRANT_REASON as cn, SetOperationReducerInputSchema as co, createDocumentState as cr, undoOperation as ct, fetchFileBrowser as d, ConfigEntrySchema as da, deleteOperation as di, isDenied as dn, SetOperationTemplateInputSchema as do, createState as dr, IntegrityIssueType as dt, updateOperationExample as ea, addModule as ei, DocumentModelHeaderSchema as en, SetNameActionInputSchema as eo, mentionedGroupIds as er, createReducer as et, getFileBrowser as f, ConfigEntryTypeSchema as fa, deleteOperationError as fi, createDocumentAction as fn, SetPreferredEditorActionInputSchema as fo, defaultAuthState as fr, addUndo as ft, writeFileBrowser as g, DeleteOperationExampleInputSchema as ga, moveOperation as gi, upgradeDocumentAction as gn, Set_PreferredEditorSchema as go, defaultLocalState as gr, baseReducerVersion as gt, readFileBrowser as h, DeleteOperationErrorInputSchema as ha, documentModelActions as hi, documentFromCreation as hn, Set_NameSchema as ho, defaultGlobalState as hr, baseCreateDocument as ht, baseLoadFromInput as i, AddModuleInputSchema as ia, addStateExample as ii, assertIsDocumentModelState as in, SetOperationErrorDescriptionInputSchema as io, setGrant as ir, operationOutcome as it, documentModelStateSchemaReducer as j, PowerhouseModuleSchema as ja, setAuthorWebsite as ji, isSignaturePolicy as jn, InvalidGrantError as jr, isUndoRedo as jt, documentModelReducer as k, PieceModuleSchema as ka, reorderStateExamples as ki, deriveDocumentId as kn, GrantSchema as kr, isNoopOperation as kt, documentModelLoadFromInput as l, AuthorSchema as la, deleteChangeLogItem as li, AUTH_VERSION_UNSUPPORTED_REASON as ln, SetOperationSchemaInputSchema as lo, createGlobalState as lr, undoOperationV2 as lt, parseBulkArchive as m, DeleteModuleInputSchema as ma, deleteStateExample as mi, creationState as mn, SetStateSchemaInputSchema as mo, defaultDocumentState as mr, attachBranch as mt, headNewDocument as n, verifyOperationSignature as na, addOperationError as ni, DocumentModelSchema as nn, SetOperationDescriptionInputSchema as no, removeGrant as nr, replayOperations as nt, baseSaveToFileHandle as o, AddOperationExampleInputSchema as oa, buildOperationSignature as oi, isDocumentModelState as on, SetOperationErrorTemplateInputSchema as oo, createAuthState as or, setNameOperation as ot, isDocumentZip as p, DeleteChangeLogItemInputSchema as pa, deleteOperationExample as pi, creationActions as pn, SetPreferredEditorActionSchema as po, defaultBaseState as pr, appendWithoutApplying as pt, validateModule as q, SetInitialStateInputSchema as qa, setOperationSchema as qi, assertAuthPreservedOnDuplicate as qn, groupDocumentType as qr, sortOperations as qt, selectDocumentModelModule as r, AddChangeLogItemInputSchema as ra, addOperationExample as ri, assertIsDocumentModelDocument as rn, SetOperationErrorCodeInputSchema as ro, resolveSnapshotAuth as rr, updateDocument as rt, createMinimalZip as s, AddOperationInputSchema as sa, buildSignedAction as si, AUTH_DENIED_BY_GRANT_REASON as sn, SetOperationNameInputSchema as so, createBaseState as sr, setPreferredEditorOperation as st, createVersionsOf as t, updateStateExample as ta, addOperation as ti, DocumentModelPHStateSchema as tn, SetNameActionSchema as to, moveGrant as tr, processUndoRedo as tt, documentModelSaveToFileHandle as u, CodeExampleSchema as ua, deleteModule as ui, DOCUMENT_DELETED_REASON as un, SetOperationScopeInputSchema as uo, createLocalState as ur, IntegrityIssueSubType as ut, replayDocumentVersioned as v, DeleteStateExampleInputSchema as va, operationExampleCreators as vi, createPresignedHeader as vn, UndoActionInputSchema as vo, HASH_ALGORITHM_SHA1 as vr, checkOperationsIntegrity as vt, documentModelHeaderReducer as w, ModuleSchema as wa, reorderChangeLogItems as wi, validateHeader as wn, definedNonNullAnySchema as wo, documentModelGlobalState as wr, garbageCollectV2 as wt, computeUpgradeTransitions as x, DocumentModelInputSchema as xa, operationWithContext as xi, createVerificationSigner as xn, UpdateChangeLogItemInputSchema as xo, HASH_ENCODING_BASE64 as xr, filterDuplicatedOperations as xt, applyDeleteDocumentAction as y, DocumentActionSchema as ya, operationFromAction as yi, createSignedHeader as yn, UndoActionSchema as yo, HASH_ALGORITHM_SHA256 as yr, diffOperations as yt, findModuleOrThrow as z, ReorderModuleOperationsInputSchema as za, setName as zi, MoveGrantActionInputSchema as zn, assertValidInitialGrants as zr, prepareOperations as zt };
5634
+ //#region document-model/undo-redo-plan.ts
5635
+ /** An older host serves no header versions; CREATE_DOCUMENT carries them. */
5636
+ function undoCapabilitiesOf(header, createInput) {
5637
+ return optionalBaseReducerCapabilities(header) ?? createdCapabilities(createInput);
5638
+ }
5639
+ /** Whether undo resolves a target before it can be planned. */
5640
+ function undoNeedsTargets(caps) {
5641
+ switch (caps.undo) {
5642
+ case "retraction": return true;
5643
+ case "skip":
5644
+ case "noop-chain": return false;
5645
+ default: return assertNever(caps.undo, "undo model");
5646
+ }
5647
+ }
5648
+ /** What a client submits, signed by its author; throws NoUndoRedoTargetError when nothing is retractable. */
5649
+ function undoRedoActions(caps, type, scope, targets) {
5650
+ switch (caps.undo) {
5651
+ case "skip":
5652
+ case "noop-chain": return [type === "UNDO" ? undo(1, scope) : redo(1, scope)];
5653
+ case "retraction": {
5654
+ const target = type === "UNDO" ? targets?.undoTarget : targets?.redoTarget;
5655
+ if (target === void 0) throw new NoUndoRedoTargetError(type, scope);
5656
+ return [retract(target, scope)];
5657
+ }
5658
+ default: return assertNever(caps.undo, "undo model");
5659
+ }
5660
+ }
5661
+ /** Below the retraction model reads serve no clipboard: undo is approximate. */
5662
+ function undoRedoAvailabilityOf(caps, targets, revision, readable) {
5663
+ switch (caps.undo) {
5664
+ case "skip":
5665
+ case "noop-chain": return {
5666
+ canUndo: readable && revision > 0,
5667
+ canRedo: false
5668
+ };
5669
+ case "retraction": return {
5670
+ canUndo: targets?.undoTarget !== void 0,
5671
+ canRedo: targets?.redoTarget !== void 0
5672
+ };
5673
+ default: return assertNever(caps.undo, "undo model");
5674
+ }
5675
+ }
5676
+ /** Runs `run` after every earlier call with the same key has settled. */
5677
+ function serializeByKey(chains, key, run) {
5678
+ const next = (chains.get(key) ?? Promise.resolve()).catch(() => void 0).then(run);
5679
+ chains.set(key, next);
5680
+ next.catch(() => void 0).finally(() => {
5681
+ if (chains.get(key) === next) chains.delete(key);
5682
+ });
5683
+ return next;
5684
+ }
5685
+ //#endregion
5686
+ //#region document-model/undo-redo-batch.ts
5687
+ /** Base-reducer 3 only. Create each action as it is added: a v3 job runs in creation order. */
5688
+ function undoRedoBatch(document, caps, reducer) {
5689
+ if (!undoNeedsTargets(caps)) throw new Error(`Base-reducer ${caps.version} undoes without targets; submit UNDO and REDO`);
5690
+ const actions = [];
5691
+ const streams = /* @__PURE__ */ new Map();
5692
+ const streamOf = (scope) => {
5693
+ let stream = streams.get(scope);
5694
+ if (stream === void 0) {
5695
+ stream = [...document.operations[scope] ?? []];
5696
+ streams.set(scope, stream);
5697
+ }
5698
+ return stream;
5699
+ };
5700
+ const add = (action) => {
5701
+ actions.push(action);
5702
+ const stream = streamOf(action.scope);
5703
+ const index = stream.reduce((max, row) => Math.max(max, row.index), -1);
5704
+ stream.push({
5705
+ id: "",
5706
+ index: index + 1,
5707
+ skip: 0,
5708
+ hash: "",
5709
+ timestampUtcMs: action.timestampUtcMs,
5710
+ action
5711
+ });
5712
+ };
5713
+ const targetsOf = (scope) => undoRedoTargetsOf({
5714
+ ...document,
5715
+ operations: {
5716
+ ...document.operations,
5717
+ [scope]: streamOf(scope)
5718
+ }
5719
+ }, caps, scope, reducer);
5720
+ return {
5721
+ actions,
5722
+ add,
5723
+ undoOrRedo(type, scope) {
5724
+ for (const action of undoRedoActions(caps, type, scope, targetsOf(scope))) add(action);
5725
+ }
5726
+ };
5727
+ }
5728
+ //#endregion
5729
+ export { validateModule as $, OperationSpecificationSchema as $a, reorderStateExamples as $i, isDerivedDocumentId as $n, deserializeSignature as $o, GrantSchema as $r, deriveScope as $t, documentModelHeaderReducer as A, AddOperationErrorInputSchema as Aa, buildOperationSignature as Ai, AUTH_DENIED_BY_GRANT_REASON as An, SetOperationErrorDescriptionInputSchema as Ao, createAuthState as Ar, isUndoRedo as At, RESERVED_OPERATION_NAMES as B, DeleteOperationErrorInputSchema as Ba, moveOperation as Bi, createCopyHeader as Bn, SetStateSchemaInputSchema as Bo, defaultLocalState as Br, replayDocument as Bt, zipEntries as C, undo as Ca, addChangeLogItem as Ci, DocumentModelHeaderSchema as Cn, SetModelNameInputSchema as Co, isDocumentCreator as Cr, garbageCollectDocumentOperations as Ct, computeUpgradeTransitions as D, verifyOperationSignature as Da, addOperationExample as Di, assertIsDocumentModelState as Dn, SetNameActionSchema as Do, resolveSnapshotAuth as Dr, hashDocumentStateForScope as Dt, applyUpgradeDocumentAction as E, updateStateExample as Ea, addOperationError as Ei, assertIsDocumentModelDocument as En, SetNameActionInputSchema as Eo, removeGrant as Er, groupOperationsByScope as Et, documentModelReducer as F, CodeExampleSchema as Fa, deleteOperation as Fi, createDocumentAction as Fn, SetOperationSchemaInputSchema as Fo, createState as Fr, parseResultingState as Ft, findModuleOrThrow as G, DocumentModelGlobalStateSchema as Ga, operationWithContext as Gi, hasDerivedDocumentId as Gn, UndoActionSchema as Go, HASH_ENCODING_BASE64 as Gr, sortMappedOperations as Gt, assertOperationErrorIdUnique as H, DeleteOperationInputSchema as Ha, operationExampleCreators as Hi, createSignedHeader as Hn, Set_PreferredEditorSchema as Ho, HASH_ALGORITHM_SHA1 as Hr, reshuffleByTimestamp as Ht, documentModelStateReducer as I, ConfigEntrySchema as Ia, deleteOperationError as Ii, creationActions as In, SetOperationScopeInputSchema as Io, defaultAuthState as Ir, precedes as It, findOperationOrThrow as J, ManifestSchema as Ja, reorderChangeLogItems as Ji, verify as Jn, UpdateOperationExampleInputSchema as Jo, documentModelGlobalState as Jr, withScopeRevisions as Jt, findOperationErrorOrThrow as K, DocumentModelInputSchema as Ka, redo as Ki, sign as Kn, UndoSchema as Ko, HASH_ENCODING_HEX as Kr, split as Kt, documentModelStateSchemaReducer as L, ConfigEntryTypeSchema as La, deleteOperationExample as Li, creationState as Ln, SetOperationTemplateInputSchema as Lo, defaultBaseState as Lr, prepareOperations as Lt, documentModelOperationErrorReducer as M, AddOperationInputSchema as Ma, createAction as Mi, AUTH_VERSION_UNSUPPORTED_REASON as Mn, SetOperationErrorTemplateInputSchema as Mo, createDocumentState as Mr, mapSkippedOperationsV2 as Mt, documentModelOperationExampleReducer as N, AddStateExampleInputSchema as Na, deleteChangeLogItem as Ni, DOCUMENT_DELETED_REASON as Nn, SetOperationNameInputSchema as No, createGlobalState as Nr, merge as Nt, latestVersionOf as O, AddChangeLogItemInputSchema as Oa, addStateExample as Oi, isDocumentModelDocument as On, SetOperationDescriptionInputSchema as Oo, setGrant as Or, isNoopOperation as Ot, documentModelOperationReducer as P, AuthorSchema as Pa, deleteModule as Pi, isDenied as Pn, SetOperationReducerInputSchema as Po, createLocalState as Pr, operationsAreEqual as Pt, validateInitialState as Q, OperationScopeSchema as Qa, reorderOperationExamples as Qi, deriveDocumentId as Qn, toTransportAction as Qo, AuthAdministrationMissingError as Qr, appliedOperations as Qt, documentModelVersioningReducer as R, DeleteChangeLogItemInputSchema as Ra, deleteStateExample as Ri, documentFromCreation as Rn, SetPreferredEditorActionInputSchema as Ro, defaultDocumentState as Rr, readOnly as Rt, writeFileBrowser as S, setStateSchema as Sa, actions as Si, BaseDocumentStateSchema as Sn, SetModelIdInputSchema as So, isAuthAction as Sr, filterDuplicatedOperations as St, applyDeleteDocumentAction as T, updateOperationExample as Ta, addOperation as Ti, DocumentModelSchema as Tn, SetModuleNameInputSchema as To, moveGrant as Tr, getDocumentLastModified as Tt, assertOperationExampleIdUnique as U, DeleteStateExampleInputSchema as Ua, operationFromAction as Ui, createSignedHeaderForSigner as Un, StateSchema as Uo, HASH_ALGORITHM_SHA256 as Ur, reshuffleByTimestampAndIndex as Ut, assertModuleIdUnique as V, DeleteOperationExampleInputSchema as Va, noop as Vi, createPresignedHeader as Vn, Set_NameSchema as Vo, defaultPHState as Vr, requireStateReducer as Vt, assertOperationIdUnique as W, DocumentActionSchema as Wa, operationFromOperation as Wi, createVerificationSigner as Wn, UndoActionInputSchema as Wo, HASH_ALGORITHM_SHA512 as Wr, skipHeaderOperations as Wt, isReservedOperationName as X, MoveOperationInputSchema as Xa, reorderModules as Xi, SIGNATURE_PROTOCOL as Xn, definedNonNullAnySchema as Xo, documentModelInitialLocalState as Xr, actionReferences as Xt, getAllOperationNames as Y, ModuleSchema as Ya, reorderModuleOperations as Yi, DEFAULT_SIGNATURE_POLICY as Yn, UpdateStateExampleInputSchema as Yo, documentModelInitialGlobalState as Yr, withSignaturePolicy as Yt, isValidOperationNameFormat as Z, OperationErrorSchema as Za, reorderOperationErrors as Zi, SIGNATURE_PROTOCOL_V2 as Zn, isDefinedNonNullAny as Zo, AuthAdministrationLockoutError as Zr, advanceUndoTargets as Zt, fetchFileBrowser as _, setOperationReducer as _a, groupDocumentType as _i, garbageCollect as _n, SetAuthorNameInputSchema as _o, assertAuthPreservedOnDuplicate as _r, baseCreateDocument as _t, undoRedoActions as a, setModelExtension as aa, MAX_CONDITION_NODES as ai, retractionRewrites as an, PwaConfigSchema as ao, fitCreateBaseReducer as ar, baseReducer as at, parseBulkArchive as b, setOperationTemplate as ba, actionFromAction as bi, sortOperations as bn, SetModelDescriptionInputSchema as bo, evaluate as br, diffOperations as bt, headNewDocument as c, setModuleDescription as ca, assertValidGrantUpsert as ci, undoRedoTargetsOf as cn, RedoSchema as co, MAX_SUPPORTED_AUTH_VERSION as cr, replayOperations as ct, baseLoadFromInputVersioned as d, setOperationDescription as da, evaluateGrantStack as di, operationOutcome as dn, ReorderModulesInputSchema as do, SetGrantActionInputSchema as dr, IntegrityIssueType as dt, retract as ea, GroupPrincipalNotAllowedError as ei, deriveScopeVersioned as en, PieceModuleSchema as eo, isSignaturePolicy as er, serializeSignature as es, validateModuleOperation as et, baseSaveToFileHandle as f, setOperationErrorCode as fa, evaluateGrants as fi, redoOperation as fn, ReorderOperationErrorsInputSchema as fo, applyAuthAction as fr, addUndo as ft, documentModelSaveToFileHandle as g, setOperationName as ga, documentModelDocumentType as gi, undoOperationV2 as gn, ScopeStateSchema as go, applySetGrantAction as gr, attachBranch as gt, documentModelLoadFromInput as h, setOperationErrorTemplate as ha, referencedGroupIds as hi, undoOperation as hn, RetractActionInputSchema as ho, applyRemoveGrantAction as hr, assertReplayIndices as ht, undoNeedsTargets as i, setModelDescription as ia, MAX_CONDITION_DEPTH as ii, retractedActionIds as in, PublisherSchema as io, v2RequiredProtocolVersions as ir, validateStateSchemaName as it, documentModelModuleReducer as j, AddOperationExampleInputSchema as ja, buildSignedAction as ji, AUTH_NO_GRANT_REASON as jn, SetOperationErrorNameInputSchema as jo, createBaseState as jr, mapSkippedOperations as jt, withProtocolVersions as k, AddModuleInputSchema as ka, baseActions as ki, isDocumentModelState as kn, SetOperationErrorCodeInputSchema as ko, backfillAuthState as kr, isUndo as kt, selectDocumentModelModule as l, setModuleName as la, assertValidInitialGrants as li, undoTarget as ln, ReorderChangeLogItemsInputSchema as lo, MoveGrantActionInputSchema as lr, updateDocument as lt, createZip as m, setOperationErrorName as ma, isPlainValue as mi, setPreferredEditorOperation as mn, ReorderStateExamplesInputSchema as mo, applyMoveGrantAction as mr, appendWithoutApplying as mt, serializeByKey as n, setAuthorWebsite as na, MAX_AUTH_GRANTS as ni, redoTarget as nn, PowerhouseModuleSchema as no, requestedSignaturePolicy as nr, validateOperationName as nt, undoRedoAvailabilityOf as o, setModelId as oa, assertAuthAdministrationRetained as oi, retractionTarget as on, RedoActionInputSchema as oo, AUTH_ACTION_TYPES as or, createReducer as ot, createMinimalZip as p, setOperationErrorDescription as pa, grantProblem as pi, setNameOperation as pn, ReorderOperationExamplesInputSchema as po, applyInitializeAuthAction as pr, appendRows as pt, findOperationExampleOrThrow as q, DocumentSpecificationSchema as qa, releaseNewVersion as qi, validateHeader as qn, UpdateChangeLogItemInputSchema as qo, documentModelFileExtension as qr, updateHeaderRevision as qt, undoCapabilitiesOf as r, setInitialState as ra, MAX_CAPABILITY_OPERATIONS as ri, reduceOne as rn, PowerhouseModulesSchema as ro, signaturePolicyOf as rr, validateOperations as rt, createVersionsOf as s, setModelName as sa, assertValidGrant as si, tailAppliesIncrementally as sn, RedoActionSchema as so, InitializeAuthActionInputSchema as sr, processUndoRedo as st, undoRedoBatch as t, setAuthorName as ta, InvalidGrantError as ti, positionalOperations as tn, PieceModulesSchema as to, protocolVersionsFor as tr, validateModules as tt, baseLoadFromInput as u, setName as ua, evaluateCondition as ui, undoTargetsBase as un, ReorderModuleOperationsInputSchema as uo, RemoveGrantActionInputSchema as ur, IntegrityIssueSubType as ut, getFileBrowser as v, setOperationSchema as va, groupMembershipActionTypes as vi, isDocumentAction as vn, SetAuthorWebsiteInputSchema as vo, assertAuthScopeActionAllowed as vr, checkCleanedOperationsIntegrity as vt, replayDocumentVersioned as w, updateChangeLogItem as wa, addModule as wi, DocumentModelPHStateSchema as wn, SetModuleDescriptionInputSchema as wo, mentionedGroupIds as wr, garbageCollectV2 as wt, readFileBrowser as x, setPreferredEditor as xa, actionSigner as xi, BaseDocumentHeaderSchema as xn, SetModelExtensionInputSchema as xo, initializeAuth as xr, filterDocumentOperationsResultingState as xt, isDocumentZip as y, setOperationScope as ya, actionContext as yi, nextSkipNumber as yn, SetInitialStateInputSchema as yo, decide as yr, checkOperationsIntegrity as yt, OPERATION_NAME_PATTERN as z, DeleteModuleInputSchema as za, documentModelActions as zi, upgradeDocumentAction as zn, SetPreferredEditorActionSchema as zo, defaultGlobalState as zr, removeExistingOperations as zt };
5205
5730
 
5206
- //# sourceMappingURL=document-model-CMyP_XZ8.js.map
5731
+ //# sourceMappingURL=document-model-B98EymhI.js.map