@powerhousedao/powerhouse-vetra-packages 6.2.2-dev.15 → 6.2.2-dev.16

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 (61) hide show
  1. package/dist/browser/assets/{entry-Cvoo4_c9.js → entry-PJ7Jewgi.js} +2 -2
  2. package/dist/browser/assets/{projection-entry-DVec8YRh.js → projection-entry-DI6tCI4R.js} +3 -3
  3. package/dist/browser/{connect-DSoIVHMW.js → connect-BjyXOuXJ.js} +4 -4
  4. package/dist/browser/{connect-DSoIVHMW.js.map → connect-BjyXOuXJ.js.map} +1 -1
  5. package/dist/browser/{dist-DMJv_4W0.js → dist-DrFQ11JR.js} +7 -6
  6. package/dist/browser/dist-DrFQ11JR.js.map +1 -0
  7. package/dist/browser/{document-drive-DYZGC0Dz.js → document-drive-BJ3S7Tuc.js} +561 -112
  8. package/dist/browser/document-drive-BJ3S7Tuc.js.map +1 -0
  9. package/dist/browser/document-models/index.js +1 -1
  10. package/dist/browser/{editor-sdV1WCg-.js → editor-DiltcAcB.js} +6 -6
  11. package/dist/browser/{editor-sdV1WCg-.js.map → editor-DiltcAcB.js.map} +1 -1
  12. package/dist/browser/{editor-Dsx-49N2.js → editor-nkPvitTX.js} +5 -5
  13. package/dist/browser/{editor-Dsx-49N2.js.map → editor-nkPvitTX.js.map} +1 -1
  14. package/dist/browser/editors/document-model-editor/module.js +1 -1
  15. package/dist/browser/editors/generic-drive-explorer/index.js +4 -4
  16. package/dist/browser/editors/generic-drive-explorer/module.js +1 -1
  17. package/dist/browser/{folder-view-B-XELAhq.js → folder-view-DaWh_ZLU.js} +3 -3
  18. package/dist/browser/{folder-view-B-XELAhq.js.map → folder-view-DaWh_ZLU.js.map} +1 -1
  19. package/dist/browser/{graphql-editor-BuU1hB9h.js → graphql-editor-CLewUIZr.js} +3 -3
  20. package/dist/browser/{graphql-editor-BuU1hB9h.js.map → graphql-editor-CLewUIZr.js.map} +1 -1
  21. package/dist/browser/index.js +2 -2
  22. package/dist/browser/index.js.map +1 -1
  23. package/dist/browser/{json-editor-CfSH58CC.js → json-editor-C-rxO4Mi.js} +3 -3
  24. package/dist/browser/{json-editor-CfSH58CC.js.map → json-editor-C-rxO4Mi.js.map} +1 -1
  25. package/dist/browser/{lib-CZuRjhln.js → lib-CdrAIBwG.js} +2 -2
  26. package/dist/browser/lib-CdrAIBwG.js.map +1 -0
  27. package/dist/browser/{state-schemas-BTb2-kMv.js → state-schemas-BOTYft7X.js} +3 -3
  28. package/dist/browser/{state-schemas-BTb2-kMv.js.map → state-schemas-BOTYft7X.js.map} +1 -1
  29. package/dist/node/{connect-DZxwsMOj.mjs → connect-BvY53UWP.mjs} +4 -4
  30. package/dist/node/{connect-DZxwsMOj.mjs.map → connect-BvY53UWP.mjs.map} +1 -1
  31. package/dist/node/{dist-BWxsIpdg.mjs → dist-BorJ6dO3.mjs} +7 -6
  32. package/dist/node/dist-BorJ6dO3.mjs.map +1 -0
  33. package/dist/node/{document-drive-DKHGrX9P.mjs → document-drive-CKlCgojv.mjs} +561 -112
  34. package/dist/node/document-drive-CKlCgojv.mjs.map +1 -0
  35. package/dist/node/document-models/index.mjs +1 -1
  36. package/dist/node/{editor-D43wDsdp.mjs → editor-B6xeXOnb.mjs} +6 -6
  37. package/dist/node/{editor-D43wDsdp.mjs.map → editor-B6xeXOnb.mjs.map} +1 -1
  38. package/dist/node/{editor-J7bEXv1X.mjs → editor-BMp6km6d.mjs} +5 -5
  39. package/dist/node/{editor-J7bEXv1X.mjs.map → editor-BMp6km6d.mjs.map} +1 -1
  40. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  41. package/dist/node/editors/generic-drive-explorer/index.mjs +4 -4
  42. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  43. package/dist/node/{folder-view-CUWumU5-.mjs → folder-view-BQ3pm1uI.mjs} +3 -3
  44. package/dist/node/{folder-view-CUWumU5-.mjs.map → folder-view-BQ3pm1uI.mjs.map} +1 -1
  45. package/dist/node/{graphql-editor-DA-R6Qd0.mjs → graphql-editor-CNmYqxGe.mjs} +3 -3
  46. package/dist/node/{graphql-editor-DA-R6Qd0.mjs.map → graphql-editor-CNmYqxGe.mjs.map} +1 -1
  47. package/dist/node/index.mjs +2 -2
  48. package/dist/node/index.mjs.map +1 -1
  49. package/dist/node/{json-editor-BHbwl235.mjs → json-editor-CPWkyWVo.mjs} +3 -3
  50. package/dist/node/{json-editor-BHbwl235.mjs.map → json-editor-CPWkyWVo.mjs.map} +1 -1
  51. package/dist/node/{main-DMZ7Ros2.mjs → main-Djluvvdu.mjs} +2 -2
  52. package/dist/node/main-Djluvvdu.mjs.map +1 -0
  53. package/dist/node/{state-schemas-C1K6Xug7.mjs → state-schemas-BqLT0vQR.mjs} +3 -3
  54. package/dist/node/{state-schemas-C1K6Xug7.mjs.map → state-schemas-BqLT0vQR.mjs.map} +1 -1
  55. package/package.json +6 -6
  56. package/dist/browser/dist-DMJv_4W0.js.map +0 -1
  57. package/dist/browser/document-drive-DYZGC0Dz.js.map +0 -1
  58. package/dist/browser/lib-CZuRjhln.js.map +0 -1
  59. package/dist/node/dist-BWxsIpdg.mjs.map +0 -1
  60. package/dist/node/document-drive-DKHGrX9P.mjs.map +0 -1
  61. package/dist/node/main-DMZ7Ros2.mjs.map +0 -1
@@ -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();
@@ -2979,6 +3013,75 @@ var DowngradeNotSupportedError = class extends Error {
2979
3013
  this.toVersion = toVersion;
2980
3014
  }
2981
3015
  };
3016
+ /**
3017
+ * Thrown when INITIALIZE_AUTH is applied to an already-initialized auth scope.
3018
+ * The genesis action is valid only at auth revision zero.
3019
+ */
3020
+ var AuthAlreadyInitializedError = class extends Error {
3021
+ documentId;
3022
+ constructor(documentId) {
3023
+ super(`Auth scope already initialized for document ${documentId}: INITIALIZE_AUTH is valid only at auth revision zero`);
3024
+ this.name = "AuthAlreadyInitializedError";
3025
+ this.documentId = documentId;
3026
+ }
3027
+ };
3028
+ /**
3029
+ * Thrown when INITIALIZE_AUTH is not signed by the document creator (its signer
3030
+ * does not match `header.sig.publicKey`), so it cannot set the auth policy.
3031
+ */
3032
+ var AuthInitializerNotCreatorError = class extends Error {
3033
+ documentId;
3034
+ constructor(documentId) {
3035
+ super(`INITIALIZE_AUTH for document ${documentId} must be signed by the document creator`);
3036
+ this.name = "AuthInitializerNotCreatorError";
3037
+ this.documentId = documentId;
3038
+ }
3039
+ };
3040
+ /**
3041
+ * Thrown when INITIALIZE_AUTH carries a version below 1. Version 0 is reserved
3042
+ * for the uninitialized auth scope.
3043
+ */
3044
+ var InvalidAuthVersionError = class extends Error {
3045
+ documentId;
3046
+ version;
3047
+ constructor(documentId, version) {
3048
+ super(`Invalid auth policy version ${version} for document ${documentId}: INITIALIZE_AUTH requires an integer version >= 1`);
3049
+ this.name = "InvalidAuthVersionError";
3050
+ this.documentId = documentId;
3051
+ this.version = version;
3052
+ }
3053
+ };
3054
+ /** Thrown when a duplicate would lose the source policy's version or creator binding. */
3055
+ var AuthPolicyNotPreservedError = class extends Error {
3056
+ documentId;
3057
+ constructor(documentId) {
3058
+ super(`Duplicating document ${documentId} would not preserve its auth policy: the copy loses the policy version or its creator binding`);
3059
+ this.name = "AuthPolicyNotPreservedError";
3060
+ this.documentId = documentId;
3061
+ }
3062
+ };
3063
+ /**
3064
+ * Thrown when a grant referenced by REMOVE_GRANT or MOVE_GRANT does not exist.
3065
+ */
3066
+ var GrantNotFoundError = class extends Error {
3067
+ grantId;
3068
+ constructor(grantId) {
3069
+ super(`Grant not found in auth scope: ${grantId}`);
3070
+ this.name = "GrantNotFoundError";
3071
+ this.grantId = grantId;
3072
+ }
3073
+ };
3074
+ /**
3075
+ * Thrown when a disallowed action (UNDO, REDO, PRUNE) targets the auth scope.
3076
+ */
3077
+ var AuthActionNotAllowedError = class extends Error {
3078
+ actionType;
3079
+ constructor(actionType) {
3080
+ super(`${actionType} is not permitted on the auth scope`);
3081
+ this.name = "AuthActionNotAllowedError";
3082
+ this.actionType = actionType;
3083
+ }
3084
+ };
2982
3085
  var HashMismatchError = class extends Error {
2983
3086
  _scope;
2984
3087
  _document;
@@ -3810,6 +3913,189 @@ const actions = {
3810
3913
  ...baseActions,
3811
3914
  ...documentModelActions
3812
3915
  };
3916
+ const documentModelDocumentType = "powerhouse/document-model";
3917
+ /**
3918
+ * Thrown when a grant violates the v1 validation rules. The message is stored
3919
+ * on error operations, so it must be a pure function of the input.
3920
+ */
3921
+ var InvalidGrantError = class extends Error {
3922
+ grantId;
3923
+ constructor(grantId, problem) {
3924
+ super(`Invalid grant "${grantId}": ${problem}`);
3925
+ this.name = "InvalidGrantError";
3926
+ this.grantId = grantId;
3927
+ }
3928
+ };
3929
+ /** Thrown for a `{ group }` principal on a group document: references never chain. */
3930
+ var GroupPrincipalNotAllowedError = class extends Error {
3931
+ grantId;
3932
+ constructor(grantId) {
3933
+ super(`Grant "${grantId}" uses a group principal on a group document: a group's auth scope cannot reference other groups`);
3934
+ this.name = "GroupPrincipalNotAllowedError";
3935
+ this.grantId = grantId;
3936
+ }
3937
+ };
3938
+ const GRANT_KEYS = new Set([
3939
+ "id",
3940
+ "description",
3941
+ "effect",
3942
+ "principal",
3943
+ "capability",
3944
+ "where"
3945
+ ]);
3946
+ const PRINCIPAL_KINDS = new Set([
3947
+ "anyone",
3948
+ "address",
3949
+ "group",
3950
+ "match"
3951
+ ]);
3952
+ const COMPARISON_CONDITION_KINDS = new Set([
3953
+ "eq",
3954
+ "ne",
3955
+ "lt",
3956
+ "lte",
3957
+ "gt",
3958
+ "gte"
3959
+ ]);
3960
+ function isPlainValue(value) {
3961
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3962
+ }
3963
+ function operandProblem(value, capabilityScope, budget) {
3964
+ budget.nodes -= 1;
3965
+ if (budget.nodes < 0) return `condition exceeds 100 nodes`;
3966
+ if (!isPlainValue(value)) return "operand must be an object";
3967
+ const keys = Object.keys(value);
3968
+ if (keys.length !== 1) return "operand must have exactly one of attr or lit";
3969
+ if (keys[0] === "attr") {
3970
+ const attr = value.attr;
3971
+ if (typeof attr !== "string" || attr.length === 0) return "attr must be a non-empty string";
3972
+ if (capabilityScope !== void 0 && capabilityScope !== "*" && attr.startsWith("doc.")) {
3973
+ const pathScope = attr.split(".")[1] ?? "";
3974
+ if (pathScope !== capabilityScope) return `condition path "${attr}" reads scope "${pathScope}" but the capability covers only scope "${capabilityScope}"`;
3975
+ }
3976
+ return null;
3977
+ }
3978
+ if (keys[0] === "lit") {
3979
+ const lit = value.lit;
3980
+ if (lit !== null && typeof lit !== "string" && typeof lit !== "number" && typeof lit !== "boolean") return "lit must be a string, number, boolean, or null";
3981
+ if (typeof lit === "number" && !Number.isFinite(lit)) return "lit must be a finite number";
3982
+ if (typeof lit === "number" && Object.is(lit, -0)) return "lit must not be negative zero";
3983
+ return null;
3984
+ }
3985
+ return `unknown operand kind "${keys[0]}"`;
3986
+ }
3987
+ function conditionProblem(value, capabilityScope, depth, budget) {
3988
+ if (depth > 10) return `condition exceeds depth 10`;
3989
+ budget.nodes -= 1;
3990
+ if (budget.nodes < 0) return `condition exceeds 100 nodes`;
3991
+ if (!isPlainValue(value)) return "condition must be an object";
3992
+ const keys = Object.keys(value);
3993
+ if (keys.length !== 1) return "condition must have exactly one operator";
3994
+ const kind = keys[0];
3995
+ const body = value[kind];
3996
+ if (COMPARISON_CONDITION_KINDS.has(kind)) {
3997
+ if (!Array.isArray(body) || body.length !== 2) return `${kind} requires a pair of operands`;
3998
+ for (const operand of body) {
3999
+ const problem = operandProblem(operand, capabilityScope, budget);
4000
+ if (problem !== null) return problem;
4001
+ }
4002
+ return null;
4003
+ }
4004
+ if (kind === "in" || kind === "notIn") {
4005
+ if (!Array.isArray(body) || body.length !== 2 || !Array.isArray(body[1])) return `${kind} requires an operand and an operand list`;
4006
+ const first = operandProblem(body[0], capabilityScope, budget);
4007
+ if (first !== null) return first;
4008
+ for (const operand of body[1]) {
4009
+ const problem = operandProblem(operand, capabilityScope, budget);
4010
+ if (problem !== null) return problem;
4011
+ }
4012
+ return null;
4013
+ }
4014
+ if (kind === "exists") return operandProblem(body, capabilityScope, budget);
4015
+ if (kind === "and" || kind === "or") {
4016
+ if (!Array.isArray(body)) return `${kind} requires a condition list`;
4017
+ for (const child of body) {
4018
+ const problem = conditionProblem(child, capabilityScope, depth + 1, budget);
4019
+ if (problem !== null) return problem;
4020
+ }
4021
+ return null;
4022
+ }
4023
+ if (kind === "not") return conditionProblem(body, capabilityScope, depth + 1, budget);
4024
+ return `unknown condition operator "${kind}"`;
4025
+ }
4026
+ function principalProblem(value, capabilityScope) {
4027
+ if (!isPlainValue(value)) return "principal must be an object";
4028
+ const keys = Object.keys(value);
4029
+ if (keys.length !== 1 || !PRINCIPAL_KINDS.has(keys[0])) return "principal must have exactly one of anyone, address, group, or match";
4030
+ const kind = keys[0];
4031
+ if (kind === "anyone" && value.anyone !== true) return "anyone must be true";
4032
+ if (kind === "address") {
4033
+ const address = value.address;
4034
+ if (typeof address !== "string" || address.length === 0) return "address must be a non-empty string";
4035
+ }
4036
+ if (kind === "group") {
4037
+ const group = value.group;
4038
+ if (typeof group !== "string" || group.length === 0) return "group must be a non-empty string";
4039
+ }
4040
+ if (kind === "match") return conditionProblem(value.match, capabilityScope, 1, { nodes: 100 });
4041
+ return null;
4042
+ }
4043
+ function capabilityProblem(value) {
4044
+ if (!isPlainValue(value)) return "capability must be an object";
4045
+ const can = value.can;
4046
+ if (can !== "read" && can !== "execute") return "capability.can must be read or execute";
4047
+ const allowedKeys = can === "execute" ? [
4048
+ "can",
4049
+ "scope",
4050
+ "operation"
4051
+ ] : ["can", "scope"];
4052
+ const unknownKeys = Object.keys(value).filter((key) => !allowedKeys.includes(key)).sort();
4053
+ if (unknownKeys.length > 0) return `unknown capability key "${unknownKeys[0]}"`;
4054
+ if (value.scope !== void 0) {
4055
+ if (typeof value.scope !== "string" || value.scope.length === 0) return "capability.scope must be a non-empty string";
4056
+ }
4057
+ if (can === "execute" && value.operation !== void 0) {
4058
+ const operation = value.operation;
4059
+ if (!Array.isArray(operation)) return "capability.operation must be an array";
4060
+ if (operation.length > 100) return `capability.operation exceeds 100 entries`;
4061
+ for (const entry of operation) if (typeof entry !== "string" || entry.length === 0) return "capability.operation entries must be non-empty strings";
4062
+ }
4063
+ return null;
4064
+ }
4065
+ /** Returns the first v1-rule violation, or null. Pure, total, deterministic. */
4066
+ function grantProblem(value) {
4067
+ if (!isPlainValue(value)) return "grant must be an object";
4068
+ const unknownKeys = Object.keys(value).filter((key) => !GRANT_KEYS.has(key)).sort();
4069
+ if (unknownKeys.length > 0) return `unknown grant key "${unknownKeys[0]}"`;
4070
+ if (typeof value.id !== "string" || value.id.length === 0) return "id must be a non-empty string";
4071
+ if (typeof value.description !== "string") return "description must be a string";
4072
+ if (value.effect !== "allow" && value.effect !== "deny") return "effect must be allow or deny";
4073
+ const capabilityValue = value.capability;
4074
+ const capability = capabilityProblem(capabilityValue);
4075
+ if (capability !== null) return capability;
4076
+ const capabilityScope = capabilityValue.scope;
4077
+ const principal = principalProblem(value.principal, capabilityScope);
4078
+ if (principal !== null) return principal;
4079
+ if (value.where !== void 0) return conditionProblem(value.where, capabilityScope, 1, { nodes: 100 });
4080
+ return null;
4081
+ }
4082
+ /** V1 shape rules plus the group-document group-principal ban. */
4083
+ function assertValidGrant(grant, documentType) {
4084
+ const grantId = isPlainValue(grant) && typeof grant.id === "string" ? grant.id : "";
4085
+ const problem = grantProblem(grant);
4086
+ if (problem !== null) throw new InvalidGrantError(grantId, problem);
4087
+ if (documentType === "@powerhousedao/document-group" && "group" in grant.principal) throw new GroupPrincipalNotAllowedError(grantId);
4088
+ }
4089
+ /** Validates an initial grant list: the count cap plus every grant. */
4090
+ function assertValidInitialGrants(grants, documentType) {
4091
+ if (grants.length > 100) throw new InvalidGrantError("", `policy exceeds 100 grants`);
4092
+ for (const grant of grants) assertValidGrant(grant, documentType);
4093
+ }
4094
+ /** Validates a grant upsert: the grant itself plus the count cap on append. */
4095
+ function assertValidGrantUpsert(grant, existing, documentType) {
4096
+ assertValidGrant(grant, documentType);
4097
+ if (!existing.some((g) => g.id === grant.id) && existing.length >= 100) throw new InvalidGrantError(grant.id, `policy exceeds 100 grants`);
4098
+ }
3813
4099
  const documentModelFileExtension = "phdm";
3814
4100
  const documentModelInitialLocalState = {};
3815
4101
  const documentModelInitialGlobalState = {
@@ -4391,7 +4677,252 @@ const documentModelGlobalState = {
4391
4677
  };
4392
4678
  const HASH_ALGORITHM_SHA1 = "sha1";
4393
4679
  const HASH_ENCODING_BASE64 = "base64";
4394
- const documentModelDocumentType = "powerhouse/document-model";
4680
+ /**
4681
+ * Creates a default PHAuthState
4682
+ */
4683
+ function defaultAuthState() {
4684
+ return {
4685
+ version: 0,
4686
+ grants: []
4687
+ };
4688
+ }
4689
+ /**
4690
+ * Creates a default PHDocumentState
4691
+ */
4692
+ function defaultDocumentState() {
4693
+ return {
4694
+ version: 0,
4695
+ hash: {
4696
+ algorithm: HASH_ALGORITHM_SHA1,
4697
+ encoding: HASH_ENCODING_BASE64
4698
+ }
4699
+ };
4700
+ }
4701
+ /**
4702
+ * Creates a default PHBaseState with auth and document properties
4703
+ */
4704
+ function defaultBaseState() {
4705
+ return {
4706
+ auth: defaultAuthState(),
4707
+ document: defaultDocumentState()
4708
+ };
4709
+ }
4710
+ /**
4711
+ * Creates a PHAuthState with the given properties
4712
+ */
4713
+ function createAuthState(auth) {
4714
+ return {
4715
+ ...defaultAuthState(),
4716
+ ...auth
4717
+ };
4718
+ }
4719
+ /**
4720
+ * Creates a PHDocumentState with the given properties
4721
+ */
4722
+ function createDocumentState(document) {
4723
+ return {
4724
+ ...defaultDocumentState(),
4725
+ ...document
4726
+ };
4727
+ }
4728
+ /**
4729
+ * Creates a PHBaseState with the given auth and document properties
4730
+ */
4731
+ function createBaseState(auth, document) {
4732
+ return {
4733
+ auth: createAuthState(auth),
4734
+ document: createDocumentState(document)
4735
+ };
4736
+ }
4737
+ /**
4738
+ * Backfills the auth scope to the default for legacy documents serialized with
4739
+ * an empty `auth`. Replaces only `state.auth`. Idempotent.
4740
+ */
4741
+ function backfillAuthState(state) {
4742
+ return {
4743
+ ...state,
4744
+ auth: createAuthState(state.auth)
4745
+ };
4746
+ }
4747
+ function defaultGlobalState() {
4748
+ return {
4749
+ ...defaultBaseState(),
4750
+ author: {
4751
+ name: "",
4752
+ website: ""
4753
+ },
4754
+ description: "",
4755
+ extension: "",
4756
+ id: "",
4757
+ name: "",
4758
+ specifications: []
4759
+ };
4760
+ }
4761
+ function defaultLocalState() {
4762
+ return {};
4763
+ }
4764
+ function createGlobalState(state) {
4765
+ return {
4766
+ ...defaultGlobalState(),
4767
+ ...state || {}
4768
+ };
4769
+ }
4770
+ function createLocalState(state) {
4771
+ return {
4772
+ ...defaultLocalState(),
4773
+ ...state || {}
4774
+ };
4775
+ }
4776
+ function createState(baseState, globalState, localState) {
4777
+ return {
4778
+ ...createBaseState(baseState?.auth, baseState?.document),
4779
+ global: createGlobalState(globalState),
4780
+ local: createLocalState(localState)
4781
+ };
4782
+ }
4783
+ /**
4784
+ * Destructuring a null input (reachable via raw synced operations) would
4785
+ * store an engine-specific TypeError message on the error operation.
4786
+ */
4787
+ function assertActionInputShape(input) {
4788
+ if (!isPlainValue(input)) throw new InvalidActionInputError({ input: "must be an object" });
4789
+ }
4790
+ function withGrants(document, grants) {
4791
+ return {
4792
+ ...document,
4793
+ state: {
4794
+ ...document.state,
4795
+ auth: {
4796
+ ...document.state.auth,
4797
+ grants
4798
+ }
4799
+ }
4800
+ };
4801
+ }
4802
+ const P256_PUBKEY_MULTICODEC = [128, 36];
4803
+ const DID_KEY_PREFIX = "did:key:z";
4804
+ function bytesEqual(a, b) {
4805
+ if (a.length !== b.length) return false;
4806
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
4807
+ return true;
4808
+ }
4809
+ /**
4810
+ * True when `signerKey` (an ActionSigner app key, a did:key) identifies the same
4811
+ * key recorded as the document creator. Returns false
4812
+ * when there is no creator (empty JWK) or no signer key.
4813
+ */
4814
+ function isDocumentCreator(creatorKey, signerKey) {
4815
+ if (!creatorKey?.x || !creatorKey.y) return false;
4816
+ if (!signerKey || !signerKey.startsWith(DID_KEY_PREFIX)) return false;
4817
+ const decoded = base58Decode(signerKey.slice(9));
4818
+ if (!decoded || decoded.length !== 35) return false;
4819
+ if (decoded[0] !== P256_PUBKEY_MULTICODEC[0] || decoded[1] !== P256_PUBKEY_MULTICODEC[1]) return false;
4820
+ const parityPrefix = decoded[2];
4821
+ if (parityPrefix !== 2 && parityPrefix !== 3) return false;
4822
+ const didX = decoded.subarray(3, 35);
4823
+ const jwkX = base64UrlToBytes(creatorKey.x);
4824
+ const jwkY = base64UrlToBytes(creatorKey.y);
4825
+ if (jwkX.length !== 32 || jwkY.length !== 32) return false;
4826
+ if (!bytesEqual(didX, jwkX)) return false;
4827
+ return (jwkY[31] & 1) === 1 === (parityPrefix === 3);
4828
+ }
4829
+ /**
4830
+ * Sets the initial policy. Valid only while the auth scope is uninitialized
4831
+ * (version 0). The input version is the policy language version and must be an
4832
+ * integer >= 1; 0 is reserved for the uninitialized state. On a signed-header
4833
+ * document it must be signed by the document creator (`header.sig.publicKey`).
4834
+ */
4835
+ function applyInitializeAuthAction(document, action) {
4836
+ assertActionInputShape(action.input);
4837
+ const { version, grants } = action.input;
4838
+ if (!Number.isInteger(version) || version < 1) throw new InvalidAuthVersionError(document.header.id, version);
4839
+ if (document.state.auth.version !== 0) throw new AuthAlreadyInitializedError(document.header.id);
4840
+ if (!Array.isArray(grants)) throw new InvalidActionInputError({ grants: "must be an array" });
4841
+ assertValidInitialGrants(grants, document.header.documentType);
4842
+ const creatorKey = document.header.sig.publicKey;
4843
+ const signerKey = action.context?.signer?.app.key;
4844
+ const hasCreator = Boolean(creatorKey.kty || creatorKey.x || creatorKey.y);
4845
+ if (hasCreator && !isDocumentCreator(creatorKey, signerKey)) throw new AuthInitializerNotCreatorError(document.header.id);
4846
+ const creator = hasCreator ? signerKey : void 0;
4847
+ return {
4848
+ ...document,
4849
+ state: {
4850
+ ...document.state,
4851
+ auth: createAuthState(creator ? {
4852
+ version,
4853
+ grants,
4854
+ creator
4855
+ } : {
4856
+ version,
4857
+ grants
4858
+ })
4859
+ }
4860
+ };
4861
+ }
4862
+ /** Upserts a grant by id: replaces in place if present, otherwise appends. */
4863
+ function applySetGrantAction(document, action) {
4864
+ assertActionInputShape(action.input);
4865
+ const { grant } = action.input;
4866
+ const grants = document.state.auth.grants;
4867
+ assertValidGrantUpsert(grant, grants, document.header.documentType);
4868
+ return withGrants(document, grants.some((g) => g.id === grant.id) ? grants.map((g) => g.id === grant.id ? grant : g) : [...grants, grant]);
4869
+ }
4870
+ /** Removes a grant by id; throws if the id is not present. */
4871
+ function applyRemoveGrantAction(document, action) {
4872
+ assertActionInputShape(action.input);
4873
+ const { id } = action.input;
4874
+ const grants = document.state.auth.grants;
4875
+ if (!grants.some((g) => g.id === id)) throw new GrantNotFoundError(id);
4876
+ return withGrants(document, grants.filter((g) => g.id !== id));
4877
+ }
4878
+ /**
4879
+ * Moves a grant by id to a new index. Order is load-bearing (the last
4880
+ * applicable grant wins), so the relative order of the other grants is kept.
4881
+ * The target index is clamped to the valid range; an unknown id throws.
4882
+ */
4883
+ function applyMoveGrantAction(document, action) {
4884
+ assertActionInputShape(action.input);
4885
+ const { id, index } = action.input;
4886
+ const grants = document.state.auth.grants;
4887
+ const from = grants.findIndex((g) => g.id === id);
4888
+ if (from === -1) throw new GrantNotFoundError(id);
4889
+ const next = [...grants];
4890
+ const [moved] = next.splice(from, 1);
4891
+ const to = Math.max(0, Math.min(index, next.length));
4892
+ next.splice(to, 0, moved);
4893
+ return withGrants(document, next);
4894
+ }
4895
+ /**
4896
+ * Dispatches an auth-scope action to its handler. This is the auth scope's
4897
+ * dedicated reducer: it is applied by the base reducer instead of the model
4898
+ * reducer, mirroring the document-scope platform handlers. Unknown types are a
4899
+ * no-op, matching the model-reducer default.
4900
+ */
4901
+ function applyAuthAction(document, action) {
4902
+ switch (action.type) {
4903
+ case "INITIALIZE_AUTH": return applyInitializeAuthAction(document, action);
4904
+ case "SET_GRANT": return applySetGrantAction(document, action);
4905
+ case "REMOVE_GRANT": return applyRemoveGrantAction(document, action);
4906
+ case "MOVE_GRANT": return applyMoveGrantAction(document, action);
4907
+ default: return document;
4908
+ }
4909
+ }
4910
+ /**
4911
+ * Because only creators can initialize auth scopes, we must verify that either
4912
+ * the document has no auth or the version and creator match.
4913
+ */
4914
+ function assertAuthPreservedOnDuplicate(documentId, source, duplicated) {
4915
+ if (!source || source.version === 0) return;
4916
+ if (duplicated === void 0 || duplicated.version !== source.version || duplicated.creator !== source.creator) throw new AuthPolicyNotPreservedError(documentId);
4917
+ }
4918
+ /** UNDO, REDO and PRUNE are rejected on the auth scope. */
4919
+ function assertAuthScopeActionAllowed(action) {
4920
+ if (action.scope === "auth" && [
4921
+ "UNDO",
4922
+ "REDO",
4923
+ "PRUNE"
4924
+ ].includes(action.type)) throw new AuthActionNotAllowedError(action.type);
4925
+ }
4395
4926
  const BaseDocumentHeaderSchema = object({
4396
4927
  id: string(),
4397
4928
  name: string(),
@@ -4563,7 +5094,8 @@ const defaultCreateState = (state) => {
4563
5094
  };
4564
5095
  function replayDocument(initialState, operations, reducer, header, dispatch, skipHeaderOperations = {}, options) {
4565
5096
  const { checkHashes = true, reuseOperationResultingState, operationResultingStateParser = parseResultingState, skipIndexValidation } = options || {};
4566
- let documentState = initialState;
5097
+ const backfilledInitialState = backfillAuthState(initialState);
5098
+ let documentState = backfilledInitialState;
4567
5099
  const operationsToReplay = [];
4568
5100
  const allScopes = new Set([
4569
5101
  ...Object.keys(operations),
@@ -4598,7 +5130,7 @@ function replayDocument(initialState, operations, reducer, header, dispatch, ski
4598
5130
  const document = {
4599
5131
  header,
4600
5132
  state: defaultCreateState(documentState),
4601
- initialState,
5133
+ initialState: backfilledInitialState,
4602
5134
  operations: initialOperations,
4603
5135
  clipboard: []
4604
5136
  };
@@ -4891,7 +5423,7 @@ function loadStateOperation(document, action) {
4891
5423
  ...document.header,
4892
5424
  name: action.state.name
4893
5425
  },
4894
- state: action.state.data
5426
+ state: backfillAuthState(action.state.data)
4895
5427
  };
4896
5428
  }
4897
5429
  function replayOperations(initialState, clearedOperations, stateReducer, header, dispatch, documentReducer = baseReducer, skipHeaderOperations = {}, options) {
@@ -5065,6 +5597,7 @@ function processUndoOperation(document, scope, customReducer, reuseOperationResu
5065
5597
  function baseReducer(document, action, customReducer, dispatch, options = {}) {
5066
5598
  const { skip, ignoreSkipOperations = false, reuseOperationResultingState = false, operationResultingStateParser, pruneOnSkip = true, branch = "main" } = options;
5067
5599
  let _action = actionFromAction(action);
5600
+ assertAuthScopeActionAllowed(_action);
5068
5601
  let skipValue = skip ?? options.replayOptions?.operation.skip ?? 0;
5069
5602
  let newDocument = { ...document };
5070
5603
  let reuseLastOperationIndex = false;
@@ -5112,6 +5645,13 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
5112
5645
  }
5113
5646
  newDocument = create(newDocument, (draft) => {
5114
5647
  try {
5648
+ if (_action.scope === "auth") {
5649
+ const authState = applyAuthAction(newDocument, _action).state;
5650
+ unsafe(() => {
5651
+ draft.state = castDraft(authState);
5652
+ });
5653
+ return;
5654
+ }
5115
5655
  const newState = customReducer(draft.state, _action, dispatch);
5116
5656
  if (newState) unsafe(() => {
5117
5657
  draft.state = castDraft(newState);
@@ -5905,10 +6445,10 @@ function applyInitialState(document, action) {
5905
6445
  const input = action.input;
5906
6446
  const newState = input.initialState || input.state;
5907
6447
  if (newState) {
5908
- document.state = {
6448
+ document.state = backfillAuthState({
5909
6449
  ...document.state,
5910
6450
  ...newState
5911
- };
6451
+ });
5912
6452
  document.initialState = document.state;
5913
6453
  }
5914
6454
  }
@@ -5968,7 +6508,6 @@ function computeUpgradeTransitions(manifest, fromVersion, toVersion) {
5968
6508
  }
5969
6509
  return transitions;
5970
6510
  }
5971
- const NON_DOMAIN_SCOPES$1 = new Set(["auth", "document"]);
5972
6511
  function highestReducerVersion(reducers) {
5973
6512
  const keys = Object.keys(reducers).map(Number);
5974
6513
  if (keys.length === 0) throw new Error("VersionedReplayConfig.reducers must not be empty");
@@ -6000,11 +6539,11 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6000
6539
  const spine = (operations["document"] ?? []).slice().sort((a, b) => a.index - b.index);
6001
6540
  const upgrades = spine.filter((op) => op.action.type === "UPGRADE_DOCUMENT");
6002
6541
  const legacyFallback = () => {
6003
- const domainOps = Object.fromEntries(Object.entries(operations).filter(([s]) => !NON_DOMAIN_SCOPES$1.has(s)));
6542
+ const replayOps = Object.fromEntries(Object.entries(operations).filter(([s]) => s !== "document"));
6004
6543
  const latestVersion = highestReducerVersion(config.reducers);
6005
6544
  const reducer = config.reducers[latestVersion];
6006
6545
  return {
6007
- ...replayDocument(initialState, domainOps, reducer, header, dispatch, {}, options),
6546
+ ...replayDocument(initialState, replayOps, reducer, header, dispatch, {}, options),
6008
6547
  operations
6009
6548
  };
6010
6549
  };
@@ -6028,14 +6567,14 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6028
6567
  const a = op.action;
6029
6568
  return a.input.fromVersion > 0 && a.input.fromVersion < a.input.toVersion;
6030
6569
  });
6031
- const domainScopes = Object.keys(operations).filter((s) => !NON_DOMAIN_SCOPES$1.has(s));
6570
+ const replayScopes = Object.keys(operations).filter((s) => s !== "document");
6032
6571
  const scopeOps = {};
6033
- for (const s of domainScopes) scopeOps[s] = (operations[s] ?? []).slice().sort((a, b) => a.index - b.index);
6572
+ for (const s of replayScopes) scopeOps[s] = (operations[s] ?? []).slice().sort((a, b) => a.index - b.index);
6034
6573
  const boundaries = validatedUpgrades.map((upgradeOp) => {
6035
6574
  const revisionSnapshot = upgradeOp.action.input.revision;
6036
6575
  const upgradeTimestamp = upgradeOp.timestampUtcMs;
6037
6576
  const boundary = {};
6038
- for (const s of domainScopes) {
6577
+ for (const s of replayScopes) {
6039
6578
  const ops = scopeOps[s] ?? [];
6040
6579
  if (revisionSnapshot !== void 0) {
6041
6580
  const rev = revisionSnapshot[s] ?? 0;
@@ -6053,7 +6592,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6053
6592
  }
6054
6593
  return boundary;
6055
6594
  });
6056
- for (let i = 1; i < boundaries.length; i++) for (const s of domainScopes) {
6595
+ for (let i = 1; i < boundaries.length; i++) for (const s of replayScopes) {
6057
6596
  const prev = boundaries[i - 1]?.[s] ?? 0;
6058
6597
  const curr = boundaries[i]?.[s] ?? 0;
6059
6598
  if (boundaries[i]) boundaries[i][s] = Math.max(prev, curr);
@@ -6065,10 +6604,11 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6065
6604
  ]);
6066
6605
  const initialOperations = {};
6067
6606
  for (const s of allScopes) initialOperations[s] = [];
6607
+ const backfilledSeed = backfillAuthState(seedState);
6068
6608
  let document = {
6069
6609
  header,
6070
- state: seedState,
6071
- initialState: seedState,
6610
+ state: backfilledSeed,
6611
+ initialState: backfilledSeed,
6072
6612
  operations: initialOperations,
6073
6613
  clipboard: []
6074
6614
  };
@@ -6080,7 +6620,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6080
6620
  const available = Object.keys(config.reducers).join(", ");
6081
6621
  throw new Error(`No reducer registered for document version ${currentVersion}. Available versions: ${available}`);
6082
6622
  }
6083
- for (const s of domainScopes) {
6623
+ for (const s of replayScopes) {
6084
6624
  const ops = scopeOps[s] ?? [];
6085
6625
  const segStart = k === 0 ? 0 : boundaries[k - 1]?.[s] ?? 0;
6086
6626
  const segEnd = k < validatedUpgrades.length ? boundaries[k]?.[s] ?? ops.length : ops.length;
@@ -6133,7 +6673,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6133
6673
  }
6134
6674
  };
6135
6675
  if (!checkHashes) {
6136
- const allReplayedOps = domainScopes.flatMap((s) => scopeOps[s] ?? []);
6676
+ const allReplayedOps = replayScopes.flatMap((s) => scopeOps[s] ?? []);
6137
6677
  for (const scope of Object.keys(document.state)) {
6138
6678
  const capturedHash = segmentEndHashPerScope.get(scope);
6139
6679
  const scopeHash = capturedHash !== void 0 ? capturedHash : hashDocumentStateForScope(document, scope);
@@ -6175,7 +6715,6 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6175
6715
  }
6176
6716
  };
6177
6717
  }
6178
- const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
6179
6718
  function zipAsync(data) {
6180
6719
  return new Promise((resolve, reject) => {
6181
6720
  zip(data, (err, out) => err ? reject(err) : resolve(out));
@@ -6254,7 +6793,7 @@ async function parseZipData(data) {
6254
6793
  async function loadFromZipData(data, reducer, options) {
6255
6794
  const { initialState, header, clearedOperations } = await parseZipData(data);
6256
6795
  return {
6257
- ...replayDocument(initialState, Object.fromEntries(Object.entries(clearedOperations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope))), reducer, header, void 0, {}, options),
6796
+ ...replayDocument(initialState, Object.fromEntries(Object.entries(clearedOperations).filter(([scope]) => scope !== "document")), reducer, header, void 0, {}, options),
6258
6797
  operations: clearedOperations
6259
6798
  };
6260
6799
  }
@@ -6277,96 +6816,6 @@ const documentModelLoadFromInput = (input) => {
6277
6816
  const documentModelSaveToFileHandle = (document, input) => {
6278
6817
  return baseSaveToFileHandle(document, input);
6279
6818
  };
6280
- /**
6281
- * Creates a default PHAuthState
6282
- */
6283
- function defaultAuthState() {
6284
- return {};
6285
- }
6286
- /**
6287
- * Creates a default PHDocumentState
6288
- */
6289
- function defaultDocumentState() {
6290
- return {
6291
- version: 0,
6292
- hash: {
6293
- algorithm: HASH_ALGORITHM_SHA1,
6294
- encoding: HASH_ENCODING_BASE64
6295
- }
6296
- };
6297
- }
6298
- /**
6299
- * Creates a default PHBaseState with auth and document properties
6300
- */
6301
- function defaultBaseState() {
6302
- return {
6303
- auth: defaultAuthState(),
6304
- document: defaultDocumentState()
6305
- };
6306
- }
6307
- /**
6308
- * Creates a PHAuthState with the given properties
6309
- */
6310
- function createAuthState(auth) {
6311
- return {
6312
- ...defaultAuthState(),
6313
- ...auth
6314
- };
6315
- }
6316
- /**
6317
- * Creates a PHDocumentState with the given properties
6318
- */
6319
- function createDocumentState(document) {
6320
- return {
6321
- ...defaultDocumentState(),
6322
- ...document
6323
- };
6324
- }
6325
- /**
6326
- * Creates a PHBaseState with the given auth and document properties
6327
- */
6328
- function createBaseState(auth, document) {
6329
- return {
6330
- auth: createAuthState(auth),
6331
- document: createDocumentState(document)
6332
- };
6333
- }
6334
- function defaultGlobalState() {
6335
- return {
6336
- ...defaultBaseState(),
6337
- author: {
6338
- name: "",
6339
- website: ""
6340
- },
6341
- description: "",
6342
- extension: "",
6343
- id: "",
6344
- name: "",
6345
- specifications: []
6346
- };
6347
- }
6348
- function defaultLocalState() {
6349
- return {};
6350
- }
6351
- function createGlobalState(state) {
6352
- return {
6353
- ...defaultGlobalState(),
6354
- ...state || {}
6355
- };
6356
- }
6357
- function createLocalState(state) {
6358
- return {
6359
- ...defaultLocalState(),
6360
- ...state || {}
6361
- };
6362
- }
6363
- function createState(baseState, globalState, localState) {
6364
- return {
6365
- ...createBaseState(baseState?.auth, baseState?.document),
6366
- global: createGlobalState(globalState),
6367
- local: createLocalState(localState)
6368
- };
6369
- }
6370
6819
  //#endregion
6371
6820
  //#region ../document-model/dist/index.js
6372
6821
  const isStateOfType$1 = (state) => {
@@ -7445,6 +7894,6 @@ const driveDocumentModelModule = {
7445
7894
  }
7446
7895
  };
7447
7896
  //#endregion
7448
- 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 };
7897
+ export { isDocumentAction as A, setModuleName as B, createState as C, deleteOperation as D, deleteModule as E, setInitialState as F, setOperationSchema as G, setOperationDescription as H, setModelDescription as I, validateInitialState as J, setStateSchema as K, setModelExtension as L, replayDocumentVersioned as M, setAuthorName as N, deleteOperationError as O, setAuthorWebsite as P, setModelId as R, createReducer as S, defaultBaseState as T, setOperationErrorName as U, setName as V, setOperationName as W, validateStateSchemaName as X, validateModules as Y, generateId as Z, baseLoadFromInput as _, handleTargetNameCollisions as a, buildSignedAction as b, moveNode as c, logger as d, addModule as f, baseCreateDocument as g, assertAuthPreservedOnDuplicate as h, generateNodesCopy as i, redo as j, documentModelDocumentType as k, updateNode as l, addOperationError as m, copyNode as n, isFileNode as o, addOperation as p, undo as q, driveDocumentModelModule as r, isFolderNode as s, addFolder as t, documentModelDocumentModelModule as u, baseLoadFromInputVersioned as v, createZip as w, createPresignedHeader as x, baseSaveToFileHandle as y, setModelName as z };
7449
7898
 
7450
- //# sourceMappingURL=document-drive-DYZGC0Dz.js.map
7899
+ //# sourceMappingURL=document-drive-BJ3S7Tuc.js.map