@voidhash/mimic 0.0.2 → 0.0.3

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 (273) hide show
  1. package/.turbo/turbo-build.log +257 -42
  2. package/dist/Document.cjs +152 -0
  3. package/dist/Document.d.cts +67 -0
  4. package/dist/Document.d.cts.map +1 -0
  5. package/dist/Document.d.mts +68 -0
  6. package/dist/Document.d.mts.map +1 -0
  7. package/dist/Document.mjs +147 -0
  8. package/dist/Document.mjs.map +1 -0
  9. package/dist/EffectSchema.cjs +180 -0
  10. package/dist/EffectSchema.d.cts +84 -0
  11. package/dist/EffectSchema.d.cts.map +1 -0
  12. package/dist/EffectSchema.d.mts +84 -0
  13. package/dist/EffectSchema.d.mts.map +1 -0
  14. package/dist/EffectSchema.mjs +176 -0
  15. package/dist/EffectSchema.mjs.map +1 -0
  16. package/dist/FractionalIndex.cjs +365 -0
  17. package/dist/FractionalIndex.mjs +364 -0
  18. package/dist/FractionalIndex.mjs.map +1 -0
  19. package/dist/Operation.cjs +53 -0
  20. package/dist/Operation.d.cts +39 -0
  21. package/dist/Operation.d.cts.map +1 -0
  22. package/dist/Operation.d.mts +39 -0
  23. package/dist/Operation.d.mts.map +1 -0
  24. package/dist/Operation.mjs +46 -0
  25. package/dist/Operation.mjs.map +1 -0
  26. package/dist/OperationDefinition.cjs +13 -0
  27. package/dist/OperationDefinition.d.cts +12 -0
  28. package/dist/OperationDefinition.d.cts.map +1 -0
  29. package/dist/OperationDefinition.d.mts +12 -0
  30. package/dist/OperationDefinition.d.mts.map +1 -0
  31. package/dist/OperationDefinition.mjs +13 -0
  32. package/dist/OperationDefinition.mjs.map +1 -0
  33. package/dist/OperationPath.cjs +148 -0
  34. package/dist/OperationPath.d.cts +60 -0
  35. package/dist/OperationPath.d.cts.map +1 -0
  36. package/dist/OperationPath.d.mts +60 -0
  37. package/dist/OperationPath.d.mts.map +1 -0
  38. package/dist/OperationPath.mjs +138 -0
  39. package/dist/OperationPath.mjs.map +1 -0
  40. package/dist/{Presence-gWrmGBeu.cjs → Presence.cjs} +4 -39
  41. package/dist/{Presence-N8u7Eppr.d.mts → Presence.d.cts} +2 -2
  42. package/dist/Presence.d.cts.map +1 -0
  43. package/dist/{Presence-DKKP4v5X.d.cts → Presence.d.mts} +2 -2
  44. package/dist/Presence.d.mts.map +1 -0
  45. package/dist/{Presence-DdMVKcOv.mjs → Presence.mjs} +3 -28
  46. package/dist/Presence.mjs.map +1 -0
  47. package/dist/Primitive.cjs +52 -0
  48. package/dist/Primitive.d.cts +20 -0
  49. package/dist/Primitive.d.cts.map +1 -0
  50. package/dist/Primitive.d.mts +20 -0
  51. package/dist/Primitive.d.mts.map +1 -0
  52. package/dist/Primitive.mjs +48 -0
  53. package/dist/Primitive.mjs.map +1 -0
  54. package/dist/ProxyEnvironment.cjs +34 -0
  55. package/dist/ProxyEnvironment.d.cts +31 -0
  56. package/dist/ProxyEnvironment.d.cts.map +1 -0
  57. package/dist/ProxyEnvironment.d.mts +31 -0
  58. package/dist/ProxyEnvironment.d.mts.map +1 -0
  59. package/dist/ProxyEnvironment.mjs +29 -0
  60. package/dist/ProxyEnvironment.mjs.map +1 -0
  61. package/dist/Transaction.cjs +66 -0
  62. package/dist/Transaction.d.cts +56 -0
  63. package/dist/Transaction.d.cts.map +1 -0
  64. package/dist/Transaction.d.mts +56 -0
  65. package/dist/Transaction.d.mts.map +1 -0
  66. package/dist/Transaction.mjs +58 -0
  67. package/dist/Transaction.mjs.map +1 -0
  68. package/dist/Transform.cjs +11 -0
  69. package/dist/Transform.d.cts +21 -0
  70. package/dist/Transform.d.cts.map +1 -0
  71. package/dist/Transform.d.mts +21 -0
  72. package/dist/Transform.d.mts.map +1 -0
  73. package/dist/Transform.mjs +6 -0
  74. package/dist/Transform.mjs.map +1 -0
  75. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/defineProperty.cjs +14 -0
  76. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/defineProperty.mjs +14 -0
  77. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/objectSpread2.cjs +27 -0
  78. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/objectSpread2.mjs +27 -0
  79. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/toPrimitive.cjs +16 -0
  80. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/toPrimitive.mjs +16 -0
  81. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/toPropertyKey.cjs +11 -0
  82. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/toPropertyKey.mjs +11 -0
  83. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/typeof.cjs +18 -0
  84. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/typeof.mjs +12 -0
  85. package/dist/_virtual/rolldown_runtime.cjs +43 -0
  86. package/dist/{chunk-CLMFDpHK.mjs → _virtual/rolldown_runtime.mjs} +1 -1
  87. package/dist/client/ClientDocument.cjs +590 -0
  88. package/dist/client/ClientDocument.d.cts +161 -0
  89. package/dist/client/ClientDocument.d.cts.map +1 -0
  90. package/dist/client/ClientDocument.d.mts +162 -0
  91. package/dist/client/ClientDocument.d.mts.map +1 -0
  92. package/dist/client/ClientDocument.mjs +586 -0
  93. package/dist/client/ClientDocument.mjs.map +1 -0
  94. package/dist/client/Rebase.cjs +204 -0
  95. package/dist/client/Rebase.d.cts +87 -0
  96. package/dist/client/Rebase.d.cts.map +1 -0
  97. package/dist/client/Rebase.d.mts +88 -0
  98. package/dist/client/Rebase.d.mts.map +1 -0
  99. package/dist/client/Rebase.mjs +198 -0
  100. package/dist/client/Rebase.mjs.map +1 -0
  101. package/dist/client/StateMonitor.cjs +133 -0
  102. package/dist/client/StateMonitor.d.cts +122 -0
  103. package/dist/client/StateMonitor.d.cts.map +1 -0
  104. package/dist/client/StateMonitor.d.mts +122 -0
  105. package/dist/client/StateMonitor.d.mts.map +1 -0
  106. package/dist/client/StateMonitor.mjs +129 -0
  107. package/dist/client/StateMonitor.mjs.map +1 -0
  108. package/dist/client/Transport.cjs +11 -0
  109. package/dist/client/Transport.d.cts +237 -0
  110. package/dist/client/Transport.d.cts.map +1 -0
  111. package/dist/client/Transport.d.mts +237 -0
  112. package/dist/client/Transport.d.mts.map +1 -0
  113. package/dist/client/Transport.mjs +6 -0
  114. package/dist/client/Transport.mjs.map +1 -0
  115. package/dist/client/WebSocketTransport.cjs +396 -0
  116. package/dist/client/WebSocketTransport.d.cts +29 -0
  117. package/dist/client/WebSocketTransport.d.cts.map +1 -0
  118. package/dist/client/WebSocketTransport.d.mts +29 -0
  119. package/dist/client/WebSocketTransport.d.mts.map +1 -0
  120. package/dist/client/WebSocketTransport.mjs +392 -0
  121. package/dist/client/WebSocketTransport.mjs.map +1 -0
  122. package/dist/client/errors.cjs +135 -0
  123. package/dist/client/errors.d.cts +87 -0
  124. package/dist/client/errors.d.cts.map +1 -0
  125. package/dist/client/errors.d.mts +87 -0
  126. package/dist/client/errors.d.mts.map +1 -0
  127. package/dist/client/errors.mjs +127 -0
  128. package/dist/client/errors.mjs.map +1 -0
  129. package/dist/client/index.cjs +22 -1424
  130. package/dist/client/index.d.cts +8 -692
  131. package/dist/client/index.d.mts +8 -692
  132. package/dist/client/index.mjs +9 -1413
  133. package/dist/index.cjs +20 -2973
  134. package/dist/index.d.cts +12 -419
  135. package/dist/index.d.mts +12 -419
  136. package/dist/index.mjs +13 -2968
  137. package/dist/primitives/Array.cjs +302 -0
  138. package/dist/primitives/Array.d.cts +95 -0
  139. package/dist/primitives/Array.d.cts.map +1 -0
  140. package/dist/primitives/Array.d.mts +95 -0
  141. package/dist/primitives/Array.d.mts.map +1 -0
  142. package/dist/primitives/Array.mjs +301 -0
  143. package/dist/primitives/Array.mjs.map +1 -0
  144. package/dist/primitives/Boolean.cjs +95 -0
  145. package/dist/primitives/Boolean.d.cts +44 -0
  146. package/dist/primitives/Boolean.d.cts.map +1 -0
  147. package/dist/primitives/Boolean.d.mts +44 -0
  148. package/dist/primitives/Boolean.d.mts.map +1 -0
  149. package/dist/primitives/Boolean.mjs +94 -0
  150. package/dist/primitives/Boolean.mjs.map +1 -0
  151. package/dist/primitives/Either.cjs +200 -0
  152. package/dist/primitives/Either.d.cts +113 -0
  153. package/dist/primitives/Either.d.cts.map +1 -0
  154. package/dist/primitives/Either.d.mts +113 -0
  155. package/dist/primitives/Either.d.mts.map +1 -0
  156. package/dist/primitives/Either.mjs +199 -0
  157. package/dist/primitives/Either.mjs.map +1 -0
  158. package/dist/primitives/Lazy.cjs +46 -0
  159. package/dist/primitives/Lazy.d.cts +46 -0
  160. package/dist/primitives/Lazy.d.cts.map +1 -0
  161. package/dist/primitives/Lazy.d.mts +46 -0
  162. package/dist/primitives/Lazy.d.mts.map +1 -0
  163. package/dist/primitives/Lazy.mjs +46 -0
  164. package/dist/primitives/Lazy.mjs.map +1 -0
  165. package/dist/primitives/Literal.cjs +91 -0
  166. package/dist/primitives/Literal.d.cts +46 -0
  167. package/dist/primitives/Literal.d.cts.map +1 -0
  168. package/dist/primitives/Literal.d.mts +46 -0
  169. package/dist/primitives/Literal.d.mts.map +1 -0
  170. package/dist/primitives/Literal.mjs +90 -0
  171. package/dist/primitives/Literal.mjs.map +1 -0
  172. package/dist/primitives/Number.cjs +115 -0
  173. package/dist/primitives/Number.d.cts +54 -0
  174. package/dist/primitives/Number.d.cts.map +1 -0
  175. package/dist/primitives/Number.d.mts +54 -0
  176. package/dist/primitives/Number.d.mts.map +1 -0
  177. package/dist/primitives/Number.mjs +114 -0
  178. package/dist/primitives/Number.mjs.map +1 -0
  179. package/dist/primitives/String.cjs +127 -0
  180. package/dist/primitives/String.d.cts +56 -0
  181. package/dist/primitives/String.d.cts.map +1 -0
  182. package/dist/primitives/String.d.mts +56 -0
  183. package/dist/primitives/String.d.mts.map +1 -0
  184. package/dist/primitives/String.mjs +126 -0
  185. package/dist/primitives/String.mjs.map +1 -0
  186. package/dist/primitives/Struct.cjs +207 -0
  187. package/dist/primitives/Struct.d.cts +96 -0
  188. package/dist/primitives/Struct.d.cts.map +1 -0
  189. package/dist/primitives/Struct.d.mts +97 -0
  190. package/dist/primitives/Struct.d.mts.map +1 -0
  191. package/dist/primitives/Struct.mjs +206 -0
  192. package/dist/primitives/Struct.mjs.map +1 -0
  193. package/dist/primitives/Tree.cjs +575 -0
  194. package/dist/primitives/Tree.d.cts +185 -0
  195. package/dist/primitives/Tree.d.cts.map +1 -0
  196. package/dist/primitives/Tree.d.mts +185 -0
  197. package/dist/primitives/Tree.d.mts.map +1 -0
  198. package/dist/primitives/Tree.mjs +574 -0
  199. package/dist/primitives/Tree.mjs.map +1 -0
  200. package/dist/primitives/TreeNode.cjs +73 -0
  201. package/dist/primitives/TreeNode.d.cts +92 -0
  202. package/dist/primitives/TreeNode.d.cts.map +1 -0
  203. package/dist/primitives/TreeNode.d.mts +93 -0
  204. package/dist/primitives/TreeNode.d.mts.map +1 -0
  205. package/dist/primitives/TreeNode.mjs +72 -0
  206. package/dist/primitives/TreeNode.mjs.map +1 -0
  207. package/dist/primitives/Union.cjs +170 -0
  208. package/dist/primitives/Union.d.cts +81 -0
  209. package/dist/primitives/Union.d.cts.map +1 -0
  210. package/dist/primitives/Union.d.mts +81 -0
  211. package/dist/primitives/Union.d.mts.map +1 -0
  212. package/dist/primitives/Union.mjs +169 -0
  213. package/dist/primitives/Union.mjs.map +1 -0
  214. package/dist/primitives/shared.cjs +60 -0
  215. package/dist/primitives/shared.d.cts +147 -0
  216. package/dist/primitives/shared.d.cts.map +1 -0
  217. package/dist/primitives/shared.d.mts +147 -0
  218. package/dist/primitives/shared.d.mts.map +1 -0
  219. package/dist/primitives/shared.mjs +58 -0
  220. package/dist/primitives/shared.mjs.map +1 -0
  221. package/dist/server/ServerDocument.cjs +110 -0
  222. package/dist/server/ServerDocument.d.cts +98 -0
  223. package/dist/server/ServerDocument.d.cts.map +1 -0
  224. package/dist/server/ServerDocument.d.mts +99 -0
  225. package/dist/server/ServerDocument.d.mts.map +1 -0
  226. package/dist/server/ServerDocument.mjs +106 -0
  227. package/dist/server/ServerDocument.mjs.map +1 -0
  228. package/dist/server/errors.cjs +85 -0
  229. package/dist/server/errors.d.cts +53 -0
  230. package/dist/server/errors.d.cts.map +1 -0
  231. package/dist/server/errors.d.mts +53 -0
  232. package/dist/server/errors.d.mts.map +1 -0
  233. package/dist/server/errors.mjs +81 -0
  234. package/dist/server/errors.mjs.map +1 -0
  235. package/dist/server/index.cjs +9 -185
  236. package/dist/server/index.d.cts +3 -148
  237. package/dist/server/index.d.mts +3 -148
  238. package/dist/server/index.mjs +3 -181
  239. package/dist/types/index.cjs +16 -0
  240. package/dist/types/index.d.cts +16 -0
  241. package/dist/types/index.d.cts.map +1 -0
  242. package/dist/types/index.d.mts +16 -0
  243. package/dist/types/index.d.mts.map +1 -0
  244. package/dist/types/index.mjs +12 -0
  245. package/dist/types/index.mjs.map +1 -0
  246. package/dist/utils/tree-helpers.cjs +443 -0
  247. package/dist/utils/tree-helpers.d.cts +280 -0
  248. package/dist/utils/tree-helpers.d.cts.map +1 -0
  249. package/dist/utils/tree-helpers.d.mts +280 -0
  250. package/dist/utils/tree-helpers.d.mts.map +1 -0
  251. package/dist/utils/tree-helpers.mjs +439 -0
  252. package/dist/utils/tree-helpers.mjs.map +1 -0
  253. package/package.json +2 -2
  254. package/tsdown.config.ts +1 -1
  255. package/dist/Document-ChuFrTk1.cjs +0 -571
  256. package/dist/Document-CwiAFTIq.mjs +0 -438
  257. package/dist/Document-CwiAFTIq.mjs.map +0 -1
  258. package/dist/Presence-DKKP4v5X.d.cts.map +0 -1
  259. package/dist/Presence-DdMVKcOv.mjs.map +0 -1
  260. package/dist/Presence-N8u7Eppr.d.mts.map +0 -1
  261. package/dist/Primitive-DqQFc3Gu.d.mts +0 -1180
  262. package/dist/Primitive-DqQFc3Gu.d.mts.map +0 -1
  263. package/dist/Primitive-awpEjnKL.d.cts +0 -1180
  264. package/dist/Primitive-awpEjnKL.d.cts.map +0 -1
  265. package/dist/client/index.d.cts.map +0 -1
  266. package/dist/client/index.d.mts.map +0 -1
  267. package/dist/client/index.mjs.map +0 -1
  268. package/dist/index.d.cts.map +0 -1
  269. package/dist/index.d.mts.map +0 -1
  270. package/dist/index.mjs.map +0 -1
  271. package/dist/server/index.d.cts.map +0 -1
  272. package/dist/server/index.d.mts.map +0 -1
  273. package/dist/server/index.mjs.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,2968 +1,15 @@
1
- const require_Document = require('./Document-ChuFrTk1.cjs');
2
- const require_Presence = require('./Presence-gWrmGBeu.cjs');
3
- let effect = require("effect");
1
+ const require_OperationPath = require('./OperationPath.cjs');
2
+ const require_Operation = require('./Operation.cjs');
3
+ const require_Primitive = require('./Primitive.cjs');
4
+ const require_ProxyEnvironment = require('./ProxyEnvironment.cjs');
5
+ const require_Transaction = require('./Transaction.cjs');
6
+ const require_Document = require('./Document.cjs');
7
+ const require_Transform = require('./Transform.cjs');
8
+ const require_Presence = require('./Presence.cjs');
9
+ const require_EffectSchema = require('./EffectSchema.cjs');
10
+ const require_index = require('./types/index.cjs');
11
+ const require_tree_helpers = require('./utils/tree-helpers.cjs');
4
12
 
5
- //#region src/primitives/shared.ts
6
- var ValidationError = class extends Error {
7
- constructor(message) {
8
- super(message);
9
- require_Document._defineProperty(this, "_tag", "ValidationError");
10
- this.name = "ValidationError";
11
- }
12
- };
13
- /**
14
- * Runs all validators against a value, throwing ValidationError if any fail.
15
- */
16
- function runValidators(value, validators) {
17
- for (const validator of validators) if (!validator.validate(value)) throw new ValidationError(validator.message);
18
- }
19
- /**
20
- * Checks if an operation is compatible with the given operation definitions.
21
- * @param operation - The operation to check.
22
- * @param operationDefinitions - The operation definitions to check against.
23
- * @returns True if the operation is compatible, false otherwise.
24
- */
25
- function isCompatibleOperation(operation, operationDefinitions) {
26
- return Object.values(operationDefinitions).some((value) => value.kind === operation.kind);
27
- }
28
- /**
29
- * Applies default values to a partial input, recursively handling nested structs.
30
- *
31
- * Uses a two-layer approach:
32
- * 1. First, get the struct's initial state (which includes struct-level defaults)
33
- * 2. Then, layer the provided values on top
34
- * 3. Finally, ensure nested structs are recursively processed
35
- *
36
- * @param primitive - The primitive definition containing field information
37
- * @param value - The partial value provided by the user
38
- * @returns The value with defaults applied for missing fields
39
- */
40
- function applyDefaults(primitive, value) {
41
- if (primitive._tag === "StructPrimitive") {
42
- var _structPrimitive$_int;
43
- const structPrimitive = primitive;
44
- const result = require_Presence._objectSpread2(require_Presence._objectSpread2({}, (_structPrimitive$_int = structPrimitive._internal.getInitialState()) !== null && _structPrimitive$_int !== void 0 ? _structPrimitive$_int : {}), value);
45
- for (const key in structPrimitive.fields) {
46
- const fieldPrimitive = structPrimitive.fields[key];
47
- if (result[key] === void 0) {
48
- const fieldDefault = fieldPrimitive._internal.getInitialState();
49
- if (fieldDefault !== void 0) result[key] = fieldDefault;
50
- } else if (fieldPrimitive._tag === "StructPrimitive" && typeof result[key] === "object" && result[key] !== null) result[key] = applyDefaults(fieldPrimitive, result[key]);
51
- }
52
- return result;
53
- }
54
- return value;
55
- }
56
-
57
- //#endregion
58
- //#region src/OperationDefinition.ts
59
- const make = (options) => {
60
- return {
61
- kind: options.kind,
62
- payload: options.payload,
63
- target: options.target,
64
- apply: options.apply
65
- };
66
- };
67
-
68
- //#endregion
69
- //#region src/primitives/String.ts
70
- var StringPrimitive = class StringPrimitive {
71
- constructor(schema) {
72
- require_Document._defineProperty(this, "_tag", "StringPrimitive");
73
- require_Document._defineProperty(this, "_State", void 0);
74
- require_Document._defineProperty(this, "_Proxy", void 0);
75
- require_Document._defineProperty(this, "_TRequired", void 0);
76
- require_Document._defineProperty(this, "_THasDefault", void 0);
77
- require_Document._defineProperty(this, "TUpdateInput", void 0);
78
- require_Document._defineProperty(this, "TSetInput", void 0);
79
- require_Document._defineProperty(this, "_schema", void 0);
80
- require_Document._defineProperty(this, "_opDefinitions", { set: make({
81
- kind: "string.set",
82
- payload: effect.Schema.String,
83
- target: effect.Schema.String,
84
- apply: (payload) => payload
85
- }) });
86
- require_Document._defineProperty(this, "_internal", {
87
- createProxy: (env, operationPath) => {
88
- const defaultValue = this._schema.defaultValue;
89
- return {
90
- get: () => {
91
- const state = env.getState(operationPath);
92
- return state !== null && state !== void 0 ? state : defaultValue;
93
- },
94
- set: (value) => {
95
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.set, value));
96
- },
97
- update: (value) => {
98
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.set, value));
99
- },
100
- toSnapshot: () => {
101
- const state = env.getState(operationPath);
102
- return state !== null && state !== void 0 ? state : defaultValue;
103
- }
104
- };
105
- },
106
- applyOperation: (_state, operation) => {
107
- if (!isCompatibleOperation(operation, this._opDefinitions)) throw new ValidationError(`StringPrimitive cannot apply operation of kind: ${operation.kind}`);
108
- const payload = operation.payload;
109
- if (typeof payload !== "string") throw new ValidationError(`StringPrimitive.set requires a string payload, got: ${typeof payload}`);
110
- runValidators(payload, this._schema.validators);
111
- return payload;
112
- },
113
- getInitialState: () => {
114
- return this._schema.defaultValue;
115
- },
116
- transformOperation: (clientOp, serverOp) => {
117
- if (!require_Document.pathsOverlap(clientOp.path, serverOp.path)) return {
118
- type: "transformed",
119
- operation: clientOp
120
- };
121
- return {
122
- type: "transformed",
123
- operation: clientOp
124
- };
125
- }
126
- });
127
- this._schema = schema;
128
- }
129
- /** Mark this string as required */
130
- required() {
131
- return new StringPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { required: true }));
132
- }
133
- /** Set a default value for this string */
134
- default(defaultValue) {
135
- return new StringPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { defaultValue }));
136
- }
137
- /** Add a custom validation rule */
138
- refine(fn, message) {
139
- return new StringPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { validators: [...this._schema.validators, {
140
- validate: fn,
141
- message
142
- }] }));
143
- }
144
- /** Minimum string length */
145
- min(length) {
146
- return this.refine((v) => v.length >= length, `String must be at least ${length} characters`);
147
- }
148
- /** Maximum string length */
149
- max(length) {
150
- return this.refine((v) => v.length <= length, `String must be at most ${length} characters`);
151
- }
152
- /** Exact string length */
153
- length(exact) {
154
- return this.refine((v) => v.length === exact, `String must be exactly ${exact} characters`);
155
- }
156
- /** Match a regex pattern */
157
- regex(pattern, message) {
158
- return this.refine((v) => pattern.test(v), message !== null && message !== void 0 ? message : `String must match pattern ${pattern}`);
159
- }
160
- /** Validate as email format */
161
- email() {
162
- const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
163
- return this.refine((v) => emailPattern.test(v), "Invalid email format");
164
- }
165
- /** Validate as URL format */
166
- url() {
167
- return this.refine((v) => {
168
- try {
169
- new URL(v);
170
- return true;
171
- } catch (_unused) {
172
- return false;
173
- }
174
- }, "Invalid URL format");
175
- }
176
- };
177
- /** Creates a new StringPrimitive */
178
- const String = () => new StringPrimitive({
179
- required: false,
180
- defaultValue: void 0,
181
- validators: []
182
- });
183
-
184
- //#endregion
185
- //#region src/primitives/Struct.ts
186
- var StructPrimitive = class StructPrimitive {
187
- constructor(schema) {
188
- require_Document._defineProperty(this, "_tag", "StructPrimitive");
189
- require_Document._defineProperty(this, "_State", void 0);
190
- require_Document._defineProperty(this, "_Proxy", void 0);
191
- require_Document._defineProperty(this, "_TRequired", void 0);
192
- require_Document._defineProperty(this, "_THasDefault", void 0);
193
- require_Document._defineProperty(this, "TSetInput", void 0);
194
- require_Document._defineProperty(this, "TUpdateInput", void 0);
195
- require_Document._defineProperty(this, "_schema", void 0);
196
- require_Document._defineProperty(this, "_opDefinitions", { set: make({
197
- kind: "struct.set",
198
- payload: effect.Schema.Unknown,
199
- target: effect.Schema.Unknown,
200
- apply: (payload) => payload
201
- }) });
202
- require_Document._defineProperty(this, "_internal", {
203
- createProxy: (env, operationPath) => {
204
- const fields = this._schema.fields;
205
- const defaultValue = this._schema.defaultValue;
206
- const buildSnapshot = () => {
207
- const state = env.getState(operationPath);
208
- const snapshot = {};
209
- let hasAnyDefinedField = false;
210
- for (const key in fields) {
211
- const fieldPrimitive = fields[key];
212
- const fieldPath = operationPath.append(key);
213
- const fieldSnapshot = fieldPrimitive._internal.createProxy(env, fieldPath).toSnapshot();
214
- snapshot[key] = fieldSnapshot;
215
- if (fieldSnapshot !== void 0) hasAnyDefinedField = true;
216
- }
217
- if (state === void 0 && defaultValue === void 0 && !hasAnyDefinedField) return;
218
- return snapshot;
219
- };
220
- return new globalThis.Proxy({
221
- get: () => {
222
- const state = env.getState(operationPath);
223
- return state !== null && state !== void 0 ? state : defaultValue;
224
- },
225
- set: (value) => {
226
- const merged = applyDefaults(this, value);
227
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.set, merged));
228
- },
229
- update: (value) => {
230
- for (const key in value) if (Object.prototype.hasOwnProperty.call(value, key)) {
231
- const fieldValue = value[key];
232
- if (fieldValue === void 0) continue;
233
- const fieldPrimitive = fields[key];
234
- if (!fieldPrimitive) continue;
235
- const fieldPath = operationPath.append(key);
236
- const fieldProxy = fieldPrimitive._internal.createProxy(env, fieldPath);
237
- if (fieldPrimitive._tag === "StructPrimitive" && typeof fieldValue === "object" && fieldValue !== null && !Array.isArray(fieldValue)) fieldProxy.update(fieldValue);
238
- else fieldProxy.set(fieldValue);
239
- }
240
- },
241
- toSnapshot: () => {
242
- return buildSnapshot();
243
- }
244
- }, {
245
- get: (target, prop, _receiver) => {
246
- if (prop === "get") return target.get;
247
- if (prop === "set") return target.set;
248
- if (prop === "update") return target.update;
249
- if (prop === "toSnapshot") return target.toSnapshot;
250
- if (typeof prop === "symbol") return;
251
- if (prop in fields) {
252
- const fieldPrimitive = fields[prop];
253
- const fieldPath = operationPath.append(prop);
254
- return fieldPrimitive._internal.createProxy(env, fieldPath);
255
- }
256
- },
257
- has: (_target, prop) => {
258
- if (prop === "get" || prop === "set" || prop === "update" || prop === "toSnapshot") return true;
259
- if (typeof prop === "string" && prop in fields) return true;
260
- return false;
261
- }
262
- });
263
- },
264
- applyOperation: (state, operation) => {
265
- const path = operation.path;
266
- const tokens = path.toTokens().filter((t) => t !== "");
267
- let newState;
268
- if (tokens.length === 0) {
269
- if (operation.kind !== "struct.set") throw new ValidationError(`StructPrimitive root cannot apply operation of kind: ${operation.kind}`);
270
- const payload = operation.payload;
271
- if (typeof payload !== "object" || payload === null) throw new ValidationError(`StructPrimitive.set requires an object payload`);
272
- newState = payload;
273
- } else {
274
- const fieldName = tokens[0];
275
- if (!(fieldName in this._schema.fields)) throw new ValidationError(`Unknown field: ${globalThis.String(fieldName)}`);
276
- const fieldPrimitive = this._schema.fields[fieldName];
277
- const remainingPath = path.shift();
278
- const fieldOperation = require_Presence._objectSpread2(require_Presence._objectSpread2({}, operation), {}, { path: remainingPath });
279
- const currentState = state !== null && state !== void 0 ? state : {};
280
- const currentFieldState = currentState[fieldName];
281
- const newFieldState = fieldPrimitive._internal.applyOperation(currentFieldState, fieldOperation);
282
- newState = require_Presence._objectSpread2(require_Presence._objectSpread2({}, currentState), {}, { [fieldName]: newFieldState });
283
- }
284
- runValidators(newState, this._schema.validators);
285
- return newState;
286
- },
287
- getInitialState: () => {
288
- if (this._schema.defaultValue !== void 0) return this._schema.defaultValue;
289
- const fields = this._schema.fields;
290
- const initialState = {};
291
- let hasAnyDefault = false;
292
- for (const key in fields) {
293
- const fieldDefault = fields[key]._internal.getInitialState();
294
- if (fieldDefault !== void 0) {
295
- initialState[key] = fieldDefault;
296
- hasAnyDefault = true;
297
- }
298
- }
299
- return hasAnyDefault ? initialState : void 0;
300
- },
301
- transformOperation: (clientOp, serverOp) => {
302
- const clientPath = clientOp.path;
303
- const serverPath = serverOp.path;
304
- if (!require_Document.pathsOverlap(clientPath, serverPath)) return {
305
- type: "transformed",
306
- operation: clientOp
307
- };
308
- const clientTokens = clientPath.toTokens().filter((t) => t !== "");
309
- const serverTokens = serverPath.toTokens().filter((t) => t !== "");
310
- if (clientTokens.length === 0 && serverTokens.length === 0) return {
311
- type: "transformed",
312
- operation: clientOp
313
- };
314
- if (serverTokens.length === 0 && serverOp.kind === "struct.set") return {
315
- type: "transformed",
316
- operation: clientOp
317
- };
318
- if (clientTokens.length === 0 && clientOp.kind === "struct.set") return {
319
- type: "transformed",
320
- operation: clientOp
321
- };
322
- if (clientTokens.length > 0 && serverTokens.length > 0) {
323
- const clientField = clientTokens[0];
324
- if (clientField !== serverTokens[0]) return {
325
- type: "transformed",
326
- operation: clientOp
327
- };
328
- const fieldPrimitive = this._schema.fields[clientField];
329
- if (!fieldPrimitive) return {
330
- type: "transformed",
331
- operation: clientOp
332
- };
333
- const clientOpForField = require_Presence._objectSpread2(require_Presence._objectSpread2({}, clientOp), {}, { path: clientOp.path.shift() });
334
- const serverOpForField = require_Presence._objectSpread2(require_Presence._objectSpread2({}, serverOp), {}, { path: serverOp.path.shift() });
335
- const result = fieldPrimitive._internal.transformOperation(clientOpForField, serverOpForField);
336
- if (result.type === "transformed") return {
337
- type: "transformed",
338
- operation: require_Presence._objectSpread2(require_Presence._objectSpread2({}, result.operation), {}, { path: clientOp.path })
339
- };
340
- return result;
341
- }
342
- return {
343
- type: "transformed",
344
- operation: clientOp
345
- };
346
- }
347
- });
348
- this._schema = schema;
349
- }
350
- /** Mark this struct as required */
351
- required() {
352
- return new StructPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { required: true }));
353
- }
354
- /** Set a default value for this struct */
355
- default(defaultValue) {
356
- const merged = applyDefaults(this, defaultValue);
357
- return new StructPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { defaultValue: merged }));
358
- }
359
- /** Get the fields schema */
360
- get fields() {
361
- return this._schema.fields;
362
- }
363
- /** Add a custom validation rule (useful for cross-field validation) */
364
- refine(fn, message) {
365
- return new StructPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { validators: [...this._schema.validators, {
366
- validate: fn,
367
- message
368
- }] }));
369
- }
370
- };
371
- /** Creates a new StructPrimitive with the given fields */
372
- const Struct = (fields) => new StructPrimitive({
373
- required: false,
374
- defaultValue: void 0,
375
- fields,
376
- validators: []
377
- });
378
-
379
- //#endregion
380
- //#region src/primitives/Boolean.ts
381
- var BooleanPrimitive = class BooleanPrimitive {
382
- constructor(schema) {
383
- require_Document._defineProperty(this, "_tag", "BooleanPrimitive");
384
- require_Document._defineProperty(this, "_State", void 0);
385
- require_Document._defineProperty(this, "_Proxy", void 0);
386
- require_Document._defineProperty(this, "_TRequired", void 0);
387
- require_Document._defineProperty(this, "_THasDefault", void 0);
388
- require_Document._defineProperty(this, "TUpdateInput", void 0);
389
- require_Document._defineProperty(this, "TSetInput", void 0);
390
- require_Document._defineProperty(this, "_schema", void 0);
391
- require_Document._defineProperty(this, "_opDefinitions", { set: make({
392
- kind: "boolean.set",
393
- payload: effect.Schema.Boolean,
394
- target: effect.Schema.Boolean,
395
- apply: (payload) => payload
396
- }) });
397
- require_Document._defineProperty(this, "_internal", {
398
- createProxy: (env, operationPath) => {
399
- const defaultValue = this._schema.defaultValue;
400
- return {
401
- get: () => {
402
- const state = env.getState(operationPath);
403
- return state !== null && state !== void 0 ? state : defaultValue;
404
- },
405
- set: (value) => {
406
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.set, value));
407
- },
408
- update: (value) => {
409
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.set, value));
410
- },
411
- toSnapshot: () => {
412
- const state = env.getState(operationPath);
413
- return state !== null && state !== void 0 ? state : defaultValue;
414
- }
415
- };
416
- },
417
- applyOperation: (_state, operation) => {
418
- if (operation.kind !== "boolean.set") throw new ValidationError(`BooleanPrimitive cannot apply operation of kind: ${operation.kind}`);
419
- const payload = operation.payload;
420
- if (typeof payload !== "boolean") throw new ValidationError(`BooleanPrimitive.set requires a boolean payload, got: ${typeof payload}`);
421
- runValidators(payload, this._schema.validators);
422
- return payload;
423
- },
424
- getInitialState: () => {
425
- return this._schema.defaultValue;
426
- },
427
- transformOperation: (clientOp, serverOp) => {
428
- if (!require_Document.pathsOverlap(clientOp.path, serverOp.path)) return {
429
- type: "transformed",
430
- operation: clientOp
431
- };
432
- return {
433
- type: "transformed",
434
- operation: clientOp
435
- };
436
- }
437
- });
438
- this._schema = schema;
439
- }
440
- /** Mark this boolean as required */
441
- required() {
442
- return new BooleanPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { required: true }));
443
- }
444
- /** Set a default value for this boolean */
445
- default(defaultValue) {
446
- return new BooleanPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { defaultValue }));
447
- }
448
- /** Add a custom validation rule */
449
- refine(fn, message) {
450
- return new BooleanPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { validators: [...this._schema.validators, {
451
- validate: fn,
452
- message
453
- }] }));
454
- }
455
- };
456
- /** Creates a new BooleanPrimitive */
457
- const Boolean = () => new BooleanPrimitive({
458
- required: false,
459
- defaultValue: void 0,
460
- validators: []
461
- });
462
-
463
- //#endregion
464
- //#region src/primitives/Number.ts
465
- var NumberPrimitive = class NumberPrimitive {
466
- constructor(schema) {
467
- require_Document._defineProperty(this, "_tag", "NumberPrimitive");
468
- require_Document._defineProperty(this, "_State", void 0);
469
- require_Document._defineProperty(this, "_Proxy", void 0);
470
- require_Document._defineProperty(this, "_TRequired", void 0);
471
- require_Document._defineProperty(this, "_THasDefault", void 0);
472
- require_Document._defineProperty(this, "TUpdateInput", void 0);
473
- require_Document._defineProperty(this, "TSetInput", void 0);
474
- require_Document._defineProperty(this, "_schema", void 0);
475
- require_Document._defineProperty(this, "_opDefinitions", { set: make({
476
- kind: "number.set",
477
- payload: effect.Schema.Number,
478
- target: effect.Schema.Number,
479
- apply: (payload) => payload
480
- }) });
481
- require_Document._defineProperty(this, "_internal", {
482
- createProxy: (env, operationPath) => {
483
- const defaultValue = this._schema.defaultValue;
484
- return {
485
- get: () => {
486
- const state = env.getState(operationPath);
487
- return state !== null && state !== void 0 ? state : defaultValue;
488
- },
489
- set: (value) => {
490
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.set, value));
491
- },
492
- update: (value) => {
493
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.set, value));
494
- },
495
- toSnapshot: () => {
496
- const state = env.getState(operationPath);
497
- return state !== null && state !== void 0 ? state : defaultValue;
498
- }
499
- };
500
- },
501
- applyOperation: (_state, operation) => {
502
- if (operation.kind !== "number.set") throw new ValidationError(`NumberPrimitive cannot apply operation of kind: ${operation.kind}`);
503
- const payload = operation.payload;
504
- if (typeof payload !== "number") throw new ValidationError(`NumberPrimitive.set requires a number payload, got: ${typeof payload}`);
505
- runValidators(payload, this._schema.validators);
506
- return payload;
507
- },
508
- getInitialState: () => {
509
- return this._schema.defaultValue;
510
- },
511
- transformOperation: (clientOp, serverOp) => {
512
- if (!require_Document.pathsOverlap(clientOp.path, serverOp.path)) return {
513
- type: "transformed",
514
- operation: clientOp
515
- };
516
- return {
517
- type: "transformed",
518
- operation: clientOp
519
- };
520
- }
521
- });
522
- this._schema = schema;
523
- }
524
- /** Mark this number as required */
525
- required() {
526
- return new NumberPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { required: true }));
527
- }
528
- /** Set a default value for this number */
529
- default(defaultValue) {
530
- return new NumberPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { defaultValue }));
531
- }
532
- /** Add a custom validation rule */
533
- refine(fn, message) {
534
- return new NumberPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { validators: [...this._schema.validators, {
535
- validate: fn,
536
- message
537
- }] }));
538
- }
539
- /** Minimum value (inclusive) */
540
- min(value) {
541
- return this.refine((v) => v >= value, `Number must be at least ${value}`);
542
- }
543
- /** Maximum value (inclusive) */
544
- max(value) {
545
- return this.refine((v) => v <= value, `Number must be at most ${value}`);
546
- }
547
- /** Must be positive (> 0) */
548
- positive() {
549
- return this.refine((v) => v > 0, "Number must be positive");
550
- }
551
- /** Must be negative (< 0) */
552
- negative() {
553
- return this.refine((v) => v < 0, "Number must be negative");
554
- }
555
- /** Must be an integer */
556
- int() {
557
- return this.refine((v) => globalThis.Number.isInteger(v), "Number must be an integer");
558
- }
559
- };
560
- /** Creates a new NumberPrimitive */
561
- const Number = () => new NumberPrimitive({
562
- required: false,
563
- defaultValue: void 0,
564
- validators: []
565
- });
566
-
567
- //#endregion
568
- //#region src/primitives/Literal.ts
569
- var LiteralPrimitive = class LiteralPrimitive {
570
- constructor(schema) {
571
- require_Document._defineProperty(this, "_tag", "LiteralPrimitive");
572
- require_Document._defineProperty(this, "_State", void 0);
573
- require_Document._defineProperty(this, "_Proxy", void 0);
574
- require_Document._defineProperty(this, "_TRequired", void 0);
575
- require_Document._defineProperty(this, "_THasDefault", void 0);
576
- require_Document._defineProperty(this, "TUpdateInput", void 0);
577
- require_Document._defineProperty(this, "TSetInput", void 0);
578
- require_Document._defineProperty(this, "_schema", void 0);
579
- require_Document._defineProperty(this, "_opDefinitions", { set: make({
580
- kind: "literal.set",
581
- payload: effect.Schema.Unknown,
582
- target: effect.Schema.Unknown,
583
- apply: (payload) => payload
584
- }) });
585
- require_Document._defineProperty(this, "_internal", {
586
- createProxy: (env, operationPath) => {
587
- const defaultValue = this._schema.defaultValue;
588
- return {
589
- get: () => {
590
- const state = env.getState(operationPath);
591
- return state !== null && state !== void 0 ? state : defaultValue;
592
- },
593
- set: (value) => {
594
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.set, value));
595
- },
596
- update: (value) => {
597
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.set, value));
598
- },
599
- toSnapshot: () => {
600
- const state = env.getState(operationPath);
601
- return state !== null && state !== void 0 ? state : defaultValue;
602
- }
603
- };
604
- },
605
- applyOperation: (_state, operation) => {
606
- if (operation.kind !== "literal.set") throw new ValidationError(`LiteralPrimitive cannot apply operation of kind: ${operation.kind}`);
607
- const payload = operation.payload;
608
- if (payload !== this._schema.literal) throw new ValidationError(`LiteralPrimitive.set requires the exact literal value "${globalThis.String(this._schema.literal)}", got: "${globalThis.String(payload)}"`);
609
- return payload;
610
- },
611
- getInitialState: () => {
612
- return this._schema.defaultValue;
613
- },
614
- transformOperation: (clientOp, serverOp) => {
615
- if (!require_Document.pathsOverlap(clientOp.path, serverOp.path)) return {
616
- type: "transformed",
617
- operation: clientOp
618
- };
619
- return {
620
- type: "transformed",
621
- operation: clientOp
622
- };
623
- }
624
- });
625
- this._schema = schema;
626
- }
627
- /** Mark this literal as required */
628
- required() {
629
- return new LiteralPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { required: true }));
630
- }
631
- /** Set a default value for this literal */
632
- default(defaultValue) {
633
- return new LiteralPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { defaultValue }));
634
- }
635
- /** Get the literal value this primitive represents */
636
- get literal() {
637
- return this._schema.literal;
638
- }
639
- };
640
- /** Creates a new LiteralPrimitive with the given literal value */
641
- const Literal = (literal) => new LiteralPrimitive({
642
- required: false,
643
- defaultValue: void 0,
644
- literal
645
- });
646
-
647
- //#endregion
648
- //#region src/FractionalIndex.ts
649
- function createCharSetDicts(charSet) {
650
- const byCode = {};
651
- const byChar = {};
652
- const length = charSet.length;
653
- for (let i = 0; i < length; i++) {
654
- const char = charSet[i];
655
- if (char === void 0) throw new Error("invalid charSet: missing character at index " + i);
656
- byCode[i] = char;
657
- byChar[char] = i;
658
- }
659
- return {
660
- byCode,
661
- byChar,
662
- length
663
- };
664
- }
665
- function integerLimits(dicts, firstPositive, mostPositive, mostNegative) {
666
- return effect.Effect.gen(function* () {
667
- const firstPositiveIndex = firstPositive ? dicts.byChar[firstPositive] : Math.ceil(dicts.length / 2);
668
- const mostPositiveIndex = mostPositive ? dicts.byChar[mostPositive] : dicts.length - 1;
669
- const mostNegativeIndex = mostNegative ? dicts.byChar[mostNegative] : 0;
670
- if (firstPositiveIndex === void 0 || mostPositiveIndex === void 0 || mostNegativeIndex === void 0) return yield* effect.Effect.fail(/* @__PURE__ */ new Error("invalid charSet"));
671
- if (mostPositiveIndex - firstPositiveIndex < 3) return yield* effect.Effect.fail(/* @__PURE__ */ new Error("mostPositive must be at least 3 characters away from neutral"));
672
- if (firstPositiveIndex - mostNegativeIndex < 3) return yield* effect.Effect.fail(/* @__PURE__ */ new Error("mostNegative must be at least 3 characters away from neutral"));
673
- const firstPositiveChar = dicts.byCode[firstPositiveIndex];
674
- const mostPositiveChar = dicts.byCode[mostPositiveIndex];
675
- const firstNegativeChar = dicts.byCode[firstPositiveIndex - 1];
676
- const mostNegativeChar = dicts.byCode[mostNegativeIndex];
677
- if (firstPositiveChar === void 0 || mostPositiveChar === void 0 || firstNegativeChar === void 0 || mostNegativeChar === void 0) return yield* effect.Effect.fail(/* @__PURE__ */ new Error("invalid charSet"));
678
- return {
679
- firstPositive: firstPositiveChar,
680
- mostPositive: mostPositiveChar,
681
- firstNegative: firstNegativeChar,
682
- mostNegative: mostNegativeChar
683
- };
684
- });
685
- }
686
- function paddingDict(jitterRange, charSetLength) {
687
- const paddingDict$1 = {};
688
- for (let i = 0; i < 100; i++) {
689
- const value = Math.pow(charSetLength, i);
690
- paddingDict$1[i] = value;
691
- if (value > jitterRange) break;
692
- }
693
- return paddingDict$1;
694
- }
695
- function validateChars(characters) {
696
- if (characters.length < 7) return effect.Effect.fail(/* @__PURE__ */ new Error("charSet must be at least 7 characters long"));
697
- if (!(characters.split("").sort().join("") === characters)) return effect.Effect.fail(/* @__PURE__ */ new Error("charSet must be sorted"));
698
- return effect.Effect.void;
699
- }
700
- function indexCharacterSet(options) {
701
- return effect.Effect.gen(function* () {
702
- var _options$jitterRange;
703
- yield* validateChars(options.chars);
704
- const dicts = createCharSetDicts(options.chars);
705
- const limits = yield* integerLimits(dicts, options.firstPositive, options.mostPositive, options.mostNegative);
706
- const jitterRange = (_options$jitterRange = options.jitterRange) !== null && _options$jitterRange !== void 0 ? _options$jitterRange : Math.floor(Math.pow(dicts.length, 3) / 5);
707
- const paddingRange = paddingDict(jitterRange, dicts.length);
708
- const first = dicts.byCode[0];
709
- const last = dicts.byCode[dicts.length - 1];
710
- if (first === void 0 || last === void 0) return yield* effect.Effect.fail(/* @__PURE__ */ new Error("invalid charSet"));
711
- return {
712
- chars: options.chars,
713
- byChar: dicts.byChar,
714
- byCode: dicts.byCode,
715
- length: dicts.length,
716
- first,
717
- last,
718
- firstPositive: limits.firstPositive,
719
- mostPositive: limits.mostPositive,
720
- firstNegative: limits.firstNegative,
721
- mostNegative: limits.mostNegative,
722
- jitterRange,
723
- paddingDict: paddingRange
724
- };
725
- });
726
- }
727
- let _base62CharSet = null;
728
- function base62CharSet() {
729
- if (_base62CharSet) return _base62CharSet;
730
- _base62CharSet = effect.Effect.runSync(indexCharacterSet({
731
- chars: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
732
- firstPositive: "a",
733
- mostPositive: "z",
734
- mostNegative: "A"
735
- }));
736
- return _base62CharSet;
737
- }
738
- function makeSameLength(a, b, pad, fillChar, forceLength) {
739
- const max = forceLength !== null && forceLength !== void 0 ? forceLength : Math.max(a.length, b.length);
740
- if (pad === "start") return [a.padStart(max, fillChar), b.padStart(max, fillChar)];
741
- return [a.padEnd(max, fillChar), b.padEnd(max, fillChar)];
742
- }
743
- function distanceBetween(a, b, charSet) {
744
- const indexA = charSet.byChar[a];
745
- const indexB = charSet.byChar[b];
746
- if (indexA === void 0 || indexB === void 0) return effect.Effect.fail(/* @__PURE__ */ new Error("invalid character in distance calculation"));
747
- return effect.Effect.succeed(Math.abs(indexA - indexB));
748
- }
749
- function integerLengthFromSecondLevel(key, direction, charSet) {
750
- if (key.length === 0) return effect.Effect.succeed(0);
751
- const firstChar = key[0];
752
- if (!firstChar || firstChar > charSet.mostPositive || firstChar < charSet.mostNegative) return effect.Effect.fail(/* @__PURE__ */ new Error("invalid firstChar on key"));
753
- if (firstChar === charSet.mostPositive && direction === "positive") return effect.Effect.gen(function* () {
754
- const totalPositiveRoom = yield* distanceBetween(firstChar, charSet.mostNegative, charSet);
755
- const rest = yield* integerLengthFromSecondLevel(key.slice(1), direction, charSet);
756
- return totalPositiveRoom + 1 + rest;
757
- });
758
- if (firstChar === charSet.mostNegative && direction === "negative") return effect.Effect.gen(function* () {
759
- const totalNegativeRoom = yield* distanceBetween(firstChar, charSet.mostPositive, charSet);
760
- const rest = yield* integerLengthFromSecondLevel(key.slice(1), direction, charSet);
761
- return totalNegativeRoom + 1 + rest;
762
- });
763
- if (direction === "positive") return effect.Effect.gen(function* () {
764
- return (yield* distanceBetween(firstChar, charSet.mostNegative, charSet)) + 2;
765
- });
766
- else return effect.Effect.gen(function* () {
767
- return (yield* distanceBetween(firstChar, charSet.mostPositive, charSet)) + 2;
768
- });
769
- }
770
- function integerLength(head, charSet) {
771
- if (head.length === 0) return effect.Effect.fail(/* @__PURE__ */ new Error("head cannot be empty"));
772
- const firstChar = head[0];
773
- if (!firstChar || firstChar > charSet.mostPositive || firstChar < charSet.mostNegative) return effect.Effect.fail(/* @__PURE__ */ new Error("invalid firstChar on key"));
774
- if (firstChar === charSet.mostPositive) return effect.Effect.gen(function* () {
775
- const firstLevel = yield* distanceBetween(firstChar, charSet.firstPositive, charSet);
776
- const rest = yield* integerLengthFromSecondLevel(head.slice(1), "positive", charSet);
777
- return firstLevel + 1 + rest;
778
- });
779
- if (firstChar === charSet.mostNegative) return effect.Effect.gen(function* () {
780
- const firstLevel = yield* distanceBetween(firstChar, charSet.firstNegative, charSet);
781
- const rest = yield* integerLengthFromSecondLevel(head.slice(1), "negative", charSet);
782
- return firstLevel + 1 + rest;
783
- });
784
- if (firstChar >= charSet.firstPositive) return effect.Effect.gen(function* () {
785
- return (yield* distanceBetween(firstChar, charSet.firstPositive, charSet)) + 2;
786
- });
787
- else return effect.Effect.gen(function* () {
788
- return (yield* distanceBetween(firstChar, charSet.firstNegative, charSet)) + 2;
789
- });
790
- }
791
- function encodeToCharSet(int, charSet) {
792
- if (int === 0) {
793
- const zero = charSet.byCode[0];
794
- if (zero === void 0) return effect.Effect.fail(/* @__PURE__ */ new Error("invalid charSet: missing code 0"));
795
- return effect.Effect.succeed(zero);
796
- }
797
- let res = "";
798
- const max = charSet.length;
799
- while (int > 0) {
800
- const code = charSet.byCode[int % max];
801
- if (code === void 0) return effect.Effect.fail(/* @__PURE__ */ new Error("invalid character code in encodeToCharSet"));
802
- res = code + res;
803
- int = Math.floor(int / max);
804
- }
805
- return effect.Effect.succeed(res);
806
- }
807
- function decodeCharSetToNumber(key, charSet) {
808
- let res = 0;
809
- const length = key.length;
810
- const max = charSet.length;
811
- for (let i = 0; i < length; i++) {
812
- const char = key[i];
813
- if (char === void 0) continue;
814
- const charIndex = charSet.byChar[char];
815
- if (charIndex === void 0) continue;
816
- res += charIndex * Math.pow(max, length - i - 1);
817
- }
818
- return res;
819
- }
820
- function addCharSetKeys(a, b, charSet) {
821
- const base = charSet.length;
822
- const [paddedA, paddedB] = makeSameLength(a, b, "start", charSet.first);
823
- const result = [];
824
- let carry = 0;
825
- for (let i = paddedA.length - 1; i >= 0; i--) {
826
- const charA = paddedA[i];
827
- const charB = paddedB[i];
828
- if (!charA || !charB) return effect.Effect.fail(/* @__PURE__ */ new Error("invalid character in addCharSetKeys"));
829
- const digitA = charSet.byChar[charA];
830
- const digitB = charSet.byChar[charB];
831
- if (digitA === void 0 || digitB === void 0) return effect.Effect.fail(/* @__PURE__ */ new Error("invalid character in addCharSetKeys"));
832
- const sum = digitA + digitB + carry;
833
- carry = Math.floor(sum / base);
834
- const remainder = sum % base;
835
- const codeChar = charSet.byCode[remainder];
836
- if (codeChar === void 0) return effect.Effect.fail(/* @__PURE__ */ new Error("invalid character code in addCharSetKeys"));
837
- result.unshift(codeChar);
838
- }
839
- if (carry > 0) {
840
- const carryChar = charSet.byCode[carry];
841
- if (carryChar === void 0) return effect.Effect.fail(/* @__PURE__ */ new Error("invalid carry character code"));
842
- result.unshift(carryChar);
843
- }
844
- return effect.Effect.succeed(result.join(""));
845
- }
846
- function subtractCharSetKeys(a, b, charSet, stripLeadingZeros = true) {
847
- const base = charSet.length;
848
- const [paddedA, paddedB] = makeSameLength(a, b, "start", charSet.first);
849
- const result = [];
850
- let borrow = 0;
851
- for (let i = paddedA.length - 1; i >= 0; i--) {
852
- const charA = paddedA[i];
853
- const charB = paddedB[i];
854
- if (!charA || !charB) return effect.Effect.fail(/* @__PURE__ */ new Error("invalid character in subtractCharSetKeys"));
855
- let digitA = charSet.byChar[charA];
856
- const digitBValue = charSet.byChar[charB];
857
- if (digitA === void 0 || digitBValue === void 0) return effect.Effect.fail(/* @__PURE__ */ new Error("invalid character in subtractCharSetKeys"));
858
- const digitB = digitBValue + borrow;
859
- if (digitA < digitB) {
860
- borrow = 1;
861
- digitA += base;
862
- } else borrow = 0;
863
- const difference = digitA - digitB;
864
- const codeChar = charSet.byCode[difference];
865
- if (codeChar === void 0) return effect.Effect.fail(/* @__PURE__ */ new Error("invalid character code in subtractCharSetKeys"));
866
- result.unshift(codeChar);
867
- }
868
- if (borrow > 0) return effect.Effect.fail(/* @__PURE__ */ new Error("Subtraction result is negative. Ensure a is greater than or equal to b."));
869
- while (stripLeadingZeros && result.length > 1 && result[0] === charSet.first) result.shift();
870
- return effect.Effect.succeed(result.join(""));
871
- }
872
- function incrementKey(key, charSet) {
873
- const one = charSet.byCode[1];
874
- if (one === void 0) return effect.Effect.fail(/* @__PURE__ */ new Error("invalid charSet: missing code 1"));
875
- return addCharSetKeys(key, one, charSet);
876
- }
877
- function decrementKey(key, charSet) {
878
- const one = charSet.byCode[1];
879
- if (one === void 0) return effect.Effect.fail(/* @__PURE__ */ new Error("invalid charSet: missing code 1"));
880
- return subtractCharSetKeys(key, one, charSet, false);
881
- }
882
- function lexicalDistance(a, b, charSet) {
883
- const [lower, upper] = makeSameLength(a, b, "end", charSet.first).sort();
884
- return effect.Effect.gen(function* () {
885
- return decodeCharSetToNumber(yield* subtractCharSetKeys(upper, lower, charSet), charSet);
886
- });
887
- }
888
- function midPoint(lower, upper, charSet) {
889
- return effect.Effect.gen(function* () {
890
- let [paddedLower, paddedUpper] = makeSameLength(lower, upper, "end", charSet.first);
891
- let distance = yield* lexicalDistance(paddedLower, paddedUpper, charSet);
892
- if (distance === 1) {
893
- paddedLower = paddedLower.padEnd(paddedLower.length + 1, charSet.first);
894
- distance = charSet.length;
895
- }
896
- const mid = yield* encodeToCharSet(Math.floor(distance / 2), charSet);
897
- return yield* addCharSetKeys(paddedLower, mid, charSet);
898
- });
899
- }
900
- function startKey(charSet) {
901
- return charSet.firstPositive + charSet.byCode[0];
902
- }
903
- function validInteger(integer, charSet) {
904
- return effect.Effect.gen(function* () {
905
- return (yield* integerLength(integer, charSet)) === integer.length;
906
- });
907
- }
908
- function validateOrderKey(orderKey, charSet) {
909
- return effect.Effect.gen(function* () {
910
- yield* getIntegerPart(orderKey, charSet);
911
- });
912
- }
913
- function getIntegerPart(orderKey, charSet) {
914
- return effect.Effect.gen(function* () {
915
- const integerPartLength = yield* integerLength(integerHead(orderKey, charSet), charSet);
916
- if (integerPartLength > orderKey.length) return yield* effect.Effect.fail(/* @__PURE__ */ new Error("invalid order key length: " + orderKey));
917
- return orderKey.slice(0, integerPartLength);
918
- });
919
- }
920
- function validateInteger(integer, charSet) {
921
- return effect.Effect.gen(function* () {
922
- if (!(yield* validInteger(integer, charSet))) return yield* effect.Effect.fail(/* @__PURE__ */ new Error("invalid integer length: " + integer));
923
- });
924
- }
925
- function integerHead(integer, charSet) {
926
- let i = 0;
927
- if (integer[0] === charSet.mostPositive) while (integer[i] === charSet.mostPositive) i = i + 1;
928
- if (integer[0] === charSet.mostNegative) while (integer[i] === charSet.mostNegative) i = i + 1;
929
- return integer.slice(0, i + 1);
930
- }
931
- function splitInteger(integer, charSet) {
932
- return effect.Effect.gen(function* () {
933
- const head = integerHead(integer, {
934
- firstPositive: charSet.firstPositive,
935
- mostPositive: charSet.mostPositive,
936
- firstNegative: charSet.firstNegative,
937
- mostNegative: charSet.mostNegative
938
- });
939
- return [head, integer.slice(head.length)];
940
- });
941
- }
942
- function incrementIntegerHead(head, charSet) {
943
- return effect.Effect.gen(function* () {
944
- const inPositiveRange = head >= charSet.firstPositive;
945
- const nextHead = yield* incrementKey(head, charSet);
946
- const headIsLimitMax = head[head.length - 1] === charSet.mostPositive;
947
- const nextHeadIsLimitMax = nextHead[nextHead.length - 1] === charSet.mostPositive;
948
- if (inPositiveRange && nextHeadIsLimitMax) return nextHead + charSet.mostNegative;
949
- if (!inPositiveRange && headIsLimitMax) return head.slice(0, head.length - 1);
950
- return nextHead;
951
- });
952
- }
953
- function decrementIntegerHead(head, charSet) {
954
- return effect.Effect.gen(function* () {
955
- const inPositiveRange = head >= charSet.firstPositive;
956
- const headIsLimitMin = head[head.length - 1] === charSet.mostNegative;
957
- if (inPositiveRange && headIsLimitMin) return yield* decrementKey(head.slice(0, head.length - 1), charSet);
958
- if (!inPositiveRange && headIsLimitMin) return head + charSet.mostPositive;
959
- return yield* decrementKey(head, charSet);
960
- });
961
- }
962
- function startOnNewHead(head, limit, charSet) {
963
- return effect.Effect.gen(function* () {
964
- const newLength = yield* integerLength(head, charSet);
965
- const fillCharCode = limit === "upper" ? charSet.length - 1 : 0;
966
- const fillChar = charSet.byCode[fillCharCode];
967
- if (fillChar === void 0) return yield* effect.Effect.fail(/* @__PURE__ */ new Error("invalid fill character code"));
968
- return head + fillChar.repeat(newLength - head.length);
969
- });
970
- }
971
- function incrementInteger(integer, charSet) {
972
- return effect.Effect.gen(function* () {
973
- yield* validateInteger(integer, charSet);
974
- const [head, digs] = yield* splitInteger(integer, charSet);
975
- const maxChar = charSet.byCode[charSet.length - 1];
976
- if (maxChar === void 0) return yield* effect.Effect.fail(/* @__PURE__ */ new Error("invalid charSet: missing max character"));
977
- if (digs.split("").some((d) => d !== maxChar)) return head + (yield* incrementKey(digs, charSet));
978
- return yield* startOnNewHead(yield* incrementIntegerHead(head, charSet), "lower", charSet);
979
- });
980
- }
981
- function decrementInteger(integer, charSet) {
982
- return effect.Effect.gen(function* () {
983
- yield* validateInteger(integer, charSet);
984
- const [head, digs] = yield* splitInteger(integer, charSet);
985
- const minChar = charSet.byCode[0];
986
- if (minChar === void 0) return yield* effect.Effect.fail(/* @__PURE__ */ new Error("invalid charSet: missing min character"));
987
- if (digs.split("").some((d) => d !== minChar)) return head + (yield* decrementKey(digs, charSet));
988
- return yield* startOnNewHead(yield* decrementIntegerHead(head, charSet), "upper", charSet);
989
- });
990
- }
991
- /**
992
- * Generate a key between two other keys.
993
- * If either lower or upper is null, the key will be generated at the start or end of the list.
994
- */
995
- function generateKeyBetween(lower, upper, charSet = base62CharSet()) {
996
- return effect.Effect.gen(function* () {
997
- if (lower !== null) yield* validateOrderKey(lower, charSet);
998
- if (upper !== null) yield* validateOrderKey(upper, charSet);
999
- if (lower === null && upper === null) return startKey(charSet);
1000
- if (lower === null) return yield* decrementInteger(yield* getIntegerPart(upper, charSet), charSet);
1001
- if (upper === null) return yield* incrementInteger(yield* getIntegerPart(lower, charSet), charSet);
1002
- if (lower >= upper) return yield* effect.Effect.fail(/* @__PURE__ */ new Error(lower + " >= " + upper));
1003
- return yield* midPoint(lower, upper, charSet);
1004
- });
1005
- }
1006
-
1007
- //#endregion
1008
- //#region src/primitives/Array.ts
1009
- /**
1010
- * Sort array entries by their fractional position
1011
- */
1012
- const sortByPos = (entries) => [...entries].sort((a, b) => a.pos < b.pos ? -1 : a.pos > b.pos ? 1 : 0);
1013
- /**
1014
- * Generate a fractional position between two positions
1015
- */
1016
- const generatePosBetween = (left, right) => {
1017
- const charSet = base62CharSet();
1018
- return effect.Effect.runSync(generateKeyBetween(left, right, charSet));
1019
- };
1020
- var ArrayPrimitive = class ArrayPrimitive {
1021
- constructor(schema) {
1022
- require_Document._defineProperty(this, "_tag", "ArrayPrimitive");
1023
- require_Document._defineProperty(this, "_State", void 0);
1024
- require_Document._defineProperty(this, "_Proxy", void 0);
1025
- require_Document._defineProperty(this, "_TRequired", void 0);
1026
- require_Document._defineProperty(this, "_THasDefault", void 0);
1027
- require_Document._defineProperty(this, "TSetInput", void 0);
1028
- require_Document._defineProperty(this, "TUpdateInput", void 0);
1029
- require_Document._defineProperty(this, "_schema", void 0);
1030
- require_Document._defineProperty(this, "_opDefinitions", {
1031
- set: make({
1032
- kind: "array.set",
1033
- payload: effect.Schema.Unknown,
1034
- target: effect.Schema.Unknown,
1035
- apply: (payload) => payload
1036
- }),
1037
- insert: make({
1038
- kind: "array.insert",
1039
- payload: effect.Schema.Unknown,
1040
- target: effect.Schema.Unknown,
1041
- apply: (payload) => payload
1042
- }),
1043
- remove: make({
1044
- kind: "array.remove",
1045
- payload: effect.Schema.Unknown,
1046
- target: effect.Schema.Unknown,
1047
- apply: (payload) => payload
1048
- }),
1049
- move: make({
1050
- kind: "array.move",
1051
- payload: effect.Schema.Unknown,
1052
- target: effect.Schema.Unknown,
1053
- apply: (payload) => payload
1054
- })
1055
- });
1056
- require_Document._defineProperty(this, "_internal", {
1057
- createProxy: (env, operationPath) => {
1058
- const elementPrimitive = this._schema.element;
1059
- const getCurrentState = () => {
1060
- const state = env.getState(operationPath);
1061
- if (!state || !globalThis.Array.isArray(state)) return [];
1062
- return sortByPos(state);
1063
- };
1064
- const applyElementDefaults = (value) => {
1065
- return applyDefaults(elementPrimitive, value);
1066
- };
1067
- return {
1068
- get: () => {
1069
- return getCurrentState();
1070
- },
1071
- set: (values) => {
1072
- const entries = [];
1073
- let prevPos = null;
1074
- for (const value of values) {
1075
- const id = env.generateId();
1076
- const pos = generatePosBetween(prevPos, null);
1077
- const mergedValue = applyElementDefaults(value);
1078
- entries.push({
1079
- id,
1080
- pos,
1081
- value: mergedValue
1082
- });
1083
- prevPos = pos;
1084
- }
1085
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.set, entries));
1086
- },
1087
- push: (value) => {
1088
- const sorted = getCurrentState();
1089
- const lastPos = sorted.length > 0 ? sorted[sorted.length - 1].pos : null;
1090
- const id = env.generateId();
1091
- const pos = generatePosBetween(lastPos, null);
1092
- const mergedValue = applyElementDefaults(value);
1093
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.insert, {
1094
- id,
1095
- pos,
1096
- value: mergedValue
1097
- }));
1098
- },
1099
- insertAt: (index, value) => {
1100
- const sorted = getCurrentState();
1101
- const leftPos = index > 0 && sorted[index - 1] ? sorted[index - 1].pos : null;
1102
- const rightPos = index < sorted.length && sorted[index] ? sorted[index].pos : null;
1103
- const id = env.generateId();
1104
- const pos = generatePosBetween(leftPos, rightPos);
1105
- const mergedValue = applyElementDefaults(value);
1106
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.insert, {
1107
- id,
1108
- pos,
1109
- value: mergedValue
1110
- }));
1111
- },
1112
- remove: (id) => {
1113
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.remove, { id }));
1114
- },
1115
- move: (id, toIndex) => {
1116
- const without = getCurrentState().filter((e) => e.id !== id);
1117
- const clampedIndex = Math.max(0, Math.min(toIndex, without.length));
1118
- const pos = generatePosBetween(clampedIndex > 0 && without[clampedIndex - 1] ? without[clampedIndex - 1].pos : null, clampedIndex < without.length && without[clampedIndex] ? without[clampedIndex].pos : null);
1119
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.move, {
1120
- id,
1121
- pos
1122
- }));
1123
- },
1124
- at: (id) => {
1125
- const elementPath = operationPath.append(id);
1126
- return elementPrimitive._internal.createProxy(env, elementPath);
1127
- },
1128
- find: (predicate) => {
1129
- const found = getCurrentState().find((entry) => predicate(entry.value, entry.id));
1130
- if (!found) return void 0;
1131
- const elementPath = operationPath.append(found.id);
1132
- return elementPrimitive._internal.createProxy(env, elementPath);
1133
- },
1134
- toSnapshot: () => {
1135
- return getCurrentState().map((entry) => {
1136
- const elementPath = operationPath.append(entry.id);
1137
- const elementProxy = elementPrimitive._internal.createProxy(env, elementPath);
1138
- return {
1139
- id: entry.id,
1140
- value: elementProxy.toSnapshot()
1141
- };
1142
- });
1143
- }
1144
- };
1145
- },
1146
- applyOperation: (state, operation) => {
1147
- const path = operation.path;
1148
- const tokens = path.toTokens().filter((t) => t !== "");
1149
- const currentState = state !== null && state !== void 0 ? state : [];
1150
- let newState;
1151
- if (tokens.length === 0) switch (operation.kind) {
1152
- case "array.set": {
1153
- const payload = operation.payload;
1154
- if (!globalThis.Array.isArray(payload)) throw new ValidationError(`ArrayPrimitive.set requires an array payload`);
1155
- newState = payload;
1156
- break;
1157
- }
1158
- case "array.insert": {
1159
- const { id, pos, value } = operation.payload;
1160
- newState = [...currentState, {
1161
- id,
1162
- pos,
1163
- value
1164
- }];
1165
- break;
1166
- }
1167
- case "array.remove": {
1168
- const { id } = operation.payload;
1169
- newState = currentState.filter((entry) => entry.id !== id);
1170
- break;
1171
- }
1172
- case "array.move": {
1173
- const { id, pos } = operation.payload;
1174
- newState = currentState.map((entry) => entry.id === id ? require_Presence._objectSpread2(require_Presence._objectSpread2({}, entry), {}, { pos }) : entry);
1175
- break;
1176
- }
1177
- default: throw new ValidationError(`ArrayPrimitive cannot apply operation of kind: ${operation.kind}`);
1178
- }
1179
- else {
1180
- const elementId = tokens[0];
1181
- const entryIndex = currentState.findIndex((entry) => entry.id === elementId);
1182
- if (entryIndex === -1) throw new ValidationError(`Array element not found with ID: ${elementId}`);
1183
- const elementPrimitive = this._schema.element;
1184
- const remainingPath = path.shift();
1185
- const elementOperation = require_Presence._objectSpread2(require_Presence._objectSpread2({}, operation), {}, { path: remainingPath });
1186
- const currentEntry = currentState[entryIndex];
1187
- const newValue = elementPrimitive._internal.applyOperation(currentEntry.value, elementOperation);
1188
- const mutableState = [...currentState];
1189
- mutableState[entryIndex] = require_Presence._objectSpread2(require_Presence._objectSpread2({}, currentEntry), {}, { value: newValue });
1190
- newState = mutableState;
1191
- }
1192
- runValidators(newState, this._schema.validators);
1193
- return newState;
1194
- },
1195
- getInitialState: () => {
1196
- return this._schema.defaultValue;
1197
- },
1198
- transformOperation: (clientOp, serverOp) => {
1199
- const clientPath = clientOp.path;
1200
- const serverPath = serverOp.path;
1201
- if (!require_Document.pathsOverlap(clientPath, serverPath)) return {
1202
- type: "transformed",
1203
- operation: clientOp
1204
- };
1205
- if (serverOp.kind === "array.remove") {
1206
- const removedId = serverOp.payload.id;
1207
- const clientTokens$1 = clientPath.toTokens().filter((t) => t !== "");
1208
- const serverTokens$1 = serverPath.toTokens().filter((t) => t !== "");
1209
- if (clientTokens$1.length > serverTokens$1.length) {
1210
- if (clientTokens$1[serverTokens$1.length] === removedId) return { type: "noop" };
1211
- }
1212
- }
1213
- if (serverOp.kind === "array.insert" && clientOp.kind === "array.insert") return {
1214
- type: "transformed",
1215
- operation: clientOp
1216
- };
1217
- if (serverOp.kind === "array.move" && clientOp.kind === "array.move") {
1218
- if (serverOp.payload.id === clientOp.payload.id) return {
1219
- type: "transformed",
1220
- operation: clientOp
1221
- };
1222
- return {
1223
- type: "transformed",
1224
- operation: clientOp
1225
- };
1226
- }
1227
- if (require_Document.pathsEqual(clientPath, serverPath)) return {
1228
- type: "transformed",
1229
- operation: clientOp
1230
- };
1231
- if (serverOp.kind === "array.set" && require_Document.isPrefix(serverPath, clientPath)) return {
1232
- type: "transformed",
1233
- operation: clientOp
1234
- };
1235
- const clientTokens = clientPath.toTokens().filter((t) => t !== "");
1236
- const serverTokens = serverPath.toTokens().filter((t) => t !== "");
1237
- if (clientTokens.length > 0 && serverTokens.length > 0) {
1238
- if (clientTokens[0] !== serverTokens[0]) return {
1239
- type: "transformed",
1240
- operation: clientOp
1241
- };
1242
- const elementPrimitive = this._schema.element;
1243
- const clientOpForElement = require_Presence._objectSpread2(require_Presence._objectSpread2({}, clientOp), {}, { path: clientOp.path.shift() });
1244
- const serverOpForElement = require_Presence._objectSpread2(require_Presence._objectSpread2({}, serverOp), {}, { path: serverOp.path.shift() });
1245
- const result = elementPrimitive._internal.transformOperation(clientOpForElement, serverOpForElement);
1246
- if (result.type === "transformed") return {
1247
- type: "transformed",
1248
- operation: require_Presence._objectSpread2(require_Presence._objectSpread2({}, result.operation), {}, { path: clientOp.path })
1249
- };
1250
- return result;
1251
- }
1252
- return {
1253
- type: "transformed",
1254
- operation: clientOp
1255
- };
1256
- }
1257
- });
1258
- this._schema = schema;
1259
- }
1260
- /** Mark this array as required */
1261
- required() {
1262
- return new ArrayPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { required: true }));
1263
- }
1264
- /** Set a default value for this array */
1265
- default(defaultValue) {
1266
- return new ArrayPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { defaultValue }));
1267
- }
1268
- /** Get the element primitive */
1269
- get element() {
1270
- return this._schema.element;
1271
- }
1272
- /** Add a custom validation rule */
1273
- refine(fn, message) {
1274
- return new ArrayPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { validators: [...this._schema.validators, {
1275
- validate: fn,
1276
- message
1277
- }] }));
1278
- }
1279
- /** Minimum array length */
1280
- minLength(length) {
1281
- return this.refine((v) => v.length >= length, `Array must have at least ${length} elements`);
1282
- }
1283
- /** Maximum array length */
1284
- maxLength(length) {
1285
- return this.refine((v) => v.length <= length, `Array must have at most ${length} elements`);
1286
- }
1287
- };
1288
- /** Creates a new ArrayPrimitive with the given element type */
1289
- const Array$1 = (element) => new ArrayPrimitive({
1290
- required: false,
1291
- defaultValue: void 0,
1292
- element,
1293
- validators: []
1294
- });
1295
-
1296
- //#endregion
1297
- //#region src/primitives/Lazy.ts
1298
- var LazyPrimitive = class {
1299
- constructor(thunk) {
1300
- require_Document._defineProperty(this, "_tag", "LazyPrimitive");
1301
- require_Document._defineProperty(this, "_State", void 0);
1302
- require_Document._defineProperty(this, "_Proxy", void 0);
1303
- require_Document._defineProperty(this, "_TRequired", void 0);
1304
- require_Document._defineProperty(this, "_THasDefault", void 0);
1305
- require_Document._defineProperty(this, "TSetInput", void 0);
1306
- require_Document._defineProperty(this, "TUpdateInput", void 0);
1307
- require_Document._defineProperty(this, "_thunk", void 0);
1308
- require_Document._defineProperty(this, "_resolved", void 0);
1309
- require_Document._defineProperty(this, "_internal", {
1310
- createProxy: (env, operationPath) => {
1311
- return this._resolve()._internal.createProxy(env, operationPath);
1312
- },
1313
- applyOperation: (state, operation) => {
1314
- return this._resolve()._internal.applyOperation(state, operation);
1315
- },
1316
- getInitialState: () => {
1317
- return this._resolve()._internal.getInitialState();
1318
- },
1319
- transformOperation: (clientOp, serverOp) => {
1320
- return this._resolve()._internal.transformOperation(clientOp, serverOp);
1321
- }
1322
- });
1323
- this._thunk = thunk;
1324
- }
1325
- /** Resolve and cache the lazy primitive */
1326
- _resolve() {
1327
- if (this._resolved === void 0) this._resolved = this._thunk();
1328
- return this._resolved;
1329
- }
1330
- /** Mark this lazy primitive as required (delegates to resolved) */
1331
- required() {
1332
- return this;
1333
- }
1334
- };
1335
- /** Creates a new LazyPrimitive with the given thunk */
1336
- const Lazy = (thunk) => new LazyPrimitive(thunk);
1337
-
1338
- //#endregion
1339
- //#region src/primitives/Union.ts
1340
- var UnionPrimitive = class UnionPrimitive {
1341
- constructor(schema) {
1342
- require_Document._defineProperty(this, "_tag", "UnionPrimitive");
1343
- require_Document._defineProperty(this, "_State", void 0);
1344
- require_Document._defineProperty(this, "_Proxy", void 0);
1345
- require_Document._defineProperty(this, "_TRequired", void 0);
1346
- require_Document._defineProperty(this, "_THasDefault", void 0);
1347
- require_Document._defineProperty(this, "TSetInput", void 0);
1348
- require_Document._defineProperty(this, "TUpdateInput", void 0);
1349
- require_Document._defineProperty(this, "_schema", void 0);
1350
- require_Document._defineProperty(this, "_opDefinitions", { set: make({
1351
- kind: "union.set",
1352
- payload: effect.Schema.Unknown,
1353
- target: effect.Schema.Unknown,
1354
- apply: (payload) => payload
1355
- }) });
1356
- require_Document._defineProperty(this, "_internal", {
1357
- createProxy: (env, operationPath) => {
1358
- const variants = this._schema.variants;
1359
- const defaultValue = this._schema.defaultValue;
1360
- return {
1361
- get: () => {
1362
- const state = env.getState(operationPath);
1363
- return state !== null && state !== void 0 ? state : defaultValue;
1364
- },
1365
- set: (value) => {
1366
- const merged = this._applyVariantDefaults(value);
1367
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.set, merged));
1368
- },
1369
- as: (variant) => {
1370
- const variantPrimitive = variants[variant];
1371
- if (!variantPrimitive) throw new ValidationError(`Unknown variant: ${globalThis.String(variant)}`);
1372
- return variantPrimitive._internal.createProxy(env, operationPath);
1373
- },
1374
- match: (handlers) => {
1375
- const state = env.getState(operationPath);
1376
- if (!state) return void 0;
1377
- const variantKey = this._findVariantKey(state);
1378
- if (!variantKey) return void 0;
1379
- const handler = handlers[variantKey];
1380
- if (!handler) return void 0;
1381
- return handler(variants[variantKey]._internal.createProxy(env, operationPath));
1382
- },
1383
- toSnapshot: () => {
1384
- const state = env.getState(operationPath);
1385
- const effectiveState = state !== null && state !== void 0 ? state : defaultValue;
1386
- if (!effectiveState) return;
1387
- const variantKey = this._findVariantKey(effectiveState);
1388
- if (!variantKey) return;
1389
- return variants[variantKey]._internal.createProxy(env, operationPath).toSnapshot();
1390
- }
1391
- };
1392
- },
1393
- applyOperation: (state, operation) => {
1394
- if (operation.path.toTokens().filter((t) => t !== "").length === 0) {
1395
- if (operation.kind !== "union.set") throw new ValidationError(`UnionPrimitive root cannot apply operation of kind: ${operation.kind}`);
1396
- const payload = operation.payload;
1397
- if (typeof payload !== "object" || payload === null) throw new ValidationError(`UnionPrimitive.set requires an object payload`);
1398
- if (payload[this._schema.discriminator] === void 0) throw new ValidationError(`UnionPrimitive.set requires a "${this._schema.discriminator}" discriminator field`);
1399
- return payload;
1400
- }
1401
- if (state === void 0) throw new ValidationError(`Cannot apply nested operation to undefined union state`);
1402
- const variantKey = this._findVariantKey(state);
1403
- if (variantKey === void 0) throw new ValidationError(`Cannot determine active variant from state`);
1404
- return this._schema.variants[variantKey]._internal.applyOperation(state, operation);
1405
- },
1406
- getInitialState: () => {
1407
- return this._schema.defaultValue;
1408
- },
1409
- transformOperation: (clientOp, serverOp) => {
1410
- const clientPath = clientOp.path;
1411
- const serverPath = serverOp.path;
1412
- if (!require_Document.pathsOverlap(clientPath, serverPath)) return {
1413
- type: "transformed",
1414
- operation: clientOp
1415
- };
1416
- const clientTokens = clientPath.toTokens().filter((t) => t !== "");
1417
- const serverTokens = serverPath.toTokens().filter((t) => t !== "");
1418
- if (clientTokens.length === 0 && serverTokens.length === 0) return {
1419
- type: "transformed",
1420
- operation: clientOp
1421
- };
1422
- if (serverTokens.length === 0 && serverOp.kind === "union.set") return {
1423
- type: "transformed",
1424
- operation: clientOp
1425
- };
1426
- if (clientTokens.length === 0 && clientOp.kind === "union.set") return {
1427
- type: "transformed",
1428
- operation: clientOp
1429
- };
1430
- if (clientTokens.length > 0 && serverTokens.length > 0) {
1431
- if (clientTokens[0] !== serverTokens[0]) return {
1432
- type: "transformed",
1433
- operation: clientOp
1434
- };
1435
- const variantKeys = Object.keys(this._schema.variants);
1436
- if (variantKeys.length === 0) return {
1437
- type: "transformed",
1438
- operation: clientOp
1439
- };
1440
- return this._schema.variants[variantKeys[0]]._internal.transformOperation(clientOp, serverOp);
1441
- }
1442
- return {
1443
- type: "transformed",
1444
- operation: clientOp
1445
- };
1446
- }
1447
- });
1448
- this._schema = schema;
1449
- }
1450
- /** Mark this union as required */
1451
- required() {
1452
- return new UnionPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { required: true }));
1453
- }
1454
- /** Set a default value for this union */
1455
- default(defaultValue) {
1456
- const merged = this._applyVariantDefaults(defaultValue);
1457
- return new UnionPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { defaultValue: merged }));
1458
- }
1459
- /** Get the discriminator field name */
1460
- get discriminator() {
1461
- return this._schema.discriminator;
1462
- }
1463
- /** Get the variants */
1464
- get variants() {
1465
- return this._schema.variants;
1466
- }
1467
- /** Find the variant key from a state value */
1468
- _findVariantKey(state) {
1469
- if (typeof state !== "object" || state === null) return;
1470
- const discriminatorValue = state[this._schema.discriminator];
1471
- for (const key in this._schema.variants) {
1472
- const discriminatorField = this._schema.variants[key].fields[this._schema.discriminator];
1473
- if (discriminatorField && discriminatorField._tag === "LiteralPrimitive") {
1474
- if (discriminatorField.literal === discriminatorValue) return key;
1475
- }
1476
- }
1477
- }
1478
- /** Apply defaults to a variant value based on the discriminator */
1479
- _applyVariantDefaults(value) {
1480
- const variantKey = this._findVariantKey(value);
1481
- if (!variantKey) return value;
1482
- const variantPrimitive = this._schema.variants[variantKey];
1483
- return applyDefaults(variantPrimitive, value);
1484
- }
1485
- };
1486
- function Union(options) {
1487
- var _options$discriminato;
1488
- return new UnionPrimitive({
1489
- required: false,
1490
- defaultValue: void 0,
1491
- discriminator: (_options$discriminato = options.discriminator) !== null && _options$discriminato !== void 0 ? _options$discriminato : "type",
1492
- variants: options.variants
1493
- });
1494
- }
1495
-
1496
- //#endregion
1497
- //#region src/primitives/Either.ts
1498
- var EitherPrimitive = class EitherPrimitive {
1499
- constructor(schema) {
1500
- require_Document._defineProperty(this, "_tag", "EitherPrimitive");
1501
- require_Document._defineProperty(this, "_State", void 0);
1502
- require_Document._defineProperty(this, "_Proxy", void 0);
1503
- require_Document._defineProperty(this, "_TRequired", void 0);
1504
- require_Document._defineProperty(this, "_THasDefault", void 0);
1505
- require_Document._defineProperty(this, "TUpdateInput", void 0);
1506
- require_Document._defineProperty(this, "TSetInput", void 0);
1507
- require_Document._defineProperty(this, "_schema", void 0);
1508
- require_Document._defineProperty(this, "_opDefinitions", { set: make({
1509
- kind: "either.set",
1510
- payload: effect.Schema.Unknown,
1511
- target: effect.Schema.Unknown,
1512
- apply: (payload) => payload
1513
- }) });
1514
- require_Document._defineProperty(this, "_internal", {
1515
- createProxy: (env, operationPath) => {
1516
- const defaultValue = this._schema.defaultValue;
1517
- return {
1518
- get: () => {
1519
- const state = env.getState(operationPath);
1520
- return state !== null && state !== void 0 ? state : defaultValue;
1521
- },
1522
- set: (value) => {
1523
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.set, value));
1524
- },
1525
- update: (value) => {
1526
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.set, value));
1527
- },
1528
- match: (handlers) => {
1529
- const currentState = env.getState(operationPath);
1530
- const effectiveState = currentState !== null && currentState !== void 0 ? currentState : defaultValue;
1531
- if (effectiveState === void 0) return void 0;
1532
- const valueType = this._getValueType(effectiveState);
1533
- if (!valueType) return void 0;
1534
- switch (valueType) {
1535
- case "string":
1536
- var _handlers$string;
1537
- return (_handlers$string = handlers.string) === null || _handlers$string === void 0 ? void 0 : _handlers$string.call(handlers, effectiveState);
1538
- case "number":
1539
- var _handlers$number;
1540
- return (_handlers$number = handlers.number) === null || _handlers$number === void 0 ? void 0 : _handlers$number.call(handlers, effectiveState);
1541
- case "boolean":
1542
- var _handlers$boolean;
1543
- return (_handlers$boolean = handlers.boolean) === null || _handlers$boolean === void 0 ? void 0 : _handlers$boolean.call(handlers, effectiveState);
1544
- case "literal":
1545
- var _handlers$literal;
1546
- return (_handlers$literal = handlers.literal) === null || _handlers$literal === void 0 ? void 0 : _handlers$literal.call(handlers, effectiveState);
1547
- default: return;
1548
- }
1549
- },
1550
- toSnapshot: () => {
1551
- const state = env.getState(operationPath);
1552
- return state !== null && state !== void 0 ? state : defaultValue;
1553
- }
1554
- };
1555
- },
1556
- applyOperation: (_state, operation) => {
1557
- if (operation.kind !== "either.set") throw new ValidationError(`EitherPrimitive cannot apply operation of kind: ${operation.kind}`);
1558
- const payload = operation.payload;
1559
- this._validateAndApplyToVariant(payload, operation.path);
1560
- return payload;
1561
- },
1562
- getInitialState: () => {
1563
- return this._schema.defaultValue;
1564
- },
1565
- transformOperation: (clientOp, serverOp) => {
1566
- if (!require_Document.pathsOverlap(clientOp.path, serverOp.path)) return {
1567
- type: "transformed",
1568
- operation: clientOp
1569
- };
1570
- return {
1571
- type: "transformed",
1572
- operation: clientOp
1573
- };
1574
- }
1575
- });
1576
- this._schema = schema;
1577
- }
1578
- /** Mark this either as required */
1579
- required() {
1580
- return new EitherPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { required: true }));
1581
- }
1582
- /** Set a default value for this either */
1583
- default(defaultValue) {
1584
- return new EitherPrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { defaultValue }));
1585
- }
1586
- /** Get the variants */
1587
- get variants() {
1588
- return this._schema.variants;
1589
- }
1590
- /**
1591
- * Determine the type category of a value based on the variants
1592
- */
1593
- _getValueType(value) {
1594
- const valueType = typeof value;
1595
- for (const variant of this._schema.variants) if (variant._tag === "LiteralPrimitive") {
1596
- if (value === variant.literal) return "literal";
1597
- }
1598
- if (valueType === "string") {
1599
- for (const variant of this._schema.variants) if (variant._tag === "StringPrimitive") return "string";
1600
- }
1601
- if (valueType === "number") {
1602
- for (const variant of this._schema.variants) if (variant._tag === "NumberPrimitive") return "number";
1603
- }
1604
- if (valueType === "boolean") {
1605
- for (const variant of this._schema.variants) if (variant._tag === "BooleanPrimitive") return "boolean";
1606
- }
1607
- }
1608
- /**
1609
- * Find the matching variant for a value.
1610
- * For literals, matches exact value. For other types, matches by typeof.
1611
- */
1612
- _findMatchingVariant(value) {
1613
- const valueType = typeof value;
1614
- for (const variant of this._schema.variants) if (variant._tag === "LiteralPrimitive") {
1615
- if (value === variant.literal) return variant;
1616
- }
1617
- if (valueType === "string") {
1618
- for (const variant of this._schema.variants) if (variant._tag === "StringPrimitive") return variant;
1619
- }
1620
- if (valueType === "number") {
1621
- for (const variant of this._schema.variants) if (variant._tag === "NumberPrimitive") return variant;
1622
- }
1623
- if (valueType === "boolean") {
1624
- for (const variant of this._schema.variants) if (variant._tag === "BooleanPrimitive") return variant;
1625
- }
1626
- }
1627
- /**
1628
- * Get the operation kind for a variant
1629
- */
1630
- _getVariantOperationKind(variant) {
1631
- switch (variant._tag) {
1632
- case "StringPrimitive": return "string.set";
1633
- case "NumberPrimitive": return "number.set";
1634
- case "BooleanPrimitive": return "boolean.set";
1635
- case "LiteralPrimitive": return "literal.set";
1636
- default: return "unknown.set";
1637
- }
1638
- }
1639
- /**
1640
- * Validate a value against the matching variant, including running its validators.
1641
- * Throws ValidationError if the value doesn't match any variant or fails validation.
1642
- */
1643
- _validateAndApplyToVariant(value, path) {
1644
- const matchingVariant = this._findMatchingVariant(value);
1645
- if (!matchingVariant) throw new ValidationError(`EitherPrimitive.set requires a value matching one of: ${this._schema.variants.map((v) => v._tag).join(", ")}, got: ${typeof value}`);
1646
- const syntheticOp = {
1647
- kind: this._getVariantOperationKind(matchingVariant),
1648
- path,
1649
- payload: value
1650
- };
1651
- matchingVariant._internal.applyOperation(void 0, syntheticOp);
1652
- }
1653
- };
1654
- /**
1655
- * Creates a new EitherPrimitive with the given scalar variant types.
1656
- * Validators defined on the variants are applied when validating values.
1657
- *
1658
- * @example
1659
- * ```typescript
1660
- * // String or number
1661
- * const value = Either(String(), Number());
1662
- *
1663
- * // String, number, or boolean
1664
- * const status = Either(String(), Number(), Boolean()).default("pending");
1665
- *
1666
- * // With literal types
1667
- * const mode = Either(Literal("auto"), Literal("manual"), Number());
1668
- *
1669
- * // With validators - validates string length and number range
1670
- * const constrained = Either(
1671
- * String().min(2).max(50),
1672
- * Number().max(255)
1673
- * );
1674
- * ```
1675
- */
1676
- function Either(...variants) {
1677
- if (variants.length === 0) throw new ValidationError("Either requires at least one variant");
1678
- return new EitherPrimitive({
1679
- required: false,
1680
- defaultValue: void 0,
1681
- variants
1682
- });
1683
- }
1684
-
1685
- //#endregion
1686
- //#region src/primitives/TreeNode.ts
1687
- /**
1688
- * Symbol used to identify the Self placeholder
1689
- */
1690
- const TreeNodeSelfSymbol = Symbol.for("TreeNode.Self");
1691
- /**
1692
- * Special placeholder for self-referential tree nodes.
1693
- * Use this in the children array when a node type can contain itself.
1694
- *
1695
- * @example
1696
- * ```typescript
1697
- * const FolderNode = TreeNode("folder", {
1698
- * data: Struct({ name: String() }),
1699
- * children: [TreeNodeSelf], // Folder can contain other folders
1700
- * });
1701
- * ```
1702
- */
1703
- const TreeNodeSelf = {
1704
- _tag: "TreeNodeSelf",
1705
- _symbol: TreeNodeSelfSymbol
1706
- };
1707
- /**
1708
- * Check if a value is the Self placeholder
1709
- */
1710
- const isSelf = (value) => {
1711
- return typeof value === "object" && value !== null && "_symbol" in value && value._symbol === TreeNodeSelfSymbol;
1712
- };
1713
- /**
1714
- * TreeNodePrimitive - defines a node type with its data schema and allowed children
1715
- */
1716
- var TreeNodePrimitive = class {
1717
- constructor(type, config) {
1718
- require_Document._defineProperty(this, "_tag", "TreeNodePrimitive");
1719
- require_Document._defineProperty(this, "_Type", void 0);
1720
- require_Document._defineProperty(this, "_Data", void 0);
1721
- require_Document._defineProperty(this, "_Children", void 0);
1722
- require_Document._defineProperty(this, "TSetInput", void 0);
1723
- require_Document._defineProperty(this, "TUpdateInput", void 0);
1724
- require_Document._defineProperty(this, "_type", void 0);
1725
- require_Document._defineProperty(this, "_data", void 0);
1726
- require_Document._defineProperty(this, "_children", void 0);
1727
- require_Document._defineProperty(this, "_resolvedChildren", void 0);
1728
- this._type = type;
1729
- this._data = config.data;
1730
- this._children = config.children;
1731
- }
1732
- /** Get the node type identifier */
1733
- get type() {
1734
- return this._type;
1735
- }
1736
- /** Get the data primitive */
1737
- get data() {
1738
- return this._data;
1739
- }
1740
- /** Get resolved children (resolves lazy thunk if needed, replaces Self with this node) */
1741
- get children() {
1742
- if (this._resolvedChildren === void 0) this._resolvedChildren = (typeof this._children === "function" ? this._children() : this._children).map((child) => isSelf(child) ? this : child);
1743
- return this._resolvedChildren;
1744
- }
1745
- /** Check if a child type is allowed */
1746
- isChildAllowed(childType) {
1747
- return this.children.some((child) => child.type === childType);
1748
- }
1749
- };
1750
- /** Creates a new TreeNodePrimitive with the given type and config */
1751
- const TreeNode = (type, config) => new TreeNodePrimitive(type, config);
1752
-
1753
- //#endregion
1754
- //#region src/primitives/Tree.ts
1755
- /**
1756
- * Helper to get children sorted by position
1757
- */
1758
- const getOrderedChildren = (nodes, parentId) => {
1759
- return [...nodes].filter((n) => n.parentId === parentId).sort((a, b) => a.pos < b.pos ? -1 : a.pos > b.pos ? 1 : 0);
1760
- };
1761
- /**
1762
- * Get all descendant IDs of a node (recursive)
1763
- */
1764
- const getDescendantIds = (nodes, nodeId) => {
1765
- const children = nodes.filter((n) => n.parentId === nodeId);
1766
- const descendantIds = [];
1767
- for (const child of children) {
1768
- descendantIds.push(child.id);
1769
- descendantIds.push(...getDescendantIds(nodes, child.id));
1770
- }
1771
- return descendantIds;
1772
- };
1773
- /**
1774
- * Check if moving a node to a new parent would create a cycle
1775
- */
1776
- const wouldCreateCycle = (nodes, nodeId, newParentId) => {
1777
- if (newParentId === null) return false;
1778
- if (newParentId === nodeId) return true;
1779
- return getDescendantIds(nodes, nodeId).includes(newParentId);
1780
- };
1781
- /**
1782
- * Generate a fractional position between two positions
1783
- */
1784
- const generateTreePosBetween = (left, right) => {
1785
- const charSet = base62CharSet();
1786
- return effect.Effect.runSync(generateKeyBetween(left, right, charSet));
1787
- };
1788
- var TreePrimitive = class TreePrimitive {
1789
- constructor(schema) {
1790
- require_Document._defineProperty(this, "_tag", "TreePrimitive");
1791
- require_Document._defineProperty(this, "_State", void 0);
1792
- require_Document._defineProperty(this, "_Proxy", void 0);
1793
- require_Document._defineProperty(this, "_TRequired", void 0);
1794
- require_Document._defineProperty(this, "_THasDefault", void 0);
1795
- require_Document._defineProperty(this, "TSetInput", void 0);
1796
- require_Document._defineProperty(this, "TUpdateInput", void 0);
1797
- require_Document._defineProperty(this, "_schema", void 0);
1798
- require_Document._defineProperty(this, "_nodeTypeRegistry", void 0);
1799
- require_Document._defineProperty(this, "_opDefinitions", {
1800
- set: make({
1801
- kind: "tree.set",
1802
- payload: effect.Schema.Unknown,
1803
- target: effect.Schema.Unknown,
1804
- apply: (payload) => payload
1805
- }),
1806
- insert: make({
1807
- kind: "tree.insert",
1808
- payload: effect.Schema.Unknown,
1809
- target: effect.Schema.Unknown,
1810
- apply: (payload) => payload
1811
- }),
1812
- remove: make({
1813
- kind: "tree.remove",
1814
- payload: effect.Schema.Unknown,
1815
- target: effect.Schema.Unknown,
1816
- apply: (payload) => payload
1817
- }),
1818
- move: make({
1819
- kind: "tree.move",
1820
- payload: effect.Schema.Unknown,
1821
- target: effect.Schema.Unknown,
1822
- apply: (payload) => payload
1823
- })
1824
- });
1825
- require_Document._defineProperty(this, "_internal", {
1826
- createProxy: (env, operationPath) => {
1827
- const getCurrentState = () => {
1828
- const state = env.getState(operationPath);
1829
- return state !== null && state !== void 0 ? state : [];
1830
- };
1831
- const getParentType = (parentId) => {
1832
- var _parent$type;
1833
- if (parentId === null) return null;
1834
- const parent = getCurrentState().find((n) => n.id === parentId);
1835
- return (_parent$type = parent === null || parent === void 0 ? void 0 : parent.type) !== null && _parent$type !== void 0 ? _parent$type : null;
1836
- };
1837
- const createNodeProxy = (nodeState) => {
1838
- return {
1839
- id: nodeState.id,
1840
- type: nodeState.type,
1841
- is: (nodeType) => {
1842
- return nodeState.type === nodeType.type;
1843
- },
1844
- as: (nodeType) => {
1845
- if (nodeState.type !== nodeType.type) throw new ValidationError(`Node is of type "${nodeState.type}", not "${nodeType.type}"`);
1846
- const nodePath = operationPath.append(nodeState.id);
1847
- const dataProxy = nodeType.data._internal.createProxy(env, nodePath);
1848
- return {
1849
- id: nodeState.id,
1850
- type: nodeType.type,
1851
- data: dataProxy,
1852
- get: () => nodeState,
1853
- update: (value) => {
1854
- dataProxy.update(value);
1855
- }
1856
- };
1857
- },
1858
- get: () => nodeState
1859
- };
1860
- };
1861
- const buildSnapshot = (nodeId, nodes) => {
1862
- const node = nodes.find((n) => n.id === nodeId);
1863
- if (!node) return void 0;
1864
- const childNodes = getOrderedChildren(nodes, nodeId);
1865
- const children = [];
1866
- for (const child of childNodes) {
1867
- const childSnapshot = buildSnapshot(child.id, nodes);
1868
- if (childSnapshot) children.push(childSnapshot);
1869
- }
1870
- return require_Presence._objectSpread2(require_Presence._objectSpread2({
1871
- id: node.id,
1872
- type: node.type
1873
- }, node.data), {}, { children });
1874
- };
1875
- return {
1876
- get: () => {
1877
- return getCurrentState();
1878
- },
1879
- set: (nodes) => {
1880
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.set, nodes));
1881
- },
1882
- root: () => {
1883
- return getCurrentState().find((n) => n.parentId === null);
1884
- },
1885
- children: (parentId) => {
1886
- return getOrderedChildren(getCurrentState(), parentId);
1887
- },
1888
- node: (id) => {
1889
- const nodeState = getCurrentState().find((n) => n.id === id);
1890
- if (!nodeState) return void 0;
1891
- return createNodeProxy(nodeState);
1892
- },
1893
- insertFirst: (parentId, nodeType, data) => {
1894
- const state = getCurrentState();
1895
- const siblings = getOrderedChildren(state, parentId);
1896
- const pos = generateTreePosBetween(null, siblings.length > 0 ? siblings[0].pos : null);
1897
- const id = env.generateId();
1898
- if (parentId !== null && !state.find((n) => n.id === parentId)) throw new ValidationError(`Parent node not found: ${parentId}`);
1899
- const parentType = getParentType(parentId);
1900
- this._validateChildType(parentType, nodeType.type);
1901
- if (parentId === null && state.some((n) => n.parentId === null)) throw new ValidationError("Tree already has a root node");
1902
- const mergedData = applyDefaults(nodeType.data, data);
1903
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.insert, {
1904
- id,
1905
- type: nodeType.type,
1906
- parentId,
1907
- pos,
1908
- data: mergedData
1909
- }));
1910
- return id;
1911
- },
1912
- insertLast: (parentId, nodeType, data) => {
1913
- const state = getCurrentState();
1914
- const siblings = getOrderedChildren(state, parentId);
1915
- const pos = generateTreePosBetween(siblings.length > 0 ? siblings[siblings.length - 1].pos : null, null);
1916
- const id = env.generateId();
1917
- if (parentId !== null && !state.find((n) => n.id === parentId)) throw new ValidationError(`Parent node not found: ${parentId}`);
1918
- const parentType = getParentType(parentId);
1919
- this._validateChildType(parentType, nodeType.type);
1920
- if (parentId === null && state.some((n) => n.parentId === null)) throw new ValidationError("Tree already has a root node");
1921
- const mergedData = applyDefaults(nodeType.data, data);
1922
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.insert, {
1923
- id,
1924
- type: nodeType.type,
1925
- parentId,
1926
- pos,
1927
- data: mergedData
1928
- }));
1929
- return id;
1930
- },
1931
- insertAt: (parentId, index, nodeType, data) => {
1932
- const state = getCurrentState();
1933
- const siblings = getOrderedChildren(state, parentId);
1934
- const clampedIndex = Math.max(0, Math.min(index, siblings.length));
1935
- const pos = generateTreePosBetween(clampedIndex > 0 && siblings[clampedIndex - 1] ? siblings[clampedIndex - 1].pos : null, clampedIndex < siblings.length && siblings[clampedIndex] ? siblings[clampedIndex].pos : null);
1936
- const id = env.generateId();
1937
- if (parentId !== null && !state.find((n) => n.id === parentId)) throw new ValidationError(`Parent node not found: ${parentId}`);
1938
- const parentType = getParentType(parentId);
1939
- this._validateChildType(parentType, nodeType.type);
1940
- if (parentId === null && state.some((n) => n.parentId === null)) throw new ValidationError("Tree already has a root node");
1941
- const mergedData = applyDefaults(nodeType.data, data);
1942
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.insert, {
1943
- id,
1944
- type: nodeType.type,
1945
- parentId,
1946
- pos,
1947
- data: mergedData
1948
- }));
1949
- return id;
1950
- },
1951
- insertAfter: (siblingId, nodeType, data) => {
1952
- var _nextSibling$pos;
1953
- const state = getCurrentState();
1954
- const sibling = state.find((n) => n.id === siblingId);
1955
- if (!sibling) throw new ValidationError(`Sibling node not found: ${siblingId}`);
1956
- const parentId = sibling.parentId;
1957
- const siblings = getOrderedChildren(state, parentId);
1958
- const nextSibling = siblings[siblings.findIndex((n) => n.id === siblingId) + 1];
1959
- const pos = generateTreePosBetween(sibling.pos, (_nextSibling$pos = nextSibling === null || nextSibling === void 0 ? void 0 : nextSibling.pos) !== null && _nextSibling$pos !== void 0 ? _nextSibling$pos : null);
1960
- const id = env.generateId();
1961
- const parentType = getParentType(parentId);
1962
- this._validateChildType(parentType, nodeType.type);
1963
- const mergedData = applyDefaults(nodeType.data, data);
1964
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.insert, {
1965
- id,
1966
- type: nodeType.type,
1967
- parentId,
1968
- pos,
1969
- data: mergedData
1970
- }));
1971
- return id;
1972
- },
1973
- insertBefore: (siblingId, nodeType, data) => {
1974
- var _prevSibling$pos;
1975
- const state = getCurrentState();
1976
- const sibling = state.find((n) => n.id === siblingId);
1977
- if (!sibling) throw new ValidationError(`Sibling node not found: ${siblingId}`);
1978
- const parentId = sibling.parentId;
1979
- const siblings = getOrderedChildren(state, parentId);
1980
- const prevSibling = siblings[siblings.findIndex((n) => n.id === siblingId) - 1];
1981
- const pos = generateTreePosBetween((_prevSibling$pos = prevSibling === null || prevSibling === void 0 ? void 0 : prevSibling.pos) !== null && _prevSibling$pos !== void 0 ? _prevSibling$pos : null, sibling.pos);
1982
- const id = env.generateId();
1983
- const parentType = getParentType(parentId);
1984
- this._validateChildType(parentType, nodeType.type);
1985
- const mergedData = applyDefaults(nodeType.data, data);
1986
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.insert, {
1987
- id,
1988
- type: nodeType.type,
1989
- parentId,
1990
- pos,
1991
- data: mergedData
1992
- }));
1993
- return id;
1994
- },
1995
- remove: (id) => {
1996
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.remove, { id }));
1997
- },
1998
- move: (nodeId, newParentId, toIndex) => {
1999
- var _state$find$type, _state$find;
2000
- const state = getCurrentState();
2001
- const node = state.find((n) => n.id === nodeId);
2002
- if (!node) throw new ValidationError(`Node not found: ${nodeId}`);
2003
- if (newParentId !== null && !state.find((n) => n.id === newParentId)) throw new ValidationError(`Parent node not found: ${newParentId}`);
2004
- if (wouldCreateCycle(state, nodeId, newParentId)) throw new ValidationError("Move would create a cycle in the tree");
2005
- const newParentType = newParentId === null ? null : (_state$find$type = (_state$find = state.find((n) => n.id === newParentId)) === null || _state$find === void 0 ? void 0 : _state$find.type) !== null && _state$find$type !== void 0 ? _state$find$type : null;
2006
- this._validateChildType(newParentType, node.type);
2007
- if (node.parentId === null && newParentId !== null) throw new ValidationError("Cannot move root node to have a parent");
2008
- const siblings = getOrderedChildren(state, newParentId).filter((n) => n.id !== nodeId);
2009
- const clampedIndex = Math.max(0, Math.min(toIndex, siblings.length));
2010
- const pos = generateTreePosBetween(clampedIndex > 0 && siblings[clampedIndex - 1] ? siblings[clampedIndex - 1].pos : null, clampedIndex < siblings.length && siblings[clampedIndex] ? siblings[clampedIndex].pos : null);
2011
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.move, {
2012
- id: nodeId,
2013
- parentId: newParentId,
2014
- pos
2015
- }));
2016
- },
2017
- moveAfter: (nodeId, siblingId) => {
2018
- var _state$find$type2, _state$find2, _nextSibling$pos2;
2019
- const state = getCurrentState();
2020
- const node = state.find((n) => n.id === nodeId);
2021
- const sibling = state.find((n) => n.id === siblingId);
2022
- if (!node) throw new ValidationError(`Node not found: ${nodeId}`);
2023
- if (!sibling) throw new ValidationError(`Sibling node not found: ${siblingId}`);
2024
- const newParentId = sibling.parentId;
2025
- if (wouldCreateCycle(state, nodeId, newParentId)) throw new ValidationError("Move would create a cycle in the tree");
2026
- const newParentType = newParentId === null ? null : (_state$find$type2 = (_state$find2 = state.find((n) => n.id === newParentId)) === null || _state$find2 === void 0 ? void 0 : _state$find2.type) !== null && _state$find$type2 !== void 0 ? _state$find$type2 : null;
2027
- this._validateChildType(newParentType, node.type);
2028
- if (node.parentId === null && newParentId !== null) throw new ValidationError("Cannot move root node to have a parent");
2029
- const siblings = getOrderedChildren(state, newParentId).filter((n) => n.id !== nodeId);
2030
- const nextSibling = siblings[siblings.findIndex((n) => n.id === siblingId) + 1];
2031
- const pos = generateTreePosBetween(sibling.pos, (_nextSibling$pos2 = nextSibling === null || nextSibling === void 0 ? void 0 : nextSibling.pos) !== null && _nextSibling$pos2 !== void 0 ? _nextSibling$pos2 : null);
2032
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.move, {
2033
- id: nodeId,
2034
- parentId: newParentId,
2035
- pos
2036
- }));
2037
- },
2038
- moveBefore: (nodeId, siblingId) => {
2039
- var _state$find$type3, _state$find3, _prevSibling$pos2;
2040
- const state = getCurrentState();
2041
- const node = state.find((n) => n.id === nodeId);
2042
- const sibling = state.find((n) => n.id === siblingId);
2043
- if (!node) throw new ValidationError(`Node not found: ${nodeId}`);
2044
- if (!sibling) throw new ValidationError(`Sibling node not found: ${siblingId}`);
2045
- const newParentId = sibling.parentId;
2046
- if (wouldCreateCycle(state, nodeId, newParentId)) throw new ValidationError("Move would create a cycle in the tree");
2047
- const newParentType = newParentId === null ? null : (_state$find$type3 = (_state$find3 = state.find((n) => n.id === newParentId)) === null || _state$find3 === void 0 ? void 0 : _state$find3.type) !== null && _state$find$type3 !== void 0 ? _state$find$type3 : null;
2048
- this._validateChildType(newParentType, node.type);
2049
- if (node.parentId === null && newParentId !== null) throw new ValidationError("Cannot move root node to have a parent");
2050
- const siblings = getOrderedChildren(state, newParentId).filter((n) => n.id !== nodeId);
2051
- const prevSibling = siblings[siblings.findIndex((n) => n.id === siblingId) - 1];
2052
- const pos = generateTreePosBetween((_prevSibling$pos2 = prevSibling === null || prevSibling === void 0 ? void 0 : prevSibling.pos) !== null && _prevSibling$pos2 !== void 0 ? _prevSibling$pos2 : null, sibling.pos);
2053
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.move, {
2054
- id: nodeId,
2055
- parentId: newParentId,
2056
- pos
2057
- }));
2058
- },
2059
- moveToFirst: (nodeId, newParentId) => {
2060
- var _state$find$type4, _state$find4;
2061
- const state = getCurrentState();
2062
- const node = state.find((n) => n.id === nodeId);
2063
- if (!node) throw new ValidationError(`Node not found: ${nodeId}`);
2064
- if (newParentId !== null && !state.find((n) => n.id === newParentId)) throw new ValidationError(`Parent node not found: ${newParentId}`);
2065
- if (wouldCreateCycle(state, nodeId, newParentId)) throw new ValidationError("Move would create a cycle in the tree");
2066
- const newParentType = newParentId === null ? null : (_state$find$type4 = (_state$find4 = state.find((n) => n.id === newParentId)) === null || _state$find4 === void 0 ? void 0 : _state$find4.type) !== null && _state$find$type4 !== void 0 ? _state$find$type4 : null;
2067
- this._validateChildType(newParentType, node.type);
2068
- if (node.parentId === null && newParentId !== null) throw new ValidationError("Cannot move root node to have a parent");
2069
- const siblings = getOrderedChildren(state, newParentId).filter((n) => n.id !== nodeId);
2070
- const pos = generateTreePosBetween(null, siblings.length > 0 ? siblings[0].pos : null);
2071
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.move, {
2072
- id: nodeId,
2073
- parentId: newParentId,
2074
- pos
2075
- }));
2076
- },
2077
- moveToLast: (nodeId, newParentId) => {
2078
- var _state$find$type5, _state$find5;
2079
- const state = getCurrentState();
2080
- const node = state.find((n) => n.id === nodeId);
2081
- if (!node) throw new ValidationError(`Node not found: ${nodeId}`);
2082
- if (newParentId !== null && !state.find((n) => n.id === newParentId)) throw new ValidationError(`Parent node not found: ${newParentId}`);
2083
- if (wouldCreateCycle(state, nodeId, newParentId)) throw new ValidationError("Move would create a cycle in the tree");
2084
- const newParentType = newParentId === null ? null : (_state$find$type5 = (_state$find5 = state.find((n) => n.id === newParentId)) === null || _state$find5 === void 0 ? void 0 : _state$find5.type) !== null && _state$find$type5 !== void 0 ? _state$find$type5 : null;
2085
- this._validateChildType(newParentType, node.type);
2086
- if (node.parentId === null && newParentId !== null) throw new ValidationError("Cannot move root node to have a parent");
2087
- const siblings = getOrderedChildren(state, newParentId).filter((n) => n.id !== nodeId);
2088
- const pos = generateTreePosBetween(siblings.length > 0 ? siblings[siblings.length - 1].pos : null, null);
2089
- env.addOperation(require_Document.fromDefinition(operationPath, this._opDefinitions.move, {
2090
- id: nodeId,
2091
- parentId: newParentId,
2092
- pos
2093
- }));
2094
- },
2095
- at: (id, nodeType) => {
2096
- const node = getCurrentState().find((n) => n.id === id);
2097
- if (!node) throw new ValidationError(`Node not found: ${id}`);
2098
- if (node.type !== nodeType.type) throw new ValidationError(`Node is of type "${node.type}", not "${nodeType.type}"`);
2099
- const nodePath = operationPath.append(id);
2100
- return nodeType.data._internal.createProxy(env, nodePath);
2101
- },
2102
- updateAt: (id, nodeType, value) => {
2103
- const node = getCurrentState().find((n) => n.id === id);
2104
- if (!node) throw new ValidationError(`Node not found: ${id}`);
2105
- if (node.type !== nodeType.type) throw new ValidationError(`Node is of type "${node.type}", not "${nodeType.type}"`);
2106
- const nodePath = operationPath.append(id);
2107
- nodeType.data._internal.createProxy(env, nodePath).update(value);
2108
- },
2109
- toSnapshot: () => {
2110
- const state = getCurrentState();
2111
- const rootNode = state.find((n) => n.parentId === null);
2112
- if (!rootNode) return void 0;
2113
- return buildSnapshot(rootNode.id, state);
2114
- }
2115
- };
2116
- },
2117
- applyOperation: (state, operation) => {
2118
- const path = operation.path;
2119
- const tokens = path.toTokens().filter((t) => t !== "");
2120
- const currentState = state !== null && state !== void 0 ? state : [];
2121
- let newState;
2122
- if (tokens.length === 0) switch (operation.kind) {
2123
- case "tree.set": {
2124
- const payload = operation.payload;
2125
- if (!globalThis.Array.isArray(payload)) throw new ValidationError(`TreePrimitive.set requires an array payload`);
2126
- newState = payload;
2127
- break;
2128
- }
2129
- case "tree.insert": {
2130
- const { id, type, parentId, pos, data } = operation.payload;
2131
- newState = [...currentState, {
2132
- id,
2133
- type,
2134
- parentId,
2135
- pos,
2136
- data
2137
- }];
2138
- break;
2139
- }
2140
- case "tree.remove": {
2141
- const { id } = operation.payload;
2142
- const descendantIds = getDescendantIds(currentState, id);
2143
- const idsToRemove = new Set([id, ...descendantIds]);
2144
- newState = currentState.filter((node) => !idsToRemove.has(node.id));
2145
- break;
2146
- }
2147
- case "tree.move": {
2148
- const { id, parentId, pos } = operation.payload;
2149
- newState = currentState.map((node) => node.id === id ? require_Presence._objectSpread2(require_Presence._objectSpread2({}, node), {}, {
2150
- parentId,
2151
- pos
2152
- }) : node);
2153
- break;
2154
- }
2155
- default: throw new ValidationError(`TreePrimitive cannot apply operation of kind: ${operation.kind}`);
2156
- }
2157
- else {
2158
- const nodeId = tokens[0];
2159
- const nodeIndex = currentState.findIndex((node$1) => node$1.id === nodeId);
2160
- if (nodeIndex === -1) throw new ValidationError(`Tree node not found with ID: ${nodeId}`);
2161
- const node = currentState[nodeIndex];
2162
- const nodeTypePrimitive = this._getNodeTypePrimitive(node.type);
2163
- const remainingPath = path.shift();
2164
- const nodeOperation = require_Presence._objectSpread2(require_Presence._objectSpread2({}, operation), {}, { path: remainingPath });
2165
- const newData = nodeTypePrimitive.data._internal.applyOperation(node.data, nodeOperation);
2166
- const mutableState = [...currentState];
2167
- mutableState[nodeIndex] = require_Presence._objectSpread2(require_Presence._objectSpread2({}, node), {}, { data: newData });
2168
- newState = mutableState;
2169
- }
2170
- runValidators(newState, this._schema.validators);
2171
- return newState;
2172
- },
2173
- getInitialState: () => {
2174
- var _rootNodeType$data$_i;
2175
- if (this._schema.defaultValue !== void 0) return this._schema.defaultValue;
2176
- const rootNodeType = this._schema.root;
2177
- const rootData = (_rootNodeType$data$_i = rootNodeType.data._internal.getInitialState()) !== null && _rootNodeType$data$_i !== void 0 ? _rootNodeType$data$_i : {};
2178
- const rootId = crypto.randomUUID();
2179
- const rootPos = generateTreePosBetween(null, null);
2180
- return [{
2181
- id: rootId,
2182
- type: rootNodeType.type,
2183
- parentId: null,
2184
- pos: rootPos,
2185
- data: rootData
2186
- }];
2187
- },
2188
- transformOperation: (clientOp, serverOp) => {
2189
- const clientPath = clientOp.path;
2190
- const serverPath = serverOp.path;
2191
- if (!require_Document.pathsOverlap(clientPath, serverPath)) return {
2192
- type: "transformed",
2193
- operation: clientOp
2194
- };
2195
- if (serverOp.kind === "tree.remove") {
2196
- const removedId = serverOp.payload.id;
2197
- const clientTokens$1 = clientPath.toTokens().filter((t) => t !== "");
2198
- const serverTokens$1 = serverPath.toTokens().filter((t) => t !== "");
2199
- if (clientOp.kind === "tree.move") {
2200
- const movePayload = clientOp.payload;
2201
- if (movePayload.id === removedId || movePayload.parentId === removedId) return { type: "noop" };
2202
- }
2203
- if (clientOp.kind === "tree.insert") {
2204
- if (clientOp.payload.parentId === removedId) return { type: "noop" };
2205
- }
2206
- if (clientTokens$1.length > serverTokens$1.length) {
2207
- if (clientTokens$1[serverTokens$1.length] === removedId) return { type: "noop" };
2208
- }
2209
- }
2210
- if (serverOp.kind === "tree.insert" && clientOp.kind === "tree.insert") return {
2211
- type: "transformed",
2212
- operation: clientOp
2213
- };
2214
- if (serverOp.kind === "tree.move" && clientOp.kind === "tree.move") {
2215
- if (serverOp.payload.id === clientOp.payload.id) return {
2216
- type: "transformed",
2217
- operation: clientOp
2218
- };
2219
- return {
2220
- type: "transformed",
2221
- operation: clientOp
2222
- };
2223
- }
2224
- if (require_Document.pathsEqual(clientPath, serverPath)) return {
2225
- type: "transformed",
2226
- operation: clientOp
2227
- };
2228
- if (serverOp.kind === "tree.set" && require_Document.isPrefix(serverPath, clientPath)) return {
2229
- type: "transformed",
2230
- operation: clientOp
2231
- };
2232
- const clientTokens = clientPath.toTokens().filter((t) => t !== "");
2233
- const serverTokens = serverPath.toTokens().filter((t) => t !== "");
2234
- if (clientTokens.length > 0 && serverTokens.length > 0) {
2235
- if (clientTokens[0] !== serverTokens[0]) return {
2236
- type: "transformed",
2237
- operation: clientOp
2238
- };
2239
- return {
2240
- type: "transformed",
2241
- operation: clientOp
2242
- };
2243
- }
2244
- return {
2245
- type: "transformed",
2246
- operation: clientOp
2247
- };
2248
- }
2249
- });
2250
- this._schema = schema;
2251
- }
2252
- /** Mark this tree as required */
2253
- required() {
2254
- return new TreePrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { required: true }));
2255
- }
2256
- /** Set a default value for this tree */
2257
- default(defaultValue) {
2258
- return new TreePrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { defaultValue }));
2259
- }
2260
- /** Get the root node type */
2261
- get root() {
2262
- return this._schema.root;
2263
- }
2264
- /** Add a custom validation rule */
2265
- refine(fn, message) {
2266
- return new TreePrimitive(require_Presence._objectSpread2(require_Presence._objectSpread2({}, this._schema), {}, { validators: [...this._schema.validators, {
2267
- validate: fn,
2268
- message
2269
- }] }));
2270
- }
2271
- /**
2272
- * Build a registry of all node types reachable from root
2273
- */
2274
- _buildNodeTypeRegistry() {
2275
- if (this._nodeTypeRegistry !== void 0) return this._nodeTypeRegistry;
2276
- const registry = /* @__PURE__ */ new Map();
2277
- const visited = /* @__PURE__ */ new Set();
2278
- const visit = (node) => {
2279
- if (visited.has(node.type)) return;
2280
- visited.add(node.type);
2281
- registry.set(node.type, node);
2282
- for (const child of node.children) visit(child);
2283
- };
2284
- visit(this._schema.root);
2285
- this._nodeTypeRegistry = registry;
2286
- return registry;
2287
- }
2288
- /**
2289
- * Get a node type primitive by its type string
2290
- */
2291
- _getNodeTypePrimitive(type) {
2292
- const nodeType = this._buildNodeTypeRegistry().get(type);
2293
- if (!nodeType) throw new ValidationError(`Unknown node type: ${type}`);
2294
- return nodeType;
2295
- }
2296
- /**
2297
- * Validate that a node type can be a child of a parent node type
2298
- */
2299
- _validateChildType(parentType, childType) {
2300
- if (parentType === null) {
2301
- if (childType !== this._schema.root.type) throw new ValidationError(`Root node must be of type "${this._schema.root.type}", got "${childType}"`);
2302
- return;
2303
- }
2304
- const parentNodePrimitive = this._getNodeTypePrimitive(parentType);
2305
- if (!parentNodePrimitive.isChildAllowed(childType)) throw new ValidationError(`Node type "${childType}" is not allowed as a child of "${parentType}". Allowed types: ${parentNodePrimitive.children.map((c) => c.type).join(", ") || "none"}`);
2306
- }
2307
- };
2308
- /** Creates a new TreePrimitive with the given root node type */
2309
- const Tree = (options) => new TreePrimitive({
2310
- required: false,
2311
- defaultValue: void 0,
2312
- root: options.root,
2313
- validators: []
2314
- });
2315
-
2316
- //#endregion
2317
- //#region src/Primitive.ts
2318
- var Primitive_exports = /* @__PURE__ */ require_Document.__export({
2319
- Array: () => Array$1,
2320
- ArrayPrimitive: () => ArrayPrimitive,
2321
- Boolean: () => Boolean,
2322
- BooleanPrimitive: () => BooleanPrimitive,
2323
- Either: () => Either,
2324
- EitherPrimitive: () => EitherPrimitive,
2325
- Lazy: () => Lazy,
2326
- LazyPrimitive: () => LazyPrimitive,
2327
- Literal: () => Literal,
2328
- LiteralPrimitive: () => LiteralPrimitive,
2329
- Number: () => Number,
2330
- NumberPrimitive: () => NumberPrimitive,
2331
- String: () => String,
2332
- StringPrimitive: () => StringPrimitive,
2333
- Struct: () => Struct,
2334
- StructPrimitive: () => StructPrimitive,
2335
- Tree: () => Tree,
2336
- TreeNode: () => TreeNode,
2337
- TreeNodePrimitive: () => TreeNodePrimitive,
2338
- TreeNodeSelf: () => TreeNodeSelf,
2339
- TreePrimitive: () => TreePrimitive,
2340
- Union: () => Union,
2341
- UnionPrimitive: () => UnionPrimitive,
2342
- ValidationError: () => ValidationError,
2343
- applyDefaults: () => applyDefaults,
2344
- isCompatibleOperation: () => isCompatibleOperation,
2345
- runValidators: () => runValidators
2346
- });
2347
-
2348
- //#endregion
2349
- //#region src/Transform.ts
2350
- var Transform_exports = {};
2351
-
2352
- //#endregion
2353
- //#region src/EffectSchema.ts
2354
- /**
2355
- * Effect.Schema utilities for converting Mimic primitives to Effect.Schema schemas.
2356
- *
2357
- * @since 0.0.1
2358
- */
2359
- var EffectSchema_exports = /* @__PURE__ */ require_Document.__export({
2360
- TreeNodeStateSchema: () => TreeNodeStateSchema,
2361
- toSetSchema: () => toSetSchema,
2362
- toUpdateSchema: () => toUpdateSchema
2363
- });
2364
- /**
2365
- * Schema for a tree node state (flat storage format).
2366
- */
2367
- const TreeNodeStateSchema = effect.Schema.Struct({
2368
- id: effect.Schema.String,
2369
- type: effect.Schema.String,
2370
- parentId: effect.Schema.NullOr(effect.Schema.String),
2371
- pos: effect.Schema.String,
2372
- data: effect.Schema.Unknown
2373
- });
2374
- /**
2375
- * Check if a field is required for set operations.
2376
- * A field is required if: TRequired is true AND THasDefault is false.
2377
- *
2378
- * We determine this by checking the primitive's schema properties.
2379
- */
2380
- function isRequiredForSet(primitive) {
2381
- const schema = primitive._schema;
2382
- if (!schema) return false;
2383
- return schema.required === true && schema.defaultValue === void 0;
2384
- }
2385
- /**
2386
- * Get the base Effect.Schema for a primitive type (without optional wrapper).
2387
- */
2388
- function getBaseSchema(primitive) {
2389
- switch (primitive._tag) {
2390
- case "StringPrimitive": return effect.Schema.String;
2391
- case "NumberPrimitive": return effect.Schema.Number;
2392
- case "BooleanPrimitive": return effect.Schema.Boolean;
2393
- case "LiteralPrimitive": {
2394
- var _schema$literal, _schema;
2395
- const literalPrimitive = primitive;
2396
- const literalValue = (_schema$literal = (_schema = literalPrimitive._schema) === null || _schema === void 0 ? void 0 : _schema.literal) !== null && _schema$literal !== void 0 ? _schema$literal : literalPrimitive.literal;
2397
- return effect.Schema.Literal(literalValue);
2398
- }
2399
- case "StructPrimitive": return buildStructSetSchema(primitive);
2400
- case "ArrayPrimitive": {
2401
- const elementSchema = buildElementSetSchema(primitive.element);
2402
- return effect.Schema.Array(elementSchema);
2403
- }
2404
- case "UnionPrimitive": return buildUnionSetSchema(primitive);
2405
- case "EitherPrimitive": return buildEitherSchema(primitive);
2406
- case "LazyPrimitive": {
2407
- var _resolve, _resolve2;
2408
- const lazyPrimitive = primitive;
2409
- return getBaseSchema((_resolve = (_resolve2 = lazyPrimitive._resolve) === null || _resolve2 === void 0 ? void 0 : _resolve2.call(lazyPrimitive)) !== null && _resolve !== void 0 ? _resolve : lazyPrimitive._thunk());
2410
- }
2411
- case "TreeNodePrimitive": return buildStructSetSchema(primitive.data);
2412
- case "TreePrimitive": return effect.Schema.Array(TreeNodeStateSchema);
2413
- default: return effect.Schema.Unknown;
2414
- }
2415
- }
2416
- /**
2417
- * Build the set schema for a struct primitive.
2418
- * Required fields (required=true, no default) are non-optional.
2419
- * Other fields are wrapped with Schema.optional.
2420
- */
2421
- function buildStructSetSchema(structPrimitive) {
2422
- const fields = structPrimitive.fields;
2423
- const schemaFields = {};
2424
- for (const key in fields) {
2425
- const fieldPrimitive = fields[key];
2426
- const baseSchema = getBaseSchema(fieldPrimitive);
2427
- if (isRequiredForSet(fieldPrimitive)) schemaFields[key] = baseSchema;
2428
- else schemaFields[key] = effect.Schema.optional(baseSchema);
2429
- }
2430
- return effect.Schema.Struct(schemaFields);
2431
- }
2432
- /**
2433
- * Build the update schema for a struct primitive.
2434
- * All fields are optional for partial updates.
2435
- */
2436
- function buildStructUpdateSchema(structPrimitive) {
2437
- const fields = structPrimitive.fields;
2438
- const schemaFields = {};
2439
- for (const key in fields) {
2440
- const fieldPrimitive = fields[key];
2441
- let fieldSchema;
2442
- if (fieldPrimitive._tag === "StructPrimitive") fieldSchema = buildStructUpdateSchema(fieldPrimitive);
2443
- else fieldSchema = getBaseSchema(fieldPrimitive);
2444
- schemaFields[key] = effect.Schema.optional(fieldSchema);
2445
- }
2446
- return effect.Schema.Struct(schemaFields);
2447
- }
2448
- /**
2449
- * Build the set schema for an array element.
2450
- * For struct elements, uses the struct's set input schema.
2451
- */
2452
- function buildElementSetSchema(elementPrimitive) {
2453
- if (elementPrimitive._tag === "StructPrimitive") return buildStructSetSchema(elementPrimitive);
2454
- return getBaseSchema(elementPrimitive);
2455
- }
2456
- /**
2457
- * Build the set schema for a union primitive.
2458
- * Creates a Schema.Union of all variant schemas.
2459
- */
2460
- function buildUnionSetSchema(unionPrimitive) {
2461
- const variants = unionPrimitive.variants;
2462
- const variantSchemas = [];
2463
- for (const key in variants) {
2464
- const variantPrimitive = variants[key];
2465
- variantSchemas.push(buildStructSetSchema(variantPrimitive));
2466
- }
2467
- if (variantSchemas.length === 0) return effect.Schema.Unknown;
2468
- if (variantSchemas.length === 1) return variantSchemas[0];
2469
- return effect.Schema.Union(...variantSchemas);
2470
- }
2471
- /**
2472
- * Build the schema for an either primitive.
2473
- * Creates a Schema.Union of all scalar variant types.
2474
- */
2475
- function buildEitherSchema(eitherPrimitive) {
2476
- const variants = eitherPrimitive.variants;
2477
- const variantSchemas = [];
2478
- for (const variant of variants) variantSchemas.push(getBaseSchema(variant));
2479
- if (variantSchemas.length === 0) return effect.Schema.Unknown;
2480
- if (variantSchemas.length === 1) return variantSchemas[0];
2481
- return effect.Schema.Union(...variantSchemas);
2482
- }
2483
- /**
2484
- * Build the update schema for a union primitive.
2485
- * Creates a Schema.Union of all variant update schemas.
2486
- */
2487
- function buildUnionUpdateSchema(unionPrimitive) {
2488
- const variants = unionPrimitive.variants;
2489
- const variantSchemas = [];
2490
- for (const key in variants) {
2491
- const variantPrimitive = variants[key];
2492
- variantSchemas.push(buildStructUpdateSchema(variantPrimitive));
2493
- }
2494
- if (variantSchemas.length === 0) return effect.Schema.Unknown;
2495
- if (variantSchemas.length === 1) return variantSchemas[0];
2496
- return effect.Schema.Union(...variantSchemas);
2497
- }
2498
- /**
2499
- * Get the update schema for a primitive.
2500
- * For structs, all fields are optional (partial updates).
2501
- * For simple primitives, same as set schema.
2502
- */
2503
- function getUpdateSchema(primitive) {
2504
- switch (primitive._tag) {
2505
- case "StructPrimitive": return buildStructUpdateSchema(primitive);
2506
- case "UnionPrimitive": return buildUnionUpdateSchema(primitive);
2507
- case "TreeNodePrimitive": return buildStructUpdateSchema(primitive.data);
2508
- case "LazyPrimitive": {
2509
- var _resolve3, _resolve4;
2510
- const lazyPrimitive = primitive;
2511
- return getUpdateSchema((_resolve3 = (_resolve4 = lazyPrimitive._resolve) === null || _resolve4 === void 0 ? void 0 : _resolve4.call(lazyPrimitive)) !== null && _resolve3 !== void 0 ? _resolve3 : lazyPrimitive._thunk());
2512
- }
2513
- default: return getBaseSchema(primitive);
2514
- }
2515
- }
2516
- function toSetSchema(primitive) {
2517
- return getBaseSchema(primitive);
2518
- }
2519
- function toUpdateSchema(primitive) {
2520
- return getUpdateSchema(primitive);
2521
- }
2522
-
2523
- //#endregion
2524
- //#region src/types/index.ts
2525
- var types_exports = /* @__PURE__ */ require_Document.__export({
2526
- TreeNodePrimitive: () => TreeNodePrimitive,
2527
- TreeNodeSelf: () => TreeNodeSelf
2528
- });
2529
-
2530
- //#endregion
2531
- //#region src/utils/tree-helpers.ts
2532
- var tree_helpers_exports = /* @__PURE__ */ require_Document.__export({
2533
- buildNodeTypeMap: () => buildNodeTypeMap,
2534
- canAddChildType: () => canAddChildType,
2535
- findNode: () => findNode,
2536
- findNodeById: () => findNodeById,
2537
- findNodeWithPath: () => findNodeWithPath,
2538
- findNodes: () => findNodes,
2539
- flattenTree: () => flattenTree,
2540
- getAllNodeTypes: () => getAllNodeTypes,
2541
- getAllowedChildTypes: () => getAllowedChildTypes,
2542
- getAllowedChildTypesForNode: () => getAllowedChildTypesForNode,
2543
- getAncestors: () => getAncestors,
2544
- getDescendants: () => getDescendants,
2545
- getNodeDepth: () => getNodeDepth,
2546
- getNodePrimitive: () => getNodePrimitive,
2547
- getNodeTypeByName: () => getNodeTypeByName,
2548
- getParent: () => getParent,
2549
- getSiblings: () => getSiblings,
2550
- getSubtree: () => getSubtree,
2551
- isAncestorOf: () => isAncestorOf,
2552
- isChildTypeAllowed: () => isChildTypeAllowed,
2553
- mapTree: () => mapTree,
2554
- traverse: () => traverse
2555
- });
2556
- /**
2557
- * Find a node by ID in a tree snapshot.
2558
- *
2559
- * @param snapshot - The root tree snapshot
2560
- * @param id - The node ID to find
2561
- * @returns The node snapshot if found, undefined otherwise
2562
- */
2563
- function findNodeById(snapshot, id) {
2564
- if (!snapshot) return void 0;
2565
- if (snapshot.id === id) return snapshot;
2566
- for (const child of snapshot.children) {
2567
- const found = findNodeById(child, id);
2568
- if (found) return found;
2569
- }
2570
- }
2571
- /**
2572
- * Find a node by ID with full path information.
2573
- *
2574
- * @param snapshot - The root tree snapshot
2575
- * @param id - The node ID to find
2576
- * @returns NodeSearchResult with node, path, and depth, or undefined if not found
2577
- */
2578
- function findNodeWithPath(snapshot, id) {
2579
- if (!snapshot) return void 0;
2580
- const search = (node, currentPath, depth) => {
2581
- const path = [...currentPath, node.id];
2582
- if (node.id === id) return {
2583
- node,
2584
- path,
2585
- depth
2586
- };
2587
- for (const child of node.children) {
2588
- const result = search(child, path, depth + 1);
2589
- if (result) return result;
2590
- }
2591
- };
2592
- return search(snapshot, [], 0);
2593
- }
2594
- /**
2595
- * Get the parent node of a given node ID.
2596
- *
2597
- * @param snapshot - The root tree snapshot
2598
- * @param nodeId - The ID of the node whose parent we want
2599
- * @returns ParentSearchResult with parent node and child index, or undefined
2600
- */
2601
- function getParent(snapshot, nodeId) {
2602
- if (!snapshot) return void 0;
2603
- for (let i = 0; i < snapshot.children.length; i++) {
2604
- const child = snapshot.children[i];
2605
- if (child && child.id === nodeId) return {
2606
- parent: snapshot,
2607
- childIndex: i
2608
- };
2609
- }
2610
- for (const child of snapshot.children) {
2611
- const result = getParent(child, nodeId);
2612
- if (result) return result;
2613
- }
2614
- }
2615
- /**
2616
- * Get a subtree rooted at a specific node ID.
2617
- *
2618
- * @param snapshot - The root tree snapshot
2619
- * @param nodeId - The ID of the node to use as new root
2620
- * @returns The subtree snapshot, or undefined if node not found
2621
- */
2622
- function getSubtree(snapshot, nodeId) {
2623
- return findNodeById(snapshot, nodeId);
2624
- }
2625
- /**
2626
- * Get all ancestor nodes from a node up to the root.
2627
- *
2628
- * @param snapshot - The root tree snapshot
2629
- * @param nodeId - The ID of the node
2630
- * @returns Array of ancestor snapshots from immediate parent to root, or empty array
2631
- */
2632
- function getAncestors(snapshot, nodeId) {
2633
- if (!snapshot) return [];
2634
- const result = findNodeWithPath(snapshot, nodeId);
2635
- if (!result || result.path.length <= 1) return [];
2636
- const ancestorIds = result.path.slice(0, -1);
2637
- const ancestors = [];
2638
- for (let i = ancestorIds.length - 1; i >= 0; i--) {
2639
- const id = ancestorIds[i];
2640
- if (id) {
2641
- const ancestor = findNodeById(snapshot, id);
2642
- if (ancestor) ancestors.push(ancestor);
2643
- }
2644
- }
2645
- return ancestors;
2646
- }
2647
- /**
2648
- * Get all descendant nodes of a given node (flat array).
2649
- *
2650
- * @param snapshot - The root tree snapshot
2651
- * @param nodeId - The ID of the node (if undefined, returns all descendants of root)
2652
- * @returns Flat array of all descendant node snapshots
2653
- */
2654
- function getDescendants(snapshot, nodeId) {
2655
- if (!snapshot) return [];
2656
- const startNode = nodeId ? findNodeById(snapshot, nodeId) : snapshot;
2657
- if (!startNode) return [];
2658
- const descendants = [];
2659
- const collect = (node) => {
2660
- for (const child of node.children) {
2661
- descendants.push(child);
2662
- collect(child);
2663
- }
2664
- };
2665
- collect(startNode);
2666
- return descendants;
2667
- }
2668
- /**
2669
- * Get siblings of a node (nodes with the same parent).
2670
- *
2671
- * @param snapshot - The root tree snapshot
2672
- * @param nodeId - The ID of the node
2673
- * @param includeSelf - Whether to include the node itself (default: false)
2674
- * @returns Array of sibling snapshots
2675
- */
2676
- function getSiblings(snapshot, nodeId, includeSelf = false) {
2677
- if (!snapshot) return [];
2678
- const parentResult = getParent(snapshot, nodeId);
2679
- if (!parentResult) return [];
2680
- const siblings = parentResult.parent.children;
2681
- if (includeSelf) return siblings;
2682
- return siblings.filter((s) => s.id !== nodeId);
2683
- }
2684
- /**
2685
- * Find the first node matching a predicate.
2686
- *
2687
- * @param snapshot - The root tree snapshot
2688
- * @param predicate - Function to test each node
2689
- * @returns First matching node snapshot, or undefined
2690
- */
2691
- function findNode(snapshot, predicate) {
2692
- if (!snapshot) return void 0;
2693
- if (predicate(snapshot)) return snapshot;
2694
- for (const child of snapshot.children) {
2695
- const found = findNode(child, predicate);
2696
- if (found) return found;
2697
- }
2698
- }
2699
- /**
2700
- * Find all nodes matching a predicate.
2701
- *
2702
- * @param snapshot - The root tree snapshot
2703
- * @param predicate - Function to test each node
2704
- * @returns Array of matching node snapshots
2705
- */
2706
- function findNodes(snapshot, predicate) {
2707
- if (!snapshot) return [];
2708
- const results = [];
2709
- const search = (node) => {
2710
- if (predicate(node)) results.push(node);
2711
- for (const child of node.children) search(child);
2712
- };
2713
- search(snapshot);
2714
- return results;
2715
- }
2716
- /**
2717
- * Get the depth of a specific node (0 = root).
2718
- *
2719
- * @param snapshot - The root tree snapshot
2720
- * @param nodeId - The ID of the node
2721
- * @returns The depth, or -1 if not found
2722
- */
2723
- function getNodeDepth(snapshot, nodeId) {
2724
- if (!snapshot) return -1;
2725
- const result = findNodeWithPath(snapshot, nodeId);
2726
- return result ? result.depth : -1;
2727
- }
2728
- /**
2729
- * Check if one node is an ancestor of another.
2730
- *
2731
- * @param snapshot - The root tree snapshot
2732
- * @param ancestorId - Potential ancestor node ID
2733
- * @param descendantId - Potential descendant node ID
2734
- * @returns true if ancestorId is an ancestor of descendantId
2735
- */
2736
- function isAncestorOf(snapshot, ancestorId, descendantId) {
2737
- if (!snapshot) return false;
2738
- const result = findNodeWithPath(snapshot, descendantId);
2739
- if (!result) return false;
2740
- return result.path.slice(0, -1).includes(ancestorId);
2741
- }
2742
- /**
2743
- * Traverse the tree and call a visitor function for each node.
2744
- * Return false from visitor to stop traversal.
2745
- *
2746
- * @param snapshot - The root tree snapshot
2747
- * @param visitor - Function called for each node (return false to stop)
2748
- * @param options - Traversal options (order: 'pre' | 'post')
2749
- */
2750
- function traverse(snapshot, visitor, options = {}) {
2751
- if (!snapshot) return;
2752
- const { order = "pre" } = options;
2753
- const visit = (node, depth) => {
2754
- if (order === "pre") {
2755
- if (visitor(node, depth) === false) return false;
2756
- }
2757
- for (const child of node.children) if (!visit(child, depth + 1)) return false;
2758
- if (order === "post") {
2759
- if (visitor(node, depth) === false) return false;
2760
- }
2761
- return true;
2762
- };
2763
- visit(snapshot, 0);
2764
- }
2765
- /**
2766
- * Flatten the tree into an array with parent information.
2767
- *
2768
- * @param snapshot - The root tree snapshot
2769
- * @returns Array of { node, parentId, depth } objects
2770
- */
2771
- function flattenTree(snapshot) {
2772
- if (!snapshot) return [];
2773
- const result = [];
2774
- const flatten = (node, parentId, depth) => {
2775
- result.push({
2776
- node,
2777
- parentId,
2778
- depth
2779
- });
2780
- for (const child of node.children) flatten(child, node.id, depth + 1);
2781
- };
2782
- flatten(snapshot, null, 0);
2783
- return result;
2784
- }
2785
- /**
2786
- * Map over all nodes in the tree, transforming each node's data.
2787
- * Preserves tree structure while transforming node content.
2788
- *
2789
- * @param snapshot - The root tree snapshot
2790
- * @param mapper - Function to transform each node
2791
- * @returns New tree structure with transformed nodes, or undefined
2792
- */
2793
- function mapTree(snapshot, mapper) {
2794
- if (!snapshot) return void 0;
2795
- const map = (node, depth) => {
2796
- return {
2797
- value: mapper(node, depth),
2798
- children: node.children.map((child) => map(child, depth + 1))
2799
- };
2800
- };
2801
- return map(snapshot, 0);
2802
- }
2803
- /**
2804
- * Build a lookup map from node type strings to their TreeNodePrimitive definitions.
2805
- * Useful for resolving snapshot node types back to their schema definitions.
2806
- *
2807
- * @param tree - The TreePrimitive to analyze
2808
- * @returns Map from type string to TreeNodePrimitive
2809
- *
2810
- * @example
2811
- * ```ts
2812
- * const typeMap = buildNodeTypeMap(fileTree);
2813
- * const folderPrimitive = typeMap.get("folder"); // FolderNode
2814
- * ```
2815
- */
2816
- function buildNodeTypeMap(tree) {
2817
- const map = /* @__PURE__ */ new Map();
2818
- const visited = /* @__PURE__ */ new Set();
2819
- const visit = (node) => {
2820
- if (visited.has(node.type)) return;
2821
- visited.add(node.type);
2822
- map.set(node.type, node);
2823
- for (const child of node.children) visit(child);
2824
- };
2825
- visit(tree.root);
2826
- return map;
2827
- }
2828
- /**
2829
- * Get the TreeNodePrimitive definition for a snapshot node.
2830
- * Requires the tree schema to resolve the type string to its primitive.
2831
- *
2832
- * @param tree - The TreePrimitive schema
2833
- * @param snapshot - The node snapshot to get the primitive for
2834
- * @returns The TreeNodePrimitive, or undefined if not found
2835
- *
2836
- * @example
2837
- * ```ts
2838
- * const node = findNodeById(treeSnapshot, "some-id");
2839
- * const primitive = getNodePrimitive(fileTree, node);
2840
- * // primitive is FolderNode or FileNode depending on node.type
2841
- * ```
2842
- */
2843
- function getNodePrimitive(tree, snapshot) {
2844
- return getNodeTypeByName(tree, snapshot.type);
2845
- }
2846
- /**
2847
- * Get the allowed child types for a snapshot node.
2848
- * Combines schema lookup with the node's allowed children.
2849
- *
2850
- * @param tree - The TreePrimitive schema
2851
- * @param snapshot - The node snapshot to get allowed children for
2852
- * @returns Array of allowed child TreeNodePrimitives, or empty array if not found
2853
- *
2854
- * @example
2855
- * ```ts
2856
- * const node = findNodeById(treeSnapshot, "folder-id");
2857
- * const allowedChildren = getAllowedChildTypesForNode(fileTree, node);
2858
- * // Returns [FolderNode, FileNode] if the folder can contain both
2859
- * ```
2860
- */
2861
- function getAllowedChildTypesForNode(tree, snapshot) {
2862
- const primitive = getNodePrimitive(tree, snapshot);
2863
- if (!primitive) return [];
2864
- return primitive.children;
2865
- }
2866
- /**
2867
- * Check if a child type is allowed for a specific snapshot node.
2868
- *
2869
- * @param tree - The TreePrimitive schema
2870
- * @param parentSnapshot - The parent node snapshot
2871
- * @param childTypeName - The type string of the potential child
2872
- * @returns true if the child type is allowed
2873
- *
2874
- * @example
2875
- * ```ts
2876
- * const folder = findNodeById(treeSnapshot, "folder-id");
2877
- * canAddChildType(fileTree, folder, "file"); // true
2878
- * canAddChildType(fileTree, folder, "unknown"); // false
2879
- * ```
2880
- */
2881
- function canAddChildType(tree, parentSnapshot, childTypeName) {
2882
- const primitive = getNodePrimitive(tree, parentSnapshot);
2883
- if (!primitive) return false;
2884
- return primitive.isChildAllowed(childTypeName);
2885
- }
2886
- /**
2887
- * Get all allowed child node types for a specific node type.
2888
- *
2889
- * @param nodeType - The TreeNodePrimitive to get children for
2890
- * @returns Array of allowed child TreeNodePrimitives
2891
- *
2892
- * @example
2893
- * ```ts
2894
- * const FolderNode = TreeNode("folder", { ... });
2895
- * const FileNode = TreeNode("file", { ... });
2896
- *
2897
- * // Get allowed children for FolderNode
2898
- * const allowedChildren = getAllowedChildTypes(FolderNode);
2899
- * // Returns [FolderNode, FileNode] if folder can contain both
2900
- * ```
2901
- */
2902
- function getAllowedChildTypes(nodeType) {
2903
- return nodeType.children;
2904
- }
2905
- /**
2906
- * Get all unique node types reachable in a tree schema.
2907
- * Recursively traverses the tree structure starting from the root.
2908
- *
2909
- * @param tree - The TreePrimitive to analyze
2910
- * @returns Array of all unique TreeNodePrimitives in the tree schema
2911
- *
2912
- * @example
2913
- * ```ts
2914
- * const fileTree = Tree({ root: FolderNode });
2915
- * const allNodeTypes = getAllNodeTypes(fileTree);
2916
- * // Returns [FolderNode, FileNode] - all possible node types
2917
- * ```
2918
- */
2919
- function getAllNodeTypes(tree) {
2920
- const visited = /* @__PURE__ */ new Set();
2921
- const result = [];
2922
- const visit = (node) => {
2923
- if (visited.has(node.type)) return;
2924
- visited.add(node.type);
2925
- result.push(node);
2926
- for (const child of node.children) visit(child);
2927
- };
2928
- visit(tree.root);
2929
- return result;
2930
- }
2931
- /**
2932
- * Get the node type primitive by its type string from a tree schema.
2933
- *
2934
- * @param tree - The TreePrimitive to search
2935
- * @param typeName - The type string to find (e.g., "folder", "file")
2936
- * @returns The matching TreeNodePrimitive, or undefined if not found
2937
- *
2938
- * @example
2939
- * ```ts
2940
- * const fileTree = Tree({ root: FolderNode });
2941
- * const folderType = getNodeTypeByName(fileTree, "folder");
2942
- * // Returns FolderNode
2943
- * ```
2944
- */
2945
- function getNodeTypeByName(tree, typeName) {
2946
- return getAllNodeTypes(tree).find((node) => node.type === typeName);
2947
- }
2948
- /**
2949
- * Check if a child type is allowed under a parent type.
2950
- *
2951
- * @param parentType - The parent TreeNodePrimitive
2952
- * @param childTypeName - The type string of the potential child
2953
- * @returns true if the child type is allowed
2954
- *
2955
- * @example
2956
- * ```ts
2957
- * isChildTypeAllowed(FolderNode, "file"); // true if folder can contain files
2958
- * isChildTypeAllowed(FileNode, "folder"); // false - files can't have children
2959
- * ```
2960
- */
2961
- function isChildTypeAllowed(parentType, childTypeName) {
2962
- return parentType.isChildAllowed(childTypeName);
2963
- }
2964
-
2965
- //#endregion
2966
13
  Object.defineProperty(exports, 'Document', {
2967
14
  enumerable: true,
2968
15
  get: function () {
@@ -2972,19 +19,19 @@ Object.defineProperty(exports, 'Document', {
2972
19
  Object.defineProperty(exports, 'EffectSchema', {
2973
20
  enumerable: true,
2974
21
  get: function () {
2975
- return EffectSchema_exports;
22
+ return require_EffectSchema.EffectSchema_exports;
2976
23
  }
2977
24
  });
2978
25
  Object.defineProperty(exports, 'Operation', {
2979
26
  enumerable: true,
2980
27
  get: function () {
2981
- return require_Document.Operation_exports;
28
+ return require_Operation.Operation_exports;
2982
29
  }
2983
30
  });
2984
31
  Object.defineProperty(exports, 'OperationPath', {
2985
32
  enumerable: true,
2986
33
  get: function () {
2987
- return require_Document.OperationPath_exports;
34
+ return require_OperationPath.OperationPath_exports;
2988
35
  }
2989
36
  });
2990
37
  Object.defineProperty(exports, 'Presence', {
@@ -2996,36 +43,36 @@ Object.defineProperty(exports, 'Presence', {
2996
43
  Object.defineProperty(exports, 'Primitive', {
2997
44
  enumerable: true,
2998
45
  get: function () {
2999
- return Primitive_exports;
46
+ return require_Primitive.Primitive_exports;
3000
47
  }
3001
48
  });
3002
49
  Object.defineProperty(exports, 'ProxyEnvironment', {
3003
50
  enumerable: true,
3004
51
  get: function () {
3005
- return require_Document.ProxyEnvironment_exports;
52
+ return require_ProxyEnvironment.ProxyEnvironment_exports;
3006
53
  }
3007
54
  });
3008
55
  Object.defineProperty(exports, 'Transaction', {
3009
56
  enumerable: true,
3010
57
  get: function () {
3011
- return require_Document.Transaction_exports;
58
+ return require_Transaction.Transaction_exports;
3012
59
  }
3013
60
  });
3014
61
  Object.defineProperty(exports, 'Transform', {
3015
62
  enumerable: true,
3016
63
  get: function () {
3017
- return Transform_exports;
64
+ return require_Transform.Transform_exports;
3018
65
  }
3019
66
  });
3020
67
  Object.defineProperty(exports, 'TreeHelpers', {
3021
68
  enumerable: true,
3022
69
  get: function () {
3023
- return tree_helpers_exports;
70
+ return require_tree_helpers.tree_helpers_exports;
3024
71
  }
3025
72
  });
3026
73
  Object.defineProperty(exports, 'Types', {
3027
74
  enumerable: true,
3028
75
  get: function () {
3029
- return types_exports;
76
+ return require_index.types_exports;
3030
77
  }
3031
78
  });