@powerhousedao/shared 6.0.0-dev.105 → 6.0.0-dev.107

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 (131) hide show
  1. package/dist/analytics/index.d.ts +42 -4
  2. package/dist/analytics/index.d.ts.map +1 -1
  3. package/dist/analytics/index.js +307 -4
  4. package/dist/analytics/index.js.map +1 -1
  5. package/dist/clis/index.d.mts +1271 -0
  6. package/dist/clis/index.d.mts.map +1 -0
  7. package/dist/clis/index.mjs +6801 -0
  8. package/dist/clis/index.mjs.map +1 -0
  9. package/dist/connect/index.d.ts +866 -1
  10. package/dist/connect/index.d.ts.map +1 -1
  11. package/dist/connect/index.js +254 -1
  12. package/dist/connect/index.js.map +1 -1
  13. package/dist/constants.d.ts +8 -0
  14. package/dist/constants.d.ts.map +1 -0
  15. package/dist/constants.js +41 -0
  16. package/dist/constants.js.map +1 -0
  17. package/dist/document-drive/index.d.ts +546 -0
  18. package/dist/document-drive/index.d.ts.map +1 -0
  19. package/dist/document-drive/index.js +956 -0
  20. package/dist/document-drive/index.js.map +1 -0
  21. package/dist/document-model/index.d.ts +3 -5
  22. package/dist/document-model/index.js +3408 -2
  23. package/dist/document-model/index.js.map +1 -1
  24. package/dist/index-dg_xL7sp.d.ts +567 -0
  25. package/dist/index-dg_xL7sp.d.ts.map +1 -0
  26. package/dist/processors/index.d.ts +2 -5
  27. package/dist/processors/index.js +116 -3
  28. package/dist/processors/index.js.map +1 -1
  29. package/dist/registry/index.d.ts +46 -0
  30. package/dist/registry/index.d.ts.map +1 -0
  31. package/dist/registry/index.js +0 -0
  32. package/dist/types-DWXYsIF1.d.ts +158 -0
  33. package/dist/types-DWXYsIF1.d.ts.map +1 -0
  34. package/dist/types-faUXKACL.d.ts +2153 -0
  35. package/dist/types-faUXKACL.d.ts.map +1 -0
  36. package/package.json +44 -4
  37. package/dist/analytics/analytics-path.d.ts +0 -36
  38. package/dist/analytics/analytics-path.d.ts.map +0 -1
  39. package/dist/analytics/analytics-path.js +0 -170
  40. package/dist/analytics/analytics-path.js.map +0 -1
  41. package/dist/analytics/analytics-period.d.ts +0 -40
  42. package/dist/analytics/analytics-period.d.ts.map +0 -1
  43. package/dist/analytics/analytics-period.js +0 -204
  44. package/dist/analytics/analytics-period.js.map +0 -1
  45. package/dist/analytics/constants.d.ts +0 -35
  46. package/dist/analytics/constants.d.ts.map +0 -1
  47. package/dist/analytics/constants.js +0 -40
  48. package/dist/analytics/constants.js.map +0 -1
  49. package/dist/analytics/types.d.ts +0 -85
  50. package/dist/analytics/types.d.ts.map +0 -1
  51. package/dist/analytics/types.js +0 -2
  52. package/dist/analytics/types.js.map +0 -1
  53. package/dist/connect/env-config.d.ts +0 -862
  54. package/dist/connect/env-config.d.ts.map +0 -1
  55. package/dist/connect/env-config.js +0 -525
  56. package/dist/connect/env-config.js.map +0 -1
  57. package/dist/document-model/core/actions.d.ts +0 -62
  58. package/dist/document-model/core/actions.d.ts.map +0 -1
  59. package/dist/document-model/core/actions.js +0 -2
  60. package/dist/document-model/core/actions.js.map +0 -1
  61. package/dist/document-model/core/constants.d.ts +0 -6
  62. package/dist/document-model/core/constants.d.ts.map +0 -1
  63. package/dist/document-model/core/constants.js +0 -8
  64. package/dist/document-model/core/constants.js.map +0 -1
  65. package/dist/document-model/core/documents.d.ts +0 -102
  66. package/dist/document-model/core/documents.d.ts.map +0 -1
  67. package/dist/document-model/core/documents.js +0 -2
  68. package/dist/document-model/core/documents.js.map +0 -1
  69. package/dist/document-model/core/operations.d.ts +0 -74
  70. package/dist/document-model/core/operations.d.ts.map +0 -1
  71. package/dist/document-model/core/operations.js +0 -2
  72. package/dist/document-model/core/operations.js.map +0 -1
  73. package/dist/document-model/core/ph-types.d.ts +0 -7
  74. package/dist/document-model/core/ph-types.d.ts.map +0 -1
  75. package/dist/document-model/core/ph-types.js +0 -2
  76. package/dist/document-model/core/ph-types.js.map +0 -1
  77. package/dist/document-model/core/signatures.d.ts +0 -52
  78. package/dist/document-model/core/signatures.d.ts.map +0 -1
  79. package/dist/document-model/core/signatures.js +0 -2
  80. package/dist/document-model/core/signatures.js.map +0 -1
  81. package/dist/document-model/core/state.d.ts +0 -38
  82. package/dist/document-model/core/state.d.ts.map +0 -1
  83. package/dist/document-model/core/state.js +0 -2
  84. package/dist/document-model/core/state.js.map +0 -1
  85. package/dist/document-model/core/types.d.ts +0 -533
  86. package/dist/document-model/core/types.d.ts.map +0 -1
  87. package/dist/document-model/core/types.js +0 -2
  88. package/dist/document-model/core/types.js.map +0 -1
  89. package/dist/document-model/core/upgrades.d.ts +0 -24
  90. package/dist/document-model/core/upgrades.d.ts.map +0 -1
  91. package/dist/document-model/core/upgrades.js +0 -2
  92. package/dist/document-model/core/upgrades.js.map +0 -1
  93. package/dist/document-model/index.d.ts.map +0 -1
  94. package/dist/document-model/types.d.ts +0 -97
  95. package/dist/document-model/types.d.ts.map +0 -1
  96. package/dist/document-model/types.js +0 -2
  97. package/dist/document-model/types.js.map +0 -1
  98. package/dist/processors/constants.d.ts +0 -4
  99. package/dist/processors/constants.d.ts.map +0 -1
  100. package/dist/processors/constants.js +0 -4
  101. package/dist/processors/constants.js.map +0 -1
  102. package/dist/processors/drive-analytics/document-processor.d.ts +0 -10
  103. package/dist/processors/drive-analytics/document-processor.d.ts.map +0 -1
  104. package/dist/processors/drive-analytics/document-processor.js +0 -43
  105. package/dist/processors/drive-analytics/document-processor.js.map +0 -1
  106. package/dist/processors/drive-analytics/drive-processor.d.ts +0 -10
  107. package/dist/processors/drive-analytics/drive-processor.d.ts.map +0 -1
  108. package/dist/processors/drive-analytics/drive-processor.js +0 -85
  109. package/dist/processors/drive-analytics/drive-processor.js.map +0 -1
  110. package/dist/processors/drive-analytics/index.d.ts +0 -10
  111. package/dist/processors/drive-analytics/index.d.ts.map +0 -1
  112. package/dist/processors/drive-analytics/index.js +0 -28
  113. package/dist/processors/drive-analytics/index.js.map +0 -1
  114. package/dist/processors/drive-analytics/types.d.ts +0 -3
  115. package/dist/processors/drive-analytics/types.d.ts.map +0 -1
  116. package/dist/processors/drive-analytics/types.js +0 -2
  117. package/dist/processors/drive-analytics/types.js.map +0 -1
  118. package/dist/processors/index.d.ts.map +0 -1
  119. package/dist/processors/relational/types.d.ts +0 -72
  120. package/dist/processors/relational/types.d.ts.map +0 -1
  121. package/dist/processors/relational/types.js +0 -45
  122. package/dist/processors/relational/types.js.map +0 -1
  123. package/dist/processors/relational/utils.d.ts +0 -29
  124. package/dist/processors/relational/utils.d.ts.map +0 -1
  125. package/dist/processors/relational/utils.js +0 -67
  126. package/dist/processors/relational/utils.js.map +0 -1
  127. package/dist/processors/types.d.ts +0 -90
  128. package/dist/processors/types.d.ts.map +0 -1
  129. package/dist/processors/types.js +0 -2
  130. package/dist/processors/types.js.map +0 -1
  131. package/dist/tsconfig.tsbuildinfo +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../document-model/index.ts"],"names":[],"mappings":"AAAA,cAAc,qBAAqB,CAAC;AACpC,cAAc,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.js","names":["createSha1Hash"],"sources":["../../document-model/crypto.ts","../../document-model/errors.ts","../../document-model/schemas.ts","../../document-model/utils.ts","../../document-model/actions.ts","../../document-model/constants.ts","../../document-model/document-type.ts","../../document-model/document-schema.ts","../../document-model/header.ts","../../document-model/documents.ts","../../document-model/operations.ts","../../document-model/reducer.ts","../../document-model/validation.ts","../../document-model/reducers.ts","../../document-model/files.ts","../../document-model/state.ts"],"sourcesContent":["import stringifyJson from \"safe-stable-stringify\";\nimport { createHash as createSha1Hash } from \"sha1-uint8array\";\nimport type { ActionSignatureContext } from \"./types.js\";\n\nexport const hashBrowser = (\n data: string | Uint8Array | ArrayBufferView | DataView,\n algorithm = \"sha1\",\n encoding = \"base64\",\n _params?: Record<string, unknown>,\n) => {\n if (![\"sha1\"].includes(algorithm)) {\n throw new Error(\n `Hashing algorithm not supported: \"${algorithm}\". Available: sha1`,\n );\n }\n\n if (![\"base64\", \"hex\"].includes(encoding)) {\n throw new Error(\n `Hash encoding not supported: \"${encoding}\". Available: base64, hex`,\n );\n }\n\n const hash = hashUIntArray(data, algorithm);\n\n if (encoding === \"hex\") {\n return uint8ArrayToHex(hash);\n }\n\n return uint8ArrayToBase64(hash);\n};\n\nfunction uint8ArrayToBase64(uint8Array: Uint8Array) {\n // Convert the Uint8Array to a binary string\n let binaryString = \"\";\n for (let i = 0; i < uint8Array.length; i++) {\n binaryString += String.fromCharCode(uint8Array[i]);\n }\n\n // Encode the binary string to base64\n const base64String = btoa(binaryString);\n return base64String;\n}\n\nfunction uint8ArrayToHex(uint8Array: Uint8Array) {\n return Array.from(uint8Array)\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nfunction hashUIntArray(\n data: string | Uint8Array | ArrayBufferView,\n algorithm = \"sha1\",\n) {\n if (![\"sha1\"].includes(algorithm)) {\n throw new Error(\"Hashing algorithm not supported: Available: sha1\");\n }\n return createSha1Hash(\"sha1\")\n .update(data as string)\n .digest();\n}\n\nexport function getUnixTimestamp(date: Date | string): string {\n return (new Date(date).getTime() / 1000).toFixed(0);\n}\n\nexport function buildOperationSignatureParams({\n documentId,\n signer,\n action,\n previousStateHash,\n}: ActionSignatureContext): [string, string, string, string] {\n const { /*id, timestamp,*/ scope, type } = action;\n return [\n /*getUnixTimestamp(timestamp)*/ getUnixTimestamp(new Date()),\n signer.app.key,\n hashBrowser(\n [documentId, scope, /*id,*/ type, stringifyJson(action.input)].join(\"\"),\n ),\n previousStateHash,\n ];\n}\n\nconst textEncode = new TextEncoder();\n\nexport function buildOperationSignatureMessage(\n params: [string, string, string, string],\n): Uint8Array {\n const message = params.join(\"\");\n const prefix = \"\\x19Signed Operation:\\n\" + message.length.toString();\n return textEncode.encode(prefix + message);\n}\n\nexport function ab2hex(ab: ArrayBuffer | ArrayBufferView): string {\n const view = ArrayBuffer.isView(ab) ? ab : new Uint8Array(ab);\n return Array.prototype.map\n .call(view, (x: number) => (\"00\" + x.toString(16)).slice(-2))\n .join(\"\");\n}\n\nexport function hex2ab(hex: string) {\n return new Uint8Array(\n hex.match(/[\\da-f]{2}/gi)?.map(function (h) {\n return parseInt(h, 16);\n }) ?? [],\n );\n}\n","import type { ZodIssue } from \"zod\";\nimport type { PHDocument } from \"./documents.js\";\nimport type { Operation } from \"./operations.js\";\n\nexport const FileSystemError = new Error(\"File system not available.\");\n\nexport class InvalidActionInputError extends Error {\n public data: unknown;\n constructor(data: unknown) {\n super();\n this.name = \"InvalidActionInputError\";\n this.data = data;\n this.message =\n this.message || `Invalid action input: ${JSON.stringify(data, null, 2)}`;\n }\n}\n\nexport class InvalidActionInputZodError extends InvalidActionInputError {\n public issues: ZodIssue[];\n\n constructor(issues: ZodIssue[]) {\n super(issues);\n this.issues = issues;\n this.name = \"InvalidActionInputZodError\";\n }\n}\n\nexport class HashMismatchError extends Error {\n protected _scope: string;\n protected _document: PHDocument;\n protected _operation: Operation;\n\n constructor(scope: string, document: PHDocument, operation: Operation) {\n super();\n this.name = \"HashMismatchError\";\n this._document = document;\n this._scope = scope;\n this._operation = operation;\n\n this.message = JSON.stringify(\n {\n error: `Hash mismatch on document ${document.header.id}, scope ${scope}, index ${operation.index}`,\n document,\n operation,\n },\n null,\n 1,\n );\n }\n\n get document() {\n return this._document;\n }\n\n get scope() {\n return this._scope;\n }\n\n get operation() {\n return this._operation;\n }\n}\n","import { z } from \"zod\";\nimport type {\n AddChangeLogItemInput,\n AddModuleInput,\n AddOperationErrorInput,\n AddOperationExampleInput,\n AddOperationInput,\n AddStateExampleInput,\n Author,\n CodeExample,\n DeleteChangeLogItemInput,\n DeleteModuleInput,\n DeleteOperationErrorInput,\n DeleteOperationExampleInput,\n DeleteOperationInput,\n DeleteStateExampleInput,\n DocumentFile,\n DocumentModelGlobalState,\n DocumentSpecification,\n LoadStateActionInput,\n LoadStateActionStateInput,\n ModuleSpecification,\n MoveOperationInput,\n OperationErrorSpecification,\n OperationSpecification,\n PruneActionInput,\n ReorderChangeLogItemsInput,\n ReorderModuleOperationsInput,\n ReorderModulesInput,\n ReorderOperationErrorsInput,\n ReorderOperationExamplesInput,\n ReorderStateExamplesInput,\n SchemaLoadStateAction,\n SchemaPruneAction,\n SchemaRedoAction,\n SchemaSetNameAction,\n SchemaUndoAction,\n ScopeState,\n SetAuthorNameInput,\n SetAuthorWebsiteInput,\n SetInitialStateInput,\n SetModelDescriptionInput,\n SetModelExtensionInput,\n SetModelIdInput,\n SetModelNameInput,\n SetModuleDescriptionInput,\n SetModuleNameInput,\n SetOperationDescriptionInput,\n SetOperationErrorCodeInput,\n SetOperationErrorDescriptionInput,\n SetOperationErrorNameInput,\n SetOperationErrorTemplateInput,\n SetOperationNameInput,\n SetOperationReducerInput,\n SetOperationSchemaInput,\n SetOperationScopeInput,\n SetOperationTemplateInput,\n SetStateSchemaInput,\n State,\n UpdateChangeLogItemInput,\n UpdateOperationExampleInput,\n UpdateStateExampleInput,\n} from \"./types.js\";\n\ntype definedNonNullAny = {};\n\nexport const isDefinedNonNullAny = (v: any): v is definedNonNullAny =>\n v !== undefined && v !== null;\n\nexport const definedNonNullAnySchema = z\n .any()\n .refine((v) => isDefinedNonNullAny(v));\n\nexport const Load_StateSchema = z.enum([\"LOAD_STATE\"]);\n\nexport const PruneSchema = z.enum([\"PRUNE\"]);\n\nexport const RedoSchema = z.enum([\"REDO\"]);\n\nexport const Set_NameSchema = z.enum([\"SET_NAME\"]);\n\nexport const UndoSchema = z.enum([\"UNDO\"]);\n\nexport function OperationScopeSchema(): z.ZodString {\n return z.string();\n}\n\nexport function DocumentActionSchema() {\n return z.union([\n LoadStateActionSchema(),\n PruneActionSchema(),\n RedoActionSchema(),\n SetNameActionSchema(),\n UndoActionSchema(),\n ]);\n}\n\nexport function DocumentFileSchema(): z.ZodObject<Properties<DocumentFile>> {\n return z.object({\n __typename: z.literal(\"DocumentFile\").optional(),\n data: z.string(),\n extension: z.string().nullable(),\n fileName: z.string().nullable(),\n mimeType: z.string(),\n });\n}\n\nexport function LoadStateActionSchema(): z.ZodObject<\n Properties<SchemaLoadStateAction>\n> {\n return z.object({\n id: z.string(),\n timestampUtcMs: z.string(),\n input: z.lazy(() => LoadStateActionInputSchema()),\n type: Load_StateSchema,\n scope: OperationScopeSchema(),\n });\n}\n\nexport function LoadStateActionInputSchema(): z.ZodObject<\n Properties<LoadStateActionInput>\n> {\n return z.object({\n operations: z.number(),\n state: z.lazy(() => LoadStateActionStateInputSchema()),\n });\n}\n\nexport function LoadStateActionStateInputSchema(): z.ZodObject<\n Properties<LoadStateActionStateInput>\n> {\n return z.object({\n data: z.unknown().nullish(),\n name: z.string(),\n });\n}\n\nexport function PruneActionSchema(): z.ZodObject<\n Properties<SchemaPruneAction>\n> {\n return z.object({\n id: z.string(),\n timestampUtcMs: z.string(),\n input: z.lazy(() => PruneActionInputSchema()),\n type: PruneSchema,\n scope: OperationScopeSchema(),\n });\n}\n\nexport function PruneActionInputSchema(): z.ZodObject<\n Properties<PruneActionInput>\n> {\n return z.object({\n end: z.number().nullish(),\n start: z.number().nullish(),\n });\n}\n\nexport function RedoActionInputSchema() {\n return z.object({ count: z.number() });\n}\n\nexport function RedoActionSchema(): z.ZodObject<Properties<SchemaRedoAction>> {\n return z.object({\n id: z.string(),\n timestampUtcMs: z.string().datetime(),\n input: RedoActionInputSchema(),\n type: RedoSchema,\n scope: OperationScopeSchema(),\n });\n}\n\nexport function SetNameActionInputSchema() {\n return z.object({ name: z.string() });\n}\n\nexport function SetNameActionSchema(): z.ZodObject<\n Properties<SchemaSetNameAction>\n> {\n return z.object({\n id: z.string(),\n timestampUtcMs: z.string().datetime(),\n input: SetNameActionInputSchema(),\n type: Set_NameSchema,\n scope: z.literal(\"global\"),\n });\n}\n\n// export function SetNameOperationSchema(): z.ZodObject<\n// Properties<SetNameOperation>\n// > {\n// return z.object({\n// __typename: z.literal(\"SetNameOperation\").optional(),\n// hash: z.string(),\n// index: z.number(),\n// input: z.string(),\n// timestampUtcMs: z.string().datetime(),\n// type: z.string(),\n// });\n// }\n\nexport function UndoActionInputSchema() {\n return z.object({ count: z.number() });\n}\n\nexport function UndoActionSchema(): z.ZodObject<Properties<SchemaUndoAction>> {\n return z.object({\n id: z.string(),\n timestampUtcMs: z.string().datetime(),\n input: UndoActionInputSchema(),\n type: UndoSchema,\n scope: OperationScopeSchema(),\n });\n}\n\ntype Properties<T> = Required<{\n [K in keyof T]: z.ZodType<T[K], T[K]>;\n}>;\n\nexport function AddChangeLogItemInputSchema(): z.ZodObject<\n Properties<AddChangeLogItemInput>\n> {\n return z.object({\n __typename: z.literal(\"AddChangeLogItemInput\").optional(),\n content: z.string(),\n id: z.string(),\n insertBefore: z.string().nullable(),\n });\n}\n\nexport function AddModuleInputSchema(): z.ZodObject<\n Properties<AddModuleInput>\n> {\n return z.object({\n description: z.string().nullish(),\n id: z.string(),\n name: z.string(),\n });\n}\n\nexport function AddOperationErrorInputSchema(): z.ZodObject<\n Properties<AddOperationErrorInput>\n> {\n return z.object({\n errorCode: z.string().nullish(),\n errorDescription: z.string().nullish(),\n errorName: z.string().nullish(),\n errorTemplate: z.string().nullish(),\n id: z.string(),\n operationId: z.string(),\n });\n}\n\nexport function AddOperationExampleInputSchema(): z.ZodObject<\n Properties<AddOperationExampleInput>\n> {\n return z.object({\n example: z.string(),\n id: z.string(),\n operationId: z.string(),\n });\n}\n\nexport function AddOperationInputSchema(): z.ZodObject<\n Properties<AddOperationInput>\n> {\n return z.object({\n description: z.string().nullish(),\n id: z.string(),\n moduleId: z.string(),\n name: z.string(),\n reducer: z.string().nullish(),\n schema: z.string().nullish(),\n template: z.string().nullish(),\n scope: OperationScopeSchema().nullish(),\n });\n}\n\nexport function AddStateExampleInputSchema(): z.ZodObject<\n Properties<AddStateExampleInput>\n> {\n return z.object({\n scope: z.string(),\n example: z.string(),\n id: z.string(),\n insertBefore: z.string().nullish(),\n });\n}\n\nexport function AuthorSchema(): z.ZodObject<Properties<Author>> {\n return z.object({\n __typename: z.literal(\"Author\").optional(),\n name: z.string(),\n website: z.string().nullable(),\n });\n}\n\nexport function CodeExampleSchema(): z.ZodObject<Properties<CodeExample>> {\n return z.object({\n __typename: z.literal(\"CodeExample\").optional(),\n id: z.string(),\n value: z.string(),\n });\n}\n\nexport function DeleteChangeLogItemInputSchema(): z.ZodObject<\n Properties<DeleteChangeLogItemInput>\n> {\n return z.object({\n __typename: z.literal(\"DeleteChangeLogItemInput\").optional(),\n id: z.string(),\n });\n}\n\nexport function DeleteModuleInputSchema(): z.ZodObject<\n Properties<DeleteModuleInput>\n> {\n return z.object({\n id: z.string(),\n });\n}\n\nexport function DeleteOperationErrorInputSchema(): z.ZodObject<\n Properties<DeleteOperationErrorInput>\n> {\n return z.object({\n id: z.string(),\n });\n}\n\nexport function DeleteOperationExampleInputSchema(): z.ZodObject<\n Properties<DeleteOperationExampleInput>\n> {\n return z.object({\n id: z.string(),\n });\n}\n\nexport function DeleteOperationInputSchema(): z.ZodObject<\n Properties<DeleteOperationInput>\n> {\n return z.object({\n id: z.string(),\n });\n}\n\nexport function DeleteStateExampleInputSchema(): z.ZodObject<\n Properties<DeleteStateExampleInput>\n> {\n return z.object({\n scope: z.string(),\n id: z.string(),\n });\n}\n\nexport function DocumentModelInputSchema() {\n return z.union([\n AddChangeLogItemInputSchema(),\n AddModuleInputSchema(),\n AddOperationErrorInputSchema(),\n AddOperationExampleInputSchema(),\n AddOperationInputSchema(),\n AddStateExampleInputSchema(),\n DeleteChangeLogItemInputSchema(),\n DeleteModuleInputSchema(),\n DeleteOperationErrorInputSchema(),\n DeleteOperationExampleInputSchema(),\n DeleteOperationInputSchema(),\n DeleteStateExampleInputSchema(),\n MoveOperationInputSchema(),\n ReorderChangeLogItemsInputSchema(),\n ReorderModuleOperationsInputSchema(),\n ReorderModulesInputSchema(),\n ReorderOperationErrorsInputSchema(),\n ReorderOperationExamplesInputSchema(),\n ReorderStateExamplesInputSchema(),\n SetAuthorNameInputSchema(),\n SetAuthorWebsiteInputSchema(),\n SetInitialStateInputSchema(),\n SetModelDescriptionInputSchema(),\n SetModelExtensionInputSchema(),\n SetModelIdInputSchema(),\n SetModelNameInputSchema(),\n SetModuleDescriptionInputSchema(),\n SetModuleNameInputSchema(),\n SetOperationDescriptionInputSchema(),\n SetOperationErrorCodeInputSchema(),\n SetOperationErrorDescriptionInputSchema(),\n SetOperationErrorNameInputSchema(),\n SetOperationErrorTemplateInputSchema(),\n SetOperationNameInputSchema(),\n SetOperationReducerInputSchema(),\n SetOperationSchemaInputSchema(),\n SetOperationTemplateInputSchema(),\n SetStateSchemaInputSchema(),\n UpdateChangeLogItemInputSchema(),\n UpdateOperationExampleInputSchema(),\n UpdateStateExampleInputSchema(),\n ]);\n}\n\nexport function DocumentModelGlobalStateSchema(): z.ZodObject<\n Properties<DocumentModelGlobalState>\n> {\n return z.object({\n __typename: z.literal(\"DocumentModelGlobalState\").optional(),\n author: AuthorSchema(),\n description: z.string(),\n extension: z.string(),\n id: z.string(),\n name: z.string(),\n specifications: z.array(DocumentSpecificationSchema()),\n });\n}\n\nexport function DocumentSpecificationSchema(): z.ZodObject<\n Properties<DocumentSpecification>\n> {\n return z.object({\n __typename: z.literal(\"DocumentSpecification\").optional(),\n changeLog: z.array(z.string()),\n modules: z.array(ModuleSchema()),\n state: ScopeStateSchema(),\n version: z.number().int(),\n });\n}\n\nexport function ModuleSchema(): z.ZodObject<Properties<ModuleSpecification>> {\n return z.object({\n __typename: z.literal(\"ModuleSpecification\").optional(),\n description: z.string().nullable(),\n id: z.string(),\n name: z.string(),\n operations: z.array(OperationSpecificationSchema()),\n });\n}\n\nexport function MoveOperationInputSchema(): z.ZodObject<\n Properties<MoveOperationInput>\n> {\n return z.object({\n newModuleId: z.string(),\n operationId: z.string(),\n });\n}\n\nexport function OperationSpecificationSchema(): z.ZodObject<\n Properties<OperationSpecification>\n> {\n return z.object({\n __typename: z.literal(\"OperationSpecification\").optional(),\n description: z.string().nullable(),\n errors: z.array(OperationErrorSchema()),\n examples: z.array(CodeExampleSchema()),\n id: z.string(),\n name: z.string().nullable(),\n reducer: z.string().nullable(),\n schema: z.string().nullable(),\n template: z.string().nullable(),\n scope: OperationScopeSchema(),\n });\n}\n\nexport function OperationErrorSchema(): z.ZodObject<\n Properties<OperationErrorSpecification>\n> {\n return z.object({\n __typename: z.literal(\"OperationErrorSpecification\").optional(),\n code: z.string().nullable(),\n description: z.string().nullable(),\n id: z.string(),\n name: z.string().nullable(),\n template: z.string().nullable(),\n });\n}\n\nexport function ReorderChangeLogItemsInputSchema(): z.ZodObject<\n Properties<ReorderChangeLogItemsInput>\n> {\n return z.object({\n __typename: z.literal(\"ReorderChangeLogItemsInput\").optional(),\n order: z.array(z.string()),\n });\n}\n\nexport function ReorderModuleOperationsInputSchema(): z.ZodObject<\n Properties<ReorderModuleOperationsInput>\n> {\n return z.object({\n moduleId: z.string(),\n order: z.array(z.string()),\n });\n}\n\nexport function ReorderModulesInputSchema(): z.ZodObject<\n Properties<ReorderModulesInput>\n> {\n return z.object({\n order: z.array(z.string()),\n });\n}\n\nexport function ReorderOperationErrorsInputSchema(): z.ZodObject<\n Properties<ReorderOperationErrorsInput>\n> {\n return z.object({\n operationId: z.string(),\n order: z.array(z.string()),\n });\n}\n\nexport function ReorderOperationExamplesInputSchema(): z.ZodObject<\n Properties<ReorderOperationExamplesInput>\n> {\n return z.object({\n operationId: z.string(),\n order: z.array(z.string()),\n });\n}\n\nexport function ReorderStateExamplesInputSchema(): z.ZodObject<\n Properties<ReorderStateExamplesInput>\n> {\n return z.object({\n scope: z.string(),\n order: z.array(z.string()),\n });\n}\n\nexport function SetAuthorNameInputSchema(): z.ZodObject<\n Properties<SetAuthorNameInput>\n> {\n return z.object({\n authorName: z.string(),\n });\n}\n\nexport function SetAuthorWebsiteInputSchema(): z.ZodObject<\n Properties<SetAuthorWebsiteInput>\n> {\n return z.object({\n authorWebsite: z.string(),\n });\n}\n\nexport function SetInitialStateInputSchema(): z.ZodObject<\n Properties<SetInitialStateInput>\n> {\n return z.object({\n scope: z.string(),\n initialValue: z.string(),\n });\n}\n\nexport function SetModelDescriptionInputSchema(): z.ZodObject<\n Properties<SetModelDescriptionInput>\n> {\n return z.object({\n description: z.string(),\n });\n}\n\nexport function SetModelExtensionInputSchema(): z.ZodObject<\n Properties<SetModelExtensionInput>\n> {\n return z.object({\n extension: z.string(),\n });\n}\n\nexport function SetModelIdInputSchema(): z.ZodObject<\n Properties<SetModelIdInput>\n> {\n return z.object({\n id: z.string(),\n });\n}\n\nexport function SetModelNameInputSchema(): z.ZodObject<\n Properties<SetModelNameInput>\n> {\n return z.object({\n name: z.string(),\n });\n}\n\nexport function SetModuleDescriptionInputSchema(): z.ZodObject<\n Properties<SetModuleDescriptionInput>\n> {\n return z.object({\n description: z.string().nullish(),\n id: z.string(),\n });\n}\n\nexport function SetModuleNameInputSchema(): z.ZodObject<\n Properties<SetModuleNameInput>\n> {\n return z.object({\n id: z.string(),\n name: z.string().nullish(),\n });\n}\n\nexport function SetOperationDescriptionInputSchema(): z.ZodObject<\n Properties<SetOperationDescriptionInput>\n> {\n return z.object({\n description: z.string().nullish(),\n id: z.string(),\n });\n}\n\nexport function SetOperationErrorCodeInputSchema(): z.ZodObject<\n Properties<SetOperationErrorCodeInput>\n> {\n return z.object({\n errorCode: z.string().nullish(),\n id: z.string(),\n });\n}\n\nexport function SetOperationErrorDescriptionInputSchema(): z.ZodObject<\n Properties<SetOperationErrorDescriptionInput>\n> {\n return z.object({\n errorDescription: z.string().nullish(),\n id: z.string(),\n });\n}\n\nexport function SetOperationErrorNameInputSchema(): z.ZodObject<\n Properties<SetOperationErrorNameInput>\n> {\n return z.object({\n errorName: z.string().nullish(),\n id: z.string(),\n });\n}\n\nexport function SetOperationErrorTemplateInputSchema(): z.ZodObject<\n Properties<SetOperationErrorTemplateInput>\n> {\n return z.object({\n errorTemplate: z.string().nullish(),\n id: z.string(),\n });\n}\n\nexport function SetOperationNameInputSchema(): z.ZodObject<\n Properties<SetOperationNameInput>\n> {\n return z.object({\n id: z.string(),\n name: z.string().nullish(),\n });\n}\n\nexport function SetOperationScopeInputSchema(): z.ZodObject<\n Properties<SetOperationScopeInput>\n> {\n return z.object({\n id: z.string(),\n scope: OperationScopeSchema(),\n });\n}\n\nexport function SetOperationReducerInputSchema(): z.ZodObject<\n Properties<SetOperationReducerInput>\n> {\n return z.object({\n id: z.string(),\n reducer: z.string().nullish(),\n });\n}\n\nexport function SetOperationSchemaInputSchema(): z.ZodObject<\n Properties<SetOperationSchemaInput>\n> {\n return z.object({\n id: z.string(),\n schema: z.string().nullish(),\n });\n}\n\nexport function SetOperationTemplateInputSchema(): z.ZodObject<\n Properties<SetOperationTemplateInput>\n> {\n return z.object({\n id: z.string(),\n template: z.string().nullish(),\n });\n}\n\nexport function SetStateSchemaInputSchema(): z.ZodObject<\n Properties<SetStateSchemaInput>\n> {\n return z.object({\n scope: z.string(),\n schema: z.string(),\n });\n}\n\nexport function StateSchema(): z.ZodObject<Properties<State>> {\n return z.object({\n __typename: z.literal(\"State\").optional(),\n examples: z.array(CodeExampleSchema()),\n initialValue: z.string(),\n schema: z.string(),\n });\n}\n\nexport function ScopeStateSchema(): z.ZodObject<Properties<ScopeState>> {\n return z.object({\n global: StateSchema(),\n local: StateSchema(),\n });\n}\n\nexport function UpdateChangeLogItemInputSchema(): z.ZodObject<\n Properties<UpdateChangeLogItemInput>\n> {\n return z.object({\n __typename: z.literal(\"UpdateChangeLogItemInput\").optional(),\n id: z.string(),\n newContent: z.string(),\n });\n}\n\nexport function UpdateOperationExampleInputSchema(): z.ZodObject<\n Properties<UpdateOperationExampleInput>\n> {\n return z.object({\n example: z.string(),\n id: z.string(),\n });\n}\n\nexport function UpdateStateExampleInputSchema(): z.ZodObject<\n Properties<UpdateStateExampleInput>\n> {\n return z.object({\n scope: z.string(),\n id: z.string(),\n newExample: z.string(),\n });\n}\n","import { hashBrowser } from \"./crypto.js\";\n\nexport function generateId(method?: \"UUIDv4\"): string {\n if (method && method.toString() !== \"UUIDv4\") {\n throw new Error(\n `Id generation method not supported: \"${method.toString()}\"`,\n );\n }\n\n return globalThis.crypto.randomUUID();\n}\n\n/**\n * Derives a deterministic operation ID from stable properties.\n */\nexport function deriveOperationId(\n documentId: string,\n scope: string,\n branch: string,\n actionId: string,\n): string {\n const input = `${documentId}:${scope}:${branch}:${actionId}`;\n return hashBrowser(input, \"sha1\", \"hex\").slice(0, 32);\n}\n","import { ZodError } from \"zod\";\nimport {\n ab2hex,\n buildOperationSignatureMessage,\n buildOperationSignatureParams,\n hex2ab,\n} from \"./crypto.js\";\nimport type { PHDocument } from \"./documents.js\";\nimport {\n InvalidActionInputError,\n InvalidActionInputZodError,\n} from \"./errors.js\";\nimport type { Operation, OperationContext } from \"./operations.js\";\nimport {\n AddChangeLogItemInputSchema,\n AddModuleInputSchema,\n AddOperationErrorInputSchema,\n AddOperationExampleInputSchema,\n AddOperationInputSchema,\n AddStateExampleInputSchema,\n DeleteChangeLogItemInputSchema,\n DeleteModuleInputSchema,\n DeleteOperationErrorInputSchema,\n DeleteOperationExampleInputSchema,\n DeleteOperationInputSchema,\n DeleteStateExampleInputSchema,\n LoadStateActionInputSchema,\n MoveOperationInputSchema,\n PruneActionInputSchema,\n RedoActionInputSchema,\n ReorderChangeLogItemsInputSchema,\n ReorderModuleOperationsInputSchema,\n ReorderModulesInputSchema,\n ReorderOperationErrorsInputSchema,\n ReorderOperationExamplesInputSchema,\n ReorderStateExamplesInputSchema,\n SetAuthorNameInputSchema,\n SetAuthorWebsiteInputSchema,\n SetInitialStateInputSchema,\n SetModelDescriptionInputSchema,\n SetModelExtensionInputSchema,\n SetModelIdInputSchema,\n SetModelNameInputSchema,\n SetModuleDescriptionInputSchema,\n SetModuleNameInputSchema,\n SetNameActionInputSchema,\n SetOperationDescriptionInputSchema,\n SetOperationErrorCodeInputSchema,\n SetOperationErrorDescriptionInputSchema,\n SetOperationErrorNameInputSchema,\n SetOperationErrorTemplateInputSchema,\n SetOperationNameInputSchema,\n SetOperationReducerInputSchema,\n SetOperationSchemaInputSchema,\n SetOperationScopeInputSchema,\n SetOperationTemplateInputSchema,\n SetStateSchemaInputSchema,\n UndoActionInputSchema,\n UpdateChangeLogItemInputSchema,\n UpdateOperationExampleInputSchema,\n UpdateStateExampleInputSchema,\n} from \"./schemas.js\";\nimport type {\n ActionSigner,\n AppActionSigner,\n Signature,\n UserActionSigner,\n} from \"./signatures.js\";\nimport type { PHBaseState } from \"./state.js\";\nimport type {\n ActionSignatureContext,\n ActionSigningHandler,\n ActionVerificationHandler,\n AddChangeLogItemAction,\n AddChangeLogItemInput,\n AddModuleAction,\n AddModuleInput,\n AddOperationAction,\n AddOperationErrorAction,\n AddOperationErrorInput,\n AddOperationExampleAction,\n AddOperationExampleInput,\n AddOperationInput,\n AddStateExampleAction,\n AddStateExampleInput,\n DeleteChangeLogItemAction,\n DeleteChangeLogItemInput,\n DeleteModuleAction,\n DeleteModuleInput,\n DeleteOperationAction,\n DeleteOperationErrorAction,\n DeleteOperationErrorInput,\n DeleteOperationExampleAction,\n DeleteOperationExampleInput,\n DeleteOperationInput,\n DeleteStateExampleAction,\n DeleteStateExampleInput,\n LoadStateAction,\n MoveOperationAction,\n MoveOperationInput,\n NOOPAction,\n RedoAction,\n Reducer,\n ReleaseNewVersionAction,\n ReorderChangeLogItemsAction,\n ReorderChangeLogItemsInput,\n ReorderModuleOperationsAction,\n ReorderModuleOperationsInput,\n ReorderModulesAction,\n ReorderModulesInput,\n ReorderOperationErrorsAction,\n ReorderOperationErrorsInput,\n ReorderOperationExamplesAction,\n ReorderOperationExamplesInput,\n ReorderStateExamplesAction,\n ReorderStateExamplesInput,\n SchemaPruneAction,\n SetAuthorNameAction,\n SetAuthorNameInput,\n SetAuthorWebsiteAction,\n SetAuthorWebsiteInput,\n SetInitialStateAction,\n SetInitialStateInput,\n SetModelDescriptionAction,\n SetModelDescriptionInput,\n SetModelExtensionAction,\n SetModelExtensionInput,\n SetModelIdAction,\n SetModelIdInput,\n SetModelNameAction,\n SetModelNameInput,\n SetModuleDescriptionAction,\n SetModuleDescriptionInput,\n SetModuleNameAction,\n SetModuleNameInput,\n SetNameAction,\n SetOperationDescriptionAction,\n SetOperationDescriptionInput,\n SetOperationErrorCodeAction,\n SetOperationErrorCodeInput,\n SetOperationErrorDescriptionAction,\n SetOperationErrorDescriptionInput,\n SetOperationErrorNameAction,\n SetOperationErrorNameInput,\n SetOperationErrorTemplateAction,\n SetOperationErrorTemplateInput,\n SetOperationNameAction,\n SetOperationNameInput,\n SetOperationReducerAction,\n SetOperationReducerInput,\n SetOperationSchemaAction,\n SetOperationSchemaInput,\n SetOperationScopeAction,\n SetOperationScopeInput,\n SetOperationTemplateAction,\n SetOperationTemplateInput,\n SetStateSchemaAction,\n SetStateSchemaInput,\n UndoAction,\n UpdateChangeLogItemAction,\n UpdateChangeLogItemInput,\n UpdateOperationExampleAction,\n UpdateOperationExampleInput,\n UpdateStateExampleAction,\n UpdateStateExampleInput,\n} from \"./types.js\";\nimport { deriveOperationId, generateId } from \"./utils.js\";\n\n/**\n * Cancels the last `count` operations.\n *\n * @param count - Number of operations to cancel\n * @category Actions\n */\nexport const undo = (count = 1, scope = \"global\") =>\n createAction<UndoAction>(\n \"UNDO\",\n { count },\n undefined,\n UndoActionInputSchema,\n scope,\n );\n\n/**\n * Cancels the last `count` {@link undo | UNDO} operations.\n *\n * @param count - Number of UNDO operations to cancel\n * @category Actions\n */\nexport const redo = (count = 1, scope = \"global\") =>\n createAction<RedoAction>(\n \"REDO\",\n { count },\n undefined,\n RedoActionInputSchema,\n scope,\n );\n\n/**\n * Joins multiple operations into a single {@link loadState | LOAD_STATE} operation.\n *\n * @remarks\n * Useful to keep operations history smaller. Operations to prune are selected by index,\n * similar to the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | slice} method in Arrays.\n *\n * @param start - Index of the first operation to prune\n * @param end - Index of the last operation to prune\n * @category Actions\n */\nexport const prune = (start?: number, end?: number, scope = \"global\") =>\n createAction<SchemaPruneAction>(\n \"PRUNE\",\n { start, end },\n undefined,\n PruneActionInputSchema,\n scope,\n );\n\n/**\n * Replaces the state of the document.\n *\n * @remarks\n * This action shouldn't be used directly. It is dispatched by the {@link prune} action.\n *\n * @param state - State to be set in the document.\n * @param operations - Number of operations that were removed from the previous state.\n * @category Actions\n */\nexport const loadState = <TState extends PHBaseState = PHBaseState>(\n state: TState & { name: string },\n operations: number,\n) =>\n createAction<LoadStateAction>(\n \"LOAD_STATE\",\n { state, operations },\n undefined,\n LoadStateActionInputSchema,\n );\n\nexport const noop = (scope = \"global\") =>\n createAction<NOOPAction>(\"NOOP\", {}, undefined, undefined, scope);\n\n// TODO improve base actions type\n\n/**\n * Helper function to be used by action creators.\n *\n * @remarks\n * Creates an action with the given type and input properties. The input\n * properties default to an empty object.\n *\n * @typeParam A - Type of the action to be returned.\n *\n * @param type - The type of the action.\n * @param input - The input properties of the action.\n * @param attachments - The attachments included in the action.\n * @param validator - The validator to use for the input properties.\n * @param scope - The scope of the action, can either be 'global' or 'local'.\n * @param skip - The number of operations to skip before this new action is applied.\n *\n * @throws Error if the type is empty or not a string.\n *\n * @returns The new action.\n */\nexport function createAction<TAction extends Action>(\n type: TAction[\"type\"],\n input?: TAction[\"input\"],\n attachments?: TAction[\"attachments\"],\n validator?: () => { parse(v: unknown): TAction[\"input\"] },\n scope: Action[\"scope\"] = \"global\",\n): TAction {\n if (!type) throw new Error(\"Empty action type\");\n if (typeof type !== \"string\")\n throw new Error(`Invalid action type: ${JSON.stringify(type)}`);\n\n const action: Action = {\n id: generateId(),\n timestampUtcMs: new Date().toISOString(),\n type,\n input,\n scope,\n };\n\n if (attachments) action.attachments = attachments;\n\n try {\n validator?.().parse(action.input);\n } catch (error) {\n if (error instanceof ZodError) {\n throw new InvalidActionInputZodError(error.issues);\n }\n throw new InvalidActionInputError(error);\n }\n\n return action as TAction;\n}\n\n/**\n * This function should be used instead of { ...action } to ensure\n * that extra properties are not included in the action.\n */\nexport const actionFromAction = (action: Action): Action => {\n return {\n id: action.id,\n timestampUtcMs: action.timestampUtcMs,\n type: action.type,\n input: action.input,\n scope: action.scope,\n context: action.context,\n attachments: action.attachments,\n };\n};\n\nexport const operationFromAction = (\n action: Action,\n index: number,\n skip: number,\n context: OperationContext,\n): Operation => {\n return {\n ...action,\n action,\n id: deriveOperationId(\n context.documentId,\n context.scope,\n context.branch,\n action.id,\n ),\n timestampUtcMs: action.timestampUtcMs,\n hash: \"\",\n error: undefined,\n\n index,\n skip,\n };\n};\n\nexport const operationFromOperation = (\n operation: Operation,\n index: number,\n skip: number,\n context: OperationContext,\n): Operation => {\n const id = deriveOperationId(\n context.documentId,\n context.scope,\n context.branch,\n operation.action.id,\n );\n\n return {\n ...operation,\n hash: \"\",\n error: undefined,\n index,\n skip,\n id,\n };\n};\n\nexport const operationWithContext = (\n operation: Operation,\n context: ActionContext,\n): Operation => {\n if (!operation.action) {\n throw new Error(\"Operation has no action\");\n }\n\n return {\n ...operation,\n action: {\n ...operation.action,\n context,\n },\n };\n};\n\nexport const actionContext = (): ActionContext => ({});\n\nexport const actionSigner = (\n user: UserActionSigner,\n app: AppActionSigner,\n signatures: Signature[] = [],\n): ActionSigner => ({\n user,\n app,\n signatures,\n});\n\nexport async function buildOperationSignature(\n context: ActionSignatureContext,\n signMethod: ActionSigningHandler,\n): Promise<Signature> {\n const params = buildOperationSignatureParams(context);\n const message = buildOperationSignatureMessage(params);\n const signature = await signMethod(message);\n return [...params, `0x${ab2hex(signature)}`];\n}\n\nexport async function buildSignedAction<\n TState extends PHBaseState = PHBaseState,\n>(\n action: Action,\n reducer: Reducer<TState>,\n document: PHDocument<TState>,\n signer: ActionSigner,\n signHandler: ActionSigningHandler,\n) {\n const result = reducer(document, action, undefined, {\n //reuseHash: true,\n reuseOperationResultingState: true,\n });\n const scopeOperations = result.operations[action.scope];\n if (!scopeOperations) {\n throw new Error(`No operations found for scope: ${action.scope}`);\n }\n const operation = scopeOperations.at(-1);\n if (!operation) {\n throw new Error(\"Action was not applied\");\n }\n\n const previousStateHash = scopeOperations.at(-2)?.hash ?? \"\";\n const signature = await buildOperationSignature(\n {\n documentId: document.header.id,\n signer,\n action,\n previousStateHash,\n },\n signHandler,\n );\n\n const actionContext: ActionContext = {\n signer: actionSigner(signer.user, signer.app, [\n ...signer.signatures,\n signature,\n ]),\n };\n\n return operationWithContext(operation, actionContext);\n}\n\nexport async function verifyOperationSignature(\n signature: Signature,\n signer: Omit<ActionSigner, \"signatures\">,\n verifyHandler: ActionVerificationHandler,\n) {\n const publicKey = signer.app.key;\n const params = signature.slice(0, 4) as [string, string, string, string];\n const signatureBytes = hex2ab(signature[4]);\n const expectedMessage = buildOperationSignatureMessage(params);\n return verifyHandler(publicKey, signatureBytes, expectedMessage);\n}\n\n/**\n * Changes the name of the document.\n *\n * @param name - The name to be set in the document.\n * @category Actions\n */\nexport const setName = (name: string | { name: string }) =>\n createAction<SetNameAction>(\n \"SET_NAME\",\n typeof name === \"string\" ? { name } : name,\n undefined,\n SetNameActionInputSchema,\n // TODO: THIS IS A BUG: This needs to be changed to a HEADER scope action if it's changing the header.\n \"global\",\n );\nexport const setModelName = (input: SetModelNameInput) =>\n createAction<SetModelNameAction>(\n \"SET_MODEL_NAME\",\n { ...input },\n undefined,\n SetModelNameInputSchema,\n \"global\",\n );\n\nexport const setModelId = (input: SetModelIdInput) =>\n createAction<SetModelIdAction>(\n \"SET_MODEL_ID\",\n { ...input },\n undefined,\n SetModelIdInputSchema,\n \"global\",\n );\n\nexport const setModelExtension = (input: SetModelExtensionInput) =>\n createAction<SetModelExtensionAction>(\n \"SET_MODEL_EXTENSION\",\n { ...input },\n undefined,\n SetModelExtensionInputSchema,\n \"global\",\n );\n\nexport const setModelDescription = (input: SetModelDescriptionInput) =>\n createAction<SetModelDescriptionAction>(\n \"SET_MODEL_DESCRIPTION\",\n { ...input },\n undefined,\n SetModelDescriptionInputSchema,\n \"global\",\n );\n\nexport const setAuthorName = (input: SetAuthorNameInput) =>\n createAction<SetAuthorNameAction>(\n \"SET_AUTHOR_NAME\",\n { ...input },\n undefined,\n SetAuthorNameInputSchema,\n \"global\",\n );\n\nexport const setAuthorWebsite = (input: SetAuthorWebsiteInput) =>\n createAction<SetAuthorWebsiteAction>(\n \"SET_AUTHOR_WEBSITE\",\n { ...input },\n undefined,\n SetAuthorWebsiteInputSchema,\n \"global\",\n );\n\nexport const addModule = (input: AddModuleInput) =>\n createAction<AddModuleAction>(\n \"ADD_MODULE\",\n { ...input },\n undefined,\n AddModuleInputSchema,\n \"global\",\n );\n\nexport const setModuleName = (input: SetModuleNameInput) =>\n createAction<SetModuleNameAction>(\n \"SET_MODULE_NAME\",\n { ...input },\n undefined,\n SetModuleNameInputSchema,\n \"global\",\n );\n\nexport const setModuleDescription = (input: SetModuleDescriptionInput) =>\n createAction<SetModuleDescriptionAction>(\n \"SET_MODULE_DESCRIPTION\",\n { ...input },\n undefined,\n SetModuleDescriptionInputSchema,\n \"global\",\n );\n\nexport const deleteModule = (input: DeleteModuleInput) =>\n createAction<DeleteModuleAction>(\n \"DELETE_MODULE\",\n { ...input },\n undefined,\n DeleteModuleInputSchema,\n \"global\",\n );\n\nexport const reorderModules = (input: ReorderModulesInput) =>\n createAction<ReorderModulesAction>(\n \"REORDER_MODULES\",\n { ...input },\n undefined,\n ReorderModulesInputSchema,\n \"global\",\n );\n\nexport const addOperation = (input: AddOperationInput) =>\n createAction<AddOperationAction>(\n \"ADD_OPERATION\",\n { ...input },\n undefined,\n AddOperationInputSchema,\n \"global\",\n );\n\nexport const setOperationName = (input: SetOperationNameInput) =>\n createAction<SetOperationNameAction>(\n \"SET_OPERATION_NAME\",\n { ...input },\n undefined,\n SetOperationNameInputSchema,\n \"global\",\n );\n\nexport const setOperationScope = (input: SetOperationScopeInput) =>\n createAction<SetOperationScopeAction>(\n \"SET_OPERATION_SCOPE\",\n { ...input },\n undefined,\n SetOperationScopeInputSchema,\n \"global\",\n );\n\nexport const setOperationSchema = (input: SetOperationSchemaInput) =>\n createAction<SetOperationSchemaAction>(\n \"SET_OPERATION_SCHEMA\",\n { ...input },\n undefined,\n SetOperationSchemaInputSchema,\n \"global\",\n );\n\nexport const setOperationDescription = (input: SetOperationDescriptionInput) =>\n createAction<SetOperationDescriptionAction>(\n \"SET_OPERATION_DESCRIPTION\",\n { ...input },\n undefined,\n SetOperationDescriptionInputSchema,\n \"global\",\n );\n\nexport const setOperationTemplate = (input: SetOperationTemplateInput) =>\n createAction<SetOperationTemplateAction>(\n \"SET_OPERATION_TEMPLATE\",\n { ...input },\n undefined,\n SetOperationTemplateInputSchema,\n \"global\",\n );\n\nexport const setOperationReducer = (input: SetOperationReducerInput) =>\n createAction<SetOperationReducerAction>(\n \"SET_OPERATION_REDUCER\",\n { ...input },\n undefined,\n SetOperationReducerInputSchema,\n \"global\",\n );\n\nexport const moveOperation = (input: MoveOperationInput) =>\n createAction<MoveOperationAction>(\n \"MOVE_OPERATION\",\n { ...input },\n undefined,\n MoveOperationInputSchema,\n \"global\",\n );\n\nexport const deleteOperation = (input: DeleteOperationInput) =>\n createAction<DeleteOperationAction>(\n \"DELETE_OPERATION\",\n { ...input },\n undefined,\n DeleteOperationInputSchema,\n \"global\",\n );\n\nexport const reorderModuleOperations = (input: ReorderModuleOperationsInput) =>\n createAction<ReorderModuleOperationsAction>(\n \"REORDER_MODULE_OPERATIONS\",\n { ...input },\n undefined,\n ReorderModuleOperationsInputSchema,\n \"global\",\n );\n\nexport const addOperationError = (input: AddOperationErrorInput) =>\n createAction<AddOperationErrorAction>(\n \"ADD_OPERATION_ERROR\",\n { ...input },\n undefined,\n AddOperationErrorInputSchema,\n \"global\",\n );\n\nexport const setOperationErrorCode = (input: SetOperationErrorCodeInput) =>\n createAction<SetOperationErrorCodeAction>(\n \"SET_OPERATION_ERROR_CODE\",\n { ...input },\n undefined,\n SetOperationErrorCodeInputSchema,\n \"global\",\n );\n\nexport const setOperationErrorName = (input: SetOperationErrorNameInput) =>\n createAction<SetOperationErrorNameAction>(\n \"SET_OPERATION_ERROR_NAME\",\n { ...input },\n undefined,\n SetOperationErrorNameInputSchema,\n \"global\",\n );\n\nexport const setOperationErrorDescription = (\n input: SetOperationErrorDescriptionInput,\n) =>\n createAction<SetOperationErrorDescriptionAction>(\n \"SET_OPERATION_ERROR_DESCRIPTION\",\n { ...input },\n undefined,\n SetOperationErrorDescriptionInputSchema,\n \"global\",\n );\n\nexport const setOperationErrorTemplate = (\n input: SetOperationErrorTemplateInput,\n) =>\n createAction<SetOperationErrorTemplateAction>(\n \"SET_OPERATION_ERROR_TEMPLATE\",\n { ...input },\n undefined,\n SetOperationErrorTemplateInputSchema,\n \"global\",\n );\n\nexport const deleteOperationError = (input: DeleteOperationErrorInput) =>\n createAction<DeleteOperationErrorAction>(\n \"DELETE_OPERATION_ERROR\",\n { ...input },\n undefined,\n DeleteOperationErrorInputSchema,\n \"global\",\n );\n\nexport const reorderOperationErrors = (input: ReorderOperationErrorsInput) =>\n createAction<ReorderOperationErrorsAction>(\n \"REORDER_OPERATION_ERRORS\",\n { ...input },\n undefined,\n ReorderOperationErrorsInputSchema,\n \"global\",\n );\n\nexport const addOperationExample = (input: AddOperationExampleInput) =>\n createAction<AddOperationExampleAction>(\n \"ADD_OPERATION_EXAMPLE\",\n { ...input },\n undefined,\n AddOperationExampleInputSchema,\n \"global\",\n );\n\nexport const updateOperationExample = (input: UpdateOperationExampleInput) =>\n createAction<UpdateOperationExampleAction>(\n \"UPDATE_OPERATION_EXAMPLE\",\n { ...input },\n undefined,\n UpdateOperationExampleInputSchema,\n \"global\",\n );\n\nexport const deleteOperationExample = (input: DeleteOperationExampleInput) =>\n createAction<DeleteOperationExampleAction>(\n \"DELETE_OPERATION_EXAMPLE\",\n { ...input },\n undefined,\n DeleteOperationExampleInputSchema,\n \"global\",\n );\n\nexport const reorderOperationExamples = (\n input: ReorderOperationExamplesInput,\n) =>\n createAction<ReorderOperationExamplesAction>(\n \"REORDER_OPERATION_EXAMPLES\",\n { ...input },\n undefined,\n ReorderOperationExamplesInputSchema,\n \"global\",\n );\n\nexport const operationExampleCreators = {\n addOperationExample,\n updateOperationExample,\n deleteOperationExample,\n reorderOperationExamples,\n};\n\nexport const setStateSchema = (input: SetStateSchemaInput) =>\n createAction<SetStateSchemaAction>(\n \"SET_STATE_SCHEMA\",\n { ...input },\n undefined,\n SetStateSchemaInputSchema,\n \"global\",\n );\n\nexport const setInitialState = (input: SetInitialStateInput) =>\n createAction<SetInitialStateAction>(\n \"SET_INITIAL_STATE\",\n { ...input },\n undefined,\n SetInitialStateInputSchema,\n \"global\",\n );\n\nexport const addStateExample = (input: AddStateExampleInput) =>\n createAction<AddStateExampleAction>(\n \"ADD_STATE_EXAMPLE\",\n { ...input },\n undefined,\n AddStateExampleInputSchema,\n \"global\",\n );\n\nexport const updateStateExample = (input: UpdateStateExampleInput) =>\n createAction<UpdateStateExampleAction>(\n \"UPDATE_STATE_EXAMPLE\",\n { ...input },\n undefined,\n UpdateStateExampleInputSchema,\n \"global\",\n );\n\nexport const deleteStateExample = (input: DeleteStateExampleInput) =>\n createAction<DeleteStateExampleAction>(\n \"DELETE_STATE_EXAMPLE\",\n { ...input },\n undefined,\n DeleteStateExampleInputSchema,\n \"global\",\n );\n\nexport const reorderStateExamples = (input: ReorderStateExamplesInput) =>\n createAction<ReorderStateExamplesAction>(\n \"REORDER_STATE_EXAMPLES\",\n { ...input },\n undefined,\n ReorderStateExamplesInputSchema,\n \"global\",\n );\n\nexport const addChangeLogItem = (input: AddChangeLogItemInput) =>\n createAction<AddChangeLogItemAction>(\n \"ADD_CHANGE_LOG_ITEM\",\n { ...input },\n undefined,\n AddChangeLogItemInputSchema,\n \"global\",\n );\n\nexport const updateChangeLogItem = (input: UpdateChangeLogItemInput) =>\n createAction<UpdateChangeLogItemAction>(\n \"UPDATE_CHANGE_LOG_ITEM\",\n { ...input },\n undefined,\n UpdateChangeLogItemInputSchema,\n \"global\",\n );\n\nexport const deleteChangeLogItem = (input: DeleteChangeLogItemInput) =>\n createAction<DeleteChangeLogItemAction>(\n \"DELETE_CHANGE_LOG_ITEM\",\n { ...input },\n undefined,\n DeleteChangeLogItemInputSchema,\n \"global\",\n );\n\nexport const reorderChangeLogItems = (input: ReorderChangeLogItemsInput) =>\n createAction<ReorderChangeLogItemsAction>(\n \"REORDER_CHANGE_LOG_ITEMS\",\n { ...input },\n undefined,\n ReorderChangeLogItemsInputSchema,\n \"global\",\n );\n\nexport const releaseNewVersion = () =>\n createAction<ReleaseNewVersionAction>(\n \"RELEASE_NEW_VERSION\",\n {},\n undefined,\n undefined,\n \"global\",\n );\n\nexport const baseActions = {\n setName,\n undo,\n redo,\n prune,\n loadState,\n noop,\n};\n\nexport const documentModelActions = {\n setModelName,\n setModelId,\n setModelExtension,\n setModelDescription,\n setAuthorName,\n setAuthorWebsite,\n addModule,\n setModuleName,\n setModuleDescription,\n deleteModule,\n reorderModules,\n addOperation,\n setOperationName,\n setOperationScope,\n setOperationSchema,\n setOperationDescription,\n setOperationTemplate,\n setOperationReducer,\n moveOperation,\n deleteOperation,\n reorderModuleOperations,\n addOperationError,\n setOperationErrorCode,\n setOperationErrorName,\n setOperationErrorDescription,\n setOperationErrorTemplate,\n deleteOperationError,\n reorderOperationErrors,\n setStateSchema,\n setInitialState,\n addStateExample,\n updateStateExample,\n deleteStateExample,\n reorderStateExamples,\n addChangeLogItem,\n updateChangeLogItem,\n deleteChangeLogItem,\n reorderChangeLogItems,\n releaseNewVersion,\n};\n\nexport const actions = { ...baseActions, ...documentModelActions };\n\n/**\n * The context of an action.\n */\nexport type ActionContext = {\n /** The index of the previous operation, showing intended ordering. */\n prevOpIndex?: number;\n\n /** The hash of the previous operation, showing intended state. */\n prevOpHash?: string;\n\n /** A nonce, to cover specific signing attacks and to prevent replay attacks from no-ops. */\n nonce?: string;\n\n /** The signer of the action. */\n signer?: ActionSigner;\n};\n\n/**\n * Defines the basic structure of an action.\n */\nexport type Action = {\n /** The id of the action. This is distinct from the operation id. */\n id: string;\n\n /** The name of the action. */\n type: string;\n\n /** The timestamp of the action. */\n timestampUtcMs: string;\n\n /** The payload of the action. */\n input: unknown;\n\n /** The scope of the action */\n scope: string;\n\n /**\n * The attachments included in the action.\n *\n * This will be refactored in a future release.\n */\n attachments?: AttachmentInput[];\n\n /** The context of the action. */\n context?: ActionContext;\n};\n\n/**\n * The attributes stored for a file. Namely, attachments of a document.\n */\nexport type Attachment = {\n /** The binary data of the attachment in Base64 */\n data: string;\n\n /** The MIME type of the attachment */\n mimeType: string;\n\n // The extension of the attachment.\n extension?: string | null;\n\n // The file name of the attachment.\n fileName?: string | null;\n};\n\nexport type AttachmentInput = Attachment & {\n hash: string;\n};\n\nexport type ActionWithAttachment = Action & {\n attachments: AttachmentInput[];\n};\n\n/**\n * String type representing an attachment in a Document.\n *\n * @remarks\n * Attachment string is formatted as `attachment://<filename>`.\n */\nexport type AttachmentRef = string; // TODO `attachment://${string}`;\n","import type {\n DocumentModelGlobalState,\n DocumentModelLocalState,\n} from \"./types.js\";\n\nexport const documentModelFileExtension = \"phdm\" as const;\n\nexport const documentModelInitialLocalState: DocumentModelLocalState = {};\nexport const documentModelInitialGlobalState: DocumentModelGlobalState = {\n id: \"\",\n name: \"\",\n extension: \"\",\n description: \"\",\n author: {\n name: \"\",\n website: \"\",\n },\n specifications: [\n {\n version: 1,\n changeLog: [],\n state: {\n global: {\n schema: \"\",\n initialValue: \"\",\n examples: [],\n },\n local: {\n schema: \"\",\n initialValue: \"\",\n examples: [],\n },\n },\n modules: [],\n },\n ],\n};\nexport const documentModelGlobalState: DocumentModelGlobalState = {\n id: \"powerhouse/document-model\",\n name: \"DocumentModel\",\n extension: \"phdm\",\n description:\n \"The Powerhouse Document Model describes the state and operations of a document type.\",\n author: {\n name: \"Powerhouse\",\n website: \"https://www.powerhouse.inc/\",\n },\n specifications: [\n {\n version: 1,\n changeLog: [],\n state: {\n global: {\n schema:\n \"type CodeExample {\\n id: ID!\\n value: String!\\n}\\n\\ntype OperationError {\\n id: ID!\\n code: String\\n name: String\\n description: String\\n template: String\\n}\\n\\ntype Operation {\\n id: ID!\\n name: String\\n schema: String\\n description: String\\n template: String\\n errors: [OperationError!]!\\n examples: [CodeExample!]!\\n reducer: String\\n scope: String\\n}\\n\\ntype Module {\\n id: ID!\\n name: String!\\n description: String\\n operations: [Operation!]!\\n}\\n\\ntype State {\\n schema: String!\\n initialValue: String!\\n examples: [CodeExample!]!\\n}\\n\\ntype ScopeState {\\n global: State!\\n local: State!\\n}\\n\\ntype Author {\\n name: String!\\n website: String\\n}\\n\\ntype DocumentSpecification {\\n version: Int!\\n state: ScopeState!\\n modules: [Module!]!\\n changeLog: [String!]!\\n}\\n\\ntype DocumentModelGlobalState {\\n name: String!\\n id: String!\\n extension: String!\\n description: String!\\n author: Author!\\n specifications: [DocumentSpecification!]!\\n}\",\n initialValue:\n '{\\n \"id\": \"\",\\n \"name\": \"\",\\n \"extension\": \"\",\\n \"description\": \"\",\\n \"author\": {\\n \"name\": \"\",\\n \"website\": \"\"\\n },\\n \"specifications\": [\\n {\\n \"version\": 1,\\n \"changeLog\": [],\\n \"state\": {\\n \"global\": {\\n \"schema\": \"\",\\n \"initialValue\": \"\",\\n \"examples\": []\\n },\\n \"local\": {\\n \"schema\": \"\",\\n \"initialValue\": \"\",\\n \"examples\": []\\n }\\n },\\n \"modules\": []\\n }\\n ]\\n}',\n examples: [],\n },\n local: {\n schema: \"\",\n initialValue: \"\",\n examples: [],\n },\n },\n modules: [\n {\n name: \"header\",\n operations: [\n {\n name: \"SET_MODEL_NAME\",\n id: \"\",\n description: \"Sets the name of the document model\",\n schema: \"input SetModelNameInput {\\n name: String!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_MODEL_ID\",\n id: \"\",\n description: \"Sets the unique identifier for the document model\",\n schema: \"input SetModelIdInput {\\n id: String!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_MODEL_EXTENSION\",\n id: \"\",\n description:\n \"Sets the file extension associated with this document model\",\n schema:\n \"input SetModelExtensionInput {\\n extension: String!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_MODEL_DESCRIPTION\",\n id: \"\",\n description: \"Sets the description text for the document model\",\n schema:\n \"input SetModelDescriptionInput {\\n description: String!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_AUTHOR_NAME\",\n id: \"\",\n description: \"Sets the name of the document model author\",\n schema: \"input SetAuthorNameInput {\\n authorName: String!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_AUTHOR_WEBSITE\",\n id: \"\",\n description: \"Sets the website URL of the document model author\",\n schema:\n \"input SetAuthorWebsiteInput {\\n authorWebsite: String!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n ],\n id: \"\",\n description: \"\",\n },\n {\n name: \"versioning\",\n operations: [\n {\n name: \"ADD_CHANGE_LOG_ITEM\",\n id: \"\",\n description: \"Adds a new item to the document model changelog\",\n schema:\n \"input AddChangeLogItemInput {\\n id: ID!\\n insertBefore: ID\\n content: String!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"UPDATE_CHANGE_LOG_ITEM\",\n id: \"\",\n description: \"Updates an existing changelog item\",\n schema:\n \"input UpdateChangeLogItemInput {\\n id: ID!\\n newContent: String!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"DELETE_CHANGE_LOG_ITEM\",\n id: \"\",\n description: \"Removes an item from the document model changelog\",\n schema: \"input DeleteChangeLogItemInput {\\n id: ID!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"REORDER_CHANGE_LOG_ITEMS\",\n id: \"\",\n description: \"Changes the order of changelog items\",\n schema:\n \"input ReorderChangeLogItemsInput {\\n order: [ID!]!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"RELEASE_NEW_VERSION\",\n schema: null,\n id: \"\",\n description:\n \"Creates a new version of the document model specification\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n ],\n id: \"\",\n description: \"\",\n },\n {\n name: \"module\",\n operations: [\n {\n name: \"ADD_MODULE\",\n id: \"\",\n description:\n \"Adds a new module to the document model specification\",\n schema:\n \"input AddModuleInput {\\n id: ID!\\n name: String!\\n description: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_MODULE_NAME\",\n id: \"\",\n description: \"Sets the name of an existing module\",\n schema:\n \"input SetModuleNameInput {\\n id: ID!\\n name: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_MODULE_DESCRIPTION\",\n id: \"\",\n description: \"Sets the description of an existing module\",\n schema:\n \"input SetModuleDescriptionInput {\\n id: ID!\\n description: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"DELETE_MODULE\",\n id: \"\",\n description:\n \"Removes a module from the document model specification\",\n schema: \"input DeleteModuleInput {\\n id: ID!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"REORDER_MODULES\",\n id: \"\",\n description:\n \"Changes the order of modules in the document model specification\",\n schema: \"input ReorderModulesInput {\\n order: [ID!]!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n ],\n id: \"\",\n description: \"\",\n },\n {\n name: \"operation-error\",\n operations: [\n {\n name: \"ADD_OPERATION_ERROR\",\n id: \"\",\n description: \"Adds a new error definition to an operation\",\n schema:\n \"input AddOperationErrorInput {\\n operationId: ID!\\n id: ID!\\n errorCode: String\\n errorName: String\\n errorDescription: String\\n errorTemplate: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_OPERATION_ERROR_CODE\",\n id: \"\",\n description: \"Sets the error code for an operation error\",\n schema:\n \"input SetOperationErrorCodeInput {\\n id: ID!\\n errorCode: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_OPERATION_ERROR_NAME\",\n id: \"\",\n description: \"Sets the name of an operation error\",\n schema:\n \"input SetOperationErrorNameInput {\\n id: ID!\\n errorName: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_OPERATION_ERROR_DESCRIPTION\",\n id: \"\",\n description: \"Sets the description of an operation error\",\n schema:\n \"input SetOperationErrorDescriptionInput {\\n id: ID!\\n errorDescription: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_OPERATION_ERROR_TEMPLATE\",\n id: \"\",\n description: \"Sets the template for an operation error\",\n schema:\n \"input SetOperationErrorTemplateInput {\\n id: ID!\\n errorTemplate: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"DELETE_OPERATION_ERROR\",\n id: \"\",\n description: \"Removes an error definition from an operation\",\n schema: \"input DeleteOperationErrorInput {\\n id: ID!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"REORDER_OPERATION_ERRORS\",\n id: \"\",\n description:\n \"Changes the order of error definitions for an operation\",\n schema:\n \"input ReorderOperationErrorsInput {\\n operationId: ID!\\n order: [ID!]!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n ],\n id: \"\",\n description: \"\",\n },\n {\n name: \"operation-example\",\n operations: [\n {\n name: \"ADD_OPERATION_EXAMPLE\",\n id: \"\",\n description: \"Adds a new code example to an operation\",\n schema:\n \"input AddOperationExampleInput {\\n operationId: ID!\\n id: ID!\\n example: String!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"UPDATE_OPERATION_EXAMPLE\",\n id: \"\",\n description: \"Updates an existing code example for an operation\",\n schema:\n \"input UpdateOperationExampleInput {\\n id: ID!\\n example: String!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"DELETE_OPERATION_EXAMPLE\",\n id: \"\",\n description: \"Removes a code example from an operation\",\n schema: \"input DeleteOperationExampleInput {\\n id: ID!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"REORDER_OPERATION_EXAMPLES\",\n id: \"\",\n description:\n \"Changes the order of code examples for an operation\",\n schema:\n \"input ReorderOperationExamplesInput {\\n operationId: ID!\\n order: [ID!]!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n ],\n id: \"\",\n description: \"\",\n },\n {\n name: \"operation\",\n operations: [\n {\n name: \"ADD_OPERATION\",\n id: \"\",\n description: \"Adds a new operation to a module\",\n schema:\n \"input AddOperationInput {\\n moduleId: ID!\\n id: ID!\\n name: String!\\n schema: String\\n description: String\\n template: String\\n reducer: String\\n scope: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_OPERATION_NAME\",\n id: \"\",\n description: \"Sets the name of an operation\",\n schema:\n \"input SetOperationNameInput {\\n id: ID!\\n name: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_OPERATION_SCHEMA\",\n id: \"\",\n description:\n \"Sets the GraphQL schema definition for an operation's input\",\n schema:\n \"input SetOperationSchemaInput {\\n id: ID!\\n schema: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_OPERATION_DESCRIPTION\",\n id: \"\",\n description: \"Sets the description of an operation\",\n schema:\n \"input SetOperationDescriptionInput {\\n id: ID!\\n description: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_OPERATION_TEMPLATE\",\n id: \"\",\n description: \"Sets the template code for an operation\",\n schema:\n \"input SetOperationTemplateInput {\\n id: ID!\\n template: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_OPERATION_REDUCER\",\n id: \"\",\n description: \"Sets the reducer function code for an operation\",\n schema:\n \"input SetOperationReducerInput {\\n id: ID!\\n reducer: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_OPERATION_SCOPE\",\n id: \"\",\n description: \"Sets the scope of an operation (global or local)\",\n schema:\n \"input SetOperationScopeInput {\\n id: ID!\\n scope: String\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"MOVE_OPERATION\",\n id: \"\",\n description: \"Moves an operation from one module to another\",\n schema:\n \"input MoveOperationInput {\\n operationId: ID!\\n newModuleId: ID!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"DELETE_OPERATION\",\n id: \"\",\n description: \"Removes an operation from a module\",\n schema: \"input DeleteOperationInput {\\n id: ID!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"REORDER_MODULE_OPERATIONS\",\n id: \"\",\n description: \"Changes the order of operations within a module\",\n schema:\n \"input ReorderModuleOperationsInput {\\n moduleId: ID!\\n order: [ID!]!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n ],\n id: \"\",\n description: \"\",\n },\n {\n name: \"state\",\n operations: [\n {\n name: \"SET_STATE_SCHEMA\",\n id: \"\",\n description:\n \"Sets the GraphQL schema definition for document state\",\n schema:\n \"input SetStateSchemaInput {\\n scope: String!\\n schema: String!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"SET_INITIAL_STATE\",\n id: \"\",\n description: \"Sets the initial state value for a document scope\",\n schema:\n \"input SetInitialStateInput {\\n scope: String!\\n initialValue: String!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"ADD_STATE_EXAMPLE\",\n id: \"\",\n description: \"Adds a new state example to a document scope\",\n schema:\n \"input AddStateExampleInput {\\n scope: String!\\n id: ID!\\n insertBefore: ID\\n example: String!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"UPDATE_STATE_EXAMPLE\",\n id: \"\",\n description:\n \"Updates an existing state example for a document scope\",\n schema:\n \"input UpdateStateExampleInput {\\n scope: String!\\n id: ID!\\n newExample: String!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"DELETE_STATE_EXAMPLE\",\n id: \"\",\n description: \"Removes a state example from a document scope\",\n schema:\n \"input DeleteStateExampleInput {\\n scope: String!\\n id: ID!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n {\n name: \"REORDER_STATE_EXAMPLES\",\n id: \"\",\n description:\n \"Changes the order of state examples for a document scope\",\n schema:\n \"input ReorderStateExamplesInput {\\n scope: String!\\n order: [ID!]!\\n}\",\n template: \"\",\n reducer: \"\",\n examples: [],\n errors: [],\n scope: \"global\",\n },\n ],\n id: \"\",\n description: \"\",\n },\n ],\n },\n ],\n};\n\n// Known hash algorithms (can be extended without breaking changes)\nexport const HASH_ALGORITHM_SHA1 = \"sha1\";\nexport const HASH_ALGORITHM_SHA256 = \"sha256\";\nexport const HASH_ALGORITHM_SHA512 = \"sha512\";\n\n// Known encodings (can be extended without breaking changes)\nexport const HASH_ENCODING_BASE64 = \"base64\";\nexport const HASH_ENCODING_HEX = \"hex\";\n","export const documentModelDocumentType = \"powerhouse/document-model\";\n","import { z } from \"zod\";\nimport { documentModelDocumentType } from \"./document-type.js\";\nimport { DocumentModelGlobalStateSchema } from \"./schemas.js\";\nimport type { DocumentModelDocument, DocumentModelPHState } from \"./types.js\";\n\nexport const BaseDocumentHeaderSchema = z.object({\n id: z.string(),\n name: z.string(),\n createdAtUtcIso: z.string(),\n lastModifiedAtUtcIso: z.string(),\n documentType: z.string(),\n});\n\nexport const BaseDocumentStateSchema = z.object({\n global: z.unknown(),\n});\n\n/** Schema for validating the header object of a DocumentModel document */\nexport const DocumentModelHeaderSchema = BaseDocumentHeaderSchema.extend({\n documentType: z.literal(documentModelDocumentType),\n});\n\n/** Schema for validating the state object of a DocumentModel document */\nexport const DocumentModelPHStateSchema = BaseDocumentStateSchema.extend({\n global: DocumentModelGlobalStateSchema(),\n});\n\nexport const DocumentModelSchema = z.object({\n header: DocumentModelHeaderSchema,\n state: DocumentModelPHStateSchema,\n initialState: DocumentModelPHStateSchema,\n});\n\n/** Simple helper function to check if a state object is a DocumentModel document state object */\nexport function isDocumentModelState(\n state: unknown,\n): state is DocumentModelPHState {\n return DocumentModelPHStateSchema.safeParse(state).success;\n}\n\n/** Simple helper function to assert that a document state object is a DocumentModel document state object */\nexport function assertIsDocumentModelState(\n state: unknown,\n): asserts state is DocumentModelPHState {\n DocumentModelPHStateSchema.parse(state);\n}\n\n/** Simple helper function to check if a document is a DocumentModel document */\nexport function isDocumentModelDocument(\n document: unknown,\n): document is DocumentModelDocument {\n return DocumentModelSchema.safeParse(document).success;\n}\n\n/** Simple helper function to assert that a document is a DocumentModel document */\nexport function assertIsDocumentModelDocument(\n document: unknown,\n): asserts document is DocumentModelDocument {\n DocumentModelSchema.parse(document);\n}\n","import type { Action } from \"./actions.js\";\nimport type { PHDocumentHeader } from \"./documents.js\";\nimport type { Signature } from \"./signatures.js\";\nimport type { ISigner, SigningParameters } from \"./types.js\";\nimport { generateId } from \"./utils.js\";\n\n/**\n * Generates a deterministic payload from signing parameters\n */\nconst generateStablePayload = (parameters: SigningParameters): string =>\n `${parameters.documentType}:${parameters.createdAtUtcIso}:${parameters.nonce}`;\n\n/**\n * Creates a verification-only signer from a public key.\n * This signer can only verify signatures, not sign data.\n *\n * @param pubKey - The public key to use for verification.\n * @returns An ISigner that can only verify signatures.\n */\nexport async function createVerificationSigner(\n pubKey: JsonWebKey,\n): Promise<ISigner> {\n const cryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n pubKey,\n { name: \"ECDSA\", namedCurve: \"P-256\" },\n true,\n [\"verify\"],\n );\n return {\n publicKey: cryptoKey,\n\n async sign(_data: Uint8Array): Promise<Uint8Array> {\n throw new Error(\"verification-only signer cannot sign data\");\n },\n\n async signAction(\n _action: Action,\n _abortSignal?: AbortSignal,\n ): Promise<Signature> {\n throw new Error(\"verification-only signer cannot sign actions\");\n },\n\n async verify(data: Uint8Array, signature: Uint8Array): Promise<void> {\n let isValid: boolean;\n try {\n isValid = await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n cryptoKey,\n new Uint8Array(signature),\n new Uint8Array(data),\n );\n } catch {\n throw new Error(\"invalid signature\");\n }\n\n if (!isValid) {\n throw new Error(\"invalid signature\");\n }\n },\n };\n}\n\n/**\n * Creates a verification-only signer from a header.\n *\n * @param header - The header to create a signer from.\n * @returns A signer that can verify the header's signature.\n */\nconst createSignerFromHeader = async (\n header: PHDocumentHeader,\n): Promise<ISigner> => {\n return createVerificationSigner(header.sig.publicKey);\n};\n\n/**\n * Signs a header. Generally, this is not called directly, but rather through\n * {@link createSignedHeader}.\n *\n * @param parameters - The parameters used to sign the header.\n * @param signer - The signer of the document.\n *\n * @returns The signature of the header.\n */\nexport const sign = async (\n parameters: SigningParameters,\n signer: ISigner,\n): Promise<string> => {\n // Generate stable payload\n const payload = generateStablePayload(parameters);\n\n // Convert payload to Uint8Array for signing\n const encoder = new TextEncoder();\n const data = encoder.encode(payload);\n\n // Create signature using Web Crypto API with Ed25519\n const signature = await signer.sign(data);\n\n // Convert signature to base64 string for JSON serialization\n const signatureArray = new Uint8Array(signature);\n const signatureBase64 = btoa(String.fromCharCode(...signatureArray));\n return signatureBase64;\n};\n\n/**\n * Verifies a header signature. Generally, this is not called directly, but\n * rather through {@link validateHeader}.\n *\n * @param parameters - The parameters used to sign the header.\n * @param signature - The signature to verify.\n * @param signer - The signer of the document.\n */\nexport const verify = async (\n parameters: SigningParameters,\n signature: string,\n signer: ISigner,\n): Promise<void> => {\n // Generate the same stable payload that was signed\n const payload = generateStablePayload(parameters);\n\n // Convert payload to Uint8Array for verification\n const encoder = new TextEncoder();\n const data = encoder.encode(payload);\n\n // Decode the base64 signature back to binary\n const signatureBytes = Uint8Array.from(atob(signature), (c) =>\n c.charCodeAt(0),\n );\n\n await signer.verify(data, signatureBytes);\n};\n\n/**\n * Validates a header signature.\n */\nexport const validateHeader = async (\n header: PHDocumentHeader,\n): Promise<void> => {\n const signer = await createSignerFromHeader(header);\n\n return verify(\n {\n documentType: header.documentType,\n createdAtUtcIso: header.createdAtUtcIso,\n nonce: header.sig.nonce,\n },\n header.id,\n signer,\n );\n};\n\n/**\n * Creates a header that has yet to be signed. This header is not valid, but\n * can be input into {@link createSignedHeader} to create a signed header.\n *\n * @returns An unsigned header for a document.\n */\nexport const createPresignedHeader = (\n id: string = generateId(),\n documentType = \"\",\n): PHDocumentHeader => {\n return {\n id,\n sig: {\n publicKey: {},\n nonce: \"\",\n },\n documentType,\n createdAtUtcIso: new Date().toISOString(),\n slug: \"\",\n name: \"\",\n branch: \"main\",\n revision: {\n document: 0,\n },\n lastModifiedAtUtcIso: new Date().toISOString(),\n meta: {},\n };\n};\n\n/**\n * Creates a new, signed header for a document. This will replace the id of the\n * document.\n *\n * @param unsignedHeader - The unsigned header to created the signed header from.\n * @param signer - The signer of the document.\n *\n * @returns A new signed header for a document. Some fields are mutable and\n * some are not. See the PHDocumentHeader type for more information.\n */\nexport const createSignedHeader = async (\n unsignedHeader: PHDocumentHeader,\n documentType: string,\n signer: ISigner,\n): Promise<PHDocumentHeader> => {\n const parameters: SigningParameters = {\n documentType,\n createdAtUtcIso: unsignedHeader.createdAtUtcIso,\n nonce: generateId(),\n };\n\n const signature = await sign(parameters, signer);\n\n const jsonPublicKey = await crypto.subtle.exportKey(\"jwk\", signer.publicKey);\n\n return {\n // immutable fields\n id: signature,\n sig: {\n publicKey: jsonPublicKey,\n nonce: parameters.nonce,\n },\n documentType,\n createdAtUtcIso: unsignedHeader.createdAtUtcIso,\n\n // mutable fields\n slug: unsignedHeader.slug,\n name: unsignedHeader.name,\n branch: unsignedHeader.branch,\n revision: unsignedHeader.revision,\n lastModifiedAtUtcIso: unsignedHeader.lastModifiedAtUtcIso,\n meta: unsignedHeader.meta,\n };\n};\n\n/**\n * Creates a signed header for a document. The document header requires a signer\n * as the document id is a cryptographic signature.\n *\n * @param documentType - The type of the document.\n * @param signer - The signer of the document.\n *\n * @returns The signed header for a document. Some fields are mutable and\n * some are not. See the PHDocumentHeader type for more information.\n */\nexport const createSignedHeaderForSigner = async (\n documentType: string,\n signer: ISigner,\n): Promise<PHDocumentHeader> => {\n const unsignedHeader = createPresignedHeader();\n const signedHeader = await createSignedHeader(\n unsignedHeader,\n documentType,\n signer,\n );\n\n return signedHeader;\n};\n","import stringifyJson, { stringify } from \"safe-stable-stringify\";\nimport type { Action } from \"./actions.js\";\nimport { hashBrowser } from \"./crypto.js\";\nimport { HashMismatchError } from \"./errors.js\";\nimport { createPresignedHeader } from \"./header.js\";\nimport type { DocumentOperations, Operation } from \"./operations.js\";\nimport type { PHDocumentSignatureInfo } from \"./signatures.js\";\nimport type { PHBaseState } from \"./state.js\";\nimport type {\n CreateState,\n DocumentAction,\n DocumentOperationsIgnoreMap,\n MappedOperation,\n OperationIndex,\n OperationsByScope,\n Reducer,\n ReplayDocumentOptions,\n SignalDispatch,\n SkipHeaderOperationIndex,\n SkipHeaderOperations,\n UndoAction,\n UndoRedoAction,\n} from \"./types.js\";\nimport { generateId } from \"./utils.js\";\n\n/** Meta information about the document. */\nexport type PHDocumentMeta = {\n /** The preferred editor for the document. */\n preferredEditor?: string;\n};\n\n/**\n * The header of a document.\n */\nexport type PHDocumentHeader = {\n /**\n * The id of the document.\n *\n * This is a Ed25519 signature and is immutable.\n **/\n id: string;\n\n /**\n * Information to verify the document creator.\n *\n * This is immutable.\n **/\n sig: PHDocumentSignatureInfo;\n\n /**\n * The type of the document.\n *\n * This is used as part of the signature payload and thus, cannot be changed\n * after the document header has been created.\n **/\n documentType: string;\n\n /**\n * The timestamp of the creation date of the document, in UTC ISO format.\n *\n * This is used as part of the signature payload and thus, cannot be changed\n * after the document header has been created.\n **/\n createdAtUtcIso: string;\n\n /** The slug of the document. */\n slug: string;\n\n /** The name of the document. */\n name: string;\n\n /** The branch of this document. */\n branch: string;\n\n /**\n * The revision of each scope of the document. This object is updated every\n * time any _other_ scope is updated.\n */\n revision: {\n [scope: string]: number;\n };\n\n /**\n * The timestamp of the last change in the document, in UTC ISO format.\n **/\n lastModifiedAtUtcIso: string;\n\n /**\n * This is a map from protocol name to version. A protocol can be any set of\n * rules that are applied to the document.\n *\n * Examples of protocols include:\n *\n * - \"base-reducer\"\n */\n protocolVersions?: { [key: string]: number };\n\n /** Meta information about the document. */\n meta?: PHDocumentMeta;\n};\n\n/**\n * The base type of a document model.\n *\n * @remarks\n * This type is extended by all Document models.\n *\n * @typeParam TState - The type of the document state.\n */\nexport type PHDocument<TState extends PHBaseState = PHBaseState> = {\n /** The header of the document. */\n header: PHDocumentHeader;\n\n /** The document model specific state. */\n state: TState;\n\n /**\n * The initial state of the document, enabling replaying operations.\n *\n * This will be removed in a future release.\n */\n initialState: TState;\n\n /**\n * The operations history of the document.\n *\n * This will be removed in a future release.\n */\n operations: DocumentOperations;\n\n /**\n * A list of undone operations\n *\n * This will be removed in a future release.\n */\n clipboard: Operation[];\n};\n\nexport function isNoopOperation<\n TOp extends {\n type: string;\n skip: number;\n hash: string;\n },\n>(op: Partial<TOp>): boolean {\n return (\n op.type === \"NOOP\" &&\n op.skip !== undefined &&\n op.skip > 0 &&\n op.hash !== undefined\n );\n}\n\nexport function isUndoRedo(action: Action): action is UndoRedoAction {\n return [\"UNDO\", \"REDO\"].includes(action.type);\n}\n\nexport function isUndo(action: Action): action is UndoAction {\n return action.type === \"UNDO\";\n}\n\nexport function isDocumentAction(action: Action): action is DocumentAction {\n return [\"SET_NAME\", \"UNDO\", \"REDO\", \"PRUNE\", \"LOAD_STATE\"].includes(\n action.type,\n );\n}\n\n/**\n * Important note: it is the responsibility of the caller to set the document type\n * on the header.\n */\nexport function baseCreateDocument<TState extends PHBaseState = PHBaseState>(\n createState: CreateState<TState>,\n initialState?: Partial<TState>,\n): PHDocument<TState> {\n const state = createState(initialState);\n const header = createPresignedHeader();\n const phDocument: PHDocument<TState> = {\n header,\n state,\n initialState: state,\n operations: { global: [], local: [] },\n clipboard: [],\n };\n\n return phDocument;\n}\n\nexport function hashDocumentStateForScope(\n document: {\n state: {\n [key: string]: unknown;\n };\n },\n scope = \"global\",\n) {\n const stateString = stringifyJson(document.state[scope] || \"\");\n return hashBrowser(stateString);\n}\n\nexport function readOnly<T>(value: T): Readonly<T> {\n return Object.freeze(value);\n}\n\n/**\n * Maps skipped operations in an array of operations.\n * Skipped operations are operations that are ignored during processing.\n * @param operations - The array of operations to map.\n * @param skippedHeadOperations - The number of operations to skip at the head of the array of operations.\n * @returns An array of mapped operations with ignore flag indicating if the operation is skipped.\n * @throws Error if the operation index is invalid and there are missing operations.\n */\nexport function mapSkippedOperations(\n operations: Operation[],\n skippedHeadOperations?: number,\n): MappedOperation[] {\n const ops = [...operations];\n\n let skipped = skippedHeadOperations || 0;\n let latestOpIndex = ops.length > 0 ? ops[ops.length - 1].index : 0;\n\n const scopeOpsWithIgnore: MappedOperation[] = [];\n\n for (const operation of ops.reverse()) {\n if (skipped > 0) {\n const operationsDiff = latestOpIndex - operation.index;\n skipped -= operationsDiff;\n }\n\n if (skipped < 0) {\n throw new Error(\"Invalid operation index, missing operations\");\n }\n\n const mappedOp = {\n ignore: skipped > 0,\n operation,\n };\n\n // here we add 1 to the skip number because we want to get the number of\n // operations that we want to move the pointer back to get the latest valid operation\n // operation.skip = 1 means that we want to move the pointer back 2 operations to get to the latest valid operation\n const operationSkip = operation.skip > 0 ? operation.skip + 1 : 0;\n\n if (operationSkip > 0 && operationSkip > skipped) {\n const skipDiff = operationSkip - skipped;\n skipped = skipped + skipDiff;\n }\n\n latestOpIndex = operation.index;\n scopeOpsWithIgnore.push(mappedOp);\n }\n\n return scopeOpsWithIgnore.reverse();\n}\n\n/**\n * V2 version of mapSkippedOperations for protocol version 2+.\n * In V2, all NOOPs have skip=1 and consecutive NOOPs form chains.\n * N consecutive NOOPs at any point skip N preceding content operations.\n *\n * Algorithm: Process from end to start\n * - When hitting a NOOP: increment chain length, mark as ignored\n * - When hitting a non-NOOP:\n * - If chain > 0: decrement chain, mark as ignored (this op was undone)\n * - If chain == 0: mark as not ignored (apply this op)\n */\nexport function mapSkippedOperationsV2(\n operations: Operation[],\n): MappedOperation[] {\n const ops = [...operations];\n const result: MappedOperation[] = [];\n\n let noopChainLength = 0;\n\n for (let i = ops.length - 1; i >= 0; i--) {\n const operation = ops[i];\n const isNoop = operation.action.type === \"NOOP\";\n\n if (isNoop) {\n noopChainLength++;\n result.unshift({ ignore: true, operation });\n } else if (noopChainLength > 0) {\n noopChainLength--;\n result.unshift({ ignore: true, operation });\n } else {\n result.unshift({ ignore: false, operation });\n }\n }\n\n return result;\n}\n\n/**\n * V2 garbage collect that returns only operations that should be applied for state.\n * Uses the V2 model where consecutive NOOPs form chains.\n * Unlike V1 garbageCollect, this preserves ALL operations but marks which to apply.\n */\nexport function garbageCollectV2<TOpIndex extends OperationIndex>(\n sortedOperations: TOpIndex[],\n): TOpIndex[] {\n const result: TOpIndex[] = [];\n let noopChainLength = 0;\n\n for (let i = sortedOperations.length - 1; i >= 0; i--) {\n const op = sortedOperations[i];\n // Check if this is a NOOP operation\n const isNoop =\n \"action\" in op &&\n (op as unknown as Operation).action.type === \"NOOP\" &&\n op.skip > 0;\n\n if (isNoop) {\n noopChainLength++;\n // Include the NOOP in result (for operation history)\n result.unshift(op);\n } else if (noopChainLength > 0) {\n noopChainLength--;\n // Skip this operation - it was undone\n } else {\n // Include this operation\n result.unshift(op);\n }\n }\n\n return result;\n}\n\n// Flattens the mapped operations (with ignore flag) from all scopes into\n// a single array and sorts them by timestamp\nexport function sortMappedOperations(operations: DocumentOperationsIgnoreMap) {\n return Object.values(operations)\n .flatMap((array) => array)\n .sort(\n (a, b) =>\n new Date(a.operation.timestampUtcMs).getTime() -\n new Date(b.operation.timestampUtcMs).getTime(),\n );\n}\n\n// Default createState function that just returns the state as-is\nconst defaultCreateState = <TState extends PHBaseState = PHBaseState>(\n state?: Partial<TState>,\n) => {\n return state as TState;\n};\n\n// Runs the operations on the initial data using the\n// provided document reducer.\n// This rebuilds the document according to the provided actions.\nexport function replayDocument<TState extends PHBaseState = PHBaseState>(\n initialState: TState,\n operations: DocumentOperations,\n reducer: Reducer<TState>,\n header: PHDocumentHeader,\n dispatch?: SignalDispatch,\n skipHeaderOperations: SkipHeaderOperations = {},\n options?: ReplayDocumentOptions,\n): PHDocument<TState> {\n const {\n checkHashes = true,\n reuseOperationResultingState,\n operationResultingStateParser = parseResultingState,\n skipIndexValidation,\n } = options || {};\n\n let documentState = initialState;\n const operationsToReplay: Operation[] = [];\n // Initialize with all scopes found in operations, plus global and local for backward compatibility\n const allScopes = new Set([...Object.keys(operations), \"global\", \"local\"]);\n const initialOperations: DocumentOperations = {};\n for (const scope of allScopes) {\n initialOperations[scope] = [];\n }\n\n // if operation resulting state is to be used then\n // looks for the last operation with state of each\n // scope to use it as the starting point and only\n // replay operations that follow it\n if (reuseOperationResultingState) {\n for (const [scope, scopeOperations] of Object.entries(operations)) {\n if (!scopeOperations) {\n continue;\n }\n const index = scopeOperations.findLastIndex((s) => !!s.resultingState);\n if (index < 0) {\n operationsToReplay.push(...scopeOperations);\n continue;\n }\n const opWithState = scopeOperations[index];\n if (!opWithState || !opWithState.resultingState) continue;\n try {\n const scopeState = operationResultingStateParser(\n opWithState.resultingState,\n );\n documentState = {\n ...documentState,\n // TODO how to deal with attachments?\n [scope]: scopeState,\n };\n const scopeInitialOps =\n initialOperations[scope as keyof typeof initialOperations];\n if (scopeInitialOps) {\n scopeInitialOps.push(...scopeOperations.slice(0, index + 1));\n }\n operationsToReplay.push(...scopeOperations.slice(index + 1));\n } catch {\n /* if parsing fails then keeps replays all scope operations */\n operationsToReplay.push(...scopeOperations);\n }\n }\n } else {\n operationsToReplay.push(\n ...Object.values(operations).flatMap((ops) => ops || []),\n );\n }\n\n // builds a new document using the provided header (no generated header)\n const document: PHDocument<TState> = {\n header,\n state: defaultCreateState<TState>(documentState),\n initialState,\n operations: initialOperations,\n clipboard: [],\n };\n\n let result = document;\n\n // if there are operations left without resulting state\n // then replays them\n if (operationsToReplay.length) {\n result = operationsToReplay.reduce((document, operation) => {\n const doc = reducer(document, operation.action, dispatch, {\n ignoreSkipOperations: true,\n checkHashes,\n skipIndexValidation,\n replayOptions: {\n operation,\n },\n });\n\n return doc;\n }, document);\n }\n // if not then updates the document header according\n // to the latest operation of each scope\n else {\n for (const scopeOperations of Object.values(initialOperations)) {\n if (!scopeOperations) {\n continue;\n }\n const lastOperation = scopeOperations.at(-1);\n if (lastOperation) {\n result = updateHeaderRevision(\n result,\n lastOperation.action.scope,\n lastOperation.timestampUtcMs,\n ) as PHDocument<TState>;\n }\n }\n }\n\n // if hash generation was skipped then checks if the hash\n // of each scope matches the hash of last operation\n if (!checkHashes) {\n for (const scope of Object.keys(result.state)) {\n for (let i = operationsToReplay.length - 1; i >= 0; i--) {\n const operation = operationsToReplay[i];\n\n if (operation.action.scope !== scope) {\n continue;\n }\n if (operation.hash !== hashDocumentStateForScope(result, scope)) {\n throw new HashMismatchError(scope, result, operation);\n } else {\n break;\n }\n }\n }\n }\n\n // reuses operation timestamp if provided\n // Initialize with all scopes from both result.operations and input operations\n const allResultScopes = new Set([\n ...Object.keys(result.operations),\n ...Object.keys(operations),\n \"global\",\n \"local\",\n ]);\n const initialResultOperations: DocumentOperations = {};\n for (const scope of allResultScopes) {\n initialResultOperations[scope] = [];\n }\n\n // Iterate over all scopes (not just result.operations) to preserve empty scopes\n const resultOperations: DocumentOperations = Array.from(\n allResultScopes,\n ).reduce((acc, scope) => {\n const scopeOps = result.operations[scope] || [];\n\n return {\n ...acc,\n [scope]: [\n ...scopeOps.map((operation, index) => {\n return {\n ...operation,\n timestamp:\n operations[scope]?.[index]?.timestampUtcMs ??\n operation.timestampUtcMs,\n };\n }),\n ],\n };\n }, initialResultOperations);\n\n // gets the last modified timestamp from the latest operation\n const lastModified = header\n ? header.lastModifiedAtUtcIso\n : Object.values(resultOperations).reduce((acc, curr) => {\n if (!curr) {\n return acc;\n }\n const operation = curr.at(-1);\n if (operation) {\n if (operation.timestampUtcMs > acc) {\n return operation.timestampUtcMs;\n }\n }\n\n return acc;\n }, document.header.lastModifiedAtUtcIso);\n\n if (header) {\n result.header = {\n ...header,\n revision: result.header.revision,\n lastModifiedAtUtcIso: lastModified,\n };\n }\n\n return {\n ...result,\n operations: resultOperations,\n } as PHDocument<TState>;\n}\n\nexport function parseResultingState<TState>(\n state: string | null | undefined,\n): TState {\n const stateType = typeof state;\n if (stateType === \"string\") {\n return JSON.parse(state!) as TState;\n } else if (stateType === \"object\") {\n return state as TState;\n } else {\n throw new Error(`Providing resulting state is of type: ${stateType}`);\n }\n}\n\nexport enum IntegrityIssueType {\n UNEXPECTED_INDEX = \"UNEXPECTED_INDEX\",\n}\n\nexport enum IntegrityIssueSubType {\n DUPLICATED_INDEX = \"DUPLICATED_INDEX\",\n MISSING_INDEX = \"MISSING_INDEX\",\n}\n\ntype IntegrityIssue = {\n operation: OperationIndex;\n issue: IntegrityIssueType;\n category: IntegrityIssueSubType;\n message: string;\n};\n\ntype Reshuffle = (\n startIndex: OperationIndex,\n opsA: Operation[],\n opsB: Operation[],\n) => Operation[];\n\nexport function checkCleanedOperationsIntegrity(\n sortedOperations: OperationIndex[],\n): IntegrityIssue[] {\n const result: IntegrityIssue[] = [];\n\n // 1:1 1\n // 0:0 0 -> 1:0 1 -> 2:0 -> 3:0 -> 4:0 -> 5:0\n // 0:0 0 -> 2:1 1 -> 3:0 -> 4:0 -> 5:0\n // 0:0 0 -> 3:2 1 -> 4:0 -> 5:0\n // 0:0 0 -> 3:2 1 -> 5:1\n\n // 0:3 (expected 0, got -3)\n // 1:2 (expected 0, got -1)\n // 0:0 -> 1:1\n // 0:0 -> 2:2\n // 0:0 -> 3:2 -> 5:2\n\n let currentIndex = -1;\n for (const nextOperation of sortedOperations) {\n const nextIndex = nextOperation.index - nextOperation.skip;\n\n if (nextIndex !== currentIndex + 1) {\n result.push({\n operation: {\n index: nextOperation.index,\n skip: nextOperation.skip,\n },\n issue: IntegrityIssueType.UNEXPECTED_INDEX,\n category:\n nextIndex > currentIndex + 1\n ? IntegrityIssueSubType.MISSING_INDEX\n : IntegrityIssueSubType.DUPLICATED_INDEX,\n message: `Expected index ${currentIndex + 1} with skip 0 or equivalent, got index ${nextOperation.index} with skip ${nextOperation.skip}`,\n });\n }\n\n currentIndex = nextOperation.index;\n }\n\n return result;\n}\n\n// [] -> []\n// [0:0] -> [0:0]\n\n// 0:0 1:0 2:0 => 0:0 1:0 2:0, removals 0, no issues\n// 0:0 1:1 2:0 => 1:1 2:0, removals 1, no issues\n\n// 0:0 1:1 2:0 3:1 => 1:1 3:1, removals 2, no issues\n// 0:0 1:1 2:0 3:3 => 3:3\n\n// 1:1 2:0 3:0 => 1:1 2:0 3:0, removals 0, no issues\n// 1:0 0:0 2:0 => 2:0, removals 2, issues [UNEXPECTED_INDEX, INDEX_OUT_OF_ORDER]\n// 0:0 1:0 2:0 => 0:0 1:0 2:0, removals 0, no issues\n// 0:0 1:0 2:0 => 0:0 1:0 2:0, removals 0, no issues\n// 0:0 1:0 2:0 => 0:0 1:0 2:0, removals 0, no issues\n\nexport function garbageCollect<TOpIndex extends OperationIndex>(\n sortedOperations: TOpIndex[],\n) {\n const result: TOpIndex[] = [];\n\n let i = sortedOperations.length - 1;\n\n while (i > -1) {\n result.unshift(sortedOperations[i]);\n const skipUntil =\n (sortedOperations[i]?.index || 0) - (sortedOperations[i]?.skip || 0) - 1;\n\n let j = i - 1;\n while (j > -1 && (sortedOperations[j]?.index || 0) > skipUntil) {\n j--;\n }\n\n i = j;\n }\n\n return result;\n}\nexport function addUndo(sortedOperations: Operation[]) {\n const operationsCopy = [...sortedOperations];\n const latestOperation = operationsCopy[operationsCopy.length - 1];\n\n if (!latestOperation) return operationsCopy;\n\n if (latestOperation.action.type === \"NOOP\") {\n operationsCopy.push({\n ...latestOperation,\n index: latestOperation.index,\n skip: nextSkipNumber(sortedOperations),\n action: {\n ...latestOperation.action,\n\n // TODO: this will break the signature...\n id: generateId(),\n timestampUtcMs: new Date().toISOString(),\n type: \"NOOP\",\n },\n });\n } else {\n operationsCopy.push({\n id: generateId(),\n timestampUtcMs: new Date().toISOString(),\n index: latestOperation.index + 1,\n skip: 1,\n hash: latestOperation.hash,\n action: {\n id: generateId(),\n timestampUtcMs: new Date().toISOString(),\n type: \"NOOP\",\n input: {},\n scope: latestOperation.action.scope,\n },\n });\n }\n\n return operationsCopy;\n}\n\n// [0:0 2:0 1:0 3:3 3:1] => [0:0 1:0 2:0 3:1 3:3]\n// Sort by index _and_ skip number\nexport function sortOperations<TOpIndex extends OperationIndex>(\n operations: TOpIndex[],\n): TOpIndex[] {\n return operations\n .slice()\n .sort((a, b) => a.skip - b.skip)\n .sort((a, b) => a.index - b.index);\n}\n\n// [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, 2:0, B3:0, B4:2, B5:0]\n// GC => [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, B4:2, B5:0]\n// Split => [0:0, 1:0] + [2:0, A3:0, A4:0, A5:0] + [B4:2, B5:0]\n// Reshuffle(6:4) => [6:4, 7:0, 8:0, 9:0, 10:0, 11:0]\n// merge => [0:0, 1:0, 6:4, 7:0, 8:0, 9:0, 10:0, 11:0]\nexport function reshuffleByTimestamp<TOp extends OperationIndex>(\n startIndex: OperationIndex,\n opsA: TOp[],\n opsB: TOp[],\n): TOp[] {\n return [...opsA, ...opsB]\n .sort((a, b) => {\n const timestampDiff =\n new Date(a.timestampUtcMs || \"\").getTime() -\n new Date(b.timestampUtcMs || \"\").getTime();\n if (timestampDiff !== 0) {\n return timestampDiff;\n }\n return (a.id || \"\").localeCompare(b.id || \"\");\n })\n .map((op, i) => ({\n ...op,\n index: startIndex.index + i,\n skip: i === 0 ? startIndex.skip : 0,\n }));\n}\n\nexport function reshuffleByTimestampAndIndex<TOp extends OperationIndex>(\n startIndex: OperationIndex,\n opsA: TOp[],\n opsB: TOp[],\n): TOp[] {\n return [...opsA, ...opsB]\n .sort((a, b) => {\n const indexDiff = a.index - b.index;\n if (indexDiff !== 0) {\n return indexDiff;\n }\n const timestampDiff =\n new Date(a.timestampUtcMs || \"\").getTime() -\n new Date(b.timestampUtcMs || \"\").getTime();\n if (timestampDiff !== 0) {\n return timestampDiff;\n }\n return (a.id || \"\").localeCompare(b.id || \"\");\n })\n .map((op, i) => ({\n ...op,\n index: startIndex.index + i,\n skip: i === 0 ? startIndex.skip : 0,\n }));\n}\n\n// TODO: implement better operation equality function\nexport function operationsAreEqual<\n TOp extends {\n index: number;\n skip: number;\n type?: string;\n scope?: string;\n input?: unknown;\n },\n>(op1: TOp, op2: TOp): boolean {\n const a = op1;\n const b = op2;\n\n const aComparable = {\n index: a.index,\n skip: a.skip,\n type: a.type ?? null,\n scope: a.scope ?? null,\n input: a.input ?? null,\n };\n\n const bComparable = {\n index: b.index,\n skip: b.skip,\n type: b.type ?? null,\n scope: b.scope ?? null,\n input: b.input ?? null,\n };\n\n return stringify(aComparable) === stringify(bComparable);\n}\n\n// [T0:0 T1:0 T2:0 T3:0] + [B4:0 B5:0] = [T0:0 T1:0 T2:0 T3:0 B4:0 B5:0]\n// [T0:0 T1:0 T2:0 T3:0] + [B3:0 B4:0] = [T0:0 T1:0 T2:0 B3:0 B4:0]\n// [T0:0 T1:0 T2:0 T3:0] + [B2:0 B3:0] = [T0:0 T1:0 B2:0 B3:0]\n\n// [T0:0 T1:0 T2:0 T3:0] + [B4:0 B4:2] = [T0:0 T1:0 T2:0 T3:0 B4:0 B4:2]\n// [T0:0 T1:0 T2:0 T3:0] + [B3:0 B3:2] = [T0:0 T1:0 T2:0 B3:0 B3:2]\n// [T0:0 T1:0 T2:0 T3:0] + [B2:3 B3:0] = [T0:0 T1:0 B2:3 B3:0]\n\nexport function attachBranch(\n trunk: Operation[],\n newBranch: Operation[],\n): [Operation[], Operation[]] {\n const trunkCopy = garbageCollect(sortOperations(trunk.slice()));\n const newOperations = garbageCollect(sortOperations(newBranch.slice()));\n if (trunkCopy.length < 1) {\n return [newOperations, []];\n }\n\n const result: Operation[] = [];\n let enteredBranch = false;\n\n while (newOperations.length > 0) {\n const newOperationCandidate = newOperations[0];\n\n let nextTrunkOperation = trunkCopy.shift();\n while (\n nextTrunkOperation &&\n precedes(nextTrunkOperation, newOperationCandidate)\n ) {\n result.push(nextTrunkOperation);\n nextTrunkOperation = trunkCopy.shift();\n }\n\n if (!nextTrunkOperation) {\n enteredBranch = true;\n } else if (!enteredBranch) {\n if (operationsAreEqual(nextTrunkOperation, newOperationCandidate)) {\n newOperations.shift();\n result.push(nextTrunkOperation);\n } else {\n trunkCopy.unshift(nextTrunkOperation);\n enteredBranch = true;\n }\n }\n\n if (enteredBranch) {\n let nextAppend = newOperations.shift();\n while (nextAppend) {\n result.push(nextAppend);\n nextAppend = newOperations.shift();\n }\n }\n }\n\n if (!enteredBranch) {\n let nextAppend = trunkCopy.shift();\n while (nextAppend) {\n result.push(nextAppend);\n nextAppend = trunkCopy.shift();\n }\n }\n\n return [garbageCollect(result), trunkCopy];\n}\n\nexport function precedes(op1: OperationIndex, op2: OperationIndex) {\n return (\n op1.index < op2.index ||\n (op1.index === op2.index && op1.id === op2.id && op1.skip < op2.skip)\n );\n}\n\nexport function split(\n sortedTargetOperations: Operation[],\n sortedMergeOperations: Operation[],\n): [Operation[], Operation[], Operation[]] {\n const commonOperations: Operation[] = [];\n const targetDiffOperations: Operation[] = [];\n const mergeDiffOperations: Operation[] = [];\n\n // get bigger array length\n const maxLength = Math.max(\n sortedTargetOperations.length,\n sortedMergeOperations.length,\n );\n\n let splitHappened = false;\n for (let i = 0; i < maxLength; i++) {\n const targetOperation = sortedTargetOperations[i];\n const mergeOperation = sortedMergeOperations[i];\n\n if (targetOperation && mergeOperation) {\n if (\n !splitHappened &&\n operationsAreEqual(targetOperation, mergeOperation)\n ) {\n commonOperations.push(targetOperation);\n } else {\n splitHappened = true;\n targetDiffOperations.push(targetOperation);\n mergeDiffOperations.push(mergeOperation);\n }\n } else if (targetOperation) {\n targetDiffOperations.push(targetOperation);\n } else if (mergeOperation) {\n mergeDiffOperations.push(mergeOperation);\n }\n }\n\n return [commonOperations, targetDiffOperations, mergeDiffOperations];\n}\n\n// [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, 2:0, B3:0, B4:2, B5:0]\n// GC => [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, B4:2, B5:0]\n// Split => [0:0, 1:0] + [2:0, A3:0, A4:0, A5:0] + [B4:2, B5:0]\n// Reshuffle(6:4) => [6:4, 7:0, 8:0, 9:0, 10:0, 11:0]\n// merge => [0:0, 1:0, 6:4, 7:0, 8:0, 9:0, 10:0, 11:0]\nexport function merge(\n sortedTargetOperations: Operation[],\n sortedMergeOperations: Operation[],\n reshuffle: Reshuffle,\n): Operation[] {\n const [_commonOperations, _targetOperations, _mergeOperations] = split(\n garbageCollect(sortedTargetOperations),\n garbageCollect(sortedMergeOperations),\n );\n\n const maxCommonIndex = getMaxIndex(_commonOperations);\n const nextIndex =\n 1 +\n Math.max(\n maxCommonIndex,\n getMaxIndex(_targetOperations),\n getMaxIndex(_mergeOperations),\n );\n\n const filteredMergeOperations = filterDuplicatedOperations(\n _mergeOperations,\n _targetOperations,\n );\n\n const newOperationHistory = reshuffle(\n {\n index: nextIndex,\n skip: nextIndex - (maxCommonIndex + 1),\n },\n _targetOperations,\n filteredMergeOperations,\n );\n\n return _commonOperations.concat(newOperationHistory);\n}\n\nfunction getMaxIndex(sortedOperations: OperationIndex[]) {\n const lastElement = sortedOperations[sortedOperations.length - 1];\n if (!lastElement) {\n return -1;\n }\n\n return lastElement.index;\n}\n\n// [] => -1\n// [0:0] => -1\n// [0:0 1:0] => 1\n// [0:0 1:1] => -1\n// [1:1] => -1\n// [0:0 1:0 2:0] => 1\n// [0:0 1:0 2:0 2:1] => 2\n// [0:0 1:0 2:0 2:1 2:2] => -1\n// [0:0 1:1 2:0] => 2\n// [0:0 1:1 2:2] => -1\n// [0:0 1:1 2:0 3:0] => 1\n// [0:0 1:1 2:0 3:1] => 3\n// [0:0 1:1 2:0 3:3] => -1\n// [50:50 100:50 150:50 151:0 152:0 153:0 154:3] => 53\n\nexport function nextSkipNumber(sortedOperations: OperationIndex[]) {\n if (sortedOperations.length < 1) {\n return -1;\n }\n\n const cleanedOperations = garbageCollect(sortedOperations);\n\n let nextSkip =\n (cleanedOperations[cleanedOperations.length - 1]?.skip || 0) + 1;\n\n if (cleanedOperations.length > 1) {\n nextSkip += cleanedOperations[cleanedOperations.length - 2]?.skip || 0;\n }\n\n return (cleanedOperations[cleanedOperations.length - 1]?.index || -1) <\n nextSkip\n ? -1\n : nextSkip;\n}\n\nexport function checkOperationsIntegrity(operations: Operation[]) {\n return checkCleanedOperationsIntegrity(\n garbageCollect(sortOperations(operations)),\n );\n}\nexport function groupOperationsByScope(operations: Operation[]) {\n const result = operations.reduce<OperationsByScope>((acc, operation) => {\n if (!acc[operation.action.scope]) {\n acc[operation.action.scope] = [];\n }\n\n acc[operation.action.scope]?.push(operation);\n\n return acc;\n }, {});\n\n return result;\n}\n\ntype PrepareOperationsResult = {\n validOperations: Operation[];\n invalidOperations: Operation[];\n duplicatedOperations: Operation[];\n integrityIssues: IntegrityIssue[];\n};\n\nexport function prepareOperations(\n operationsHistory: Operation[],\n newOperations: Operation[],\n) {\n const result: PrepareOperationsResult = {\n integrityIssues: [],\n validOperations: [],\n invalidOperations: [],\n duplicatedOperations: [],\n };\n\n const sortedOperationsHistory = sortOperations(operationsHistory);\n const sortedOperations = sortOperations(newOperations);\n\n const integrityErrors = checkCleanedOperationsIntegrity([\n ...sortedOperationsHistory,\n ...sortedOperations,\n ]);\n\n const missingIndexErrors = integrityErrors.filter(\n (integrityIssue) =>\n integrityIssue.category === IntegrityIssueSubType.MISSING_INDEX,\n );\n\n // get the integrity error with the lowest index operation\n const firstMissingIndexOperation = [...missingIndexErrors]\n .sort((a, b) => b.operation.index - a.operation.index)\n .pop()?.operation;\n\n for (const newOperation of sortedOperations) {\n // Operation is missing index or it follows an operation that is missing index\n if (\n firstMissingIndexOperation &&\n newOperation.index >= firstMissingIndexOperation.index\n ) {\n result.invalidOperations.push(newOperation);\n continue;\n }\n\n // check if operation is duplicated\n const isDuplicatedOperation = integrityErrors.some((integrityError) => {\n return (\n integrityError.operation.index === newOperation.index &&\n integrityError.operation.skip === newOperation.skip &&\n integrityError.category === IntegrityIssueSubType.DUPLICATED_INDEX\n );\n });\n\n // add to duplicated operations if it is duplicated\n if (isDuplicatedOperation) {\n result.duplicatedOperations.push(newOperation);\n continue;\n }\n\n // otherwise, add to valid operations\n result.validOperations.push(newOperation);\n }\n\n result.integrityIssues.push(...integrityErrors);\n return result;\n}\n\nexport function removeExistingOperations(\n newOperations: Operation[],\n operationsHistory: Operation[],\n) {\n return newOperations.filter((newOperation) => {\n return !operationsHistory.some((historyOperation) => {\n return (\n (newOperation.action.type === \"NOOP\" &&\n newOperation.skip === 0 &&\n newOperation.index === historyOperation.index) ||\n (newOperation.index === historyOperation.index &&\n newOperation.skip === historyOperation.skip &&\n newOperation.action.scope === historyOperation.action.scope &&\n newOperation.hash === historyOperation.hash &&\n newOperation.action.type === historyOperation.action.type)\n );\n });\n });\n}\n\n/**\n * Skips header operations and returns the remaining operations.\n *\n * @param operations - The array of operations.\n * @param skipHeaderOperation - The skip header operation index.\n * @returns The remaining operations after skipping header operations.\n */\nexport function skipHeaderOperations(\n operations: Operation[],\n skipHeaderOperation: SkipHeaderOperationIndex,\n): Operation[] {\n const lastOperation = sortOperations(operations).at(-1);\n const lastIndex = lastOperation?.index ?? -1;\n const nextIndex = lastIndex + 1;\n\n const skipOperationIndex = {\n ...skipHeaderOperation,\n index: skipHeaderOperation.index ?? nextIndex,\n };\n\n if (skipOperationIndex.index < lastIndex) {\n throw new Error(\n `The skip header operation index must be greater than or equal to ${lastIndex}`,\n );\n }\n\n const clearedOperations = garbageCollect(\n sortOperations([...operations, skipOperationIndex]),\n );\n\n return clearedOperations.slice(0, -1) as Operation[]; //clearedOperation ? [clearedOperation as TOpIndex] : [];\n}\n\nexport function garbageCollectDocumentOperations(\n documentOperations: DocumentOperations,\n) {\n const clearedOperations = Object.entries(documentOperations).reduce(\n (acc, entry) => {\n const [scope, ops] = entry;\n if (!ops) {\n return acc;\n }\n\n return {\n ...acc,\n [scope]: garbageCollect(sortOperations(ops)),\n };\n },\n {},\n );\n\n return clearedOperations as DocumentOperations;\n}\n\n/**\n * Filters out duplicated operations from the target operations array based on their IDs.\n * If an operation has an ID, it is considered duplicated if there is another operation in the source operations array with the same ID.\n * If an operation does not have an ID, it is considered unique and will not be filtered out.\n * @param targetOperations - The array of target operations to filter.\n * @param sourceOperations - The array of source operations to compare against.\n * @returns An array of operations with duplicates filtered out.\n */\nexport function filterDuplicatedOperations<T extends { id?: string | number }>(\n targetOperations: T[],\n sourceOperations: T[],\n): T[] {\n return targetOperations.filter((op) => {\n if (op.id) {\n return !sourceOperations.some((targetOp) => targetOp.id === op.id);\n }\n\n return true;\n });\n}\n\nexport function filterDocumentOperationsResultingState(\n documentOperations?: DocumentOperations,\n) {\n if (!documentOperations) {\n return {} as DocumentOperations;\n }\n\n const entries = Object.entries(documentOperations);\n\n return entries.reduce((acc, [scope, operations]) => {\n if (!operations) {\n return acc;\n }\n return {\n ...acc,\n [scope]: operations.map((op) => {\n const { resultingState, ...restProps } = op;\n\n return restProps;\n }),\n };\n }, {} as DocumentOperations);\n}\n\n/**\n * Calculates the difference between two arrays of operations.\n * Returns an array of operations that are present in `clearedOperationsA` but not in `clearedOperationsB`.\n *\n * @template TOp - The type of the operations.\n * @param {TOp[]} clearedOperationsA - The first array of operations.\n * @param {TOp[]} clearedOperationsB - The second array of operations.\n * @returns {TOp[]} - The difference between the two arrays of operations.\n */\nexport function diffOperations<TOp extends OperationIndex>(\n clearedOperationsA: TOp[],\n clearedOperationsB: TOp[],\n): TOp[] {\n return clearedOperationsA.filter(\n (operationA) =>\n !clearedOperationsB.some(\n (operationB) => operationA.index === operationB.index,\n ),\n );\n}\n\n// Returns the timestamp of the latest operation by index (and skip as tiebreaker),\n// falling back to the document header's lastModifiedAtUtcIso\nexport function getDocumentLastModified(document: PHDocument) {\n let latest: Operation | undefined;\n\n for (const ops of Object.values(document.operations)) {\n if (!ops) continue;\n for (const op of ops) {\n if (\n !latest ||\n op.index > latest.index ||\n (op.index === latest.index && op.skip > latest.skip)\n ) {\n latest = op;\n }\n }\n }\n\n return latest?.timestampUtcMs || document.header.lastModifiedAtUtcIso;\n}\n\n/**\n * Gets the next revision number based on the provided scope.\n *\n * @param state The current state of the document.\n * @param scope The scope of the operation.\n * @returns The next revision number.\n */\nfunction getNextRevision(document: PHDocument, scope: string) {\n const scopeOperations = document.operations[scope];\n const maxIndex = scopeOperations?.at(-1)?.index ?? -1;\n return maxIndex + 1;\n}\n\n/**\n * Updates the document header with the latest revision number and\n * date of last modification.\n *\n * @param document The current state of the document.\n * @param scope The scope of the operation.\n * @param lastModifiedTimestamp Optional timestamp to use directly, avoiding a scan of all operations.\n * @returns The updated document state.\n */\nexport function updateHeaderRevision(\n document: PHDocument,\n scope: string,\n lastModifiedTimestamp?: string,\n): PHDocument {\n const newTimestamp =\n lastModifiedTimestamp ?? getDocumentLastModified(document);\n const currentTimestamp = document.header.lastModifiedAtUtcIso;\n\n const header: PHDocumentHeader = {\n ...document.header,\n revision: {\n ...document.header.revision,\n [scope]: getNextRevision(document, scope),\n },\n lastModifiedAtUtcIso:\n !currentTimestamp || newTimestamp > currentTimestamp\n ? newTimestamp\n : currentTimestamp,\n };\n\n return {\n ...document,\n header,\n };\n}\n","import type { Draft } from \"mutative\";\nimport { castDraft, create } from \"mutative\";\nimport { noop, type Action } from \"./actions.js\";\nimport type { PHDocument } from \"./documents.js\";\nimport { nextSkipNumber, sortOperations } from \"./documents.js\";\nimport type { PHBaseState } from \"./state.js\";\nimport type { LoadStateActionInput } from \"./types.js\";\n\n// updates the name of the document\nexport function setNameOperation<TDocument extends PHDocument>(\n document: TDocument,\n input: { name: string },\n) {\n return { ...document, header: { ...document.header, name: input.name } };\n}\n\nexport function undoOperation<TDocument extends PHDocument>(\n document: TDocument,\n action: Action,\n skip: number,\n): {\n document: TDocument;\n action: Action;\n skip: number;\n reuseLastOperationIndex: boolean;\n} {\n // const scope = action.scope;\n const { scope } = action;\n\n const defaultResult = {\n document,\n action,\n skip,\n reuseLastOperationIndex: false,\n };\n\n return create(defaultResult, (draft) => {\n const operations = [...document.operations[scope]];\n const sortedOperations = sortOperations(operations);\n\n draft.action = noop(scope) as Draft<Action>;\n\n const lastOperation = sortedOperations.at(-1);\n let nextIndex = lastOperation?.index ?? -1;\n\n const isNewNoop = lastOperation?.action.type !== \"NOOP\";\n\n if (isNewNoop) {\n nextIndex = nextIndex + 1;\n } else {\n draft.reuseLastOperationIndex = true;\n }\n\n const nextOperationHistory = isNewNoop\n ? [...sortedOperations, { index: nextIndex, skip: 0 }]\n : sortedOperations;\n\n draft.skip = nextSkipNumber(nextOperationHistory);\n\n if (lastOperation && draft.skip > lastOperation.skip + 1) {\n // there's an overlap with a previous skip operation\n // (add 1 to the skip value because we are adding a new operation to the history)\n draft.skip = draft.skip + 1;\n }\n\n if (draft.skip < 0) {\n throw new Error(\n `Cannot undo: you can't undo more operations than the ones in the scope history`,\n );\n }\n });\n}\n\n/**\n * V2 of undoOperation for protocol version 2+.\n * Key differences from undoOperation:\n * - Never reuses operation index (always increments)\n * - Always sets skip=1 (consecutive NOOPs are handled during rebuild/GC)\n * - No complex skip calculation - simpler model where each UNDO is independent\n */\nexport function undoOperationV2<TDocument extends PHDocument>(\n document: TDocument,\n action: Action,\n skip: number,\n): {\n document: TDocument;\n action: Action;\n skip: number;\n reuseLastOperationIndex: false;\n} {\n const { scope } = action;\n\n const defaultResult = {\n document,\n action,\n skip,\n reuseLastOperationIndex: false as const,\n };\n\n return create(defaultResult, (draft) => {\n const operations = document.operations[scope] || [];\n const sortedOperations = sortOperations([...operations]);\n\n // Count non-NOOP operations to determine if there's anything to undo\n const nonNoopOps = sortedOperations.filter(\n (op) => op.action.type !== \"NOOP\",\n );\n\n // Count consecutive NOOPs at the end (these represent pending undos)\n let noopChainLength = 0;\n for (let i = sortedOperations.length - 1; i >= 0; i--) {\n if (sortedOperations[i].action.type === \"NOOP\") {\n noopChainLength++;\n } else {\n break;\n }\n }\n\n // Check if we can undo: need more non-NOOP ops than the current NOOP chain\n if (nonNoopOps.length <= noopChainLength) {\n throw new Error(\n `Cannot undo: no more operations to undo in scope history`,\n );\n }\n\n draft.action = noop(scope) as Draft<Action>;\n draft.skip = 1;\n });\n}\n\nexport function redoOperation<TDocument extends PHDocument>(\n document: TDocument,\n action: Action,\n skip: number,\n): {\n document: TDocument;\n action: Action;\n skip: number;\n reuseLastOperationIndex: boolean;\n} {\n const { scope, input } = action;\n\n const defaultResult = {\n document,\n action,\n skip,\n reuseLastOperationIndex: false,\n };\n\n return create(defaultResult, (draft) => {\n if (draft.skip > 0) {\n throw new Error(\n `Cannot redo: skip value from reducer cannot be used with REDO action`,\n );\n }\n\n // Handle both object format { count: number } and legacy number format\n const count =\n typeof input === \"object\" && input !== null && \"count\" in input\n ? (input as { count: number }).count\n : input;\n\n if (typeof count !== \"number\" || count > 1) {\n throw new Error(`Cannot redo: you can only redo one operation at a time`);\n }\n\n if (typeof count !== \"number\" || count < 1) {\n throw new Error(`Invalid REDO action: invalid redo input value`);\n }\n\n if (draft.document.clipboard.length < 1) {\n throw new Error(`Cannot redo: no operations in the clipboard`);\n }\n\n const operationIndex = draft.document.clipboard.findLastIndex(\n (op) => op.action.scope === scope,\n );\n if (operationIndex < 0) {\n throw new Error(\n `Cannot redo: no operations in clipboard for scope \"${scope}\"`,\n );\n }\n\n const operation = draft.document.clipboard.splice(operationIndex, 1)[0];\n\n draft.action = castDraft({\n type: operation.action.type,\n scope: operation.action.scope,\n input: operation.action.input,\n } as Action);\n });\n}\n\nexport function loadStateOperation<TState extends PHBaseState>(\n document: PHDocument<TState>,\n action: LoadStateActionInput,\n): PHDocument<TState> {\n return {\n ...document,\n header: { ...document.header, name: action.state.name },\n state: action.state.data as TState,\n };\n}\n\n/**\n * An operation that was applied to a {@link BaseDocument}.\n *\n * @remarks\n * Wraps an action with an index, to be added to the operations history of a Document.\n * The `index` field is used to keep all operations in order and enable replaying the\n * document's history from the beginning. Note that indices and skips are relative to\n * a specific reactor. Example below:\n *\n * For (index, skip, ts, action)\n * A - [(0, 0, 1, \"A0\"), (1, 0, 2, \"A1\")]\n * B - [(0, 0, 0, \"B0\"), (1, 0, 3, \"B1\")]\n * ...\n * B gets A's Operations Scenario:\n * B' - [(0, 0, 0, \"B0\"), (1, 0, 3, \"B1\"), (2, 1, 1, \"A0\"), (3, 0, 2, \"A1\"), (4, 0, 3, \"B1\")]\n * Then A needs to end up with:\n * A' - [(0, 0, 1, \"A0\"), (1, 0, 2, \"A1\"), (2, 2, 0, \"B0\"), (3, 0, 1, \"A0\"), (4, 0, 2, \"A1\"), (5, 0, 3, \"B1\")]\n * So that both A and B end up with the stream of actions (action):\n * [(\"B0\"), (\"A0\"), (\"A1\"), (\"B1\")]\n *\n * @typeParam A - The type of the action.\n */\nexport type Operation = {\n /**\n * This is a stable id, derived from various document and action properties\n * in deriveOperationId().\n *\n * It _cannot_ be an arbitrary string.\n *\n * It it also not unique per operation, as reshuffled operations will keep'\n * the same id they had before they were reshuffled. This means that the\n * IOperationStore may have multiple operations with the same operation id.\n **/\n id: string;\n\n /** Position of the operation in the history. This is relative to a specific reactor -- they may not all agree on this value. */\n index: number;\n\n /** The number of operations skipped with this Operation. This is relative to a specific reactor -- they may not all agree on this value. */\n skip: number;\n\n /** Timestamp of when the operation was added */\n timestampUtcMs: string;\n\n /** Hash of the resulting document data after the operation */\n hash: string;\n\n /** Error message for a failed action */\n error?: string;\n\n /** The resulting state after the operation */\n resultingState?: string;\n\n /**\n * The action that was applied to the document to produce this operation.\n */\n action: Action;\n};\n\n/**\n * The operations history of the document by scope.\n *\n * This will be removed in a future release.\n *\n * TODO: Type should be Partial<Record<string, Operation[]>>,\n * but that is a breaking change for codegen + external doc models.\n */\nexport type DocumentOperations = Record<string, Operation[]>;\n\nexport type OperationContext = {\n documentId: string;\n documentType: string;\n scope: string;\n branch: string;\n resultingState?: string;\n\n // This is a _global_ ordinal that is increasing across all documents and scopes.\n ordinal: number;\n};\n\nexport type OperationWithContext = {\n operation: Operation;\n context: OperationContext;\n};\n","import { castDraft, create, unsafe } from \"mutative\";\nimport type { Action } from \"./actions.js\";\nimport {\n actionFromAction,\n loadState,\n operationFromAction,\n operationFromOperation,\n} from \"./actions.js\";\nimport {\n diffOperations,\n garbageCollect,\n garbageCollectDocumentOperations,\n garbageCollectV2,\n hashDocumentStateForScope,\n isDocumentAction,\n isUndo,\n isUndoRedo,\n parseResultingState,\n replayDocument,\n skipHeaderOperations,\n sortOperations,\n updateHeaderRevision,\n type PHDocument,\n type PHDocumentHeader,\n} from \"./documents.js\";\nimport {\n loadStateOperation,\n redoOperation,\n setNameOperation,\n undoOperation,\n undoOperationV2,\n type DocumentOperations,\n type Operation,\n type OperationContext,\n} from \"./operations.js\";\nimport { DocumentActionSchema } from \"./schemas.js\";\nimport type { PHBaseState } from \"./state.js\";\nimport type {\n PruneActionInput,\n Reducer,\n ReducerOptions,\n ReplayDocumentOptions,\n SignalDispatch,\n SkipHeaderOperations,\n StateReducer,\n} from \"./types.js\";\n\n// This rebuilds the document according to the provided actions.\nexport function replayOperations<TState extends PHBaseState = PHBaseState>(\n initialState: TState,\n clearedOperations: DocumentOperations,\n stateReducer: StateReducer<TState>,\n header: PHDocumentHeader,\n dispatch?: SignalDispatch,\n documentReducer = baseReducer,\n skipHeaderOperations: SkipHeaderOperations = {},\n options?: ReplayDocumentOptions,\n): PHDocument<TState> {\n // wraps the provided custom reducer with the\n // base document reducer\n const wrappedReducer = createReducer(stateReducer, documentReducer);\n\n return replayDocument<TState>(\n initialState,\n clearedOperations,\n wrappedReducer,\n header,\n dispatch,\n skipHeaderOperations,\n options,\n );\n}\n\n/**\n * Updates the operations history of the document based on the provided action.\n *\n * @param state The current state of the document.\n * @param action The action being applied to the document.\n * @param index The index of the operation to update.\n * @param skip The number of operations to skip before applying the action.\n * @param reuseLastOperationIndex Whether to reuse the last operation index (used when a an UNDO operation is performed after an existing one).\n * @param context The operation context for deterministic ID generation.\n * @returns The updated document state.\n */\nfunction updateOperationsForAction<TDocument extends PHDocument>(\n document: TDocument,\n action: Action,\n reuseLastOperationIndex: boolean,\n skip: number,\n context: OperationContext,\n): TDocument {\n // UNDO, REDO and PRUNE are meta operations\n // that alter the operations history themselves\n if ([\"UNDO\", \"REDO\", \"PRUNE\"].includes(action.type)) {\n return document;\n }\n\n const scope = action.scope;\n const existing = document.operations[scope];\n // Relies on ops being sorted ascending by index — see reactor CLAUDE.md invariants.\n const lastOperationIndex = existing?.at(-1)?.index ?? -1;\n\n const index = reuseLastOperationIndex\n ? lastOperationIndex\n : lastOperationIndex + 1;\n\n const newOperation = operationFromAction(action, index, skip, context);\n\n const operations = [...(existing ?? []), newOperation];\n\n return {\n ...document,\n operations: { ...document.operations, [scope]: operations },\n };\n}\n\nfunction updateOperationsForOperation<TDocument extends PHDocument>(\n document: TDocument,\n operation: Operation,\n reuseLastOperationIndex: boolean,\n skip: number,\n context: OperationContext,\n skipIndexValidation?: boolean,\n): TDocument {\n const scope = operation.action.scope;\n const existing = document.operations[scope];\n // Relies on ops being sorted ascending by index — see reactor CLAUDE.md invariants.\n const lastOperationIndex = existing?.at(-1)?.index ?? -1;\n\n const nextIndex = reuseLastOperationIndex\n ? lastOperationIndex\n : lastOperationIndex + 1;\n\n if (!skipIndexValidation && operation.index - skip > nextIndex) {\n throw new Error(\n `Missing operations: expected ${nextIndex} with skip 0 or equivalent, got index ${operation.index} with skip ${skip}`,\n );\n }\n\n const newOperation = operationFromOperation(\n operation,\n operation.index,\n skip,\n context,\n );\n\n const operations = [...(existing ?? []), newOperation];\n\n return {\n ...document,\n operations: { ...document.operations, [scope]: operations },\n };\n}\n\n/**\n * Updates the document state based on the provided action.\n *\n * @param state The current state of the document.\n * @param action The action being applied to the document.\n * @param skip The number of operations to skip before applying the action.\n * @param reuseLastOperationIndex Whether to reuse the last operation index (used when a an UNDO operation is performed after an existing one).\n * @param context The operation context for deterministic ID generation.\n * @returns The updated document state.\n */\nexport function updateDocument<TDocument extends PHDocument>(\n document: TDocument,\n action: Action,\n reuseLastOperationIndex: boolean,\n skip: number,\n context: OperationContext,\n operation?: Operation,\n skipIndexValidation?: boolean,\n): TDocument {\n let newDocument: TDocument;\n if (operation) {\n // operation\n newDocument = updateOperationsForOperation(\n document,\n operation,\n reuseLastOperationIndex,\n skip,\n context,\n skipIndexValidation,\n ) as TDocument;\n } else {\n // action\n newDocument = updateOperationsForAction(\n document,\n action,\n reuseLastOperationIndex,\n skip,\n context,\n ) as TDocument;\n }\n\n newDocument = updateHeaderRevision(\n newDocument,\n action.scope,\n action.timestampUtcMs,\n ) as TDocument;\n return newDocument;\n}\n\n/**\n * The base document reducer function that wraps a custom reducer function.\n *\n * @param state The current state of the document.\n * @param action The action being applied to the document.\n * @param wrappedReducer The custom reducer function being wrapped by the base reducer.\n * @returns The updated document state.\n */\nfunction _baseReducer<TState extends PHBaseState = PHBaseState>(\n document: PHDocument<TState>,\n action: Action,\n wrappedReducer: StateReducer<TState>,\n): PHDocument<TState> {\n // throws if action is not valid base action\n const parsedAction = DocumentActionSchema().parse(action);\n\n switch (parsedAction.type) {\n // TODO: This needs to be changed to a HEADER scope action if it's changing the header.\n case \"SET_NAME\":\n return setNameOperation(document, parsedAction.input);\n case \"PRUNE\":\n return pruneOperation(document, parsedAction.input, wrappedReducer);\n case \"LOAD_STATE\":\n return loadStateOperation(document, parsedAction.input);\n default:\n return document;\n }\n}\n\n/**\n * Processes an UNDO or REDO action.\n *\n * @param document The current state of the document.\n * @param action The action being applied to the document.\n * @param skip The number of operations to skip before applying the action.\n * @returns The updated document, calculated skip value and transformed action (if applied).\n */\nexport function processUndoRedo<TState extends PHBaseState = PHBaseState>(\n document: PHDocument<TState>,\n action: Action,\n skip: number,\n protocolVersion = 1,\n): {\n document: PHDocument<TState>;\n action: Action;\n skip: number;\n reuseLastOperationIndex: boolean;\n} {\n switch (action.type) {\n case \"UNDO\":\n if (protocolVersion >= 2) {\n return undoOperationV2(document, action, skip);\n }\n return undoOperation(document, action, skip);\n case \"REDO\":\n return redoOperation(document, action, skip);\n default:\n return { document, action, skip, reuseLastOperationIndex: false };\n }\n}\n\nfunction processSkipOperation<TState extends PHBaseState = PHBaseState>(\n document: PHDocument<TState>,\n action: Action,\n customReducer: StateReducer<TState>,\n skipValue: number,\n reuseOperationResultingState = false,\n resultingStateParser = parseResultingState,\n): PHDocument<TState> {\n const scope = action.scope;\n\n const scopeOperations = document.operations[scope];\n if (!scopeOperations) {\n return document;\n }\n\n const latestOperation = scopeOperations.at(-1);\n\n if (!latestOperation) return document;\n\n const documentOperations = garbageCollectDocumentOperations({\n ...document.operations,\n [scope]: skipHeaderOperations(scopeOperations, latestOperation),\n });\n\n let scopeState: unknown = undefined;\n const documentScopeOps = documentOperations[scope];\n const lastRemainingOperation = documentScopeOps?.at(-1);\n\n // if the last operation has the resulting state and\n // reuseOperationResultingState is true then reuses it\n // instead of replaying the operations from the beginning\n if (reuseOperationResultingState && lastRemainingOperation?.resultingState) {\n scopeState = resultingStateParser(lastRemainingOperation.resultingState);\n } else {\n const { state } = replayOperations(\n document.initialState,\n documentOperations,\n customReducer,\n document.header,\n undefined,\n undefined,\n undefined,\n {\n reuseOperationResultingState,\n operationResultingStateParser: resultingStateParser,\n skipIndexValidation: true,\n },\n );\n\n scopeState = (state as Record<string, unknown>)[scope];\n }\n\n return {\n ...document,\n state: {\n ...document.state,\n [scope]: scopeState,\n },\n operations: garbageCollectDocumentOperations({\n ...document.operations,\n }),\n };\n}\n\nfunction processUndoOperation<TState extends PHBaseState = PHBaseState>(\n document: PHDocument<TState>,\n scope: string,\n customReducer: StateReducer<TState>,\n reuseOperationResultingState = false,\n resultingStateParser = parseResultingState,\n): PHDocument<TState> {\n const scopeOperations = document.operations[scope];\n if (!scopeOperations) {\n return document;\n }\n const operations = [...scopeOperations];\n const sortedOperations = sortOperations(operations);\n\n sortedOperations.pop();\n\n const documentOperations = garbageCollectDocumentOperations({\n ...document.operations,\n });\n\n const documentScopeOps = documentOperations[scope];\n if (!documentScopeOps) {\n return document;\n }\n const clearedOperations = [...documentScopeOps];\n const diff = diffOperations(\n garbageCollect(sortedOperations),\n clearedOperations,\n );\n\n const doc = replayOperations(\n document.initialState,\n documentOperations,\n customReducer,\n document.header,\n undefined,\n undefined,\n undefined,\n {\n reuseOperationResultingState,\n operationResultingStateParser: resultingStateParser,\n },\n );\n\n const clipboard = sortOperations(\n [...document.clipboard, ...diff].filter((op) => op.action.type !== \"NOOP\"),\n ).reverse();\n\n return { ...doc, clipboard } as PHDocument<TState>;\n}\n\n/**\n * Base document reducer that wraps a custom document reducer and handles\n * document-level actions such as undo, redo, prune, and set name.\n *\n * @template TGlobalState - The type of the state of the custom reducer.\n * @template TAction - The type of the actions of the custom reducer.\n * @param state - The current state of the document.\n * @param action - The action object to apply to the state.\n * @param customReducer - The custom reducer that implements the application logic\n * specific to the document's state.\n * @returns The new state of the document.\n */\nexport function baseReducer<TState extends PHBaseState = PHBaseState>(\n document: PHDocument<TState>,\n action: Action,\n customReducer: StateReducer<TState>,\n dispatch?: SignalDispatch,\n options: ReducerOptions = {},\n): PHDocument<TState> {\n const {\n skip,\n ignoreSkipOperations = false,\n reuseOperationResultingState = false,\n operationResultingStateParser,\n pruneOnSkip = true,\n branch = \"main\",\n } = options;\n\n let _action: Action = actionFromAction(action);\n\n let skipValue = skip ?? options.replayOptions?.operation.skip ?? 0;\n let newDocument = {\n ...document,\n };\n let reuseLastOperationIndex = false;\n\n const shouldProcessSkipOperation = !ignoreSkipOperations && skipValue > 0;\n\n if (isUndoRedo(_action)) {\n const {\n skip: calculatedSkip,\n action: transformedAction,\n document: processedDocument,\n reuseLastOperationIndex: reuseIndex,\n } = processUndoRedo(\n document,\n _action,\n skipValue,\n options.protocolVersion ?? 1,\n );\n\n _action = transformedAction;\n skipValue = calculatedSkip;\n newDocument = processedDocument;\n reuseLastOperationIndex = reuseIndex;\n } else {\n newDocument = {\n ...newDocument,\n clipboard: [],\n };\n }\n\n // if the action is one the base document actions (SET_NAME, UNDO, REDO, PRUNE)\n // then runs the base reducer first\n if (isDocumentAction(_action)) {\n newDocument = _baseReducer(newDocument, _action, customReducer);\n }\n\n // updates the document revision number, last modified date\n // and operation history\n const operationContext = {\n documentId: document.header.id,\n scope: _action.scope,\n branch,\n } as OperationContext;\n\n newDocument = updateDocument(\n newDocument,\n _action,\n reuseLastOperationIndex,\n skipValue,\n operationContext,\n options.replayOptions?.operation,\n options.skipIndexValidation,\n );\n\n // Only process undo for actual UNDO actions in protocol v1\n // For v2, NOOPs always have skip=1 and indices increment\n // NOOP operations with skip > 0 will have their clipboard populated server-side\n const protocolVersion = options.protocolVersion ?? 1;\n if (isUndo(action) && protocolVersion < 2) {\n const result = processUndoOperation(\n newDocument,\n action.scope,\n customReducer,\n );\n return result;\n }\n\n // V2 UNDO: Rebuild state using garbageCollectV2 which handles consecutive NOOPs as chains\n // Also trigger for NOOP operations loaded from sync (they have skip > 0)\n const isNoopWithSkip = _action.type === \"NOOP\" && skipValue > 0;\n if ((isUndo(action) || isNoopWithSkip) && protocolVersion >= 2) {\n const scope = _action.scope;\n const scopeOperations = newDocument.operations[scope] || [];\n const sortedOps = sortOperations([...scopeOperations]);\n\n // Get operations that should be applied (excludes undone operations)\n const effectiveOps = garbageCollectV2(sortedOps) as Operation[];\n\n // Build operations for replay - only include non-NOOP operations\n const opsToReplay = effectiveOps.filter(\n (op: Operation) => op.action.type !== \"NOOP\",\n );\n\n // Create document operations with only the effective ops for this scope\n const replayOps: DocumentOperations = {\n ...newDocument.operations,\n [scope]: opsToReplay,\n };\n\n // Replay to rebuild state using replayOperations which wraps the reducer\n // Pass skipIndexValidation since garbageCollectV2 creates gapped indices\n const rebuiltDoc = replayOperations(\n newDocument.initialState,\n replayOps,\n customReducer,\n newDocument.header,\n dispatch,\n baseReducer,\n {},\n { skipIndexValidation: true },\n );\n\n // Return document with rebuilt state but original operations (including all NOOPs)\n return {\n ...rebuiltDoc,\n operations: newDocument.operations,\n clipboard: [],\n } as PHDocument<TState>;\n }\n\n if (shouldProcessSkipOperation) {\n const processed = processSkipOperation(\n newDocument,\n _action,\n customReducer,\n skipValue,\n reuseOperationResultingState,\n operationResultingStateParser,\n );\n\n // Preserve operations when pruneOnSkip is false\n if (!pruneOnSkip) {\n newDocument = {\n ...processed,\n operations: newDocument.operations,\n };\n } else {\n newDocument = processed;\n }\n }\n\n // wraps the custom reducer with Mutative to avoid\n // mutation bugs and allow writing reducers with\n // mutating code\n newDocument = create(newDocument, (draft) => {\n // the reducer runs on a immutable version of\n // provided state\n try {\n const newState = customReducer(draft.state, _action, dispatch);\n\n // const clipboardValue = isUndoRedo(action) ? [...clipboard] : [];\n\n // if the reducer creates a new state object instead\n // of mutating the draft then returns the new state\n if (newState) {\n // Object.assign(draft.state, newState);\n unsafe(() => {\n // casts new state as draft to comply with typescript\n draft.state = castDraft(newState);\n // clipboard: [...clipboardValue],\n });\n } else {\n // unsafe(() => {\n // draft.clipboard = castDraft([...clipboardValue]);\n // });\n }\n } catch (error) {\n // if the reducer throws an error then we should keep the previous state (before replayOperations)\n // and remove skip number from action/operation\n const actionScopeOps = newDocument.operations[_action.scope];\n if (!actionScopeOps) {\n throw new Error(`No operations found for scope: ${_action.scope}`);\n }\n const lastOperationIndex = actionScopeOps.length - 1;\n const draftScopeOps = draft.operations[_action.scope];\n if (!draftScopeOps) {\n throw new Error(\n `No operations found in draft for scope: ${_action.scope}`,\n );\n }\n draftScopeOps[lastOperationIndex].error = (error as Error).message;\n\n draftScopeOps[lastOperationIndex].skip = 0;\n\n if (shouldProcessSkipOperation) {\n draft.state = castDraft({\n ...document.state,\n });\n const documentScopeOps = document.operations[_action.scope];\n if (!documentScopeOps) {\n throw new Error(`No operations found for scope: ${_action.scope}`);\n }\n draft.operations = castDraft({\n ...document.operations,\n [_action.scope]: [\n ...documentScopeOps,\n {\n ...draftScopeOps[lastOperationIndex],\n },\n ],\n });\n }\n }\n });\n // updates the document history\n // meta operations are not added to the operations history\n if ([\"UNDO\", \"REDO\", \"PRUNE\"].includes(_action.type)) {\n return newDocument;\n }\n\n // if reuseHash is true, checks if the action has\n // an hash and uses it instead of generating it\n const scope = _action.scope || \"global\";\n let hash = hashDocumentStateForScope(newDocument, scope);\n if (\n options.replayOptions?.operation.hash &&\n options.replayOptions.operation.hash !== \"\"\n ) {\n hash = options.replayOptions.operation.hash;\n }\n\n // updates the last operation with the hash of the resulting state\n const scopeOperations = newDocument.operations[scope];\n const lastOperation = scopeOperations?.at(-1);\n if (lastOperation) {\n lastOperation.hash = hash;\n\n if (reuseOperationResultingState) {\n lastOperation.resultingState = JSON.stringify(\n (newDocument.state as Record<string, unknown>)[scope],\n );\n }\n }\n\n return newDocument;\n}\n\n/**\n * Helper function to create a document model reducer.\n *\n * @remarks\n * This function creates a new reducer that wraps the provided `reducer` with\n * `documentReducer`, adding support for document actions:\n * - `SET_NAME`\n * - `UNDO`\n * - `REDO`\n * - `PRUNE`\n *\n * It also updates the document-related attributes on every operation.\n *\n * @param reducer - The custom reducer to wrap.\n * @param documentReducer - The document reducer to use.\n *\n * @returns The new reducer.\n */\nexport function createReducer<TState extends PHBaseState = PHBaseState>(\n stateReducer: StateReducer<TState>,\n documentReducer = baseReducer,\n): Reducer<TState> {\n const reducer: Reducer<TState> = (\n document: PHDocument<TState>,\n action: Action,\n dispatch?: SignalDispatch,\n options?: ReducerOptions,\n ) => {\n return documentReducer(document, action, stateReducer, dispatch, options);\n };\n return reducer;\n}\n\nexport function pruneOperation<TState extends PHBaseState = PHBaseState>(\n document: PHDocument<TState>,\n input: PruneActionInput,\n wrappedReducer: StateReducer<TState>,\n): PHDocument<TState> {\n const operations = document.operations.global;\n if (!operations) {\n throw new Error(\"No global operations found\");\n }\n\n let { start, end } = input;\n start = start || 0;\n end = end || operations.length;\n\n const actionsToPrune = operations.slice(start, end);\n const actionsToKeepStart = operations.slice(0, start);\n const actionsToKeepEnd = operations.slice(end);\n\n // runs all operations from the initial state to\n // the end of prune to get name and data\n const newDocument = replayOperations(\n document.initialState,\n {\n ...document.operations,\n global: actionsToKeepStart.concat(actionsToPrune),\n },\n wrappedReducer,\n document.header,\n );\n\n const newState = newDocument.state;\n const name = newDocument.header.name;\n\n // the new operation has the index of the first pruned operation\n const loadStateIndex = actionsToKeepStart.length;\n\n // if and operation is pruned then reuses the timestamp of the last operation\n // if not then assigns the timestamp of the following unpruned operation\n const loadStateTimestamp = actionsToKeepStart.length\n ? actionsToKeepStart[actionsToKeepStart.length - 1].timestampUtcMs\n : actionsToKeepEnd.length\n ? actionsToKeepEnd[0].timestampUtcMs\n : new Date().toISOString();\n\n const action = loadState({ name, ...newState }, actionsToPrune.length);\n\n // replaces pruned operations with LOAD_STATE\n return replayOperations(\n document.initialState,\n {\n ...document.operations,\n global: [\n ...actionsToKeepStart,\n {\n skip: 0,\n ...action,\n action,\n timestampUtcMs: loadStateTimestamp,\n index: loadStateIndex,\n hash: hashDocumentStateForScope({ state: newState }, \"global\"),\n },\n ...actionsToKeepEnd\n // updates the index for all the following operations\n .map((action, index) => ({\n ...action,\n index: loadStateIndex + index + 1,\n })),\n ],\n },\n wrappedReducer,\n document.header,\n );\n}\n","import { pascalCase } from \"change-case\";\nimport type { DocumentOperations } from \"./operations.js\";\nimport type {\n DocumentModelGlobalState,\n ModuleSpecification,\n OperationSpecification,\n ValidationError,\n} from \"./types.js\";\n\n/**\n * Reserved operation names from base reducer (core/actions.ts).\n * These names cannot be used for custom operations.\n */\nexport const RESERVED_OPERATION_NAMES = [\n \"UNDO\",\n \"REDO\",\n \"PRUNE\",\n \"LOAD_STATE\",\n \"SET_NAME\",\n \"NOOP\",\n] as const;\n\nexport type ReservedOperationName = (typeof RESERVED_OPERATION_NAMES)[number];\n\n/**\n * Check if name conflicts with base reducer actions (case-insensitive).\n */\nexport function isReservedOperationName(name: string): boolean {\n return RESERVED_OPERATION_NAMES.includes(\n name.toUpperCase() as ReservedOperationName,\n );\n}\n\n/**\n * Get all operation names from all modules in the latest specification.\n * Returns names in uppercase for case-insensitive comparison.\n */\nexport function getAllOperationNames(\n state: DocumentModelGlobalState,\n excludeOperationId?: string,\n): string[] {\n const latestSpec = state.specifications[state.specifications.length - 1];\n if (!latestSpec) return [];\n\n const names: string[] = [];\n for (const module of latestSpec.modules) {\n for (const operation of module.operations) {\n if (excludeOperationId && operation.id === excludeOperationId) continue;\n if (operation.name) names.push(operation.name.toUpperCase());\n }\n }\n return names;\n}\n\n/**\n * Validate operation name is not reserved or duplicate. Throws on failure.\n *\n * @param name - The operation name to validate\n * @param state - The document model global state\n * @param excludeOperationId - Optional operation ID to exclude (for rename validation)\n * @throws Error if the name is reserved or a duplicate\n */\nexport function validateOperationName(\n name: string,\n state: DocumentModelGlobalState,\n excludeOperationId?: string,\n): void {\n if (!name) return; // Empty names handled by existing validation\n\n const upperName = name.toUpperCase();\n\n if (isReservedOperationName(name)) {\n throw new Error(\n `Operation name \"${name}\" is reserved. Please use a different name.`,\n );\n }\n\n const existingNames = getAllOperationNames(state, excludeOperationId);\n if (existingNames.includes(upperName)) {\n throw new Error(\n `Operation name \"${name}\" is already used by another operation. Operation names must be unique across all modules.`,\n );\n }\n}\n\nexport function validateInitialState(\n initialState: string,\n allowEmptyState = false,\n): ValidationError[] {\n const errors: ValidationError[] = [];\n\n if (allowEmptyState && initialState === \"\") return errors;\n\n try {\n const state = JSON.parse(initialState) as object;\n\n if (!allowEmptyState && !Object.keys(state).length) {\n errors.push({\n message: \"Initial state cannot be empty\",\n details: {\n initialState,\n },\n });\n }\n } catch {\n errors.push({\n message: \"Invalid initial state\",\n details: {\n initialState,\n },\n });\n }\n\n return errors;\n}\n\nexport function validateStateSchemaName(\n schema: string,\n documentName: string,\n scope = \"\",\n allowEmptySchema = true,\n): ValidationError[] {\n const errors: ValidationError[] = [];\n\n if (!allowEmptySchema && !schema) {\n errors.push({\n message: \"State schema is required\",\n details: {\n schema,\n },\n });\n\n return errors;\n }\n\n if (allowEmptySchema && !schema) return errors;\n\n const expectedTypeName = `${pascalCase(documentName)}${pascalCase(scope)}State`;\n\n // Use regex to match exact type name definition\n // Pattern matches: type TypeName followed by whitespace, {, @, or end of string\n // This ensures we match \"type TodoState\" but NOT \"type TodoState2\"\n const typePattern = new RegExp(\n `\\\\btype\\\\s+${expectedTypeName}(?:\\\\s|\\\\{|@|$)`,\n );\n\n if (!typePattern.test(schema)) {\n errors.push({\n message: `Invalid state schema name. Expected type ${expectedTypeName}`,\n details: {\n schema,\n },\n });\n }\n\n return errors;\n}\n\nexport function validateModules(\n modules: ModuleSpecification[],\n): ValidationError[] {\n const errors: ValidationError[] = [];\n if (!modules.length) {\n errors.push({\n message: \"Modules are required\",\n details: {\n modules,\n },\n });\n }\n\n const modulesError = modules.reduce<ValidationError[]>(\n (acc, mod) => [...acc, ...validateModule(mod)],\n [],\n );\n\n return [...errors, ...modulesError];\n}\n\nexport function validateModule(mod: ModuleSpecification): ValidationError[] {\n const errors: ValidationError[] = [];\n\n if (!mod.name) {\n errors.push({\n message: \"Module name is required\",\n details: {\n module: mod,\n },\n });\n }\n\n if (!mod.operations.length) {\n errors.push({\n message: \"Module operations are required\",\n details: {\n module: mod,\n },\n });\n }\n\n const operationErrors = mod.operations.reduce<ValidationError[]>(\n (acc, operation) => [...acc, ...validateModuleOperation(operation)],\n [],\n );\n\n return [...errors, ...operationErrors];\n}\n\nexport function validateModuleOperation(\n operation: OperationSpecification,\n): ValidationError[] {\n const errors: ValidationError[] = [];\n\n if (!operation.name) {\n errors.push({\n message: \"Operation name is required\",\n details: {\n operation,\n },\n });\n }\n\n if (!operation.schema) {\n errors.push({\n message: \"Operation schema is required\",\n details: {\n operation,\n },\n });\n }\n\n return errors;\n}\n\nexport function validateOperations(operations: DocumentOperations) {\n const errors: ValidationError[] = [];\n const scopes = Object.keys(operations);\n\n for (const scope of scopes) {\n const scopeOperations = operations[scope];\n if (!scopeOperations) {\n continue;\n }\n const ops = scopeOperations.sort((a, b) => a.index - b.index);\n\n let opIndex = -1;\n\n for (let i = 0; i < ops.length; i++) {\n opIndex = opIndex + 1 + ops[i].skip;\n if (ops[i].index !== opIndex) {\n errors.push({\n message: `Invalid operation index ${ops[i].index} at position ${i}`,\n details: {\n position: i,\n operation: ops[i],\n scope: ops[i].action.scope,\n },\n });\n }\n }\n }\n\n return errors;\n}\n","import { isDocumentAction } from \"./documents.js\";\nimport { createReducer } from \"./reducer.js\";\nimport {\n AddChangeLogItemInputSchema,\n AddModuleInputSchema,\n AddOperationErrorInputSchema,\n AddOperationExampleInputSchema,\n AddOperationInputSchema,\n AddStateExampleInputSchema,\n DeleteChangeLogItemInputSchema,\n DeleteModuleInputSchema,\n DeleteOperationErrorInputSchema,\n DeleteOperationExampleInputSchema,\n DeleteOperationInputSchema,\n DeleteStateExampleInputSchema,\n MoveOperationInputSchema,\n ReorderChangeLogItemsInputSchema,\n ReorderModuleOperationsInputSchema,\n ReorderModulesInputSchema,\n ReorderOperationErrorsInputSchema,\n ReorderOperationExamplesInputSchema,\n ReorderStateExamplesInputSchema,\n SetAuthorNameInputSchema,\n SetAuthorWebsiteInputSchema,\n SetInitialStateInputSchema,\n SetModelDescriptionInputSchema,\n SetModelExtensionInputSchema,\n SetModelIdInputSchema,\n SetModelNameInputSchema,\n SetModuleDescriptionInputSchema,\n SetModuleNameInputSchema,\n SetOperationDescriptionInputSchema,\n SetOperationErrorCodeInputSchema,\n SetOperationErrorDescriptionInputSchema,\n SetOperationErrorNameInputSchema,\n SetOperationErrorTemplateInputSchema,\n SetOperationNameInputSchema,\n SetOperationReducerInputSchema,\n SetOperationSchemaInputSchema,\n SetOperationScopeInputSchema,\n SetOperationTemplateInputSchema,\n SetStateSchemaInputSchema,\n UpdateChangeLogItemInputSchema,\n UpdateOperationExampleInputSchema,\n UpdateStateExampleInputSchema,\n} from \"./schemas.js\";\nimport type {\n AddChangeLogItemAction,\n AddModuleAction,\n AddOperationAction,\n AddOperationErrorAction,\n AddOperationExampleAction,\n AddStateExampleAction,\n DeleteChangeLogItemAction,\n DeleteModuleAction,\n DeleteOperationAction,\n DeleteOperationErrorAction,\n DeleteOperationExampleAction,\n DeleteStateExampleAction,\n DocumentModelHeaderOperations,\n DocumentModelModuleOperations,\n DocumentModelOperationErrorOperations,\n DocumentModelOperationExampleOperations,\n DocumentModelOperationOperations,\n DocumentModelPHState,\n DocumentModelStateOperations,\n DocumentModelVersioningOperations,\n MoveOperationAction,\n OperationSpecification,\n ReleaseNewVersionAction,\n ReorderChangeLogItemsAction,\n ReorderModuleOperationsAction,\n ReorderModulesAction,\n ReorderOperationErrorsAction,\n ReorderOperationExamplesAction,\n ReorderStateExamplesAction,\n ScopeState,\n SetAuthorNameAction,\n SetAuthorWebsiteAction,\n SetInitialStateAction,\n SetModelDescriptionAction,\n SetModelExtensionAction,\n SetModelIdAction,\n SetModelNameAction,\n SetModuleDescriptionAction,\n SetModuleNameAction,\n SetOperationDescriptionAction,\n SetOperationErrorCodeAction,\n SetOperationErrorDescriptionAction,\n SetOperationErrorNameAction,\n SetOperationErrorTemplateAction,\n SetOperationNameAction,\n SetOperationReducerAction,\n SetOperationSchemaAction,\n SetOperationScopeAction,\n SetOperationTemplateAction,\n SetStateSchemaAction,\n StateReducer,\n UpdateChangeLogItemAction,\n UpdateOperationExampleAction,\n UpdateStateExampleAction,\n} from \"./types.js\";\nimport { validateOperationName } from \"./validation.js\";\n\nfunction sorter<TItem extends { id: string }>(\n order: string[],\n): (a: TItem, b: TItem) => number {\n const mapping: Record<string, number> = {};\n order.forEach((key, index) => (mapping[key] = index));\n return (a: TItem, b: TItem) =>\n (mapping[b.id] || 999999) - (mapping[a.id] || 999999);\n}\n\nexport const documentModelHeaderReducer: DocumentModelHeaderOperations = {\n setModelNameOperation(state, action) {\n state.name = action.input.name;\n },\n\n setModelIdOperation(state, action) {\n state.id = action.input.id;\n },\n\n setModelExtensionOperation(state, action) {\n state.extension = action.input.extension;\n },\n\n setModelDescriptionOperation(state, action) {\n state.description = action.input.description;\n },\n\n setAuthorNameOperation(state, action) {\n state.author = state.author || { name: \"\", website: null };\n state.author.name = action.input.authorName;\n },\n\n setAuthorWebsiteOperation(state, action) {\n state.author = state.author || { name: \"\", website: null };\n state.author.website = action.input.authorWebsite;\n },\n};\nexport const documentModelModuleReducer: DocumentModelModuleOperations = {\n addModuleOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n latestSpec.modules.push({\n id: action.input.id,\n name: action.input.name,\n description: action.input.description || \"\",\n operations: [],\n });\n },\n\n setModuleNameOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n if (latestSpec.modules[i].id === action.input.id) {\n latestSpec.modules[i].name = action.input.name || \"\";\n }\n }\n },\n\n setModuleDescriptionOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n if (latestSpec.modules[i].id === action.input.id) {\n latestSpec.modules[i].description = action.input.description || \"\";\n }\n }\n },\n\n deleteModuleOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n latestSpec.modules = latestSpec.modules.filter(\n (m) => m.id != action.input.id,\n );\n },\n\n reorderModulesOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n latestSpec.modules.sort(sorter(action.input.order));\n },\n};\nexport const documentModelOperationErrorReducer: DocumentModelOperationErrorOperations =\n {\n addOperationErrorOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n if (\n latestSpec.modules[i].operations[j].id == action.input.operationId\n ) {\n latestSpec.modules[i].operations[j].errors.push({\n id: action.input.id,\n name: action.input.errorName || \"\",\n code: action.input.errorCode || \"\",\n description: action.input.errorDescription || \"\",\n template: action.input.errorTemplate || \"\",\n });\n }\n }\n }\n },\n\n setOperationErrorCodeOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n for (\n let k = 0;\n k < latestSpec.modules[i].operations[j].errors.length;\n k++\n ) {\n if (\n latestSpec.modules[i].operations[j].errors[k].id ==\n action.input.id\n ) {\n latestSpec.modules[i].operations[j].errors[k].code =\n action.input.errorCode || \"\";\n }\n }\n }\n }\n },\n\n setOperationErrorNameOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n for (\n let k = 0;\n k < latestSpec.modules[i].operations[j].errors.length;\n k++\n ) {\n if (\n latestSpec.modules[i].operations[j].errors[k].id ==\n action.input.id\n ) {\n latestSpec.modules[i].operations[j].errors[k].name =\n action.input.errorName || \"\";\n }\n }\n }\n }\n },\n\n setOperationErrorDescriptionOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n for (\n let k = 0;\n k < latestSpec.modules[i].operations[j].errors.length;\n k++\n ) {\n if (\n latestSpec.modules[i].operations[j].errors[k].id ==\n action.input.id\n ) {\n latestSpec.modules[i].operations[j].errors[k].description =\n action.input.errorDescription || \"\";\n }\n }\n }\n }\n },\n\n setOperationErrorTemplateOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n for (\n let k = 0;\n k < latestSpec.modules[i].operations[j].errors.length;\n k++\n ) {\n if (\n latestSpec.modules[i].operations[j].errors[k].id ==\n action.input.id\n ) {\n latestSpec.modules[i].operations[j].errors[k].template =\n action.input.errorTemplate || \"\";\n }\n }\n }\n }\n },\n\n deleteOperationErrorOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n latestSpec.modules[i].operations[j].errors = latestSpec.modules[\n i\n ].operations[j].errors.filter((e) => e.id != action.input.id);\n }\n }\n },\n\n reorderOperationErrorsOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n if (\n latestSpec.modules[i].operations[j].id == action.input.operationId\n ) {\n latestSpec.modules[i].operations[j].errors.sort(\n sorter(action.input.order),\n );\n }\n }\n }\n },\n };\n\nexport const documentModelOperationExampleReducer: DocumentModelOperationExampleOperations =\n {\n addOperationExampleOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n if (\n latestSpec.modules[i].operations[j].id == action.input.operationId\n ) {\n latestSpec.modules[i].operations[j].examples.push({\n id: action.input.id,\n value: action.input.example,\n });\n }\n }\n }\n },\n\n updateOperationExampleOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n for (\n let k = 0;\n k < latestSpec.modules[i].operations[j].examples.length;\n k++\n ) {\n if (\n latestSpec.modules[i].operations[j].examples[k].id ==\n action.input.id\n ) {\n latestSpec.modules[i].operations[j].examples[k].value =\n action.input.example;\n }\n }\n }\n }\n },\n\n deleteOperationExampleOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n latestSpec.modules[i].operations[j].examples = latestSpec.modules[\n i\n ].operations[j].examples.filter((e) => e.id != action.input.id);\n }\n }\n },\n\n reorderOperationExamplesOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n if (\n latestSpec.modules[i].operations[j].id == action.input.operationId\n ) {\n latestSpec.modules[i].operations[j].examples.sort(\n sorter(action.input.order),\n );\n }\n }\n }\n },\n };\nexport const documentModelOperationReducer: DocumentModelOperationOperations = {\n addOperationOperation(state, action) {\n validateOperationName(action.input.name, state);\n\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n if (latestSpec.modules[i].id == action.input.moduleId) {\n latestSpec.modules[i].operations.push({\n id: action.input.id,\n name: action.input.name,\n description: action.input.description || \"\",\n schema: action.input.schema || \"\",\n template: action.input.template || action.input.description || \"\",\n reducer: action.input.reducer || \"\",\n errors: [],\n examples: [],\n scope: action.input.scope || \"global\",\n });\n }\n }\n },\n\n setOperationNameOperation(state, action) {\n if (action.input.name) {\n validateOperationName(action.input.name, state, action.input.id);\n }\n\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n if (latestSpec.modules[i].operations[j].id == action.input.id) {\n latestSpec.modules[i].operations[j].name = action.input.name || \"\";\n }\n }\n }\n },\n\n setOperationScopeOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n if (latestSpec.modules[i].operations[j].id == action.input.id) {\n latestSpec.modules[i].operations[j].scope =\n action.input.scope || \"global\";\n }\n }\n }\n },\n\n setOperationSchemaOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n if (latestSpec.modules[i].operations[j].id == action.input.id) {\n latestSpec.modules[i].operations[j].schema =\n action.input.schema || \"\";\n }\n }\n }\n },\n\n setOperationDescriptionOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n if (latestSpec.modules[i].operations[j].id == action.input.id) {\n latestSpec.modules[i].operations[j].description =\n action.input.description || \"\";\n }\n }\n }\n },\n\n setOperationTemplateOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n if (latestSpec.modules[i].operations[j].id == action.input.id) {\n latestSpec.modules[i].operations[j].template =\n action.input.template || \"\";\n }\n }\n }\n },\n\n setOperationReducerOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n for (let j = 0; j < latestSpec.modules[i].operations.length; j++) {\n if (latestSpec.modules[i].operations[j].id == action.input.id) {\n latestSpec.modules[i].operations[j].reducer =\n action.input.reducer || \"\";\n }\n }\n }\n },\n\n moveOperationOperation(state, action) {\n const moveOperations: OperationSpecification[] = [];\n const latestSpec = state.specifications[state.specifications.length - 1];\n\n // Filter and collect\n for (let i = 0; i < latestSpec.modules.length; i++) {\n latestSpec.modules[i].operations = latestSpec.modules[\n i\n ].operations.filter((operation) => {\n if (operation.id == action.input.operationId) {\n moveOperations.push(operation);\n return false;\n }\n\n return true;\n });\n }\n\n // Inject in target modules\n for (let i = 0; i < latestSpec.modules.length; i++) {\n if (latestSpec.modules[i].id == action.input.newModuleId) {\n latestSpec.modules[i].operations.push(...moveOperations);\n }\n }\n },\n\n deleteOperationOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n latestSpec.modules[i].operations = latestSpec.modules[\n i\n ].operations.filter((operation) => operation.id != action.input.id);\n }\n },\n\n reorderModuleOperationsOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n for (let i = 0; i < latestSpec.modules.length; i++) {\n if (latestSpec.modules[i].id == action.input.moduleId) {\n latestSpec.modules[i].operations.sort(sorter(action.input.order));\n }\n }\n },\n};\nexport const documentModelStateSchemaReducer: DocumentModelStateOperations = {\n setStateSchemaOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n if (Object.keys(latestSpec.state).includes(action.input.scope)) {\n latestSpec.state[action.input.scope as keyof ScopeState].schema =\n action.input.schema;\n } else {\n throw new Error(`Invalid scope: ${action.input.scope}`);\n }\n },\n\n setInitialStateOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n if (Object.keys(latestSpec.state).includes(action.input.scope)) {\n latestSpec.state[action.input.scope as keyof ScopeState].initialValue =\n action.input.initialValue;\n } else {\n throw new Error(`Invalid scope: ${action.input.scope}`);\n }\n },\n\n addStateExampleOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n if (Object.keys(latestSpec.state).includes(action.input.scope)) {\n latestSpec.state[action.input.scope as keyof ScopeState].examples.push({\n id: action.input.id,\n value: action.input.example,\n });\n } else {\n throw new Error(`Invalid scope: ${action.input.scope}`);\n }\n },\n\n updateStateExampleOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n if (!Object.keys(latestSpec.state).includes(action.input.scope)) {\n throw new Error(`Invalid scope: ${action.input.scope}`);\n }\n const examples =\n latestSpec.state[action.input.scope as keyof ScopeState].examples;\n\n for (let i = 0; i < examples.length; i++) {\n if (examples[i].id == action.input.id) {\n examples[i].value = action.input.newExample;\n }\n }\n },\n\n deleteStateExampleOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n if (Object.keys(latestSpec.state).includes(action.input.scope)) {\n latestSpec.state[action.input.scope as keyof ScopeState].examples =\n latestSpec.state[\n action.input.scope as keyof ScopeState\n ].examples.filter((e) => e.id != action.input.id);\n } else {\n throw new Error(`Invalid scope: ${action.input.scope}`);\n }\n },\n\n reorderStateExamplesOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n if (Object.keys(latestSpec.state).includes(action.input.scope)) {\n latestSpec.state[action.input.scope as keyof ScopeState].examples.sort(\n sorter(action.input.order),\n );\n } else {\n throw new Error(`Invalid scope: ${action.input.scope}`);\n }\n },\n};\n\nexport const documentModelVersioningReducer: DocumentModelVersioningOperations =\n {\n addChangeLogItemOperation(state, action) {\n throw new Error(\n 'Reducer \"addChangeLogItemOperation\" not yet implemented',\n );\n },\n\n updateChangeLogItemOperation(state, action) {\n throw new Error(\n 'Reducer \"updateChangeLogItemOperation\" not yet implemented',\n );\n },\n\n deleteChangeLogItemOperation(state, action) {\n throw new Error(\n 'Reducer \"deleteChangeLogItemOperation\" not yet implemented',\n );\n },\n\n reorderChangeLogItemsOperation(state, action) {\n throw new Error(\n 'Reducer \"reorderChangeLogItemsOperation\" not yet implemented',\n );\n },\n\n releaseNewVersionOperation(state, action) {\n const latestSpec = state.specifications[state.specifications.length - 1];\n\n const copiedModules = latestSpec.modules.map((module) => ({\n ...module,\n operations: module.operations.map((op) => ({\n ...op,\n errors: op.errors.map((err) => ({ ...err })),\n examples: op.examples.map((ex) => ({ ...ex })),\n })),\n }));\n\n const copiedState = {\n global: {\n ...latestSpec.state.global,\n examples: latestSpec.state.global.examples.map((ex) => ({ ...ex })),\n },\n local: {\n ...latestSpec.state.local,\n examples: latestSpec.state.local.examples.map((ex) => ({ ...ex })),\n },\n };\n\n const newSpec = {\n version: latestSpec.version + 1,\n changeLog: [],\n state: copiedState,\n modules: copiedModules,\n };\n\n state.specifications.push(newSpec);\n },\n };\n\nexport const documentModelStateReducer: StateReducer<DocumentModelPHState> = (\n state,\n action,\n) => {\n if (isDocumentAction(action)) {\n return state;\n }\n\n switch (action.type) {\n case \"SET_MODEL_NAME\":\n SetModelNameInputSchema().parse(action.input);\n documentModelHeaderReducer.setModelNameOperation(\n state.global,\n action as SetModelNameAction,\n );\n break;\n\n case \"SET_MODEL_ID\":\n SetModelIdInputSchema().parse(action.input);\n documentModelHeaderReducer.setModelIdOperation(\n state.global,\n action as SetModelIdAction,\n );\n break;\n\n case \"SET_MODEL_EXTENSION\":\n SetModelExtensionInputSchema().parse(action.input);\n documentModelHeaderReducer.setModelExtensionOperation(\n state.global,\n action as SetModelExtensionAction,\n );\n break;\n\n case \"SET_MODEL_DESCRIPTION\":\n SetModelDescriptionInputSchema().parse(action.input);\n documentModelHeaderReducer.setModelDescriptionOperation(\n state.global,\n action as SetModelDescriptionAction,\n );\n break;\n\n case \"SET_AUTHOR_NAME\":\n SetAuthorNameInputSchema().parse(action.input);\n documentModelHeaderReducer.setAuthorNameOperation(\n state.global,\n action as SetAuthorNameAction,\n );\n break;\n\n case \"SET_AUTHOR_WEBSITE\":\n SetAuthorWebsiteInputSchema().parse(action.input);\n documentModelHeaderReducer.setAuthorWebsiteOperation(\n state.global,\n action as SetAuthorWebsiteAction,\n );\n break;\n\n case \"ADD_CHANGE_LOG_ITEM\":\n AddChangeLogItemInputSchema().parse(action.input);\n documentModelVersioningReducer.addChangeLogItemOperation(\n state.global,\n action as AddChangeLogItemAction,\n );\n break;\n\n case \"UPDATE_CHANGE_LOG_ITEM\":\n UpdateChangeLogItemInputSchema().parse(action.input);\n documentModelVersioningReducer.updateChangeLogItemOperation(\n state.global,\n action as UpdateChangeLogItemAction,\n );\n break;\n\n case \"DELETE_CHANGE_LOG_ITEM\":\n DeleteChangeLogItemInputSchema().parse(action.input);\n documentModelVersioningReducer.deleteChangeLogItemOperation(\n state.global,\n action as DeleteChangeLogItemAction,\n );\n break;\n\n case \"REORDER_CHANGE_LOG_ITEMS\":\n ReorderChangeLogItemsInputSchema().parse(action.input);\n documentModelVersioningReducer.reorderChangeLogItemsOperation(\n state.global,\n action as ReorderChangeLogItemsAction,\n );\n break;\n\n case \"RELEASE_NEW_VERSION\":\n if (Object.keys(action.input as object).length > 0)\n throw new Error(\"Expected empty input for action RELEASE_NEW_VERSION\");\n documentModelVersioningReducer.releaseNewVersionOperation(\n state.global,\n action as ReleaseNewVersionAction,\n );\n break;\n\n case \"ADD_MODULE\":\n AddModuleInputSchema().parse(action.input);\n documentModelModuleReducer.addModuleOperation(\n state.global,\n action as AddModuleAction,\n );\n break;\n\n case \"SET_MODULE_NAME\":\n SetModuleNameInputSchema().parse(action.input);\n documentModelModuleReducer.setModuleNameOperation(\n state.global,\n action as SetModuleNameAction,\n );\n break;\n\n case \"SET_MODULE_DESCRIPTION\":\n SetModuleDescriptionInputSchema().parse(action.input);\n documentModelModuleReducer.setModuleDescriptionOperation(\n state.global,\n action as SetModuleDescriptionAction,\n );\n break;\n\n case \"DELETE_MODULE\":\n DeleteModuleInputSchema().parse(action.input);\n documentModelModuleReducer.deleteModuleOperation(\n state.global,\n action as DeleteModuleAction,\n );\n break;\n\n case \"REORDER_MODULES\":\n ReorderModulesInputSchema().parse(action.input);\n documentModelModuleReducer.reorderModulesOperation(\n state.global,\n action as ReorderModulesAction,\n );\n break;\n\n case \"ADD_OPERATION_ERROR\":\n AddOperationErrorInputSchema().parse(action.input);\n documentModelOperationErrorReducer.addOperationErrorOperation(\n state.global,\n action as AddOperationErrorAction,\n );\n break;\n\n case \"SET_OPERATION_ERROR_CODE\":\n SetOperationErrorCodeInputSchema().parse(action.input);\n documentModelOperationErrorReducer.setOperationErrorCodeOperation(\n state.global,\n action as SetOperationErrorCodeAction,\n );\n break;\n\n case \"SET_OPERATION_ERROR_NAME\":\n SetOperationErrorNameInputSchema().parse(action.input);\n documentModelOperationErrorReducer.setOperationErrorNameOperation(\n state.global,\n action as SetOperationErrorNameAction,\n );\n break;\n\n case \"SET_OPERATION_ERROR_DESCRIPTION\":\n SetOperationErrorDescriptionInputSchema().parse(action.input);\n documentModelOperationErrorReducer.setOperationErrorDescriptionOperation(\n state.global,\n action as SetOperationErrorDescriptionAction,\n );\n break;\n\n case \"SET_OPERATION_ERROR_TEMPLATE\":\n SetOperationErrorTemplateInputSchema().parse(action.input);\n documentModelOperationErrorReducer.setOperationErrorTemplateOperation(\n state.global,\n action as SetOperationErrorTemplateAction,\n );\n break;\n\n case \"DELETE_OPERATION_ERROR\":\n DeleteOperationErrorInputSchema().parse(action.input);\n documentModelOperationErrorReducer.deleteOperationErrorOperation(\n state.global,\n action as DeleteOperationErrorAction,\n );\n break;\n\n case \"REORDER_OPERATION_ERRORS\":\n ReorderOperationErrorsInputSchema().parse(action.input);\n documentModelOperationErrorReducer.reorderOperationErrorsOperation(\n state.global,\n action as ReorderOperationErrorsAction,\n );\n break;\n\n case \"ADD_OPERATION_EXAMPLE\":\n AddOperationExampleInputSchema().parse(action.input);\n documentModelOperationExampleReducer.addOperationExampleOperation(\n state.global,\n action as AddOperationExampleAction,\n );\n break;\n\n case \"UPDATE_OPERATION_EXAMPLE\":\n UpdateOperationExampleInputSchema().parse(action.input);\n documentModelOperationExampleReducer.updateOperationExampleOperation(\n state.global,\n action as UpdateOperationExampleAction,\n );\n break;\n\n case \"DELETE_OPERATION_EXAMPLE\":\n DeleteOperationExampleInputSchema().parse(action.input);\n documentModelOperationExampleReducer.deleteOperationExampleOperation(\n state.global,\n action as DeleteOperationExampleAction,\n );\n break;\n\n case \"REORDER_OPERATION_EXAMPLES\":\n ReorderOperationExamplesInputSchema().parse(action.input);\n documentModelOperationExampleReducer.reorderOperationExamplesOperation(\n state.global,\n action as ReorderOperationExamplesAction,\n );\n break;\n\n case \"ADD_OPERATION\":\n AddOperationInputSchema().parse(action.input);\n documentModelOperationReducer.addOperationOperation(\n state.global,\n action as AddOperationAction,\n );\n break;\n\n case \"SET_OPERATION_NAME\":\n SetOperationNameInputSchema().parse(action.input);\n documentModelOperationReducer.setOperationNameOperation(\n state.global,\n action as SetOperationNameAction,\n );\n break;\n\n case \"SET_OPERATION_SCOPE\":\n SetOperationScopeInputSchema().parse(action.input);\n documentModelOperationReducer.setOperationScopeOperation(\n state.global,\n action as SetOperationScopeAction,\n );\n break;\n\n case \"SET_OPERATION_SCHEMA\":\n SetOperationSchemaInputSchema().parse(action.input);\n documentModelOperationReducer.setOperationSchemaOperation(\n state.global,\n action as SetOperationSchemaAction,\n );\n break;\n\n case \"SET_OPERATION_DESCRIPTION\":\n SetOperationDescriptionInputSchema().parse(action.input);\n documentModelOperationReducer.setOperationDescriptionOperation(\n state.global,\n action as SetOperationDescriptionAction,\n );\n break;\n\n case \"SET_OPERATION_TEMPLATE\":\n SetOperationTemplateInputSchema().parse(action.input);\n documentModelOperationReducer.setOperationTemplateOperation(\n state.global,\n action as SetOperationTemplateAction,\n );\n break;\n\n case \"SET_OPERATION_REDUCER\":\n SetOperationReducerInputSchema().parse(action.input);\n documentModelOperationReducer.setOperationReducerOperation(\n state.global,\n action as SetOperationReducerAction,\n );\n break;\n\n case \"MOVE_OPERATION\":\n MoveOperationInputSchema().parse(action.input);\n documentModelOperationReducer.moveOperationOperation(\n state.global,\n action as MoveOperationAction,\n );\n break;\n\n case \"DELETE_OPERATION\":\n DeleteOperationInputSchema().parse(action.input);\n documentModelOperationReducer.deleteOperationOperation(\n state.global,\n action as DeleteOperationAction,\n );\n break;\n\n case \"REORDER_MODULE_OPERATIONS\":\n ReorderModuleOperationsInputSchema().parse(action.input);\n documentModelOperationReducer.reorderModuleOperationsOperation(\n state.global,\n action as ReorderModuleOperationsAction,\n );\n break;\n\n case \"SET_STATE_SCHEMA\":\n SetStateSchemaInputSchema().parse(action.input);\n documentModelStateSchemaReducer.setStateSchemaOperation(\n state.global,\n action as SetStateSchemaAction,\n );\n break;\n\n case \"SET_INITIAL_STATE\":\n SetInitialStateInputSchema().parse(action.input);\n documentModelStateSchemaReducer.setInitialStateOperation(\n state.global,\n action as SetInitialStateAction,\n );\n break;\n\n case \"ADD_STATE_EXAMPLE\":\n AddStateExampleInputSchema().parse(action.input);\n documentModelStateSchemaReducer.addStateExampleOperation(\n state.global,\n action as AddStateExampleAction,\n );\n break;\n\n case \"UPDATE_STATE_EXAMPLE\":\n UpdateStateExampleInputSchema().parse(action.input);\n documentModelStateSchemaReducer.updateStateExampleOperation(\n state.global,\n action as UpdateStateExampleAction,\n );\n break;\n\n case \"DELETE_STATE_EXAMPLE\":\n DeleteStateExampleInputSchema().parse(action.input);\n documentModelStateSchemaReducer.deleteStateExampleOperation(\n state.global,\n action as DeleteStateExampleAction,\n );\n break;\n\n case \"REORDER_STATE_EXAMPLES\":\n ReorderStateExamplesInputSchema().parse(action.input);\n documentModelStateSchemaReducer.reorderStateExamplesOperation(\n state.global,\n action as ReorderStateExamplesAction,\n );\n break;\n\n default:\n return state;\n }\n};\n\nexport const documentModelReducer = createReducer<DocumentModelPHState>(\n documentModelStateReducer,\n);\n","import { FileSystemError } from \"./errors.js\";\nimport JSZip from \"jszip\";\nimport type { PHDocument, PHDocumentHeader } from \"./documents.js\";\nimport {\n filterDocumentOperationsResultingState,\n garbageCollectDocumentOperations,\n replayDocument,\n} from \"./documents.js\";\nimport type { DocumentOperations } from \"./operations.js\";\nimport { documentModelReducer } from \"./reducers.js\";\nimport type { PHBaseState } from \"./state.js\";\nimport type {\n DocumentModelPHState,\n FileInput,\n LoadFromInput,\n MinimalBackupData,\n Reducer,\n ReplayDocumentOptions,\n SaveToFileHandle,\n} from \"./types.js\";\nimport { validateOperations } from \"./validation.js\";\n\nexport function createZip(document: PHDocument) {\n // create zip file\n const zip = new JSZip();\n\n const header = document.header;\n zip.file(\"header.json\", JSON.stringify(header, null, 2));\n zip.file(\"state.json\", JSON.stringify(document.initialState || {}, null, 2));\n zip.file(\"current-state.json\", JSON.stringify(document.state || {}, null, 2));\n zip.file(\n \"operations.json\",\n JSON.stringify(\n filterDocumentOperationsResultingState(document.operations),\n null,\n 2,\n ),\n );\n\n return zip;\n}\n\n/**\n * Creates a minimal ZIP backup from strand data.\n * Used when the full document is not available (e.g., in onOperations handler).\n * Creates a ZIP with minimal header and empty operations.\n */\nexport function createMinimalZip(data: MinimalBackupData) {\n const now = new Date().toISOString();\n const header: PHDocumentHeader = {\n id: data.documentId,\n sig: { publicKey: {}, nonce: \"\" },\n documentType: data.documentType,\n createdAtUtcIso: now,\n slug: data.name,\n name: data.name,\n branch: data.branch,\n revision: {},\n lastModifiedAtUtcIso: now,\n };\n\n const zip = new JSZip();\n zip.file(\"header.json\", JSON.stringify(header, null, 2));\n zip.file(\"state.json\", JSON.stringify(data.state, null, 2));\n zip.file(\"current-state.json\", JSON.stringify(data.state, null, 2));\n zip.file(\"operations.json\", JSON.stringify({}, null, 2));\n\n return zip;\n}\n\nexport async function baseSaveToFileHandle(\n document: PHDocument,\n input: FileSystemFileHandle,\n) {\n const zip = createZip(document);\n const blob = await zip.generateAsync({ type: \"blob\" });\n const writable = await input.createWritable();\n await writable.write(blob);\n await writable.close();\n}\n\nasync function loadFromZip<TState extends PHBaseState>(\n zip: JSZip,\n reducer: Reducer<TState>,\n options?: ReplayDocumentOptions,\n): Promise<PHDocument<TState>> {\n const initialStateZip = zip.file(\"state.json\");\n if (!initialStateZip) {\n throw new Error(\"Initial state not found\");\n }\n const initialStateStr = await initialStateZip.async(\"string\");\n const initialState = JSON.parse(initialStateStr) as TState;\n\n const headerZip = zip.file(\"header.json\");\n if (!headerZip) {\n throw new Error(\"Document header not found - file format may be outdated\");\n }\n const header = JSON.parse(\n await headerZip.async(\"string\"),\n ) as PHDocumentHeader;\n\n const operationsZip = zip.file(\"operations.json\");\n if (!operationsZip) {\n throw new Error(\"Operations history not found\");\n }\n const operations = JSON.parse(\n await operationsZip.async(\"string\"),\n ) as DocumentOperations;\n\n const clearedOperations = garbageCollectDocumentOperations(operations);\n\n const operationsError = validateOperations(clearedOperations);\n if (operationsError.length) {\n const errorMessages = operationsError.map((err) => err.message);\n throw new Error(errorMessages.join(\"\\n\"));\n }\n\n const result = replayDocument(\n initialState,\n clearedOperations,\n reducer,\n header,\n undefined,\n {},\n options,\n );\n\n return result;\n}\n\nexport async function baseLoadFromInput<TState extends PHBaseState>(\n input: FileInput,\n reducer: Reducer<TState>,\n options?: ReplayDocumentOptions,\n): Promise<PHDocument<TState>> {\n const zip = new JSZip();\n await zip.loadAsync(input);\n return loadFromZip(zip, reducer, options);\n}\n\nexport const documentModelLoadFromInput: LoadFromInput<DocumentModelPHState> = (\n input,\n) => {\n return baseLoadFromInput(input, documentModelReducer);\n};\n\nexport const documentModelSaveToFileHandle: SaveToFileHandle = (\n document,\n input,\n) => {\n return baseSaveToFileHandle(document, input);\n};\n\nexport function writeFileBrowser(\n path: string,\n name: string,\n stream: Uint8Array,\n): Promise<string> {\n throw FileSystemError;\n}\n\nexport function readFileBrowser(path: string) {\n throw FileSystemError;\n}\n\nexport function fetchFileBrowser(\n url: string,\n): Promise<{ data: Buffer; mimeType?: string }> {\n throw FileSystemError;\n}\n\nexport const getFileBrowser = async (file: string) => {\n return readFileBrowser(file);\n};\n","import { HASH_ALGORITHM_SHA1, HASH_ENCODING_BASE64 } from \"./constants.js\";\nimport type { HashConfig } from \"./signatures.js\";\nimport type {\n DocumentModelGlobalState,\n DocumentModelLocalState,\n DocumentModelPHState,\n} from \"./types.js\";\n\n/**\n * Creates a default PHAuthState\n */\nexport function defaultAuthState(): PHAuthState {\n return {};\n}\n\n/**\n * Creates a default PHDocumentState\n */\nexport function defaultDocumentState(): PHDocumentState {\n return {\n version: 0,\n hash: {\n algorithm: HASH_ALGORITHM_SHA1,\n encoding: HASH_ENCODING_BASE64,\n },\n };\n}\n/**\n * Creates a default PHBaseState with auth and document properties\n */\nexport function defaultBaseState(): PHBaseState {\n return {\n auth: defaultAuthState(),\n document: defaultDocumentState(),\n };\n}\n\n/**\n * Creates a PHAuthState with the given properties\n */\nexport function createAuthState(auth?: Partial<PHAuthState>): PHAuthState {\n return {\n ...defaultAuthState(),\n ...auth,\n };\n}\n\n/**\n * Creates a PHDocumentState with the given properties\n */\nexport function createDocumentState(\n document?: Partial<PHDocumentState>,\n): PHDocumentState {\n return {\n ...defaultDocumentState(),\n ...document,\n };\n}\n\n/**\n * Creates a PHBaseState with the given auth and document properties\n */\nexport function createBaseState(\n auth?: Partial<PHAuthState>,\n document?: Partial<PHDocumentState>,\n): PHBaseState {\n return {\n auth: createAuthState(auth),\n document: createDocumentState(document),\n };\n}\n\n/**\n * The document state of the document.\n */\nexport type PHDocumentState = {\n /**\n * The current document model schema version of the document. This is used\n * with the UPGRADE_DOCUMENT operation to specify the DocumentModelModule\n * version to use for reducer execution.\n */\n version: number;\n\n /** Hash configuration for operation state verification */\n hash: HashConfig;\n\n /** True if and only if the document has been deleted */\n isDeleted?: boolean;\n\n /** The timestamp when the document was deleted, in UTC ISO format */\n deletedAtUtcIso?: string;\n\n /** Optional: who deleted the document */\n deletedBy?: string;\n\n /** Optional: reason for deletion */\n deletionReason?: string;\n};\n\n/**\n * The authentication state of the document.\n *\n * This has yet to be implemented.\n */\nexport type PHAuthState = {};\n\n/**\n * The base state of the document.\n */\nexport type PHBaseState = {\n /** Carries authentication information. */\n auth: PHAuthState;\n\n /** Carries information about the document. */\n document: PHDocumentState;\n};\n\nexport function defaultGlobalState(): DocumentModelGlobalState {\n return {\n ...defaultBaseState(),\n author: {\n name: \"\",\n website: \"\",\n },\n description: \"\",\n extension: \"\",\n id: \"\",\n name: \"\",\n specifications: [],\n };\n}\n\nexport function defaultLocalState(): DocumentModelLocalState {\n return {};\n}\n\nexport function defaultPHState(): DocumentModelPHState {\n return {\n ...defaultBaseState(),\n global: defaultGlobalState(),\n local: defaultLocalState(),\n };\n}\n\nexport function createGlobalState(\n state?: Partial<DocumentModelGlobalState>,\n): DocumentModelGlobalState {\n return {\n ...defaultGlobalState(),\n ...(state || {}),\n } as DocumentModelGlobalState;\n}\n\nexport function createLocalState(\n state?: Partial<DocumentModelLocalState>,\n): DocumentModelLocalState {\n return {\n ...defaultLocalState(),\n ...(state || {}),\n } as DocumentModelLocalState;\n}\n\nexport function createState(\n baseState?: Partial<PHBaseState>,\n globalState?: Partial<DocumentModelGlobalState>,\n localState?: Partial<DocumentModelLocalState>,\n): DocumentModelPHState {\n return {\n ...createBaseState(baseState?.auth, baseState?.document),\n global: createGlobalState(globalState),\n local: createLocalState(localState),\n };\n}\n"],"mappings":";;;;;;;AAIA,MAAa,eACX,MACA,YAAY,QACZ,WAAW,UACX,YACG;AACH,KAAI,CAAC,CAAC,OAAO,CAAC,SAAS,UAAU,CAC/B,OAAM,IAAI,MACR,qCAAqC,UAAU,oBAChD;AAGH,KAAI,CAAC,CAAC,UAAU,MAAM,CAAC,SAAS,SAAS,CACvC,OAAM,IAAI,MACR,iCAAiC,SAAS,2BAC3C;CAGH,MAAM,OAAO,cAAc,MAAM,UAAU;AAE3C,KAAI,aAAa,MACf,QAAO,gBAAgB,KAAK;AAG9B,QA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EACZ,KAAA,GACA,+BACA,SACD;AAEH,MAAa,wBAAwB,UACnC,aACE,0BACA,EAAE,GAAG,OAAO,EACZ,KAAA,GACA,iCACA,SACD;AAEH,MAAa,oBAAoB,UAC/B,aACE,uBACA,EAAE,GAAG,OAAO,EACZ,KAAA,GACA,6BACA,SACD;AAEH,MAAa,uBAAuB,UAClC,aACE,0BACA,EAAE,GAAG,OAAO,EACZ,KAAA,GACA,gCACA,SACD;AAEH,MAAa,uBAAuB,UAClC,aACE,0BACA,EAAE,GAAG,OAAO,EACZ,KAAA,GACA,gCACA,SACD;AAEH,MAAa,yBAAyB,UACpC,aACE,4BACA,EAAE,GAAG,OAAO,EACZ,KAAA,GACA,kCACA,SACD;AAEH,MAAa,0BACX,aACE,uBACA,EAAE,EACF,KAAA,GACA,KAAA,GACA,SACD;AAEH,MAAa,cAAc;CACzB;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAa,uBAAuB;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAa,UAAU;CAAE,GAAG;CAAa,GAAG;CAAsB;;;ACn5BlE,MAAa,6BAA6B;AAE1C,MAAa,iCAA0D,EAAE;AACzE,MAAa,kCAA4D;CACvE,IAAI;CACJ,MAAM;CACN,WAAW;CACX,aAAa;CACb,QAAQ;EACN,MAAM;EACN,SAAS;EACV;CACD,gBAAgB,CACd;EACE,SAAS;EACT,WAAW,EAAE;EACb,OAAO;GACL,QAAQ;IACN,QAAQ;IACR,cAAc;IACd,UAAU,EAAE;IACb;GACD,OAAO;IACL,QAAQ;IACR,cAAc;IACd,UAAU,EAAE;IACb;GACF;EACD,SAAS,EAAE;EACZ,CACF;CACF;AACD,MAAa,2BAAqD;CAChE,IAAI;CACJ,MAAM;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