@powerhousedao/powerhouse-vetra-packages 6.2.2-dev.5 → 6.2.2-dev.50

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 (103) hide show
  1. package/dist/browser/assets/{entry-Cvoo4_c9.js → entry-CSmPhBmp.js} +3 -2
  2. package/dist/browser/assets/{projection-entry-DVec8YRh.js → projection-entry-CVK7H2AN.js} +4 -4
  3. package/dist/browser/{linting-Dn6pXRkK.js → button-CuO8Gh3v.js} +20 -6
  4. package/dist/browser/button-CuO8Gh3v.js.map +1 -0
  5. package/dist/browser/{connect-CV-z3DqA.js → connect-C104dWjH.js} +916 -200
  6. package/dist/browser/connect-C104dWjH.js.map +1 -0
  7. package/dist/browser/{dist-CXoKspdx.js → dist-B4FWbuEM.js} +10 -2
  8. package/dist/browser/{dist-CXoKspdx.js.map → dist-B4FWbuEM.js.map} +1 -1
  9. package/dist/{node/dist-BeZaEP6S.mjs → browser/dist-BAJ5nRDl.js} +21 -2
  10. package/dist/browser/{dist-D8H48e8N.js.map → dist-BAJ5nRDl.js.map} +1 -1
  11. package/dist/browser/{dist-BEs8jMgM.js → dist-DX9iadhH.js} +1559 -1292
  12. package/dist/browser/dist-DX9iadhH.js.map +1 -0
  13. package/dist/browser/{document-drive-sTKoi6L4.js → document-drive-CJz0STcj.js} +1077 -122
  14. package/dist/browser/document-drive-CJz0STcj.js.map +1 -0
  15. package/dist/browser/document-models/index.js +1 -1
  16. package/dist/browser/{documents-D4ek7Ubv.js → documents-J_l59mSV.js} +5 -604
  17. package/dist/browser/documents-J_l59mSV.js.map +1 -0
  18. package/dist/browser/{editor-Cw38euRs.js → editor-IvqnagPG.js} +671 -236
  19. package/dist/browser/editor-IvqnagPG.js.map +1 -0
  20. package/dist/browser/editor-X5l1tL2F.js +25 -0
  21. package/dist/browser/editor-X5l1tL2F.js.map +1 -0
  22. package/dist/browser/editors/document-model-editor/module.js +1 -1
  23. package/dist/browser/editors/generic-drive-explorer/index.js +5 -5
  24. package/dist/browser/editors/generic-drive-explorer/module.js +1 -1
  25. package/dist/{node/folder-view-DjKO1mAh.mjs → browser/folder-view-CRb23VC6.js} +73 -46
  26. package/dist/browser/folder-view-CRb23VC6.js.map +1 -0
  27. package/dist/browser/{graphql-editor-B-dNI5hD.js → graphql-editor-WUel_gv1.js} +8 -7
  28. package/dist/browser/{graphql-editor-B-dNI5hD.js.map → graphql-editor-WUel_gv1.js.map} +1 -1
  29. package/dist/browser/{hooks-CORHBNHb.js → hooks-KKcNp2X0.js} +2 -2
  30. package/dist/browser/{hooks-CORHBNHb.js.map → hooks-KKcNp2X0.js.map} +1 -1
  31. package/dist/browser/index.js +378 -9
  32. package/dist/browser/index.js.map +1 -1
  33. package/dist/browser/{json-editor-v_MnzQVs.js → json-editor-b1VZFbze.js} +4 -4
  34. package/dist/browser/{json-editor-v_MnzQVs.js.map → json-editor-b1VZFbze.js.map} +1 -1
  35. package/dist/browser/{lib-C-f3izXz.js → lib-DcVgOOqQ.js} +12 -2
  36. package/dist/browser/lib-DcVgOOqQ.js.map +1 -0
  37. package/dist/browser/printer-CEYr4JOg.js +604 -0
  38. package/dist/browser/printer-CEYr4JOg.js.map +1 -0
  39. package/dist/browser/{schema-context-DY-GEGnY.js → schema-context-ZyeclQwy.js} +2 -2
  40. package/dist/browser/{schema-context-DY-GEGnY.js.map → schema-context-ZyeclQwy.js.map} +1 -1
  41. package/dist/browser/{state-schemas-65Tp0ZuG.js → state-schemas-BuSO5vf_.js} +8 -18
  42. package/dist/browser/state-schemas-BuSO5vf_.js.map +1 -0
  43. package/dist/node/{linting-Dx50GuLN.mjs → button-Da7CxMn7.mjs} +20 -7
  44. package/dist/node/button-Da7CxMn7.mjs.map +1 -0
  45. package/dist/node/{connect-Bbi5wHyR.mjs → connect-s4eurJ2e.mjs} +916 -200
  46. package/dist/node/connect-s4eurJ2e.mjs.map +1 -0
  47. package/dist/{browser/dist-D8H48e8N.js → node/dist-CzYOpeXN.mjs} +21 -2
  48. package/dist/node/{dist-BeZaEP6S.mjs.map → dist-CzYOpeXN.mjs.map} +1 -1
  49. package/dist/node/{dist-fA4EItr0.mjs → dist-DT7jI9ol.mjs} +10 -2
  50. package/dist/node/{dist-fA4EItr0.mjs.map → dist-DT7jI9ol.mjs.map} +1 -1
  51. package/dist/node/{dist-8nCvrie2.mjs → dist-p5v40GE-.mjs} +1564 -1292
  52. package/dist/node/dist-p5v40GE-.mjs.map +1 -0
  53. package/dist/node/{document-drive-DjL9iikf.mjs → document-drive-BgHPyTwW.mjs} +1077 -122
  54. package/dist/node/document-drive-BgHPyTwW.mjs.map +1 -0
  55. package/dist/node/document-models/index.mjs +1 -1
  56. package/dist/node/{documents-BFBPmyw1.mjs → documents-DCf53bzO.mjs} +3 -3
  57. package/dist/node/{documents-BFBPmyw1.mjs.map → documents-DCf53bzO.mjs.map} +1 -1
  58. package/dist/node/editor-Bi7fPi7g.mjs +25 -0
  59. package/dist/node/editor-Bi7fPi7g.mjs.map +1 -0
  60. package/dist/node/{editor-DkT0krRE.mjs → editor-q-CY2cHO.mjs} +672 -237
  61. package/dist/node/editor-q-CY2cHO.mjs.map +1 -0
  62. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  63. package/dist/node/editors/generic-drive-explorer/index.mjs +5 -5
  64. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  65. package/dist/{browser/folder-view-BQWrt8wh.js → node/folder-view-1tKOZNNo.mjs} +73 -46
  66. package/dist/node/folder-view-1tKOZNNo.mjs.map +1 -0
  67. package/dist/node/{graphql-DskHmkMe.mjs → graphql-BfAoPeWM.mjs} +2 -2
  68. package/dist/node/{graphql-DskHmkMe.mjs.map → graphql-BfAoPeWM.mjs.map} +1 -1
  69. package/dist/node/{graphql-editor-x-d_DoqN.mjs → graphql-editor-Bht1MH0X.mjs} +7 -7
  70. package/dist/node/{graphql-editor-x-d_DoqN.mjs.map → graphql-editor-Bht1MH0X.mjs.map} +1 -1
  71. package/dist/node/{hooks-DJrjfVaS.mjs → hooks-D0DcS3MV.mjs} +2 -2
  72. package/dist/node/{hooks-DJrjfVaS.mjs.map → hooks-D0DcS3MV.mjs.map} +1 -1
  73. package/dist/node/index.mjs +378 -9
  74. package/dist/node/index.mjs.map +1 -1
  75. package/dist/node/{json-editor-D8QbP3jl.mjs → json-editor-1QYpJ-1F.mjs} +4 -4
  76. package/dist/node/{json-editor-D8QbP3jl.mjs.map → json-editor-1QYpJ-1F.mjs.map} +1 -1
  77. package/dist/node/{main-D82dkD7g.mjs → main-BO1p3AOa.mjs} +14 -4
  78. package/dist/node/main-BO1p3AOa.mjs.map +1 -0
  79. package/dist/node/{schema-context-CX5ml_9t.mjs → schema-context-DL8jhi_d.mjs} +3 -3
  80. package/dist/node/{schema-context-CX5ml_9t.mjs.map → schema-context-DL8jhi_d.mjs.map} +1 -1
  81. package/dist/node/{state-schemas-BwvZVEhR.mjs → state-schemas-C0CiF1-m.mjs} +10 -20
  82. package/dist/{browser/state-schemas-65Tp0ZuG.js.map → node/state-schemas-C0CiF1-m.mjs.map} +1 -1
  83. package/package.json +7 -6
  84. package/dist/browser/connect-CV-z3DqA.js.map +0 -1
  85. package/dist/browser/dist-BEs8jMgM.js.map +0 -1
  86. package/dist/browser/document-drive-sTKoi6L4.js.map +0 -1
  87. package/dist/browser/documents-D4ek7Ubv.js.map +0 -1
  88. package/dist/browser/editor-Cw38euRs.js.map +0 -1
  89. package/dist/browser/editor-DY3JsQJ3.js +0 -29
  90. package/dist/browser/editor-DY3JsQJ3.js.map +0 -1
  91. package/dist/browser/folder-view-BQWrt8wh.js.map +0 -1
  92. package/dist/browser/lib-C-f3izXz.js.map +0 -1
  93. package/dist/browser/linting-Dn6pXRkK.js.map +0 -1
  94. package/dist/node/connect-Bbi5wHyR.mjs.map +0 -1
  95. package/dist/node/dist-8nCvrie2.mjs.map +0 -1
  96. package/dist/node/document-drive-DjL9iikf.mjs.map +0 -1
  97. package/dist/node/editor-BH2gCDjt.mjs +0 -29
  98. package/dist/node/editor-BH2gCDjt.mjs.map +0 -1
  99. package/dist/node/editor-DkT0krRE.mjs.map +0 -1
  100. package/dist/node/folder-view-DjKO1mAh.mjs.map +0 -1
  101. package/dist/node/linting-Dx50GuLN.mjs.map +0 -1
  102. package/dist/node/main-D82dkD7g.mjs.map +0 -1
  103. package/dist/node/state-schemas-BwvZVEhR.mjs.map +0 -1
@@ -1,4 +1,4 @@
1
- import { E as __commonJSMin, _ as string, c as any, f as lazy, h as object, j as __toESM, l as array, m as number, n as constantCase, o as _enum, p as literal, r as pascalCase, u as boolean, v as union, x as ZodError, y as unknown } from "./dist-fA4EItr0.mjs";
1
+ import { D as __commonJSMin, M as __toESM, S as ZodError, _ as strictObject, b as unknown, c as any, f as lazy, g as record, h as object, l as array, m as number, n as constantCase, o as _enum, p as literal, r as pascalCase, u as boolean, v as string, y as union } from "./dist-DT7jI9ol.mjs";
2
2
  import { createRequire } from "module";
3
3
  //#endregion
4
4
  //#region ../../node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/esm/wrapper.js
@@ -590,7 +590,7 @@ function isBE() {
590
590
  return new Uint8Array(new Uint16Array([65279]).buffer)[0] === 254;
591
591
  }
592
592
  //#endregion
593
- //#region ../shared/dist/utils-DKOFCM0Q.js
593
+ //#region ../shared/dist/utils-CTt1XRn-.js
594
594
  const hashBrowser = (data, algorithm = "sha1", encoding = "base64", _params) => {
595
595
  if (!["sha1"].includes(algorithm)) throw new Error(`Hashing algorithm not supported: "${algorithm}". Available: sha1`);
596
596
  if (!["base64", "hex"].includes(encoding)) throw new Error(`Hash encoding not supported: "${encoding}". Available: base64, hex`);
@@ -637,6 +637,40 @@ function ab2hex(ab) {
637
637
  const view = ArrayBuffer.isView(ab) ? ab : new Uint8Array(ab);
638
638
  return Array.prototype.map.call(view, (x) => ("00" + x.toString(16)).slice(-2)).join("");
639
639
  }
640
+ const BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
641
+ /**
642
+ * Decodes a base58btc (Bitcoin/IPFS alphabet) string to bytes. Returns null on
643
+ * any character outside the alphabet.
644
+ */
645
+ function base58Decode(input) {
646
+ const bytes = [];
647
+ for (const ch of input) {
648
+ let carry = BASE58_ALPHABET.indexOf(ch);
649
+ if (carry === -1) return null;
650
+ for (let i = 0; i < bytes.length; i++) {
651
+ carry += bytes[i] * 58;
652
+ bytes[i] = carry & 255;
653
+ carry >>= 8;
654
+ }
655
+ while (carry > 0) {
656
+ bytes.push(carry & 255);
657
+ carry >>= 8;
658
+ }
659
+ }
660
+ for (let k = 0; k < input.length && input[k] === "1"; k++) bytes.push(0);
661
+ return Uint8Array.from(bytes.reverse());
662
+ }
663
+ /** Decodes a base64url string to bytes (portable across node, browsers, workers). */
664
+ function base64UrlToBytes(input) {
665
+ const base64 = input.replace(/-/g, "+").replace(/_/g, "/");
666
+ const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
667
+ let binary;
668
+ if (typeof atob === "function") binary = atob(padded);
669
+ else binary = Buffer.from(padded, "base64").toString("binary");
670
+ const bytes = new Uint8Array(binary.length);
671
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
672
+ return bytes;
673
+ }
640
674
  function generateId(method) {
641
675
  if (method && method.toString() !== "UUIDv4") throw new Error(`Id generation method not supported: "${method.toString()}"`);
642
676
  return globalThis.crypto.randomUUID();
@@ -2995,6 +3029,75 @@ var DowngradeNotSupportedError = class extends Error {
2995
3029
  this.toVersion = toVersion;
2996
3030
  }
2997
3031
  };
3032
+ /**
3033
+ * Thrown when INITIALIZE_AUTH is applied to an already-initialized auth scope.
3034
+ * The genesis action is valid only at auth revision zero.
3035
+ */
3036
+ var AuthAlreadyInitializedError = class extends Error {
3037
+ documentId;
3038
+ constructor(documentId) {
3039
+ super(`Auth scope already initialized for document ${documentId}: INITIALIZE_AUTH is valid only at auth revision zero`);
3040
+ this.name = "AuthAlreadyInitializedError";
3041
+ this.documentId = documentId;
3042
+ }
3043
+ };
3044
+ /**
3045
+ * Thrown when INITIALIZE_AUTH is not signed by the document creator (its signer
3046
+ * does not match `header.sig.publicKey`), so it cannot set the auth policy.
3047
+ */
3048
+ var AuthInitializerNotCreatorError = class extends Error {
3049
+ documentId;
3050
+ constructor(documentId) {
3051
+ super(`INITIALIZE_AUTH for document ${documentId} must be signed by the document creator`);
3052
+ this.name = "AuthInitializerNotCreatorError";
3053
+ this.documentId = documentId;
3054
+ }
3055
+ };
3056
+ /**
3057
+ * Thrown when INITIALIZE_AUTH carries a version below 1. Version 0 is reserved
3058
+ * for the uninitialized auth scope.
3059
+ */
3060
+ var InvalidAuthVersionError = class extends Error {
3061
+ documentId;
3062
+ version;
3063
+ constructor(documentId, version) {
3064
+ super(`Invalid auth policy version ${version} for document ${documentId}: INITIALIZE_AUTH requires an integer version >= 1`);
3065
+ this.name = "InvalidAuthVersionError";
3066
+ this.documentId = documentId;
3067
+ this.version = version;
3068
+ }
3069
+ };
3070
+ /** Thrown when a duplicate would lose the source policy's version or creator binding. */
3071
+ var AuthPolicyNotPreservedError = class extends Error {
3072
+ documentId;
3073
+ constructor(documentId) {
3074
+ super(`Duplicating document ${documentId} would not preserve its auth policy: the copy loses the policy version or its creator binding`);
3075
+ this.name = "AuthPolicyNotPreservedError";
3076
+ this.documentId = documentId;
3077
+ }
3078
+ };
3079
+ /**
3080
+ * Thrown when a grant referenced by REMOVE_GRANT or MOVE_GRANT does not exist.
3081
+ */
3082
+ var GrantNotFoundError = class extends Error {
3083
+ grantId;
3084
+ constructor(grantId) {
3085
+ super(`Grant not found in auth scope: ${grantId}`);
3086
+ this.name = "GrantNotFoundError";
3087
+ this.grantId = grantId;
3088
+ }
3089
+ };
3090
+ /**
3091
+ * Thrown when a disallowed action (UNDO, REDO, PRUNE) targets the auth scope.
3092
+ */
3093
+ var AuthActionNotAllowedError = class extends Error {
3094
+ actionType;
3095
+ constructor(actionType) {
3096
+ super(`${actionType} is not permitted on the auth scope`);
3097
+ this.name = "AuthActionNotAllowedError";
3098
+ this.actionType = actionType;
3099
+ }
3100
+ };
2998
3101
  var HashMismatchError = class extends Error {
2999
3102
  _scope;
3000
3103
  _document;
@@ -3021,6 +3124,25 @@ var HashMismatchError = class extends Error {
3021
3124
  return this._operation;
3022
3125
  }
3023
3126
  };
3127
+ /**
3128
+ * Thrown when replay or import requires a document model version that is not
3129
+ * registered. Carries the data the UI needs to explain the mismatch.
3130
+ */
3131
+ var UnsupportedDocumentModelVersionError = class extends Error {
3132
+ documentType;
3133
+ requiredVersion;
3134
+ availableVersions;
3135
+ constructor(documentType, requiredVersion, availableVersions) {
3136
+ super(`No reducer registered for document version ${requiredVersion}. Available versions: ${availableVersions.join(", ")}`);
3137
+ this.name = "UnsupportedDocumentModelVersionError";
3138
+ this.documentType = documentType;
3139
+ this.requiredVersion = requiredVersion;
3140
+ this.availableVersions = availableVersions;
3141
+ }
3142
+ static isError(error) {
3143
+ return Error.isError(error) && error.name === "UnsupportedDocumentModelVersionError";
3144
+ }
3145
+ };
3024
3146
  const isDefinedNonNullAny$1 = (v) => v !== void 0 && v !== null;
3025
3147
  any().refine((v) => isDefinedNonNullAny$1(v));
3026
3148
  const Load_StateSchema = _enum(["LOAD_STATE"]);
@@ -3461,17 +3583,101 @@ const ConfigEntrySchema = object({
3461
3583
  required: boolean().optional(),
3462
3584
  default: boolean().optional()
3463
3585
  });
3586
+ const PwaUrlPatternSchema = union([string(), strictObject({
3587
+ source: string(),
3588
+ flags: string().optional()
3589
+ }).refine((p) => {
3590
+ try {
3591
+ new RegExp(p.source, p.flags);
3592
+ return true;
3593
+ } catch {
3594
+ return false;
3595
+ }
3596
+ }, { message: "source/flags do not compile to a valid RegExp" })]);
3597
+ const PwaRuntimeCachingSchema = strictObject({
3598
+ urlPattern: PwaUrlPatternSchema,
3599
+ handler: _enum([
3600
+ "CacheFirst",
3601
+ "CacheOnly",
3602
+ "NetworkFirst",
3603
+ "NetworkOnly",
3604
+ "StaleWhileRevalidate"
3605
+ ]),
3606
+ method: _enum([
3607
+ "GET",
3608
+ "POST",
3609
+ "PUT",
3610
+ "DELETE",
3611
+ "HEAD",
3612
+ "PATCH"
3613
+ ]).optional(),
3614
+ options: strictObject({
3615
+ cacheName: string().optional(),
3616
+ networkTimeoutSeconds: number().optional(),
3617
+ expiration: strictObject({
3618
+ maxEntries: number().optional(),
3619
+ maxAgeSeconds: number().optional()
3620
+ }).optional(),
3621
+ cacheableResponse: strictObject({
3622
+ statuses: array(number()).optional(),
3623
+ headers: record(string(), string()).optional()
3624
+ }).optional()
3625
+ }).optional()
3626
+ });
3627
+ const PwaIconSchema = strictObject({
3628
+ src: string(),
3629
+ sizes: string().optional(),
3630
+ type: string().optional(),
3631
+ purpose: string().optional()
3632
+ });
3633
+ const PwaFileHandlerSchema = strictObject({
3634
+ accept: record(string(), array(string().regex(/^\./, "file extensions must start with '.'"))),
3635
+ icons: array(PwaIconSchema).optional(),
3636
+ launch_type: _enum(["single-client", "multiple-clients"]).optional()
3637
+ });
3638
+ const PwaConfigSchema = strictObject({
3639
+ manifest: strictObject({
3640
+ name: string().optional(),
3641
+ short_name: string().optional(),
3642
+ description: string().optional(),
3643
+ theme_color: string().optional(),
3644
+ background_color: string().optional(),
3645
+ display: _enum([
3646
+ "fullscreen",
3647
+ "standalone",
3648
+ "minimal-ui",
3649
+ "browser"
3650
+ ]).optional(),
3651
+ start_url: string().optional(),
3652
+ scope: string().optional(),
3653
+ icons: array(PwaIconSchema).optional(),
3654
+ file_handlers: array(PwaFileHandlerSchema).optional(),
3655
+ launch_handler: strictObject({ client_mode: _enum([
3656
+ "auto",
3657
+ "focus-existing",
3658
+ "navigate-existing",
3659
+ "navigate-new"
3660
+ ]) }).optional()
3661
+ }).optional(),
3662
+ globPatterns: array(string()).optional(),
3663
+ globIgnores: array(string()).optional(),
3664
+ maximumFileSizeToCacheInBytes: number().optional(),
3665
+ runtimeCaching: array(PwaRuntimeCachingSchema).optional(),
3666
+ navigateFallbackDenylist: array(PwaUrlPatternSchema).optional()
3667
+ });
3464
3668
  object({
3465
3669
  name: string(),
3466
3670
  description: string().optional(),
3467
3671
  category: string().optional(),
3672
+ image: string().optional(),
3468
3673
  publisher: PublisherSchema.optional(),
3469
3674
  documentModels: PowerhouseModulesSchema,
3470
3675
  apps: PowerhouseModulesSchema,
3471
3676
  editors: PowerhouseModulesSchema,
3472
3677
  processors: PowerhouseModulesSchema,
3473
3678
  subgraphs: PowerhouseModulesSchema,
3474
- config: array(ConfigEntrySchema).optional()
3679
+ config: array(ConfigEntrySchema).optional(),
3680
+ pwa: PwaConfigSchema.optional()
3475
3681
  });
3476
3682
  /**
3477
3683
  * Cancels the last `count` operations.
@@ -3742,6 +3948,505 @@ const actions = {
3742
3948
  ...baseActions,
3743
3949
  ...documentModelActions
3744
3950
  };
3951
+ const documentModelDocumentType = "powerhouse/document-model";
3952
+ /**
3953
+ * Thrown when a grant violates the v1 validation rules. The message is stored
3954
+ * on error operations, so it must be a pure function of the input.
3955
+ */
3956
+ var InvalidGrantError = class extends Error {
3957
+ grantId;
3958
+ constructor(grantId, problem) {
3959
+ super(`Invalid grant "${grantId}": ${problem}`);
3960
+ this.name = "InvalidGrantError";
3961
+ this.grantId = grantId;
3962
+ }
3963
+ };
3964
+ /** Thrown for a `{ group }` principal on a group document: references never chain. */
3965
+ var GroupPrincipalNotAllowedError = class extends Error {
3966
+ grantId;
3967
+ constructor(grantId) {
3968
+ super(`Grant "${grantId}" uses a group principal on a group document: a group's auth scope cannot reference other groups`);
3969
+ this.name = "GroupPrincipalNotAllowedError";
3970
+ this.grantId = grantId;
3971
+ }
3972
+ };
3973
+ /**
3974
+ * Thrown when a change would leave a creator-less policy with no grant
3975
+ * permitting execute on the auth scope. Without the creator carve-out no
3976
+ * subject could ever administer such a policy again.
3977
+ */
3978
+ var AuthAdministrationLockoutError = class extends Error {
3979
+ grantId;
3980
+ constructor(grantId) {
3981
+ super(`Change to grant "${grantId}" would leave no reachable grant permitting execute on the auth scope: a policy with no creator must always retain one`);
3982
+ this.name = "AuthAdministrationLockoutError";
3983
+ this.grantId = grantId;
3984
+ }
3985
+ };
3986
+ /**
3987
+ * Thrown when INITIALIZE_AUTH would create a creator-less policy with no grant
3988
+ * permitting execute on the auth scope. Such a policy would be born with no
3989
+ * subject able to administer it.
3990
+ */
3991
+ var AuthAdministrationMissingError = class extends Error {
3992
+ constructor() {
3993
+ super("Initial grants include no reachable grant permitting execute on the auth scope: a policy with no creator must always include one");
3994
+ this.name = "AuthAdministrationMissingError";
3995
+ }
3996
+ };
3997
+ const GRANT_KEYS = new Set([
3998
+ "id",
3999
+ "description",
4000
+ "effect",
4001
+ "principal",
4002
+ "capability",
4003
+ "where"
4004
+ ]);
4005
+ const PRINCIPAL_KINDS = new Set([
4006
+ "anyone",
4007
+ "address",
4008
+ "group",
4009
+ "match"
4010
+ ]);
4011
+ const COMPARISON_CONDITION_KINDS = new Set([
4012
+ "eq",
4013
+ "ne",
4014
+ "lt",
4015
+ "lte",
4016
+ "gt",
4017
+ "gte"
4018
+ ]);
4019
+ function isPlainValue(value) {
4020
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4021
+ }
4022
+ function operandProblem(value, capabilityScope, budget) {
4023
+ budget.nodes -= 1;
4024
+ if (budget.nodes < 0) return `condition exceeds 100 nodes`;
4025
+ if (!isPlainValue(value)) return "operand must be an object";
4026
+ const keys = Object.keys(value);
4027
+ if (keys.length !== 1) return "operand must have exactly one of attr or lit";
4028
+ if (keys[0] === "attr") {
4029
+ const attr = value.attr;
4030
+ if (typeof attr !== "string" || attr.length === 0) return "attr must be a non-empty string";
4031
+ if (capabilityScope !== void 0 && capabilityScope !== "*" && attr.startsWith("doc.")) {
4032
+ const pathScope = attr.split(".")[1] ?? "";
4033
+ if (pathScope !== capabilityScope) return `condition path "${attr}" reads scope "${pathScope}" but the capability covers only scope "${capabilityScope}"`;
4034
+ }
4035
+ return null;
4036
+ }
4037
+ if (keys[0] === "lit") {
4038
+ const lit = value.lit;
4039
+ if (lit !== null && typeof lit !== "string" && typeof lit !== "number" && typeof lit !== "boolean") return "lit must be a string, number, boolean, or null";
4040
+ if (typeof lit === "number" && !Number.isFinite(lit)) return "lit must be a finite number";
4041
+ if (typeof lit === "number" && Object.is(lit, -0)) return "lit must not be negative zero";
4042
+ return null;
4043
+ }
4044
+ return `unknown operand kind "${keys[0]}"`;
4045
+ }
4046
+ function conditionProblem(value, capabilityScope, depth, budget) {
4047
+ if (depth > 10) return `condition exceeds depth 10`;
4048
+ budget.nodes -= 1;
4049
+ if (budget.nodes < 0) return `condition exceeds 100 nodes`;
4050
+ if (!isPlainValue(value)) return "condition must be an object";
4051
+ const keys = Object.keys(value);
4052
+ if (keys.length !== 1) return "condition must have exactly one operator";
4053
+ const kind = keys[0];
4054
+ const body = value[kind];
4055
+ if (COMPARISON_CONDITION_KINDS.has(kind)) {
4056
+ if (!Array.isArray(body) || body.length !== 2) return `${kind} requires a pair of operands`;
4057
+ for (const operand of body) {
4058
+ const problem = operandProblem(operand, capabilityScope, budget);
4059
+ if (problem !== null) return problem;
4060
+ }
4061
+ return null;
4062
+ }
4063
+ if (kind === "in" || kind === "notIn") {
4064
+ if (!Array.isArray(body) || body.length !== 2 || !Array.isArray(body[1])) return `${kind} requires an operand and an operand list`;
4065
+ const first = operandProblem(body[0], capabilityScope, budget);
4066
+ if (first !== null) return first;
4067
+ for (const operand of body[1]) {
4068
+ const problem = operandProblem(operand, capabilityScope, budget);
4069
+ if (problem !== null) return problem;
4070
+ }
4071
+ return null;
4072
+ }
4073
+ if (kind === "exists") return operandProblem(body, capabilityScope, budget);
4074
+ if (kind === "and" || kind === "or") {
4075
+ if (!Array.isArray(body)) return `${kind} requires a condition list`;
4076
+ for (const child of body) {
4077
+ const problem = conditionProblem(child, capabilityScope, depth + 1, budget);
4078
+ if (problem !== null) return problem;
4079
+ }
4080
+ return null;
4081
+ }
4082
+ if (kind === "not") return conditionProblem(body, capabilityScope, depth + 1, budget);
4083
+ return `unknown condition operator "${kind}"`;
4084
+ }
4085
+ function principalProblem(value, capabilityScope) {
4086
+ if (!isPlainValue(value)) return "principal must be an object";
4087
+ const keys = Object.keys(value);
4088
+ if (keys.length !== 1 || !PRINCIPAL_KINDS.has(keys[0])) return "principal must have exactly one of anyone, address, group, or match";
4089
+ const kind = keys[0];
4090
+ if (kind === "anyone" && value.anyone !== true) return "anyone must be true";
4091
+ if (kind === "address") {
4092
+ const address = value.address;
4093
+ if (typeof address !== "string" || address.length === 0) return "address must be a non-empty string";
4094
+ }
4095
+ if (kind === "group") {
4096
+ const group = value.group;
4097
+ if (typeof group !== "string" || group.length === 0) return "group must be a non-empty string";
4098
+ }
4099
+ if (kind === "match") return conditionProblem(value.match, capabilityScope, 1, { nodes: 100 });
4100
+ return null;
4101
+ }
4102
+ function capabilityProblem(value) {
4103
+ if (!isPlainValue(value)) return "capability must be an object";
4104
+ const can = value.can;
4105
+ if (can !== "read" && can !== "execute") return "capability.can must be read or execute";
4106
+ const allowedKeys = can === "execute" ? [
4107
+ "can",
4108
+ "scope",
4109
+ "operation"
4110
+ ] : ["can", "scope"];
4111
+ const unknownKeys = Object.keys(value).filter((key) => !allowedKeys.includes(key)).sort();
4112
+ if (unknownKeys.length > 0) return `unknown capability key "${unknownKeys[0]}"`;
4113
+ if (value.scope !== void 0) {
4114
+ if (typeof value.scope !== "string" || value.scope.length === 0) return "capability.scope must be a non-empty string";
4115
+ }
4116
+ if (can === "execute" && value.operation !== void 0) {
4117
+ const operation = value.operation;
4118
+ if (!Array.isArray(operation)) return "capability.operation must be an array";
4119
+ if (operation.length > 100) return `capability.operation exceeds 100 entries`;
4120
+ for (const entry of operation) if (typeof entry !== "string" || entry.length === 0) return "capability.operation entries must be non-empty strings";
4121
+ }
4122
+ return null;
4123
+ }
4124
+ /** Returns the first v1-rule violation, or null. Pure, total, deterministic. */
4125
+ function grantProblem(value) {
4126
+ if (!isPlainValue(value)) return "grant must be an object";
4127
+ const unknownKeys = Object.keys(value).filter((key) => !GRANT_KEYS.has(key)).sort();
4128
+ if (unknownKeys.length > 0) return `unknown grant key "${unknownKeys[0]}"`;
4129
+ if (typeof value.id !== "string" || value.id.length === 0) return "id must be a non-empty string";
4130
+ if (typeof value.description !== "string") return "description must be a string";
4131
+ if (value.effect !== "allow" && value.effect !== "deny") return "effect must be allow or deny";
4132
+ const capabilityValue = value.capability;
4133
+ const capability = capabilityProblem(capabilityValue);
4134
+ if (capability !== null) return capability;
4135
+ const capabilityScope = capabilityValue.scope;
4136
+ const principal = principalProblem(value.principal, capabilityScope);
4137
+ if (principal !== null) return principal;
4138
+ if (value.where !== void 0) return conditionProblem(value.where, capabilityScope, 1, { nodes: 100 });
4139
+ return null;
4140
+ }
4141
+ /** V1 shape rules plus the group-document group-principal ban. */
4142
+ function assertValidGrant(grant, documentType) {
4143
+ const grantId = isPlainValue(grant) && typeof grant.id === "string" ? grant.id : "";
4144
+ const problem = grantProblem(grant);
4145
+ if (problem !== null) throw new InvalidGrantError(grantId, problem);
4146
+ if (documentType === "powerhouse/reactor-group" && "group" in grant.principal) throw new GroupPrincipalNotAllowedError(grantId);
4147
+ }
4148
+ /**
4149
+ * Validates an initial grant list: the count cap, every grant, and — on a
4150
+ * creator-less policy — that some grant keeps the auth scope administrable.
4151
+ */
4152
+ function assertValidInitialGrants(grants, documentType, creator) {
4153
+ if (grants.length > 100) throw new InvalidGrantError("", `policy exceeds 100 grants`);
4154
+ for (const grant of grants) assertValidGrant(grant, documentType);
4155
+ if (creator === void 0 && !administrationReachable(grants)) throw new AuthAdministrationMissingError();
4156
+ }
4157
+ /**
4158
+ * Validates a grant upsert: the grant itself, the count cap on append, and
4159
+ * administration retention. Retention is checked on an append as well as an
4160
+ * in-place replace, because a grant appended after the administration grant can
4161
+ * shadow it (evaluation is last-applicable-grant-wins) and so take
4162
+ * administration away without removing anything.
4163
+ */
4164
+ function assertValidGrantUpsert(grant, existing, documentType, creator) {
4165
+ assertValidGrant(grant, documentType);
4166
+ const exists = existing.some((g) => g.id === grant.id);
4167
+ if (!exists && existing.length >= 100) throw new InvalidGrantError(grant.id, `policy exceeds 100 grants`);
4168
+ assertAuthAdministrationRetained(creator, existing, exists ? existing.map((g) => g.id === grant.id ? grant : g) : [...existing, grant], grant.id);
4169
+ }
4170
+ /**
4171
+ * The request whose coverage keeps a policy administrable: a subject who may
4172
+ * SET_GRANT can upsert any grant, so every other repair stays reachable.
4173
+ */
4174
+ const AUTH_ADMINISTRATION_REQUEST = {
4175
+ verb: "execute",
4176
+ scope: "auth",
4177
+ operation: "SET_GRANT"
4178
+ };
4179
+ /**
4180
+ * Whether some subject can still administer the auth scope under this grant list.
4181
+ *
4182
+ * Asks the evaluator rather than pattern-matching a single grant: evaluation is
4183
+ * last-applicable-grant-wins, so an allow that some later deny shadows keeps
4184
+ * nothing reachable even though it is still present in the list. Only anyone and
4185
+ * address principals are candidates, because those are the ones v1 can match at
4186
+ * all; a `where` condition or a group or match principal never applies.
4187
+ */
4188
+ function administrationReachable(grants) {
4189
+ return grants.some((grant) => {
4190
+ const subject = administrationCandidate(grant);
4191
+ if (subject === void 0) return false;
4192
+ return evaluateGrantStack(grants, subject, AUTH_ADMINISTRATION_REQUEST).decision === "allow";
4193
+ });
4194
+ }
4195
+ /**
4196
+ * The subject to test this grant with, or undefined when the grant could never
4197
+ * carry administration for anyone.
4198
+ */
4199
+ function administrationCandidate(grant) {
4200
+ if (grant.effect !== "allow" || grant.where !== void 0 || !capabilityCovers(grant.capability, AUTH_ADMINISTRATION_REQUEST)) return;
4201
+ if ("address" in grant.principal) return {
4202
+ address: grant.principal.address,
4203
+ key: void 0
4204
+ };
4205
+ if ("anyone" in grant.principal) return {
4206
+ address: void 0,
4207
+ key: void 0
4208
+ };
4209
+ }
4210
+ /**
4211
+ * A creator-less policy must always retain a grant permitting execute on the
4212
+ * auth scope; on a signed document the creator carve-out keeps administration
4213
+ * reachable instead. Rejects a change that takes the last such grant away. A
4214
+ * policy already without one is left alone: the change is not what locks it.
4215
+ */
4216
+ function assertAuthAdministrationRetained(creator, previous, next, grantId) {
4217
+ if (creator !== void 0) return;
4218
+ if (administrationReachable(previous) && !administrationReachable(next)) throw new AuthAdministrationLockoutError(grantId);
4219
+ }
4220
+ /**
4221
+ * An operand whose shape validation would have rejected. Distinguished from
4222
+ * an unresolved path so a structurally malformed operand poisons its whole
4223
+ * condition to false rather than reading as "absent", which `not` would
4224
+ * otherwise widen to true.
4225
+ */
4226
+ const INVALID_OPERAND = Symbol("invalid-operand");
4227
+ /**
4228
+ * Narrows to the values conditions compare. An object, array, or non-finite
4229
+ * number resolves to undefined, and every comparison involving undefined is
4230
+ * false.
4231
+ */
4232
+ function asConditionValue(value) {
4233
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
4234
+ if (typeof value === "number" && Number.isFinite(value)) return value;
4235
+ }
4236
+ /**
4237
+ * Resolves one operand. Attr roots: `subject.*`, `doc.<scope>.*` where the
4238
+ * scope must be the executing scope (validation already rejects any other,
4239
+ * but resolution stays total), and `action.input.*`. Path steps read own
4240
+ * properties only, so prototype members can never influence a verdict.
4241
+ */
4242
+ function resolveOperand(operand, subject, request, conditions) {
4243
+ if (!isPlainValue(operand)) return INVALID_OPERAND;
4244
+ const keys = Object.keys(operand);
4245
+ if (keys.length !== 1) return INVALID_OPERAND;
4246
+ if (keys[0] === "lit") {
4247
+ const value = asConditionValue(operand.lit);
4248
+ return value === void 0 ? INVALID_OPERAND : value;
4249
+ }
4250
+ if (keys[0] !== "attr") return INVALID_OPERAND;
4251
+ const attr = operand.attr;
4252
+ if (typeof attr !== "string" || attr.length === 0) return INVALID_OPERAND;
4253
+ const path = attr.split(".");
4254
+ let value;
4255
+ let rest;
4256
+ if (path[0] === "subject") {
4257
+ value = subject;
4258
+ rest = path.slice(1);
4259
+ } else if (path[0] === "doc") {
4260
+ if (path[1] !== request.scope) return;
4261
+ value = conditions.scopeState;
4262
+ rest = path.slice(2);
4263
+ } else if (path[0] === "action" && path[1] === "input") {
4264
+ value = conditions.actionInput;
4265
+ rest = path.slice(2);
4266
+ } else return;
4267
+ for (const segment of rest) {
4268
+ if (!isPlainValue(value) || !Object.hasOwn(value, segment)) return;
4269
+ value = value[segment];
4270
+ }
4271
+ return asConditionValue(value);
4272
+ }
4273
+ /**
4274
+ * Total order within one type: numbers numerically, strings by code point.
4275
+ * Everything else, including mixed types, does not order.
4276
+ */
4277
+ function compareValues(left, right) {
4278
+ if (typeof left === "number" && typeof right === "number") return left < right ? -1 : left > right ? 1 : 0;
4279
+ if (typeof left === "string" && typeof right === "string") {
4280
+ const leftPoints = Array.from(left);
4281
+ const rightPoints = Array.from(right);
4282
+ const shared = Math.min(leftPoints.length, rightPoints.length);
4283
+ for (let i = 0; i < shared; i++) {
4284
+ const a = leftPoints[i].codePointAt(0) ?? 0;
4285
+ const b = rightPoints[i].codePointAt(0) ?? 0;
4286
+ if (a !== b) return a < b ? -1 : 1;
4287
+ }
4288
+ return leftPoints.length === rightPoints.length ? 0 : leftPoints.length < rightPoints.length ? -1 : 1;
4289
+ }
4290
+ }
4291
+ /**
4292
+ * Tri-state evaluation: undefined marks a structurally invalid node, which
4293
+ * poisons the whole tree to false at the top — and a structurally malformed
4294
+ * operand poisons its condition the same way. Both are distinct from an
4295
+ * operand whose path fails to resolve, which is a valid comparison that is
4296
+ * false. The distinction keeps `not` from widening over malformed input.
4297
+ */
4298
+ function evaluateNode(node, subject, request, conditions) {
4299
+ if (!isPlainValue(node)) return;
4300
+ const keys = Object.keys(node);
4301
+ if (keys.length !== 1) return;
4302
+ const kind = keys[0];
4303
+ const body = node[kind];
4304
+ switch (kind) {
4305
+ case "eq":
4306
+ case "ne":
4307
+ case "lt":
4308
+ case "lte":
4309
+ case "gt":
4310
+ case "gte": {
4311
+ if (!Array.isArray(body) || body.length !== 2) return;
4312
+ const left = resolveOperand(body[0], subject, request, conditions);
4313
+ const right = resolveOperand(body[1], subject, request, conditions);
4314
+ if (left === INVALID_OPERAND || right === INVALID_OPERAND) return;
4315
+ if (left === void 0 || right === void 0) return false;
4316
+ if (kind === "eq") return left === right;
4317
+ if (kind === "ne") return left !== right;
4318
+ const order = compareValues(left, right);
4319
+ if (order === void 0) return false;
4320
+ switch (kind) {
4321
+ case "lt": return order < 0;
4322
+ case "lte": return order <= 0;
4323
+ case "gt": return order > 0;
4324
+ case "gte": return order >= 0;
4325
+ }
4326
+ return;
4327
+ }
4328
+ case "in":
4329
+ case "notIn": {
4330
+ if (!Array.isArray(body) || body.length !== 2 || !Array.isArray(body[1])) return;
4331
+ const left = resolveOperand(body[0], subject, request, conditions);
4332
+ if (left === INVALID_OPERAND) return;
4333
+ const elements = body[1].map((element) => resolveOperand(element, subject, request, conditions));
4334
+ if (elements.some((value) => value === INVALID_OPERAND)) return;
4335
+ if (left === void 0) return false;
4336
+ const found = elements.some((value) => value !== void 0 && value === left);
4337
+ return kind === "in" ? found : !found;
4338
+ }
4339
+ case "exists": {
4340
+ const value = resolveOperand(body, subject, request, conditions);
4341
+ if (value === INVALID_OPERAND) return;
4342
+ return value !== void 0;
4343
+ }
4344
+ case "and":
4345
+ case "or": {
4346
+ if (!Array.isArray(body)) return;
4347
+ let result = kind === "and";
4348
+ for (const child of body) {
4349
+ const value = evaluateNode(child, subject, request, conditions);
4350
+ if (value === void 0) return;
4351
+ if (kind === "and") result = result && value;
4352
+ else result = result || value;
4353
+ }
4354
+ return result;
4355
+ }
4356
+ case "not": {
4357
+ const value = evaluateNode(body, subject, request, conditions);
4358
+ return value === void 0 ? void 0 : !value;
4359
+ }
4360
+ default: return;
4361
+ }
4362
+ }
4363
+ /**
4364
+ * Evaluates a version-1 condition. Deterministic, total, and pure: any input
4365
+ * shape yields a boolean and never throws, and a malformed condition is
4366
+ * false. These are consensus semantics, versioned by `PHAuthState.version`;
4367
+ * changing them requires a new version.
4368
+ */
4369
+ function evaluateCondition(condition, subject, request, conditions) {
4370
+ return evaluateNode(condition, subject, request, conditions) === true;
4371
+ }
4372
+ /** Whether a capability's scope reaches the requested one. */
4373
+ function scopeCovers(scope, requested) {
4374
+ return scope === void 0 || scope === "*" || scope === requested;
4375
+ }
4376
+ /**
4377
+ * Whether one grant answers this request.
4378
+ *
4379
+ * A grant allowing execute on a scope also allows reading it: executing an
4380
+ * operation means reading the state it applies to, so permitting the write while
4381
+ * withholding the read would describe an access nobody could use. The converse
4382
+ * does not hold -- a read grant confers no write.
4383
+ *
4384
+ * Only an allow carries across. A deny on execute withholds the write and says
4385
+ * nothing about the read, so a policy locking writes down does not silently
4386
+ * revoke a read grant sitting before it. The operation list is not consulted
4387
+ * either: it restricts which operations may be executed, not whether the scope
4388
+ * is visible, and a read carries no operation to match against.
4389
+ *
4390
+ * Reads are not consensus -- no replica records a read, and the two read call
4391
+ * sites are both inside the read gate -- so this rule is not part of what makes
4392
+ * an operation valid, and does not need a policy version of its own.
4393
+ */
4394
+ function grantAnswers(grant, request) {
4395
+ if (capabilityCovers(grant.capability, request)) return true;
4396
+ return request.verb === "read" && grant.effect === "allow" && grant.capability.can === "execute" && scopeCovers(grant.capability.scope, request.scope);
4397
+ }
4398
+ function capabilityCovers(capability, request) {
4399
+ if (capability.can !== request.verb) return false;
4400
+ if (!scopeCovers(capability.scope, request.scope)) return false;
4401
+ if (capability.can === "execute") {
4402
+ if (capability.operation === void 0) return true;
4403
+ return request.operation !== void 0 && capability.operation.includes(request.operation);
4404
+ }
4405
+ return true;
4406
+ }
4407
+ function principalMatches(principal, subject, request, groups, conditions) {
4408
+ if ("anyone" in principal) return true;
4409
+ if ("address" in principal) return subject.address !== void 0 && subject.address.toLowerCase() === principal.address.toLowerCase();
4410
+ if ("group" in principal) {
4411
+ if (groups === void 0 || subject.address === void 0) return false;
4412
+ const group = groups[principal.group];
4413
+ if (group === void 0 || !Array.isArray(group.members)) return false;
4414
+ const address = subject.address.toLowerCase();
4415
+ return group.members.some((member) => member.toLowerCase() === address);
4416
+ }
4417
+ if ("match" in principal) {
4418
+ if (conditions === void 0) return false;
4419
+ return evaluateCondition(principal.match, subject, request, conditions);
4420
+ }
4421
+ return false;
4422
+ }
4423
+ /**
4424
+ * Evaluates a v1 grant stack: default deny, last applicable grant wins, and
4425
+ * reports which grant decided it. Group principals match only against a
4426
+ * supplied groups map, and `where` clauses and { match } principals evaluate
4427
+ * only against a supplied condition context; a grant that uses an unsupplied
4428
+ * feature never applies.
4429
+ */
4430
+ function evaluateGrantStack(grants, subject, request, groups, conditions) {
4431
+ let applicable;
4432
+ for (const grant of grants) {
4433
+ if (grant.where !== void 0) {
4434
+ if (conditions === void 0) continue;
4435
+ if (!evaluateCondition(grant.where, subject, request, conditions)) continue;
4436
+ }
4437
+ if (grantAnswers(grant, request) && principalMatches(grant.principal, subject, request, groups, conditions)) applicable = grant;
4438
+ }
4439
+ if (applicable === void 0) return {
4440
+ decision: "deny",
4441
+ refusal: "no-applicable-grant"
4442
+ };
4443
+ if (applicable.effect === "deny") return {
4444
+ decision: "deny",
4445
+ refusal: "denied-by-grant",
4446
+ grantId: applicable.id
4447
+ };
4448
+ return { decision: "allow" };
4449
+ }
3745
4450
  const documentModelFileExtension = "phdm";
3746
4451
  const documentModelInitialLocalState = {};
3747
4452
  const documentModelInitialGlobalState = {
@@ -4323,7 +5028,306 @@ const documentModelGlobalState = {
4323
5028
  };
4324
5029
  const HASH_ALGORITHM_SHA1 = "sha1";
4325
5030
  const HASH_ENCODING_BASE64 = "base64";
4326
- const documentModelDocumentType = "powerhouse/document-model";
5031
+ /**
5032
+ * Creates a default PHAuthState
5033
+ */
5034
+ function defaultAuthState() {
5035
+ return {
5036
+ version: 0,
5037
+ grants: []
5038
+ };
5039
+ }
5040
+ /**
5041
+ * Creates a default PHDocumentState
5042
+ */
5043
+ function defaultDocumentState() {
5044
+ return {
5045
+ version: 0,
5046
+ hash: {
5047
+ algorithm: HASH_ALGORITHM_SHA1,
5048
+ encoding: HASH_ENCODING_BASE64
5049
+ }
5050
+ };
5051
+ }
5052
+ /**
5053
+ * Creates a default PHBaseState with auth and document properties
5054
+ */
5055
+ function defaultBaseState() {
5056
+ return {
5057
+ auth: defaultAuthState(),
5058
+ document: defaultDocumentState()
5059
+ };
5060
+ }
5061
+ /**
5062
+ * Creates a PHAuthState with the given properties
5063
+ */
5064
+ function createAuthState(auth) {
5065
+ return {
5066
+ ...defaultAuthState(),
5067
+ ...auth
5068
+ };
5069
+ }
5070
+ /**
5071
+ * Creates a PHDocumentState with the given properties
5072
+ */
5073
+ function createDocumentState(document) {
5074
+ return {
5075
+ ...defaultDocumentState(),
5076
+ ...document
5077
+ };
5078
+ }
5079
+ /**
5080
+ * Creates a PHBaseState with the given auth and document properties
5081
+ */
5082
+ function createBaseState(auth, document) {
5083
+ return {
5084
+ auth: createAuthState(auth),
5085
+ document: createDocumentState(document)
5086
+ };
5087
+ }
5088
+ /**
5089
+ * Backfills the auth scope to the default for legacy documents serialized with
5090
+ * an empty `auth`. Replaces only `state.auth`. Idempotent.
5091
+ */
5092
+ function backfillAuthState(state) {
5093
+ return {
5094
+ ...state,
5095
+ auth: createAuthState(state.auth)
5096
+ };
5097
+ }
5098
+ function defaultGlobalState() {
5099
+ return {
5100
+ ...defaultBaseState(),
5101
+ author: {
5102
+ name: "",
5103
+ website: ""
5104
+ },
5105
+ description: "",
5106
+ extension: "",
5107
+ id: "",
5108
+ name: "",
5109
+ specifications: []
5110
+ };
5111
+ }
5112
+ function defaultLocalState() {
5113
+ return {};
5114
+ }
5115
+ function createGlobalState(state) {
5116
+ return {
5117
+ ...defaultGlobalState(),
5118
+ ...state || {}
5119
+ };
5120
+ }
5121
+ function createLocalState(state) {
5122
+ return {
5123
+ ...defaultLocalState(),
5124
+ ...state || {}
5125
+ };
5126
+ }
5127
+ function createState(baseState, globalState, localState) {
5128
+ return {
5129
+ ...createBaseState(baseState?.auth, baseState?.document),
5130
+ global: createGlobalState(globalState),
5131
+ local: createLocalState(localState)
5132
+ };
5133
+ }
5134
+ /**
5135
+ * Destructuring a null input (reachable via raw synced operations) would
5136
+ * store an engine-specific TypeError message on the error operation.
5137
+ */
5138
+ function assertActionInputShape(input) {
5139
+ if (!isPlainValue(input)) throw new InvalidActionInputError({ input: "must be an object" });
5140
+ }
5141
+ function withGrants(document, grants) {
5142
+ return {
5143
+ ...document,
5144
+ state: {
5145
+ ...document.state,
5146
+ auth: {
5147
+ ...document.state.auth,
5148
+ grants
5149
+ }
5150
+ }
5151
+ };
5152
+ }
5153
+ const P256_PUBKEY_MULTICODEC = [128, 36];
5154
+ const DID_KEY_PREFIX = "did:key:z";
5155
+ function bytesEqual(a, b) {
5156
+ if (a.length !== b.length) return false;
5157
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
5158
+ return true;
5159
+ }
5160
+ /**
5161
+ * True when `signerKey` (an ActionSigner app key, a did:key) identifies the same
5162
+ * key recorded as the document creator. Returns false
5163
+ * when there is no creator (empty JWK) or no signer key.
5164
+ */
5165
+ function isDocumentCreator(creatorKey, signerKey) {
5166
+ if (!creatorKey?.x || !creatorKey.y) return false;
5167
+ if (!signerKey || !signerKey.startsWith(DID_KEY_PREFIX)) return false;
5168
+ const decoded = base58Decode(signerKey.slice(9));
5169
+ if (!decoded || decoded.length !== 35) return false;
5170
+ if (decoded[0] !== P256_PUBKEY_MULTICODEC[0] || decoded[1] !== P256_PUBKEY_MULTICODEC[1]) return false;
5171
+ const parityPrefix = decoded[2];
5172
+ if (parityPrefix !== 2 && parityPrefix !== 3) return false;
5173
+ const didX = decoded.subarray(3, 35);
5174
+ const jwkX = base64UrlToBytes(creatorKey.x);
5175
+ const jwkY = base64UrlToBytes(creatorKey.y);
5176
+ if (jwkX.length !== 32 || jwkY.length !== 32) return false;
5177
+ if (!bytesEqual(didX, jwkX)) return false;
5178
+ return (jwkY[31] & 1) === 1 === (parityPrefix === 3);
5179
+ }
5180
+ /**
5181
+ * Sets the initial policy. Valid only while the auth scope is uninitialized
5182
+ * (version 0). The input version is the policy language version and must be an
5183
+ * integer >= 1; 0 is reserved for the uninitialized state. On a signed-header
5184
+ * document it must be signed by the document creator (`header.sig.publicKey`).
5185
+ * A creator-less policy must include a grant permitting execute on the auth
5186
+ * scope, or it would be born locked out.
5187
+ */
5188
+ function applyInitializeAuthAction(document, action) {
5189
+ assertActionInputShape(action.input);
5190
+ const { version, grants } = action.input;
5191
+ if (!Number.isInteger(version) || version < 1) throw new InvalidAuthVersionError(document.header.id, version);
5192
+ if (document.state.auth.version !== 0) throw new AuthAlreadyInitializedError(document.header.id);
5193
+ if (!Array.isArray(grants)) throw new InvalidActionInputError({ grants: "must be an array" });
5194
+ const creatorKey = document.header.sig.publicKey;
5195
+ const signerKey = action.context?.signer?.app.key;
5196
+ const hasCreator = Boolean(creatorKey.kty || creatorKey.x || creatorKey.y);
5197
+ if (hasCreator && !isDocumentCreator(creatorKey, signerKey)) throw new AuthInitializerNotCreatorError(document.header.id);
5198
+ const creator = hasCreator ? signerKey : void 0;
5199
+ assertValidInitialGrants(grants, document.header.documentType, creator);
5200
+ return {
5201
+ ...document,
5202
+ state: {
5203
+ ...document.state,
5204
+ auth: createAuthState(creator ? {
5205
+ version,
5206
+ grants,
5207
+ creator
5208
+ } : {
5209
+ version,
5210
+ grants
5211
+ })
5212
+ }
5213
+ };
5214
+ }
5215
+ /** Upserts a grant by id: replaces in place if present, otherwise appends. */
5216
+ function applySetGrantAction(document, action) {
5217
+ assertActionInputShape(action.input);
5218
+ const { grant } = action.input;
5219
+ const grants = document.state.auth.grants;
5220
+ assertValidGrantUpsert(grant, grants, document.header.documentType, document.state.auth.creator);
5221
+ return withGrants(document, grants.some((g) => g.id === grant.id) ? grants.map((g) => g.id === grant.id ? grant : g) : [...grants, grant]);
5222
+ }
5223
+ /**
5224
+ * Removes a grant by id; throws if the id is not present or if the removal
5225
+ * would leave a creator-less policy with no auth-administration grant.
5226
+ */
5227
+ function applyRemoveGrantAction(document, action) {
5228
+ assertActionInputShape(action.input);
5229
+ const { id } = action.input;
5230
+ const { grants, creator } = document.state.auth;
5231
+ if (!grants.some((g) => g.id === id)) throw new GrantNotFoundError(id);
5232
+ const next = grants.filter((g) => g.id !== id);
5233
+ assertAuthAdministrationRetained(creator, grants, next, id);
5234
+ return withGrants(document, next);
5235
+ }
5236
+ /**
5237
+ * Moves a grant by id to a new index. Order is load-bearing (the last
5238
+ * applicable grant wins), so the relative order of the other grants is kept.
5239
+ * The target index is clamped to the valid range; an unknown id throws.
5240
+ *
5241
+ * Order alone decides which grant wins, so a move can take administration away
5242
+ * without changing the list's contents. It carries the same retention rule as
5243
+ * the two mutation paths.
5244
+ */
5245
+ function applyMoveGrantAction(document, action) {
5246
+ assertActionInputShape(action.input);
5247
+ const { id, index } = action.input;
5248
+ const { grants, creator } = document.state.auth;
5249
+ const from = grants.findIndex((g) => g.id === id);
5250
+ if (from === -1) throw new GrantNotFoundError(id);
5251
+ const next = [...grants];
5252
+ const [moved] = next.splice(from, 1);
5253
+ const to = Math.max(0, Math.min(index, next.length));
5254
+ next.splice(to, 0, moved);
5255
+ assertAuthAdministrationRetained(creator, grants, next, id);
5256
+ return withGrants(document, next);
5257
+ }
5258
+ /**
5259
+ * Dispatches an auth-scope action to its handler. This is the auth scope's
5260
+ * dedicated reducer: it is applied by the base reducer instead of the model
5261
+ * reducer, mirroring the document-scope platform handlers. Unknown types are a
5262
+ * no-op, matching the model-reducer default.
5263
+ */
5264
+ function applyAuthAction(document, action) {
5265
+ switch (action.type) {
5266
+ case "INITIALIZE_AUTH": return applyInitializeAuthAction(document, action);
5267
+ case "SET_GRANT": return applySetGrantAction(document, action);
5268
+ case "REMOVE_GRANT": return applyRemoveGrantAction(document, action);
5269
+ case "MOVE_GRANT": return applyMoveGrantAction(document, action);
5270
+ default: return document;
5271
+ }
5272
+ }
5273
+ /**
5274
+ * Because only creators can initialize auth scopes, we must verify that either
5275
+ * the document has no auth or the version and creator match.
5276
+ */
5277
+ function assertAuthPreservedOnDuplicate(documentId, source, duplicated) {
5278
+ if (!source || source.version === 0) return;
5279
+ if (duplicated === void 0 || duplicated.version !== source.version || duplicated.creator !== source.creator) throw new AuthPolicyNotPreservedError(documentId);
5280
+ }
5281
+ /**
5282
+ * The auth scope a state snapshot may install, given the policy already there.
5283
+ *
5284
+ * `applyAuthAction` is the validated door onto `state.auth`, but a whole-state
5285
+ * snapshot (UPGRADE_DOCUMENT's `initialState`, LOAD_STATE's `data`) replaces the
5286
+ * scope wholesale and is authorized as a `document`-scope write. Without this,
5287
+ * a subject holding `execute` on `document` and no auth grant at all can install
5288
+ * a policy of its choosing, name itself `creator` (which exempts the policy from
5289
+ * the retention rule for good), or wipe an existing policy by carrying the
5290
+ * default uninitialized one.
5291
+ *
5292
+ * Three cases:
5293
+ *
5294
+ * - the snapshot carries no policy, or an uninitialized one: the document
5295
+ * keeps the policy it has, so a default-state upgrade cannot reset it;
5296
+ * - the document is uninitialized and the snapshot carries a policy: the
5297
+ * policy is installed after the same validation genesis applies, so it
5298
+ * cannot be born locked out;
5299
+ * - both carry a policy: they must agree. A duplicate preserves its source's
5300
+ * policy (see {@link assertAuthPreservedOnDuplicate}), and anything else is
5301
+ * an attempt to replace one policy with another.
5302
+ */
5303
+ function resolveSnapshotAuth(documentId, documentType, current, incoming) {
5304
+ const currentAuth = current ?? createAuthState({
5305
+ version: 0,
5306
+ grants: []
5307
+ });
5308
+ if (!incoming || !incoming.version) return currentAuth;
5309
+ if (currentAuth.version !== 0) {
5310
+ if (stringify$1(incoming) !== stringify$1(currentAuth)) throw new AuthPolicyNotPreservedError(documentId);
5311
+ return incoming;
5312
+ }
5313
+ if (!Array.isArray(incoming.grants)) throw new InvalidActionInputError({ grants: "must be an array" });
5314
+ assertValidInitialGrants(incoming.grants, documentType, incoming.creator);
5315
+ return incoming;
5316
+ }
5317
+ /** UNDO, REDO and PRUNE are rejected on the auth scope. */
5318
+ function assertAuthScopeActionAllowed(action) {
5319
+ if (action.scope === "auth" && [
5320
+ "UNDO",
5321
+ "REDO",
5322
+ "PRUNE"
5323
+ ].includes(action.type)) throw new AuthActionNotAllowedError(action.type);
5324
+ }
5325
+ /**
5326
+ * True iff authorization rejected the action.
5327
+ */
5328
+ function isDenied(operation) {
5329
+ return operation.deniedReason !== void 0;
5330
+ }
4327
5331
  const BaseDocumentHeaderSchema = object({
4328
5332
  id: string(),
4329
5333
  name: string(),
@@ -4454,6 +5458,7 @@ function createDocumentScopeOperations(header, state) {
4454
5458
  function baseCreateDocument(createState, initialState, documentType = "") {
4455
5459
  const state = createState(initialState);
4456
5460
  const header = createPresignedHeader(generateId(), documentType);
5461
+ header.protocolVersions = { "base-reducer": 2 };
4457
5462
  return {
4458
5463
  header,
4459
5464
  state,
@@ -4477,6 +5482,18 @@ function hashDocumentStateForScope(document, scope = "global") {
4477
5482
  * Uses the V2 model where consecutive NOOPs form chains.
4478
5483
  * Unlike V1 garbageCollect, this preserves ALL operations but marks which to apply.
4479
5484
  */
5485
+ /**
5486
+ * The base-reducer protocol version a document is written against. Every
5487
+ * document carries one, set from the CREATE_DOCUMENT input. A header without
5488
+ * one was built outside that path, and choosing a version on its behalf would
5489
+ * replay the document through a reducer it was not written for, so it is an
5490
+ * error rather than a default.
5491
+ */
5492
+ function baseReducerVersion(header) {
5493
+ const version = header.protocolVersions?.["base-reducer"];
5494
+ if (typeof version !== "number") throw new Error(`Document ${header.id} carries no base-reducer protocol version`);
5495
+ return version;
5496
+ }
4480
5497
  function garbageCollectV2(sortedOperations) {
4481
5498
  const result = [];
4482
5499
  let noopChainLength = 0;
@@ -4493,9 +5510,26 @@ function garbageCollectV2(sortedOperations) {
4493
5510
  const defaultCreateState = (state) => {
4494
5511
  return state;
4495
5512
  };
5513
+ /**
5514
+ * Records an operation in the history without applying it, which is what a
5515
+ * denied operation needs: it occupies its index and contributes no state.
5516
+ *
5517
+ * The scope defaults to the action's own, and is passed explicitly by a rebuild
5518
+ * that is walking one stream and does not want to trust the action's copy.
5519
+ */
5520
+ function appendWithoutApplying(document, operation, scope = operation.action.scope) {
5521
+ return {
5522
+ ...document,
5523
+ operations: {
5524
+ ...document.operations,
5525
+ [scope]: [...document.operations[scope] ?? [], operation]
5526
+ }
5527
+ };
5528
+ }
4496
5529
  function replayDocument(initialState, operations, reducer, header, dispatch, skipHeaderOperations = {}, options) {
4497
5530
  const { checkHashes = true, reuseOperationResultingState, operationResultingStateParser = parseResultingState, skipIndexValidation } = options || {};
4498
- let documentState = initialState;
5531
+ const backfilledInitialState = backfillAuthState(initialState);
5532
+ let documentState = backfilledInitialState;
4499
5533
  const operationsToReplay = [];
4500
5534
  const allScopes = new Set([
4501
5535
  ...Object.keys(operations),
@@ -4530,12 +5564,13 @@ function replayDocument(initialState, operations, reducer, header, dispatch, ski
4530
5564
  const document = {
4531
5565
  header,
4532
5566
  state: defaultCreateState(documentState),
4533
- initialState,
5567
+ initialState: backfilledInitialState,
4534
5568
  operations: initialOperations,
4535
5569
  clipboard: []
4536
5570
  };
4537
5571
  let result = document;
4538
5572
  if (operationsToReplay.length) result = operationsToReplay.reduce((document, operation) => {
5573
+ if (isDenied(operation)) return updateHeaderRevision(appendWithoutApplying(document, operation), operation.action.scope, operation.timestampUtcMs);
4539
5574
  return reducer(document, operation.action, dispatch, {
4540
5575
  ignoreSkipOperations: true,
4541
5576
  checkHashes,
@@ -4817,13 +5852,15 @@ function redoOperation(document, action, skip) {
4817
5852
  });
4818
5853
  }
4819
5854
  function loadStateOperation(document, action) {
5855
+ const loaded = backfillAuthState(action.state.data);
5856
+ loaded.auth = resolveSnapshotAuth(document.header.id, document.header.documentType, backfillAuthState({ ...document.state }).auth, loaded.auth);
4820
5857
  return {
4821
5858
  ...document,
4822
5859
  header: {
4823
5860
  ...document.header,
4824
5861
  name: action.state.name
4825
5862
  },
4826
- state: action.state.data
5863
+ state: loaded
4827
5864
  };
4828
5865
  }
4829
5866
  function replayOperations(initialState, clearedOperations, stateReducer, header, dispatch, documentReducer = baseReducer, skipHeaderOperations = {}, options) {
@@ -4997,12 +6034,13 @@ function processUndoOperation(document, scope, customReducer, reuseOperationResu
4997
6034
  function baseReducer(document, action, customReducer, dispatch, options = {}) {
4998
6035
  const { skip, ignoreSkipOperations = false, reuseOperationResultingState = false, operationResultingStateParser, pruneOnSkip = true, branch = "main" } = options;
4999
6036
  let _action = actionFromAction(action);
6037
+ assertAuthScopeActionAllowed(_action);
5000
6038
  let skipValue = skip ?? options.replayOptions?.operation.skip ?? 0;
5001
6039
  let newDocument = { ...document };
5002
6040
  let reuseLastOperationIndex = false;
5003
6041
  const shouldProcessSkipOperation = !ignoreSkipOperations && skipValue > 0;
5004
6042
  if (isUndoRedo(_action)) {
5005
- const { skip: calculatedSkip, action: transformedAction, document: processedDocument, reuseLastOperationIndex: reuseIndex } = processUndoRedo(document, _action, skipValue, options.protocolVersion ?? 1);
6043
+ const { skip: calculatedSkip, action: transformedAction, document: processedDocument, reuseLastOperationIndex: reuseIndex } = processUndoRedo(document, _action, skipValue, options.protocolVersion ?? baseReducerVersion(document.header));
5006
6044
  _action = transformedAction;
5007
6045
  skipValue = calculatedSkip;
5008
6046
  newDocument = processedDocument;
@@ -5018,7 +6056,7 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
5018
6056
  branch
5019
6057
  };
5020
6058
  newDocument = updateDocument(newDocument, _action, reuseLastOperationIndex, skipValue, operationContext, options.replayOptions?.operation, options.skipIndexValidation);
5021
- const protocolVersion = options.protocolVersion ?? 1;
6059
+ const protocolVersion = options.protocolVersion ?? baseReducerVersion(document.header);
5022
6060
  if (isUndo(action) && protocolVersion < 2) return processUndoOperation(newDocument, action.scope, customReducer);
5023
6061
  const isNoopWithSkip = _action.type === "NOOP" && skipValue > 0;
5024
6062
  if ((isUndo(action) || isNoopWithSkip) && protocolVersion >= 2) {
@@ -5044,6 +6082,13 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
5044
6082
  }
5045
6083
  newDocument = create(newDocument, (draft) => {
5046
6084
  try {
6085
+ if (_action.scope === "auth") {
6086
+ const authState = applyAuthAction(newDocument, _action).state;
6087
+ unsafe(() => {
6088
+ draft.state = castDraft(authState);
6089
+ });
6090
+ return;
6091
+ }
5047
6092
  const newState = customReducer(draft.state, _action, dispatch);
5048
6093
  if (newState) unsafe(() => {
5049
6094
  draft.state = castDraft(newState);
@@ -5837,10 +6882,12 @@ function applyInitialState(document, action) {
5837
6882
  const input = action.input;
5838
6883
  const newState = input.initialState || input.state;
5839
6884
  if (newState) {
5840
- document.state = {
6885
+ const merged = backfillAuthState({
5841
6886
  ...document.state,
5842
6887
  ...newState
5843
- };
6888
+ });
6889
+ merged.auth = resolveSnapshotAuth(document.header.id, document.header.documentType, backfillAuthState({ ...document.state }).auth, merged.auth);
6890
+ document.state = merged;
5844
6891
  document.initialState = document.state;
5845
6892
  }
5846
6893
  }
@@ -5900,7 +6947,6 @@ function computeUpgradeTransitions(manifest, fromVersion, toVersion) {
5900
6947
  }
5901
6948
  return transitions;
5902
6949
  }
5903
- const NON_DOMAIN_SCOPES$1 = new Set(["auth", "document"]);
5904
6950
  function highestReducerVersion(reducers) {
5905
6951
  const keys = Object.keys(reducers).map(Number);
5906
6952
  if (keys.length === 0) throw new Error("VersionedReplayConfig.reducers must not be empty");
@@ -5928,15 +6974,15 @@ function highestReducerVersion(reducers) {
5928
6974
  */
5929
6975
  function replayDocumentVersioned(initialState, operations, config, header, dispatch, options) {
5930
6976
  const { checkHashes = true, skipIndexValidation } = options || {};
5931
- const protocolVersion = header.protocolVersions?.["base-reducer"] ?? 1;
6977
+ const protocolVersion = baseReducerVersion(header);
5932
6978
  const spine = (operations["document"] ?? []).slice().sort((a, b) => a.index - b.index);
5933
6979
  const upgrades = spine.filter((op) => op.action.type === "UPGRADE_DOCUMENT");
5934
6980
  const legacyFallback = () => {
5935
- const domainOps = Object.fromEntries(Object.entries(operations).filter(([s]) => !NON_DOMAIN_SCOPES$1.has(s)));
6981
+ const replayOps = Object.fromEntries(Object.entries(operations).filter(([s]) => s !== "document"));
5936
6982
  const latestVersion = highestReducerVersion(config.reducers);
5937
6983
  const reducer = config.reducers[latestVersion];
5938
6984
  return {
5939
- ...replayDocument(initialState, domainOps, reducer, header, dispatch, {}, options),
6985
+ ...replayDocument(initialState, replayOps, reducer, header, dispatch, {}, options),
5940
6986
  operations
5941
6987
  };
5942
6988
  };
@@ -5960,14 +7006,14 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
5960
7006
  const a = op.action;
5961
7007
  return a.input.fromVersion > 0 && a.input.fromVersion < a.input.toVersion;
5962
7008
  });
5963
- const domainScopes = Object.keys(operations).filter((s) => !NON_DOMAIN_SCOPES$1.has(s));
7009
+ const replayScopes = Object.keys(operations).filter((s) => s !== "document");
5964
7010
  const scopeOps = {};
5965
- for (const s of domainScopes) scopeOps[s] = (operations[s] ?? []).slice().sort((a, b) => a.index - b.index);
7011
+ for (const s of replayScopes) scopeOps[s] = (operations[s] ?? []).slice().sort((a, b) => a.index - b.index);
5966
7012
  const boundaries = validatedUpgrades.map((upgradeOp) => {
5967
7013
  const revisionSnapshot = upgradeOp.action.input.revision;
5968
7014
  const upgradeTimestamp = upgradeOp.timestampUtcMs;
5969
7015
  const boundary = {};
5970
- for (const s of domainScopes) {
7016
+ for (const s of replayScopes) {
5971
7017
  const ops = scopeOps[s] ?? [];
5972
7018
  if (revisionSnapshot !== void 0) {
5973
7019
  const rev = revisionSnapshot[s] ?? 0;
@@ -5985,7 +7031,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
5985
7031
  }
5986
7032
  return boundary;
5987
7033
  });
5988
- for (let i = 1; i < boundaries.length; i++) for (const s of domainScopes) {
7034
+ for (let i = 1; i < boundaries.length; i++) for (const s of replayScopes) {
5989
7035
  const prev = boundaries[i - 1]?.[s] ?? 0;
5990
7036
  const curr = boundaries[i]?.[s] ?? 0;
5991
7037
  if (boundaries[i]) boundaries[i][s] = Math.max(prev, curr);
@@ -5997,10 +7043,11 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
5997
7043
  ]);
5998
7044
  const initialOperations = {};
5999
7045
  for (const s of allScopes) initialOperations[s] = [];
7046
+ const backfilledSeed = backfillAuthState(seedState);
6000
7047
  let document = {
6001
7048
  header,
6002
- state: seedState,
6003
- initialState: seedState,
7049
+ state: backfilledSeed,
7050
+ initialState: backfilledSeed,
6004
7051
  operations: initialOperations,
6005
7052
  clipboard: []
6006
7053
  };
@@ -6008,17 +7055,15 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6008
7055
  const segmentEndHashPerScope = /* @__PURE__ */ new Map();
6009
7056
  for (let k = 0; k <= validatedUpgrades.length; k++) {
6010
7057
  const reducer = config.reducers[currentVersion];
6011
- if (!reducer) {
6012
- const available = Object.keys(config.reducers).join(", ");
6013
- throw new Error(`No reducer registered for document version ${currentVersion}. Available versions: ${available}`);
6014
- }
6015
- for (const s of domainScopes) {
7058
+ if (!reducer) throw new UnsupportedDocumentModelVersionError(header.documentType, currentVersion, Object.keys(config.reducers).map(Number).sort((a, b) => a - b));
7059
+ for (const s of replayScopes) {
6016
7060
  const ops = scopeOps[s] ?? [];
6017
7061
  const segStart = k === 0 ? 0 : boundaries[k - 1]?.[s] ?? 0;
6018
7062
  const segEnd = k < validatedUpgrades.length ? boundaries[k]?.[s] ?? ops.length : ops.length;
6019
7063
  const segOps = ops.slice(segStart, segEnd);
6020
7064
  for (const op of segOps) {
6021
- document = reducer(document, op.action, dispatch, {
7065
+ if (isDenied(op)) document = updateHeaderRevision(appendWithoutApplying(document, op, s), s, op.timestampUtcMs);
7066
+ else document = reducer(document, op.action, dispatch, {
6022
7067
  ignoreSkipOperations: true,
6023
7068
  checkHashes,
6024
7069
  skipIndexValidation,
@@ -6035,6 +7080,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6035
7080
  if (!spineOp) continue;
6036
7081
  const spineActionType = spineOp.action.type;
6037
7082
  if (spineActionType === "CREATE_DOCUMENT" || spineActionType === "UPGRADE_DOCUMENT") continue;
7083
+ if (isDenied(spineOp)) continue;
6038
7084
  if (spineActionType === "DELETE_DOCUMENT") document = applyDeleteDocumentAction(document, spineOp.action);
6039
7085
  else document = reducer(document, spineOp.action, dispatch, {
6040
7086
  ignoreSkipOperations: true,
@@ -6065,7 +7111,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6065
7111
  }
6066
7112
  };
6067
7113
  if (!checkHashes) {
6068
- const allReplayedOps = domainScopes.flatMap((s) => scopeOps[s] ?? []);
7114
+ const allReplayedOps = replayScopes.flatMap((s) => scopeOps[s] ?? []);
6069
7115
  for (const scope of Object.keys(document.state)) {
6070
7116
  const capturedHash = segmentEndHashPerScope.get(scope);
6071
7117
  const scopeHash = capturedHash !== void 0 ? capturedHash : hashDocumentStateForScope(document, scope);
@@ -6107,7 +7153,6 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6107
7153
  }
6108
7154
  };
6109
7155
  }
6110
- const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
6111
7156
  function zipAsync(data) {
6112
7157
  return new Promise((resolve, reject) => {
6113
7158
  zip(data, (err, out) => err ? reject(err) : resolve(out));
@@ -6186,7 +7231,7 @@ async function parseZipData(data) {
6186
7231
  async function loadFromZipData(data, reducer, options) {
6187
7232
  const { initialState, header, clearedOperations } = await parseZipData(data);
6188
7233
  return {
6189
- ...replayDocument(initialState, Object.fromEntries(Object.entries(clearedOperations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope))), reducer, header, void 0, {}, options),
7234
+ ...replayDocument(initialState, Object.fromEntries(Object.entries(clearedOperations).filter(([scope]) => scope !== "document")), reducer, header, void 0, {}, options),
6190
7235
  operations: clearedOperations
6191
7236
  };
6192
7237
  }
@@ -6209,96 +7254,6 @@ const documentModelLoadFromInput = (input) => {
6209
7254
  const documentModelSaveToFileHandle = (document, input) => {
6210
7255
  return baseSaveToFileHandle(document, input);
6211
7256
  };
6212
- /**
6213
- * Creates a default PHAuthState
6214
- */
6215
- function defaultAuthState() {
6216
- return {};
6217
- }
6218
- /**
6219
- * Creates a default PHDocumentState
6220
- */
6221
- function defaultDocumentState() {
6222
- return {
6223
- version: 0,
6224
- hash: {
6225
- algorithm: HASH_ALGORITHM_SHA1,
6226
- encoding: HASH_ENCODING_BASE64
6227
- }
6228
- };
6229
- }
6230
- /**
6231
- * Creates a default PHBaseState with auth and document properties
6232
- */
6233
- function defaultBaseState() {
6234
- return {
6235
- auth: defaultAuthState(),
6236
- document: defaultDocumentState()
6237
- };
6238
- }
6239
- /**
6240
- * Creates a PHAuthState with the given properties
6241
- */
6242
- function createAuthState(auth) {
6243
- return {
6244
- ...defaultAuthState(),
6245
- ...auth
6246
- };
6247
- }
6248
- /**
6249
- * Creates a PHDocumentState with the given properties
6250
- */
6251
- function createDocumentState(document) {
6252
- return {
6253
- ...defaultDocumentState(),
6254
- ...document
6255
- };
6256
- }
6257
- /**
6258
- * Creates a PHBaseState with the given auth and document properties
6259
- */
6260
- function createBaseState(auth, document) {
6261
- return {
6262
- auth: createAuthState(auth),
6263
- document: createDocumentState(document)
6264
- };
6265
- }
6266
- function defaultGlobalState() {
6267
- return {
6268
- ...defaultBaseState(),
6269
- author: {
6270
- name: "",
6271
- website: ""
6272
- },
6273
- description: "",
6274
- extension: "",
6275
- id: "",
6276
- name: "",
6277
- specifications: []
6278
- };
6279
- }
6280
- function defaultLocalState() {
6281
- return {};
6282
- }
6283
- function createGlobalState(state) {
6284
- return {
6285
- ...defaultGlobalState(),
6286
- ...state || {}
6287
- };
6288
- }
6289
- function createLocalState(state) {
6290
- return {
6291
- ...defaultLocalState(),
6292
- ...state || {}
6293
- };
6294
- }
6295
- function createState(baseState, globalState, localState) {
6296
- return {
6297
- ...createBaseState(baseState?.auth, baseState?.document),
6298
- global: createGlobalState(globalState),
6299
- local: createLocalState(localState)
6300
- };
6301
- }
6302
7257
  //#endregion
6303
7258
  //#region ../document-model/dist/index.js
6304
7259
  const isStateOfType$1 = (state) => {
@@ -7377,6 +8332,6 @@ const driveDocumentModelModule = {
7377
8332
  }
7378
8333
  };
7379
8334
  //#endregion
7380
- export { redo as A, setName as B, createZip as C, deleteOperationError as D, deleteOperation as E, setModelDescription as F, setStateSchema as G, setOperationErrorName as H, setModelExtension as I, validateModules as J, undo as K, setModelId as L, setAuthorName as M, setAuthorWebsite as N, documentModelDocumentType as O, setInitialState as P, setModelName as R, createState as S, deleteModule as T, setOperationName as U, setOperationDescription as V, setOperationSchema as W, generateId as X, validateStateSchemaName as Y, baseLoadFromInputVersioned as _, handleTargetNameCollisions as a, createPresignedHeader as b, moveNode as c, logger as d, addModule as f, baseLoadFromInput as g, baseCreateDocument as h, generateNodesCopy as i, replayDocumentVersioned as j, isDocumentAction as k, updateNode as l, addOperationError as m, copyNode as n, isFileNode as o, addOperation as p, validateInitialState as q, driveDocumentModelModule as r, isFolderNode as s, addFolder as t, documentModelDocumentModelModule as u, baseSaveToFileHandle as v, defaultBaseState as w, createReducer as x, buildSignedAction as y, setModuleName as z };
8335
+ export { setOperationSchema as $, createZip as A, replayDocumentVersioned as B, baseSaveToFileHandle as C, createPresignedHeader as D, createBaseState as E, documentModelDocumentType as F, setModelExtension as G, setAuthorWebsite as H, hashDocumentStateForScope as I, setModuleName as J, setModelId as K, isDocumentAction as L, deleteModule as M, deleteOperation as N, createReducer as O, deleteOperationError as P, setOperationName as Q, redo as R, baseLoadFromInputVersioned as S, createAction as T, setInitialState as U, setAuthorName as V, setModelDescription as W, setOperationDescription as X, setName as Y, setOperationErrorName as Z, addOperationError as _, handleTargetNameCollisions as a, generateId as at, baseCreateDocument as b, isValidName as c, documentModelDocumentModelModule as d, setStateSchema as et, logger as f, addOperation as g, addModule as h, generateNodesCopy as i, validateStateSchemaName as it, defaultBaseState as j, createState as k, moveNode as l, BaseDocumentStateSchema as m, copyNode as n, validateInitialState as nt, isFileNode as o, BaseDocumentHeaderSchema as p, setModelName as q, driveDocumentModelModule as r, validateModules as rt, isFolderNode as s, addFolder as t, undo as tt, updateNode as u, assertAuthPreservedOnDuplicate as v, buildSignedAction as w, baseLoadFromInput as x, baseActions as y, releaseNewVersion as z };
7381
8336
 
7382
- //# sourceMappingURL=document-drive-DjL9iikf.mjs.map
8337
+ //# sourceMappingURL=document-drive-BgHPyTwW.mjs.map