jazz-tools 0.17.14 → 0.18.1

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 (250) hide show
  1. package/.svelte-kit/__package__/jazz.class.svelte.js +1 -1
  2. package/.svelte-kit/__package__/media/image.svelte +3 -9
  3. package/.svelte-kit/__package__/media/image.svelte.d.ts +1 -6
  4. package/.svelte-kit/__package__/media/image.svelte.d.ts.map +1 -1
  5. package/.svelte-kit/__package__/media/image.types.d.ts +7 -0
  6. package/.svelte-kit/__package__/media/image.types.d.ts.map +1 -0
  7. package/.svelte-kit/__package__/media/image.types.js +1 -0
  8. package/.svelte-kit/__package__/tests/media/image.svelte.test.js +31 -31
  9. package/.turbo/turbo-build.log +60 -46
  10. package/CHANGELOG.md +41 -0
  11. package/dist/better-auth/auth/client.d.ts +29 -0
  12. package/dist/better-auth/auth/client.d.ts.map +1 -0
  13. package/dist/better-auth/auth/client.js +127 -0
  14. package/dist/better-auth/auth/client.js.map +1 -0
  15. package/dist/better-auth/auth/react.d.ts +2170 -0
  16. package/dist/better-auth/auth/react.d.ts.map +1 -0
  17. package/dist/better-auth/auth/react.js +40 -0
  18. package/dist/better-auth/auth/react.js.map +1 -0
  19. package/dist/better-auth/auth/server.d.ts +14 -0
  20. package/dist/better-auth/auth/server.d.ts.map +1 -0
  21. package/dist/better-auth/auth/server.js +198 -0
  22. package/dist/better-auth/auth/server.js.map +1 -0
  23. package/dist/better-auth/auth/tests/client.test.d.ts +2 -0
  24. package/dist/better-auth/auth/tests/client.test.d.ts.map +1 -0
  25. package/dist/better-auth/auth/tests/server.test.d.ts +2 -0
  26. package/dist/better-auth/auth/tests/server.test.d.ts.map +1 -0
  27. package/dist/browser/index.js +2 -2
  28. package/dist/browser/index.js.map +1 -1
  29. package/dist/{chunk-LZOF6WP5.js → chunk-IERUTUXB.js} +1336 -1017
  30. package/dist/chunk-IERUTUXB.js.map +1 -0
  31. package/dist/index.js +18 -18
  32. package/dist/index.js.map +1 -1
  33. package/dist/inspector/{custom-element-ZSNTCECD.js → custom-element-WCY6D3QJ.js} +3 -3
  34. package/dist/inspector/{custom-element-ZSNTCECD.js.map → custom-element-WCY6D3QJ.js.map} +1 -1
  35. package/dist/inspector/index.js +1 -1
  36. package/dist/inspector/index.js.map +1 -1
  37. package/dist/inspector/register-custom-element.js +1 -1
  38. package/dist/media/{chunk-E5J3WLQW.js → chunk-KR2V6X2N.js} +14 -9
  39. package/dist/media/chunk-KR2V6X2N.js.map +1 -0
  40. package/dist/media/create-image.d.ts +6 -6
  41. package/dist/media/index.browser.d.ts +6 -6
  42. package/dist/media/index.browser.js +1 -1
  43. package/dist/media/index.d.ts +1 -1
  44. package/dist/media/index.js +1 -1
  45. package/dist/media/index.native.d.ts +6 -6
  46. package/dist/media/index.native.js +1 -1
  47. package/dist/media/utils.d.ts.map +1 -1
  48. package/dist/prosemirror/index.js +2 -2
  49. package/dist/prosemirror/index.js.map +1 -1
  50. package/dist/react/index.js +7 -5
  51. package/dist/react/index.js.map +1 -1
  52. package/dist/react-core/hooks.d.ts.map +1 -1
  53. package/dist/react-core/index.js +4675 -23
  54. package/dist/react-core/index.js.map +1 -1
  55. package/dist/react-native-core/index.js +1 -1
  56. package/dist/react-native-core/index.js.map +1 -1
  57. package/dist/svelte/jazz.class.svelte.js +1 -1
  58. package/dist/svelte/media/image.svelte +3 -9
  59. package/dist/svelte/media/image.svelte.d.ts +1 -6
  60. package/dist/svelte/media/image.svelte.d.ts.map +1 -1
  61. package/dist/svelte/media/image.types.d.ts +7 -0
  62. package/dist/svelte/media/image.types.d.ts.map +1 -0
  63. package/dist/svelte/media/image.types.js +1 -0
  64. package/dist/svelte/tests/media/image.svelte.test.js +31 -31
  65. package/dist/testing.js +18 -14
  66. package/dist/testing.js.map +1 -1
  67. package/dist/tools/coValues/CoFieldInit.d.ts +13 -0
  68. package/dist/tools/coValues/CoFieldInit.d.ts.map +1 -0
  69. package/dist/tools/coValues/CoValueBase.d.ts +18 -15
  70. package/dist/tools/coValues/CoValueBase.d.ts.map +1 -1
  71. package/dist/tools/coValues/account.d.ts +101 -46
  72. package/dist/tools/coValues/account.d.ts.map +1 -1
  73. package/dist/tools/coValues/coFeed.d.ts +78 -62
  74. package/dist/tools/coValues/coFeed.d.ts.map +1 -1
  75. package/dist/tools/coValues/coList.d.ts +212 -99
  76. package/dist/tools/coValues/coList.d.ts.map +1 -1
  77. package/dist/tools/coValues/coMap.d.ts +210 -192
  78. package/dist/tools/coValues/coMap.d.ts.map +1 -1
  79. package/dist/tools/coValues/coPlainText.d.ts +30 -22
  80. package/dist/tools/coValues/coPlainText.d.ts.map +1 -1
  81. package/dist/tools/coValues/deepLoading.d.ts +13 -13
  82. package/dist/tools/coValues/deepLoading.d.ts.map +1 -1
  83. package/dist/tools/coValues/extensions/imageDef.d.ts +1 -1
  84. package/dist/tools/coValues/group.d.ts +32 -32
  85. package/dist/tools/coValues/group.d.ts.map +1 -1
  86. package/dist/tools/coValues/inbox.d.ts.map +1 -1
  87. package/dist/tools/coValues/interfaces.d.ts +18 -17
  88. package/dist/tools/coValues/interfaces.d.ts.map +1 -1
  89. package/dist/tools/coValues/profile.d.ts +6 -5
  90. package/dist/tools/coValues/profile.d.ts.map +1 -1
  91. package/dist/tools/coValues/schemaUnion.d.ts +3 -3
  92. package/dist/tools/coValues/schemaUnion.d.ts.map +1 -1
  93. package/dist/tools/exports.d.ts +1 -1
  94. package/dist/tools/exports.d.ts.map +1 -1
  95. package/dist/tools/implementation/anonymousJazzAgent.d.ts +2 -1
  96. package/dist/tools/implementation/anonymousJazzAgent.d.ts.map +1 -1
  97. package/dist/tools/implementation/schema.d.ts +5 -5
  98. package/dist/tools/implementation/schema.d.ts.map +1 -1
  99. package/dist/tools/implementation/symbols.d.ts +2 -0
  100. package/dist/tools/implementation/symbols.d.ts.map +1 -1
  101. package/dist/tools/implementation/zodSchema/schemaTypes/AccountSchema.d.ts +2 -2
  102. package/dist/tools/implementation/zodSchema/schemaTypes/AccountSchema.d.ts.map +1 -1
  103. package/dist/tools/implementation/zodSchema/schemaTypes/CoFeedSchema.d.ts +6 -2
  104. package/dist/tools/implementation/zodSchema/schemaTypes/CoFeedSchema.d.ts.map +1 -1
  105. package/dist/tools/implementation/zodSchema/schemaTypes/CoListSchema.d.ts +8 -3
  106. package/dist/tools/implementation/zodSchema/schemaTypes/CoListSchema.d.ts.map +1 -1
  107. package/dist/tools/implementation/zodSchema/schemaTypes/CoMapSchema.d.ts +12 -7
  108. package/dist/tools/implementation/zodSchema/schemaTypes/CoMapSchema.d.ts.map +1 -1
  109. package/dist/tools/implementation/zodSchema/schemaTypes/CoRecordSchema.d.ts +13 -7
  110. package/dist/tools/implementation/zodSchema/schemaTypes/CoRecordSchema.d.ts.map +1 -1
  111. package/dist/tools/implementation/zodSchema/schemaTypes/FileStreamSchema.d.ts +11 -2
  112. package/dist/tools/implementation/zodSchema/schemaTypes/FileStreamSchema.d.ts.map +1 -1
  113. package/dist/tools/implementation/zodSchema/schemaTypes/PlainTextSchema.d.ts +4 -0
  114. package/dist/tools/implementation/zodSchema/schemaTypes/PlainTextSchema.d.ts.map +1 -1
  115. package/dist/tools/implementation/zodSchema/schemaTypes/RichTextSchema.d.ts +4 -0
  116. package/dist/tools/implementation/zodSchema/schemaTypes/RichTextSchema.d.ts.map +1 -1
  117. package/dist/tools/implementation/zodSchema/typeConverters/{CoFieldInit.d.ts → CoFieldSchemaInit.d.ts} +7 -7
  118. package/dist/tools/implementation/zodSchema/typeConverters/CoFieldSchemaInit.d.ts.map +1 -0
  119. package/dist/tools/implementation/zodSchema/typeConverters/InstanceOfSchema.d.ts +4 -4
  120. package/dist/tools/implementation/zodSchema/typeConverters/InstanceOfSchema.d.ts.map +1 -1
  121. package/dist/tools/implementation/zodSchema/typeConverters/InstanceOfSchemaCoValuesNullable.d.ts +4 -4
  122. package/dist/tools/implementation/zodSchema/typeConverters/InstanceOfSchemaCoValuesNullable.d.ts.map +1 -1
  123. package/dist/tools/implementation/zodSchema/zodCo.d.ts +3 -3
  124. package/dist/tools/implementation/zodSchema/zodCo.d.ts.map +1 -1
  125. package/dist/tools/internal.d.ts +2 -1
  126. package/dist/tools/internal.d.ts.map +1 -1
  127. package/dist/tools/lib/migration.d.ts +1 -1
  128. package/dist/tools/lib/migration.d.ts.map +1 -1
  129. package/dist/tools/subscribe/SubscriptionScope.d.ts.map +1 -1
  130. package/dist/tools/subscribe/index.d.ts +1 -1
  131. package/dist/tools/subscribe/index.d.ts.map +1 -1
  132. package/dist/tools/subscribe/utils.d.ts +2 -2
  133. package/dist/tools/subscribe/utils.d.ts.map +1 -1
  134. package/dist/tools/testing.d.ts.map +1 -1
  135. package/dist/tools/tests/utils.d.ts +2 -6
  136. package/dist/tools/tests/utils.d.ts.map +1 -1
  137. package/dist/worker/index.js +3 -3
  138. package/dist/worker/index.js.map +1 -1
  139. package/package.json +23 -4
  140. package/src/better-auth/auth/client.ts +169 -0
  141. package/src/better-auth/auth/react.tsx +105 -0
  142. package/src/better-auth/auth/server.ts +250 -0
  143. package/src/better-auth/auth/tests/client.test.ts +249 -0
  144. package/src/better-auth/auth/tests/server.test.ts +226 -0
  145. package/src/browser/auth/PasskeyAuth.ts +2 -2
  146. package/src/browser/createBrowserContext.ts +2 -2
  147. package/src/browser/tests/PasskeyAuth.test.ts +2 -2
  148. package/src/inspector/custom-element.tsx +2 -2
  149. package/src/inspector/viewer/new-app.tsx +1 -1
  150. package/src/media/create-image.test.ts +7 -7
  151. package/src/media/create-image.ts +5 -3
  152. package/src/media/index.ts +1 -1
  153. package/src/media/utils.test.ts +72 -66
  154. package/src/media/utils.ts +9 -6
  155. package/src/prosemirror/lib/plugin.ts +1 -1
  156. package/src/prosemirror/lib/sync.ts +1 -1
  157. package/src/prosemirror/tests/plugin.test.ts +4 -4
  158. package/src/react/media/image.tsx +2 -2
  159. package/src/react/tests/media/image.test.tsx +52 -32
  160. package/src/react-core/hooks.ts +11 -5
  161. package/src/react-core/tests/useAccount.test.ts +16 -22
  162. package/src/react-core/tests/useCoState.test.ts +19 -19
  163. package/src/react-core/tests/useInboxSender.test.ts +5 -2
  164. package/src/react-core/tests/usePassPhraseAuth.test.ts +6 -6
  165. package/src/react-native-core/media/image.tsx +1 -1
  166. package/src/svelte/jazz.class.svelte.ts +1 -1
  167. package/src/svelte/media/image.svelte +3 -9
  168. package/src/svelte/media/image.types.ts +7 -0
  169. package/src/svelte/tests/media/image.svelte.test.ts +34 -32
  170. package/src/tools/auth/DemoAuth.ts +2 -2
  171. package/src/tools/auth/PassphraseAuth.ts +2 -2
  172. package/src/tools/auth/clerk/index.ts +2 -2
  173. package/src/tools/auth/clerk/tests/JazzClerkAuth.test.ts +1 -1
  174. package/src/tools/coValues/CoFieldInit.ts +20 -0
  175. package/src/tools/coValues/CoValueBase.ts +40 -60
  176. package/src/tools/coValues/account.ts +311 -232
  177. package/src/tools/coValues/coFeed.ts +185 -153
  178. package/src/tools/coValues/coList.ts +507 -334
  179. package/src/tools/coValues/coMap.ts +434 -286
  180. package/src/tools/coValues/coPlainText.ts +94 -110
  181. package/src/tools/coValues/deepLoading.ts +13 -13
  182. package/src/tools/coValues/group.ts +100 -114
  183. package/src/tools/coValues/inbox.ts +16 -14
  184. package/src/tools/coValues/interfaces.ts +49 -31
  185. package/src/tools/coValues/profile.ts +8 -6
  186. package/src/tools/coValues/request.ts +9 -9
  187. package/src/tools/coValues/schemaUnion.ts +11 -5
  188. package/src/tools/exports.ts +1 -1
  189. package/src/tools/implementation/ContextManager.ts +4 -4
  190. package/src/tools/implementation/anonymousJazzAgent.ts +2 -1
  191. package/src/tools/implementation/createContext.ts +1 -1
  192. package/src/tools/implementation/devtoolsFormatters.ts +9 -9
  193. package/src/tools/implementation/invites.ts +2 -2
  194. package/src/tools/implementation/schema.ts +7 -7
  195. package/src/tools/implementation/symbols.ts +3 -0
  196. package/src/tools/implementation/zodSchema/schemaTypes/AccountSchema.ts +2 -2
  197. package/src/tools/implementation/zodSchema/schemaTypes/CoFeedSchema.ts +11 -2
  198. package/src/tools/implementation/zodSchema/schemaTypes/CoListSchema.ts +18 -7
  199. package/src/tools/implementation/zodSchema/schemaTypes/CoMapSchema.ts +17 -7
  200. package/src/tools/implementation/zodSchema/schemaTypes/CoRecordSchema.ts +20 -11
  201. package/src/tools/implementation/zodSchema/schemaTypes/FileStreamSchema.ts +19 -2
  202. package/src/tools/implementation/zodSchema/schemaTypes/PlainTextSchema.ts +6 -0
  203. package/src/tools/implementation/zodSchema/schemaTypes/RichTextSchema.ts +6 -0
  204. package/src/tools/implementation/zodSchema/typeConverters/{CoFieldInit.ts → CoFieldSchemaInit.ts} +11 -11
  205. package/src/tools/implementation/zodSchema/typeConverters/InstanceOfSchema.ts +4 -4
  206. package/src/tools/implementation/zodSchema/typeConverters/InstanceOfSchemaCoValuesNullable.ts +4 -4
  207. package/src/tools/implementation/zodSchema/zodCo.ts +3 -3
  208. package/src/tools/internal.ts +2 -1
  209. package/src/tools/lib/migration.ts +5 -5
  210. package/src/tools/subscribe/SubscriptionScope.ts +32 -24
  211. package/src/tools/subscribe/index.ts +4 -4
  212. package/src/tools/subscribe/utils.ts +11 -11
  213. package/src/tools/testing.ts +17 -13
  214. package/src/tools/tests/ContextManager.test.ts +70 -59
  215. package/src/tools/tests/PassphraseAuth.test.ts +2 -2
  216. package/src/tools/tests/account.test.ts +188 -67
  217. package/src/tools/tests/coDiscriminatedUnion.test-d.ts +12 -6
  218. package/src/tools/tests/coDiscriminatedUnion.test.ts +26 -17
  219. package/src/tools/tests/coFeed.test-d.ts +18 -17
  220. package/src/tools/tests/coFeed.test.ts +108 -97
  221. package/src/tools/tests/coList.test-d.ts +18 -23
  222. package/src/tools/tests/coList.test.ts +350 -165
  223. package/src/tools/tests/coMap.record.test-d.ts +9 -13
  224. package/src/tools/tests/coMap.record.test.ts +37 -23
  225. package/src/tools/tests/coMap.test-d.ts +43 -21
  226. package/src/tools/tests/coMap.test.ts +459 -182
  227. package/src/tools/tests/coOptional.test.ts +28 -13
  228. package/src/tools/tests/coPlainText.test.ts +15 -15
  229. package/src/tools/tests/createContext.test.ts +14 -14
  230. package/src/tools/tests/deepLoading.test.ts +95 -94
  231. package/src/tools/tests/exportImport.test.ts +61 -41
  232. package/src/tools/tests/groupsAndAccounts.test.ts +333 -116
  233. package/src/tools/tests/inbox.test.ts +22 -17
  234. package/src/tools/tests/interfaces.test.ts +12 -11
  235. package/src/tools/tests/invites.test.ts +6 -4
  236. package/src/tools/tests/load.test.ts +20 -18
  237. package/src/tools/tests/patterns/notifications.test.ts +7 -7
  238. package/src/tools/tests/patterns/quest.test.ts +3 -3
  239. package/src/tools/tests/patterns/requestToJoin.test.ts +22 -22
  240. package/src/tools/tests/request.test.ts +38 -39
  241. package/src/tools/tests/schemaUnion.test.ts +64 -10
  242. package/src/tools/tests/subscribe.test.ts +64 -64
  243. package/src/tools/tests/testing.test.ts +7 -11
  244. package/src/tools/tests/utils.ts +3 -3
  245. package/src/tools/tests/zod.test.ts +3 -3
  246. package/src/worker/index.ts +3 -3
  247. package/tsup.config.ts +9 -0
  248. package/dist/chunk-LZOF6WP5.js.map +0 -1
  249. package/dist/media/chunk-E5J3WLQW.js.map +0 -1
  250. package/dist/tools/implementation/zodSchema/typeConverters/CoFieldInit.d.ts.map +0 -1
@@ -12,10 +12,10 @@ import React, {
12
12
  useSyncExternalStore
13
13
  } from "react";
14
14
  import {
15
- Account,
15
+ Account as Account13,
16
16
  InboxSender,
17
- SubscriptionScope,
18
- coValueClassFromCoValueClassOrSchema
17
+ SubscriptionScope as SubscriptionScope2,
18
+ coValueClassFromCoValueClassOrSchema as coValueClassFromCoValueClassOrSchema2
19
19
  } from "jazz-tools";
20
20
 
21
21
  // src/react-core/utils.ts
@@ -27,6 +27,4652 @@ function getCurrentAccountFromContextManager(contextManager) {
27
27
  return "me" in context ? context.me : context.guest;
28
28
  }
29
29
 
30
+ // src/tools/coValues/interfaces.ts
31
+ function isCoValueClass(value) {
32
+ return typeof value === "function" && value.fromRaw !== void 0;
33
+ }
34
+ function loadCoValueWithoutMe(cls, id, options) {
35
+ return loadCoValue(cls, id, {
36
+ ...options,
37
+ loadAs: options?.loadAs ?? activeAccountContext.get()
38
+ });
39
+ }
40
+ function loadCoValue(cls, id, options) {
41
+ return new Promise((resolve) => {
42
+ subscribeToCoValue(
43
+ cls,
44
+ id,
45
+ {
46
+ resolve: options.resolve,
47
+ loadAs: options.loadAs,
48
+ syncResolution: true,
49
+ skipRetry: options.skipRetry,
50
+ onUnavailable: () => {
51
+ resolve(null);
52
+ },
53
+ onUnauthorized: () => {
54
+ resolve(null);
55
+ }
56
+ },
57
+ (value, unsubscribe) => {
58
+ resolve(value);
59
+ unsubscribe();
60
+ }
61
+ );
62
+ });
63
+ }
64
+ async function ensureCoValueLoaded(existing, options) {
65
+ const response = await loadCoValue(
66
+ existing.constructor,
67
+ existing.$jazz.id,
68
+ {
69
+ loadAs: existing.$jazz.loadedAs,
70
+ resolve: options?.resolve
71
+ }
72
+ );
73
+ if (!response) {
74
+ throw new Error("Failed to deeply load CoValue " + existing.$jazz.id);
75
+ }
76
+ return response;
77
+ }
78
+ function parseSubscribeRestArgs(args) {
79
+ if (args.length === 2) {
80
+ if (typeof args[0] === "object" && args[0] && typeof args[1] === "function") {
81
+ return {
82
+ options: {
83
+ resolve: args[0].resolve,
84
+ loadAs: args[0].loadAs,
85
+ onUnauthorized: args[0].onUnauthorized,
86
+ onUnavailable: args[0].onUnavailable
87
+ },
88
+ listener: args[1]
89
+ };
90
+ } else {
91
+ throw new Error("Invalid arguments");
92
+ }
93
+ } else {
94
+ if (typeof args[0] === "function") {
95
+ return { options: {}, listener: args[0] };
96
+ } else {
97
+ throw new Error("Invalid arguments");
98
+ }
99
+ }
100
+ }
101
+ function subscribeToCoValueWithoutMe(cls, id, options, listener) {
102
+ return subscribeToCoValue(
103
+ cls,
104
+ id,
105
+ {
106
+ ...options,
107
+ loadAs: options.loadAs ?? activeAccountContext.get()
108
+ },
109
+ listener
110
+ );
111
+ }
112
+ function subscribeToCoValue(cls, id, options, listener) {
113
+ const loadAs = options.loadAs ?? activeAccountContext.get();
114
+ const node = "node" in loadAs ? loadAs.node : loadAs.$jazz.localNode;
115
+ const resolve = options.resolve ?? true;
116
+ let unsubscribed = false;
117
+ const rootNode = new SubscriptionScope(
118
+ node,
119
+ resolve,
120
+ id,
121
+ {
122
+ ref: cls,
123
+ optional: false
124
+ },
125
+ options.skipRetry
126
+ );
127
+ const handleUpdate = (value) => {
128
+ if (unsubscribed) return;
129
+ if (value.type === "unavailable") {
130
+ options.onUnavailable?.();
131
+ console.error(value.toString());
132
+ } else if (value.type === "unauthorized") {
133
+ options.onUnauthorized?.();
134
+ console.error(value.toString());
135
+ } else if (value.type === "loaded") {
136
+ listener(value.value, unsubscribe);
137
+ }
138
+ };
139
+ let shouldDefer = !options.syncResolution;
140
+ rootNode.setListener((value) => {
141
+ if (shouldDefer) {
142
+ shouldDefer = false;
143
+ Promise.resolve().then(() => {
144
+ handleUpdate(value);
145
+ });
146
+ } else {
147
+ handleUpdate(value);
148
+ }
149
+ });
150
+ function unsubscribe() {
151
+ unsubscribed = true;
152
+ rootNode.destroy();
153
+ }
154
+ return unsubscribe;
155
+ }
156
+ function subscribeToExistingCoValue(existing, options, listener) {
157
+ return subscribeToCoValue(
158
+ existing.constructor,
159
+ existing.$jazz.id,
160
+ {
161
+ loadAs: existing.$jazz.loadedAs,
162
+ resolve: options?.resolve,
163
+ onUnavailable: options?.onUnavailable,
164
+ onUnauthorized: options?.onUnauthorized
165
+ },
166
+ listener
167
+ );
168
+ }
169
+ function isAccountInstance(instance) {
170
+ if (typeof instance !== "object" || instance === null) {
171
+ return false;
172
+ }
173
+ return TypeSym in instance && instance[TypeSym] === "Account";
174
+ }
175
+ function parseCoValueCreateOptions(options) {
176
+ const Group16 = RegisteredSchemas["Group"];
177
+ if (!options) {
178
+ return { owner: Group16.create(), uniqueness: void 0 };
179
+ }
180
+ if (TypeSym in options) {
181
+ if (options[TypeSym] === "Account") {
182
+ return { owner: accountOrGroupToGroup(options), uniqueness: void 0 };
183
+ } else if (options[TypeSym] === "Group") {
184
+ return { owner: options, uniqueness: void 0 };
185
+ }
186
+ }
187
+ const uniqueness = options.unique ? { uniqueness: options.unique } : void 0;
188
+ const opts = {
189
+ owner: options.owner ? accountOrGroupToGroup(options.owner) : Group16.create(),
190
+ uniqueness
191
+ };
192
+ return opts;
193
+ }
194
+ function accountOrGroupToGroup(accountOrGroup) {
195
+ if (accountOrGroup[TypeSym] === "Group") {
196
+ return accountOrGroup;
197
+ }
198
+ return RegisteredSchemas["Group"].fromRaw(accountOrGroup.$jazz.raw);
199
+ }
200
+ function parseGroupCreateOptions(options) {
201
+ if (!options) {
202
+ return { owner: activeAccountContext.get() };
203
+ }
204
+ return TypeSym in options && isAccountInstance(options) ? { owner: options } : { owner: options.owner ?? activeAccountContext.get() };
205
+ }
206
+
207
+ // src/tools/coValues/CoValueBase.ts
208
+ import { ControlledAccount } from "cojson";
209
+ var CoValueBase = class {
210
+ /** @category Internals */
211
+ static fromRaw(raw) {
212
+ return new this({ fromRaw: raw });
213
+ }
214
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
215
+ toJSON() {
216
+ return {
217
+ id: this.$jazz.id,
218
+ type: this[TypeSym],
219
+ error: "unknown CoValue class"
220
+ };
221
+ }
222
+ [inspect2]() {
223
+ return this.toJSON();
224
+ }
225
+ };
226
+ var CoValueJazzApi = class {
227
+ constructor(coValue) {
228
+ this.coValue = coValue;
229
+ Object.defineProperty(this, "_instanceID", {
230
+ value: `instance-${Math.random().toString(36).slice(2)}`,
231
+ enumerable: false
232
+ });
233
+ }
234
+ /** @internal */
235
+ get localNode() {
236
+ return this.raw.core.node;
237
+ }
238
+ /** @private */
239
+ get loadedAs() {
240
+ const agent = this.localNode.getCurrentAgent();
241
+ if (agent instanceof ControlledAccount) {
242
+ return coValuesCache.get(
243
+ agent.account,
244
+ () => coValueClassFromCoValueClassOrSchema(
245
+ RegisteredSchemas["Account"]
246
+ ).fromRaw(agent.account)
247
+ );
248
+ }
249
+ return new AnonymousJazzAgent2(this.localNode);
250
+ }
251
+ };
252
+
253
+ // src/tools/implementation/inspect.ts
254
+ var inspect2 = Symbol.for("nodejs.util.inspect.custom");
255
+
256
+ // src/tools/implementation/symbols.ts
257
+ var SchemaInit = "$SchemaInit$";
258
+ var ItemsSym = "$items$";
259
+ var TypeSym = "$type$";
260
+
261
+ // src/tools/coValues/registeredSchemas.ts
262
+ var RegisteredSchemas = {};
263
+
264
+ // src/tools/coValues/coMap.ts
265
+ import {
266
+ cojsonInternals
267
+ } from "cojson";
268
+ var _CoMap = class _CoMap extends CoValueBase {
269
+ /** @internal */
270
+ constructor(options) {
271
+ super();
272
+ const proxy = new Proxy(this, CoMapProxyHandler);
273
+ if (options) {
274
+ if ("fromRaw" in options) {
275
+ Object.defineProperties(this, {
276
+ $jazz: {
277
+ value: new CoMapJazzApi(proxy, () => options.fromRaw),
278
+ enumerable: false
279
+ }
280
+ });
281
+ } else {
282
+ throw new Error("Invalid CoMap constructor arguments");
283
+ }
284
+ }
285
+ return proxy;
286
+ }
287
+ /**
288
+ * Create a new CoMap with the given initial values and owner.
289
+ *
290
+ * The owner (a Group or Account) determines access rights to the CoMap.
291
+ *
292
+ * The CoMap will immediately be persisted and synced to connected peers.
293
+ *
294
+ * @example
295
+ * ```ts
296
+ * const person = Person.create({
297
+ * name: "Alice",
298
+ * age: 42,
299
+ * pet: cat,
300
+ * }, { owner: friendGroup });
301
+ * ```
302
+ *
303
+ * @category Creation
304
+ *
305
+ * @deprecated Use `co.map(...).create`.
306
+ **/
307
+ static create(init, options) {
308
+ const instance = new this();
309
+ return _CoMap._createCoMap(instance, init, options);
310
+ }
311
+ /**
312
+ * Return a JSON representation of the `CoMap`
313
+ * @category Content
314
+ */
315
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
316
+ toJSON(_key, processedValues) {
317
+ const result = {};
318
+ for (const key of this.$jazz.raw.keys()) {
319
+ const tKey = key;
320
+ const descriptor = this.$jazz.getDescriptor(tKey);
321
+ if (!descriptor) {
322
+ continue;
323
+ }
324
+ if (descriptor == "json" || "encoded" in descriptor) {
325
+ result[key] = this.$jazz.raw.get(key);
326
+ } else if (isRefEncoded(descriptor)) {
327
+ const id = this.$jazz.raw.get(key);
328
+ if (processedValues?.includes(id) || id === this.$jazz.id) {
329
+ result[key] = { _circular: id };
330
+ continue;
331
+ }
332
+ const ref2 = this[tKey];
333
+ if (ref2 && typeof ref2 === "object" && "toJSON" in ref2 && typeof ref2.toJSON === "function") {
334
+ const jsonedRef = ref2.toJSON(tKey, [
335
+ ...processedValues || [],
336
+ this.$jazz.id
337
+ ]);
338
+ result[key] = jsonedRef;
339
+ }
340
+ } else {
341
+ result[key] = void 0;
342
+ }
343
+ }
344
+ return result;
345
+ }
346
+ [inspect2]() {
347
+ return this.toJSON();
348
+ }
349
+ /**
350
+ * @internal
351
+ */
352
+ static _createCoMap(instance, init, options) {
353
+ const { owner, uniqueness } = parseCoValueCreateOptions(options);
354
+ Object.defineProperties(instance, {
355
+ $jazz: {
356
+ value: new CoMapJazzApi(instance, () => raw),
357
+ enumerable: false
358
+ }
359
+ });
360
+ const raw = _CoMap.rawFromInit(instance, init, owner, uniqueness);
361
+ return instance;
362
+ }
363
+ /**
364
+ * Create a new `RawCoMap` from an initialization object
365
+ * @internal
366
+ */
367
+ static rawFromInit(instance, init, owner, uniqueness) {
368
+ const rawOwner = owner.$jazz.raw;
369
+ const rawInit = {};
370
+ if (init)
371
+ for (const key of Object.keys(init)) {
372
+ const initValue = init[key];
373
+ const descriptor = instance.$jazz.getDescriptor(key);
374
+ if (!descriptor) {
375
+ continue;
376
+ }
377
+ if (descriptor === "json") {
378
+ rawInit[key] = initValue;
379
+ } else if (isRefEncoded(descriptor)) {
380
+ if (initValue != null) {
381
+ let refId = initValue.$jazz?.id;
382
+ if (!refId) {
383
+ const coValue = instantiateRefEncodedWithInit(
384
+ descriptor,
385
+ initValue,
386
+ owner
387
+ );
388
+ refId = coValue.$jazz.id;
389
+ }
390
+ rawInit[key] = refId;
391
+ }
392
+ } else if ("encoded" in descriptor) {
393
+ rawInit[key] = descriptor.encoded.encode(
394
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
395
+ initValue
396
+ );
397
+ }
398
+ }
399
+ return rawOwner.createMap(rawInit, null, "private", uniqueness);
400
+ }
401
+ /**
402
+ * Declare a Record-like CoMap schema, by extending `CoMap.Record(...)` and passing the value schema using `co`. Keys are always `string`.
403
+ *
404
+ * @example
405
+ * ```ts
406
+ * import { coField, CoMap } from "jazz-tools";
407
+ *
408
+ * class ColorToFruitMap extends CoMap.Record(
409
+ * coField.ref(Fruit)
410
+ * ) {}
411
+ *
412
+ * // assume we have map: ColorToFruitMap
413
+ * // and strawberry: Fruit
414
+ * map["red"] = strawberry;
415
+ * ```
416
+ *
417
+ * @category Declaration
418
+ */
419
+ static Record(value) {
420
+ var _a2, _b;
421
+ class RecordLikeCoMap extends (_b = _CoMap, _a2 = ItemsSym, _b) {
422
+ constructor() {
423
+ super(...arguments);
424
+ this[_a2] = value;
425
+ }
426
+ }
427
+ return RecordLikeCoMap;
428
+ }
429
+ /**
430
+ * Load a `CoMap` with a given ID, as a given account.
431
+ *
432
+ * `depth` specifies which (if any) fields that reference other CoValues to load as well before resolving.
433
+ * The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth.
434
+ *
435
+ * You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues.
436
+ *
437
+ * Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.
438
+ *
439
+ * @example
440
+ * ```ts
441
+ * const person = await Person.load(
442
+ * "co_zdsMhHtfG6VNKt7RqPUPvUtN2Ax",
443
+ * { pet: {} }
444
+ * );
445
+ * ```
446
+ *
447
+ * @category Subscription & Loading
448
+ *
449
+ * @deprecated Use `co.map(...).load` instead.
450
+ */
451
+ static load(id, options) {
452
+ return loadCoValueWithoutMe(this, id, options);
453
+ }
454
+ static subscribe(id, ...args) {
455
+ const { options, listener } = parseSubscribeRestArgs(args);
456
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
457
+ }
458
+ /** @deprecated Use `CoMap.upsertUnique` and `CoMap.loadUnique` instead. */
459
+ static findUnique(unique, ownerID, as) {
460
+ return _CoMap._findUnique(unique, ownerID, as);
461
+ }
462
+ /** @internal */
463
+ static _findUnique(unique, ownerID, as) {
464
+ as ||= activeAccountContext.get();
465
+ const header = {
466
+ type: "comap",
467
+ ruleset: {
468
+ type: "ownedByGroup",
469
+ group: ownerID
470
+ },
471
+ meta: null,
472
+ uniqueness: unique
473
+ };
474
+ const crypto = as[TypeSym] === "Anonymous" ? as.node.crypto : as.$jazz.localNode.crypto;
475
+ return cojsonInternals.idforHeader(header, crypto);
476
+ }
477
+ /**
478
+ * Given some data, updates an existing CoMap or initialises a new one if none exists.
479
+ *
480
+ * Note: This method respects resolve options, and thus can return `null` if the references cannot be resolved.
481
+ *
482
+ * @example
483
+ * ```ts
484
+ * const activeEvent = await Event.upsertUnique(
485
+ * sourceData.identifier,
486
+ * workspace.id,
487
+ * {
488
+ * title: sourceData.title,
489
+ * identifier: sourceData.identifier,
490
+ * external_id: sourceData._id,
491
+ * },
492
+ * workspace
493
+ * );
494
+ * ```
495
+ *
496
+ * @param options The options for creating or loading the CoMap. This includes the intended state of the CoMap, its unique identifier, its owner, and the references to resolve.
497
+ * @returns Either an existing & modified CoMap, or a new initialised CoMap if none exists.
498
+ * @category Subscription & Loading
499
+ *
500
+ * @deprecated Use `co.map(...).upsertUnique` instead.
501
+ */
502
+ static async upsertUnique(options) {
503
+ const mapId = _CoMap._findUnique(
504
+ options.unique,
505
+ options.owner.$jazz.id,
506
+ options.owner.$jazz.loadedAs
507
+ );
508
+ let map = await loadCoValueWithoutMe(this, mapId, {
509
+ ...options,
510
+ loadAs: options.owner.$jazz.loadedAs,
511
+ skipRetry: true
512
+ });
513
+ if (!map) {
514
+ const instance = new this();
515
+ map = _CoMap._createCoMap(instance, options.value, {
516
+ owner: options.owner,
517
+ unique: options.unique
518
+ });
519
+ } else {
520
+ map.$jazz.applyDiff(
521
+ options.value
522
+ );
523
+ }
524
+ return await loadCoValueWithoutMe(this, mapId, {
525
+ ...options,
526
+ loadAs: options.owner.$jazz.loadedAs,
527
+ skipRetry: true
528
+ });
529
+ }
530
+ /**
531
+ * Loads a CoMap by its unique identifier and owner's ID.
532
+ * @param unique The unique identifier of the CoMap to load.
533
+ * @param ownerID The ID of the owner of the CoMap.
534
+ * @param options Additional options for loading the CoMap.
535
+ * @returns The loaded CoMap, or null if unavailable.
536
+ *
537
+ * @deprecated Use `co.map(...).loadUnique` instead.
538
+ */
539
+ static loadUnique(unique, ownerID, options) {
540
+ return loadCoValueWithoutMe(
541
+ this,
542
+ _CoMap._findUnique(unique, ownerID, options?.loadAs),
543
+ { ...options, skipRetry: true }
544
+ );
545
+ }
546
+ };
547
+ _CoMap.prototype[TypeSym] = "CoMap";
548
+ var CoMap = _CoMap;
549
+ var CoMapJazzApi = class extends CoValueJazzApi {
550
+ constructor(coMap, getRaw) {
551
+ super(coMap);
552
+ this.coMap = coMap;
553
+ this.getRaw = getRaw;
554
+ }
555
+ /**
556
+ * The ID of this `CoMap`
557
+ * @category Content
558
+ */
559
+ get id() {
560
+ return this.raw.id;
561
+ }
562
+ get owner() {
563
+ return getCoValueOwner(this.coMap);
564
+ }
565
+ /**
566
+ * Check if a key is defined in the CoMap.
567
+ *
568
+ * This check does not load the referenced value or validate permissions.
569
+ *
570
+ * @param key The key to check
571
+ * @returns True if the key is defined, false otherwise
572
+ * @category Content
573
+ */
574
+ has(key) {
575
+ const entry = this.raw.getRaw(key);
576
+ return entry?.change !== void 0 && entry.change.op !== "del";
577
+ }
578
+ /**
579
+ * Set a value on the CoMap
580
+ *
581
+ * @param key The key to set
582
+ * @param value The value to set
583
+ *
584
+ * @category Content
585
+ */
586
+ set(key, value) {
587
+ const descriptor = this.getDescriptor(key);
588
+ if (!descriptor) {
589
+ throw Error(`Cannot set unknown key ${key}`);
590
+ }
591
+ let refId = value?.$jazz?.id;
592
+ if (descriptor === "json") {
593
+ this.raw.set(key, value);
594
+ } else if ("encoded" in descriptor) {
595
+ this.raw.set(key, descriptor.encoded.encode(value));
596
+ } else if (isRefEncoded(descriptor)) {
597
+ if (value === void 0) {
598
+ if (!descriptor.optional) {
599
+ throw Error(`Cannot set required reference ${key} to undefined`);
600
+ }
601
+ this.raw.set(key, null);
602
+ } else {
603
+ if (!refId) {
604
+ const coValue = instantiateRefEncodedWithInit(
605
+ descriptor,
606
+ value,
607
+ this.owner
608
+ );
609
+ refId = coValue.$jazz.id;
610
+ }
611
+ this.raw.set(key, refId);
612
+ }
613
+ }
614
+ }
615
+ /**
616
+ * Delete a value from a CoMap.
617
+ *
618
+ * For record-like CoMaps (created with `co.record`), any string key can be deleted.
619
+ * For struct-like CoMaps (created with `co.map`), only optional properties can be deleted.
620
+ *
621
+ * @param key The key to delete
622
+ *
623
+ * @category Content
624
+ */
625
+ delete(key) {
626
+ this.raw.delete(key);
627
+ }
628
+ /**
629
+ * Modify the `CoMap` to match another map.
630
+ *
631
+ * The new values are assigned to the CoMap, overwriting existing values
632
+ * when the property already exists.
633
+ *
634
+ * @param newValues - The new values to apply to the CoMap. For collaborative values,
635
+ * both CoValues and JSON values are supported.
636
+ * @returns The modified CoMap.
637
+ *
638
+ * @category Content
639
+ */
640
+ applyDiff(newValues) {
641
+ for (const key in newValues) {
642
+ if (Object.prototype.hasOwnProperty.call(newValues, key)) {
643
+ const tKey = key;
644
+ const descriptor = this.getDescriptor(key);
645
+ if (!descriptor) continue;
646
+ const newValue = newValues[tKey];
647
+ const currentValue = this.coMap[tKey];
648
+ if (descriptor === "json" || "encoded" in descriptor) {
649
+ if (currentValue !== newValue) {
650
+ this.set(tKey, newValue);
651
+ }
652
+ } else if (isRefEncoded(descriptor)) {
653
+ const currentId = currentValue?.$jazz.id;
654
+ let newId = newValue?.$jazz?.id;
655
+ if (currentId !== newId) {
656
+ this.set(tKey, newValue);
657
+ }
658
+ }
659
+ }
660
+ }
661
+ return this.coMap;
662
+ }
663
+ /**
664
+ * Given an already loaded `CoMap`, ensure that the specified fields are loaded to the specified depth.
665
+ *
666
+ * Works like `CoMap.load()`, but you don't need to pass the ID or the account to load as again.
667
+ *
668
+ * @category Subscription & Loading
669
+ */
670
+ ensureLoaded(options) {
671
+ return ensureCoValueLoaded(this.coMap, options);
672
+ }
673
+ subscribe(...args) {
674
+ const { options, listener } = parseSubscribeRestArgs(args);
675
+ return subscribeToExistingCoValue(this.coMap, options, listener);
676
+ }
677
+ /**
678
+ * Wait for the `CoMap` to be uploaded to the other peers.
679
+ *
680
+ * @category Subscription & Loading
681
+ */
682
+ async waitForSync(options) {
683
+ await this.raw.core.waitForSync(options);
684
+ }
685
+ /**
686
+ * Get the descriptor for a given key
687
+ * @internal
688
+ */
689
+ getDescriptor(key) {
690
+ return this.schema?.[key] || this.schema?.[ItemsSym];
691
+ }
692
+ /**
693
+ * If property `prop` is a `coField.ref(...)`, you can use `coMap.$jazz.refs.prop` to access
694
+ * the `Ref` instead of the potentially loaded/null value.
695
+ *
696
+ * This allows you to always get the ID or load the value manually.
697
+ *
698
+ * @example
699
+ * ```ts
700
+ * person.$jazz.refs.pet.id; // => ID<Animal>
701
+ * person.$jazz.refs.pet.value;
702
+ * // => Animal | null
703
+ * const pet = await person.$jazz.refs.pet.load();
704
+ * ```
705
+ *
706
+ * @category Content
707
+ **/
708
+ get refs() {
709
+ return makeRefs(
710
+ this.coMap,
711
+ (key) => this.raw.get(key),
712
+ () => {
713
+ const keys = this.raw.keys().filter((key) => {
714
+ const descriptor = this.getDescriptor(key);
715
+ return descriptor && descriptor !== "json" && isRefEncoded(descriptor);
716
+ });
717
+ return keys;
718
+ },
719
+ this.loadedAs,
720
+ (key) => this.getDescriptor(key)
721
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
722
+ );
723
+ }
724
+ /**
725
+ * Get the edits made to the CoMap.
726
+ *
727
+ * @category Collaboration
728
+ */
729
+ getEdits() {
730
+ const map = this.coMap;
731
+ return new Proxy(
732
+ {},
733
+ {
734
+ get(_target, key) {
735
+ const rawEdit = map.$jazz.raw.lastEditAt(key);
736
+ if (!rawEdit) return void 0;
737
+ const descriptor = map.$jazz.getDescriptor(key);
738
+ if (!descriptor) return void 0;
739
+ return {
740
+ ...getEditFromRaw(map, rawEdit, descriptor, key),
741
+ get all() {
742
+ return [...map.$jazz.raw.editsAt(key)].map(
743
+ (rawEdit2) => getEditFromRaw(map, rawEdit2, descriptor, key)
744
+ );
745
+ }
746
+ };
747
+ },
748
+ ownKeys(_target) {
749
+ return map.$jazz.raw.keys();
750
+ },
751
+ getOwnPropertyDescriptor(target, key) {
752
+ return {
753
+ value: Reflect.get(target, key),
754
+ writable: false,
755
+ enumerable: true,
756
+ configurable: true
757
+ };
758
+ }
759
+ }
760
+ );
761
+ }
762
+ /** @internal */
763
+ get raw() {
764
+ return this.getRaw();
765
+ }
766
+ /**
767
+ * The timestamp of the creation time of the CoMap
768
+ *
769
+ * @category Content
770
+ */
771
+ get createdAt() {
772
+ return this.raw.earliestTxMadeAt ?? Number.MAX_SAFE_INTEGER;
773
+ }
774
+ /**
775
+ * The timestamp of the last updated time of the CoMap
776
+ *
777
+ * @category Content
778
+ */
779
+ get lastUpdatedAt() {
780
+ return this.raw.latestTxMadeAt;
781
+ }
782
+ /** @internal */
783
+ get schema() {
784
+ return this.coMap.constructor._schema;
785
+ }
786
+ };
787
+ var CoMapProxyHandler = {
788
+ get(target, key, receiver) {
789
+ if (key === "_schema") {
790
+ return Reflect.get(target, key);
791
+ } else if (key in target) {
792
+ return Reflect.get(target, key, receiver);
793
+ } else {
794
+ if (typeof key !== "string") {
795
+ return void 0;
796
+ }
797
+ const descriptor = target.$jazz.getDescriptor(key);
798
+ if (!descriptor) {
799
+ return void 0;
800
+ }
801
+ const raw = target.$jazz.raw.get(key);
802
+ if (descriptor === "json") {
803
+ return raw;
804
+ } else if ("encoded" in descriptor) {
805
+ return raw === void 0 ? void 0 : descriptor.encoded.decode(raw);
806
+ } else if (isRefEncoded(descriptor)) {
807
+ return raw === void 0 || raw === null ? void 0 : accessChildByKey(target, raw, key);
808
+ }
809
+ }
810
+ },
811
+ set(target, key, value, receiver) {
812
+ if (typeof key === "string" && typeof value === "object" && value !== null && SchemaInit in value) {
813
+ target.constructor._schema ||= {};
814
+ target.constructor._schema[key] = value[SchemaInit];
815
+ return true;
816
+ }
817
+ const descriptor = target.$jazz.getDescriptor(key);
818
+ if (!descriptor) return false;
819
+ if (typeof key === "string") {
820
+ throw Error("Cannot update a CoMap directly. Use `$jazz.set` instead.");
821
+ } else {
822
+ return Reflect.set(target, key, value, receiver);
823
+ }
824
+ },
825
+ defineProperty(target, key, attributes) {
826
+ if ("value" in attributes && typeof attributes.value === "object" && SchemaInit in attributes.value) {
827
+ target.constructor._schema ||= {};
828
+ target.constructor._schema[key] = attributes.value[SchemaInit];
829
+ return true;
830
+ } else {
831
+ return Reflect.defineProperty(target, key, attributes);
832
+ }
833
+ },
834
+ ownKeys(target) {
835
+ const keys = Reflect.ownKeys(target).filter((k) => k !== ItemsSym);
836
+ for (const key of target.$jazz.raw.keys()) {
837
+ if (!keys.includes(key)) {
838
+ keys.push(key);
839
+ }
840
+ }
841
+ return keys;
842
+ },
843
+ getOwnPropertyDescriptor(target, key) {
844
+ if (key in target) {
845
+ return Reflect.getOwnPropertyDescriptor(target, key);
846
+ } else {
847
+ const descriptor = target.$jazz.getDescriptor(key);
848
+ if (descriptor || key in target.$jazz.raw.latest) {
849
+ return {
850
+ enumerable: true,
851
+ configurable: true,
852
+ writable: true
853
+ };
854
+ }
855
+ }
856
+ },
857
+ has(target, key) {
858
+ const descriptor = target.$jazz?.getDescriptor(key);
859
+ if (target.$jazz?.raw && typeof key === "string" && descriptor) {
860
+ return target.$jazz.raw.get(key) !== void 0;
861
+ } else {
862
+ return Reflect.has(target, key);
863
+ }
864
+ },
865
+ deleteProperty(target, key) {
866
+ const descriptor = target.$jazz.getDescriptor(key);
867
+ if (typeof key === "string" && descriptor) {
868
+ throw Error(
869
+ "Cannot delete a CoMap property directly. Use `$jazz.delete` instead."
870
+ );
871
+ } else {
872
+ return Reflect.deleteProperty(target, key);
873
+ }
874
+ }
875
+ };
876
+ RegisteredSchemas["CoMap"] = CoMap;
877
+ function getEditFromRaw(target, rawEdit, descriptor, key) {
878
+ return {
879
+ value: descriptor === "json" ? rawEdit.value : "encoded" in descriptor ? rawEdit.value === null || rawEdit.value === void 0 ? rawEdit.value : descriptor.encoded.decode(rawEdit.value) : accessChildById(target, rawEdit.value, descriptor),
880
+ ref: descriptor !== "json" && isRefEncoded(descriptor) ? new Ref(
881
+ rawEdit.value,
882
+ target.$jazz.loadedAs,
883
+ descriptor,
884
+ target
885
+ ) : void 0,
886
+ get by() {
887
+ return rawEdit.by && accessChildById(target, rawEdit.by, {
888
+ ref: Account,
889
+ optional: false
890
+ });
891
+ },
892
+ madeAt: rawEdit.at,
893
+ key
894
+ };
895
+ }
896
+
897
+ // src/tools/coValues/coList.ts
898
+ import { cojsonInternals as cojsonInternals2 } from "cojson";
899
+ import { calcPatch } from "fast-myers-diff";
900
+ var _CoList = class _CoList extends Array {
901
+ /**
902
+ * Declare a `CoList` by subclassing `CoList.Of(...)` and passing the item schema using `co`.
903
+ *
904
+ * @example
905
+ * ```ts
906
+ * class ColorList extends CoList.Of(
907
+ * coField.string
908
+ * ) {}
909
+ * class AnimalList extends CoList.Of(
910
+ * coField.ref(Animal)
911
+ * ) {}
912
+ * ```
913
+ *
914
+ * @category Declaration
915
+ */
916
+ static Of(item) {
917
+ var _a2, _b;
918
+ return class CoListOf extends (_b = _CoList, _a2 = coField.items, _b) {
919
+ constructor() {
920
+ super(...arguments);
921
+ this[_a2] = item;
922
+ }
923
+ };
924
+ }
925
+ /**
926
+ * @ignore
927
+ * @deprecated Use UPPERCASE `CoList.Of` instead! */
928
+ static of(..._args) {
929
+ throw new Error("Can't use Array.of with CoLists");
930
+ }
931
+ static get [(ItemsSym, Symbol.species)]() {
932
+ return Array;
933
+ }
934
+ constructor(options) {
935
+ super();
936
+ const proxy = new Proxy(this, CoListProxyHandler);
937
+ if (options && "fromRaw" in options) {
938
+ Object.defineProperties(this, {
939
+ $jazz: {
940
+ value: new CoListJazzApi(proxy, () => options.fromRaw),
941
+ enumerable: false
942
+ }
943
+ });
944
+ }
945
+ return proxy;
946
+ }
947
+ /**
948
+ * Create a new CoList with the given initial values and owner.
949
+ *
950
+ * The owner (a Group or Account) determines access rights to the CoMap.
951
+ *
952
+ * The CoList will immediately be persisted and synced to connected peers.
953
+ *
954
+ * @example
955
+ * ```ts
956
+ * const colours = ColorList.create(
957
+ * ["red", "green", "blue"],
958
+ * { owner: me }
959
+ * );
960
+ * const animals = AnimalList.create(
961
+ * [cat, dog, fish],
962
+ * { owner: me }
963
+ * );
964
+ * ```
965
+ *
966
+ * @category Creation
967
+ * @deprecated Use `co.list(...).create` instead.
968
+ **/
969
+ static create(items, options) {
970
+ const { owner, uniqueness } = parseCoValueCreateOptions(options);
971
+ const instance = new this();
972
+ Object.defineProperties(instance, {
973
+ $jazz: {
974
+ value: new CoListJazzApi(instance, () => raw),
975
+ enumerable: false
976
+ }
977
+ });
978
+ const raw = owner.$jazz.raw.createList(
979
+ toRawItems(items, instance.$jazz.schema[ItemsSym], owner),
980
+ null,
981
+ "private",
982
+ uniqueness
983
+ );
984
+ return instance;
985
+ }
986
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
987
+ toJSON(_key, seenAbove) {
988
+ const itemDescriptor = this.$jazz.schema[ItemsSym];
989
+ if (itemDescriptor === "json") {
990
+ return this.$jazz.raw.asArray();
991
+ } else if ("encoded" in itemDescriptor) {
992
+ return this.$jazz.raw.asArray().map((e) => itemDescriptor.encoded.encode(e));
993
+ } else if (isRefEncoded(itemDescriptor)) {
994
+ return this.map(
995
+ (item, idx) => seenAbove?.includes(item?.$jazz.id) ? { _circular: item.$jazz.id } : item?.toJSON(idx + "", [
996
+ ...seenAbove || [],
997
+ this.$jazz.id
998
+ ])
999
+ );
1000
+ } else {
1001
+ return [];
1002
+ }
1003
+ }
1004
+ [inspect2]() {
1005
+ return this.toJSON();
1006
+ }
1007
+ /** @category Internals */
1008
+ static fromRaw(raw) {
1009
+ return new this({ fromRaw: raw });
1010
+ }
1011
+ /** @internal */
1012
+ static schema(def) {
1013
+ this._schema ||= {};
1014
+ Object.assign(this._schema, def);
1015
+ }
1016
+ /**
1017
+ * Load a `CoList` with a given ID, as a given account.
1018
+ *
1019
+ * `depth` specifies if item CoValue references should be loaded as well before resolving.
1020
+ * The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth.
1021
+ *
1022
+ * You can pass `[]` or for shallowly loading only this CoList, or `[itemDepth]` for recursively loading referenced CoValues.
1023
+ *
1024
+ * Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.
1025
+ *
1026
+ * @example
1027
+ * ```ts
1028
+ * const animalsWithVets =
1029
+ * await ListOfAnimals.load(
1030
+ * "co_zdsMhHtfG6VNKt7RqPUPvUtN2Ax",
1031
+ * me,
1032
+ * [{ vet: {} }]
1033
+ * );
1034
+ * ```
1035
+ *
1036
+ * @category Subscription & Loading
1037
+ * @deprecated Use `co.list(...).load` instead.
1038
+ */
1039
+ static load(id, options) {
1040
+ return loadCoValueWithoutMe(this, id, options);
1041
+ }
1042
+ static subscribe(id, ...args) {
1043
+ const { options, listener } = parseSubscribeRestArgs(args);
1044
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
1045
+ }
1046
+ /** @deprecated Use `CoList.upsertUnique` and `CoList.loadUnique` instead. */
1047
+ static findUnique(unique, ownerID, as) {
1048
+ return _CoList._findUnique(unique, ownerID, as);
1049
+ }
1050
+ /** @internal */
1051
+ static _findUnique(unique, ownerID, as) {
1052
+ as ||= activeAccountContext.get();
1053
+ const header = {
1054
+ type: "colist",
1055
+ ruleset: {
1056
+ type: "ownedByGroup",
1057
+ group: ownerID
1058
+ },
1059
+ meta: null,
1060
+ uniqueness: unique
1061
+ };
1062
+ const crypto = as[TypeSym] === "Anonymous" ? as.node.crypto : as.$jazz.localNode.crypto;
1063
+ return cojsonInternals2.idforHeader(header, crypto);
1064
+ }
1065
+ /**
1066
+ * Given some data, updates an existing CoList or initialises a new one if none exists.
1067
+ *
1068
+ * Note: This method respects resolve options, and thus can return `null` if the references cannot be resolved.
1069
+ *
1070
+ * @example
1071
+ * ```ts
1072
+ * const activeItems = await ItemList.upsertUnique(
1073
+ * {
1074
+ * value: [item1, item2, item3],
1075
+ * unique: sourceData.identifier,
1076
+ * owner: workspace,
1077
+ * }
1078
+ * );
1079
+ * ```
1080
+ *
1081
+ * @param options The options for creating or loading the CoList. This includes the intended state of the CoList, its unique identifier, its owner, and the references to resolve.
1082
+ * @returns Either an existing & modified CoList, or a new initialised CoList if none exists.
1083
+ * @category Subscription & Loading
1084
+ */
1085
+ static async upsertUnique(options) {
1086
+ const listId = _CoList._findUnique(
1087
+ options.unique,
1088
+ options.owner.$jazz.id,
1089
+ options.owner.$jazz.loadedAs
1090
+ );
1091
+ let list = await loadCoValueWithoutMe(this, listId, {
1092
+ ...options,
1093
+ loadAs: options.owner.$jazz.loadedAs,
1094
+ skipRetry: true
1095
+ });
1096
+ if (!list) {
1097
+ list = this.create(options.value, {
1098
+ owner: options.owner,
1099
+ unique: options.unique
1100
+ });
1101
+ } else {
1102
+ list.$jazz.applyDiff(options.value);
1103
+ }
1104
+ return await loadCoValueWithoutMe(this, listId, {
1105
+ ...options,
1106
+ loadAs: options.owner.$jazz.loadedAs,
1107
+ skipRetry: true
1108
+ });
1109
+ }
1110
+ /**
1111
+ * Loads a CoList by its unique identifier and owner's ID.
1112
+ * @param unique The unique identifier of the CoList to load.
1113
+ * @param ownerID The ID of the owner of the CoList.
1114
+ * @param options Additional options for loading the CoList.
1115
+ * @returns The loaded CoList, or null if unavailable.
1116
+ */
1117
+ static loadUnique(unique, ownerID, options) {
1118
+ return loadCoValueWithoutMe(
1119
+ this,
1120
+ _CoList._findUnique(unique, ownerID, options?.loadAs),
1121
+ { ...options, skipRetry: true }
1122
+ );
1123
+ }
1124
+ // Override mutation methods defined on Array, as CoLists aren't meant to be mutated directly
1125
+ /**
1126
+ * @deprecated Use `.$jazz.push` instead.
1127
+ */
1128
+ push(...items) {
1129
+ throw new Error(
1130
+ "Cannot mutate a CoList directly. Use `.$jazz.push` instead."
1131
+ );
1132
+ }
1133
+ /**
1134
+ * @deprecated Use `.$jazz.unshift` instead.
1135
+ */
1136
+ unshift(...items) {
1137
+ throw new Error(
1138
+ "Cannot mutate a CoList directly. Use `.$jazz.unshift` instead."
1139
+ );
1140
+ }
1141
+ /**
1142
+ * @deprecated Use `.$jazz.pop` instead.
1143
+ */
1144
+ // @ts-expect-error
1145
+ pop(value) {
1146
+ throw new Error(
1147
+ "Cannot mutate a CoList directly. Use `.$jazz.pop` instead."
1148
+ );
1149
+ }
1150
+ /**
1151
+ * @deprecated Use `.$jazz.shift` instead.
1152
+ */
1153
+ // @ts-expect-error
1154
+ shift(value) {
1155
+ throw new Error(
1156
+ "Cannot mutate a CoList directly. Use `.$jazz.shift` instead."
1157
+ );
1158
+ }
1159
+ /**
1160
+ * @deprecated Use `.$jazz.splice` instead.
1161
+ */
1162
+ splice(start, deleteCount, ...items) {
1163
+ throw new Error(
1164
+ "Cannot mutate a CoList directly. Use `.$jazz.splice` instead."
1165
+ );
1166
+ }
1167
+ /**
1168
+ * @deprecated Use `.$jazz.set` instead.
1169
+ */
1170
+ copyWithin(target, start, end) {
1171
+ throw new Error(
1172
+ "Cannot mutate a CoList directly. Use `.$jazz.set` instead."
1173
+ );
1174
+ }
1175
+ /**
1176
+ * @deprecated Use `.$jazz.set` instead.
1177
+ */
1178
+ fill(value, start, end) {
1179
+ throw new Error(
1180
+ "Cannot mutate a CoList directly. Use `.$jazz.set` instead."
1181
+ );
1182
+ }
1183
+ /**
1184
+ * @deprecated Use `.toReversed` if you want a reversed copy, or `.$jazz.set` to mutate the CoList.
1185
+ */
1186
+ // @ts-expect-error
1187
+ reverse(value) {
1188
+ throw new Error(
1189
+ "Cannot mutate a CoList directly. Use `.toReversed` if you want a reversed copy, or `.$jazz.set` to mutate the CoList."
1190
+ );
1191
+ }
1192
+ /**
1193
+ * @deprecated Use `.toSorted()` if you want a sorted copy, or `.$jazz.set` to mutate the CoList.
1194
+ */
1195
+ sort(compareFn) {
1196
+ throw new Error(
1197
+ "Cannot mutate a CoList directly. Use `.toSorted` if you want a sorted copy, or `.$jazz.set` to mutate the CoList."
1198
+ );
1199
+ }
1200
+ };
1201
+ _CoList.prototype[TypeSym] = "CoList";
1202
+ var CoList = _CoList;
1203
+ var CoListJazzApi = class extends CoValueJazzApi {
1204
+ constructor(coList, getRaw) {
1205
+ super(coList);
1206
+ this.coList = coList;
1207
+ this.getRaw = getRaw;
1208
+ }
1209
+ /**
1210
+ * The ID of this `CoList`
1211
+ * @category Content
1212
+ */
1213
+ get id() {
1214
+ return this.raw.id;
1215
+ }
1216
+ /** @category Collaboration */
1217
+ get owner() {
1218
+ return getCoValueOwner(this.coList);
1219
+ }
1220
+ set(index, value) {
1221
+ const itemDescriptor = this.schema[ItemsSym];
1222
+ const rawValue = toRawItems([value], itemDescriptor, this.owner)[0];
1223
+ if (rawValue === null && !itemDescriptor.optional) {
1224
+ throw new Error(`Cannot set required reference ${index} to undefined`);
1225
+ }
1226
+ this.raw.replace(index, rawValue);
1227
+ }
1228
+ /**
1229
+ * Appends new elements to the end of an array, and returns the new length of the array.
1230
+ * @param items New elements to add to the array.
1231
+ *
1232
+ * @category Content
1233
+ */
1234
+ push(...items) {
1235
+ this.raw.appendItems(
1236
+ toRawItems(items, this.schema[ItemsSym], this.owner),
1237
+ void 0,
1238
+ "private"
1239
+ );
1240
+ return this.raw.entries().length;
1241
+ }
1242
+ /**
1243
+ * Inserts new elements at the start of an array, and returns the new length of the array.
1244
+ * @param items Elements to insert at the start of the array.
1245
+ *
1246
+ * @category Content
1247
+ */
1248
+ unshift(...items) {
1249
+ for (const item of toRawItems(
1250
+ items,
1251
+ this.schema[ItemsSym],
1252
+ this.owner
1253
+ )) {
1254
+ this.raw.prepend(item);
1255
+ }
1256
+ return this.raw.entries().length;
1257
+ }
1258
+ /**
1259
+ * Removes the last element from an array and returns it.
1260
+ * If the array is empty, undefined is returned and the array is not modified.
1261
+ *
1262
+ * @category Content
1263
+ */
1264
+ pop() {
1265
+ const last = this.coList[this.coList.length - 1];
1266
+ this.raw.delete(this.coList.length - 1);
1267
+ return last;
1268
+ }
1269
+ /**
1270
+ * Removes the first element from an array and returns it.
1271
+ * If the array is empty, undefined is returned and the array is not modified.
1272
+ *
1273
+ * @category Content
1274
+ */
1275
+ shift() {
1276
+ const first = this.coList[0];
1277
+ this.raw.delete(0);
1278
+ return first;
1279
+ }
1280
+ /**
1281
+ * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
1282
+ * @param start The zero-based location in the array from which to start removing elements.
1283
+ * @param deleteCount The number of elements to remove.
1284
+ * @param items Elements to insert into the array in place of the deleted elements.
1285
+ * @returns An array containing the elements that were deleted.
1286
+ *
1287
+ * @category Content
1288
+ */
1289
+ splice(start, deleteCount, ...items) {
1290
+ const deleted = this.coList.slice(start, start + deleteCount);
1291
+ for (let idxToDelete = start + deleteCount - 1; idxToDelete >= start; idxToDelete--) {
1292
+ this.raw.delete(idxToDelete);
1293
+ }
1294
+ const rawItems = toRawItems(
1295
+ items,
1296
+ this.schema[ItemsSym],
1297
+ this.owner
1298
+ );
1299
+ if (rawItems.length === 0) {
1300
+ return deleted;
1301
+ }
1302
+ if (rawItems.length === 1) {
1303
+ const item = rawItems[0];
1304
+ if (item === void 0) return deleted;
1305
+ if (start === 0) {
1306
+ this.raw.prepend(item);
1307
+ } else {
1308
+ this.raw.append(item, Math.max(start - 1, 0));
1309
+ }
1310
+ return deleted;
1311
+ }
1312
+ if (start === 0) {
1313
+ for (let i = rawItems.length - 1; i >= 0; i--) {
1314
+ const item = rawItems[i];
1315
+ if (item === void 0) continue;
1316
+ this.raw.prepend(item);
1317
+ }
1318
+ } else {
1319
+ let appendAfter = Math.max(start - 1, 0);
1320
+ for (const item of rawItems) {
1321
+ if (item === void 0) continue;
1322
+ this.raw.append(item, appendAfter);
1323
+ appendAfter++;
1324
+ }
1325
+ }
1326
+ return deleted;
1327
+ }
1328
+ remove(...args) {
1329
+ const predicate = args[0] instanceof Function ? args[0] : void 0;
1330
+ let indices = [];
1331
+ if (predicate) {
1332
+ for (let i = 0; i < this.coList.length; i++) {
1333
+ if (predicate(this.coList[i], i, this.coList)) {
1334
+ indices.push(i);
1335
+ }
1336
+ }
1337
+ } else {
1338
+ indices = args.filter((index) => index >= 0 && index < this.coList.length).sort((a, b) => a - b);
1339
+ }
1340
+ const deletedItems = indices.map((index) => this.coList[index]);
1341
+ for (const index of indices.reverse()) {
1342
+ this.raw.delete(index);
1343
+ }
1344
+ return deletedItems;
1345
+ }
1346
+ /**
1347
+ * Retains only the elements matching the predicate from the array.
1348
+ * @param predicate The predicate to match the elements to retain.
1349
+ * @returns The removed elements.
1350
+ *
1351
+ * @category Content
1352
+ */
1353
+ retain(predicate) {
1354
+ return this.remove((...args) => !predicate(...args));
1355
+ }
1356
+ /**
1357
+ * Modify the `CoList` to match another list, where the changes are managed internally.
1358
+ *
1359
+ * Changes are detected using `Object.is` for non-collaborative values and `$jazz.id` for collaborative values.
1360
+ *
1361
+ * @param result - The resolved list of items. For collaborative values, both CoValues and JSON values are supported.
1362
+ * @returns The modified CoList.
1363
+ *
1364
+ * @category Content
1365
+ */
1366
+ applyDiff(result) {
1367
+ const current = this.raw.asArray();
1368
+ const comparator = isRefEncoded(this.schema[ItemsSym]) ? (aIdx, bIdx) => {
1369
+ const oldCoValueId = current[aIdx]?.$jazz?.id;
1370
+ const newCoValueId = result[bIdx]?.$jazz?.id;
1371
+ const isSame = !!oldCoValueId && !!newCoValueId && oldCoValueId === newCoValueId;
1372
+ return isSame;
1373
+ } : void 0;
1374
+ const patches = [...calcPatch(current, result, comparator)];
1375
+ for (const [from, to, insert] of patches.reverse()) {
1376
+ this.splice(from, to - from, ...insert);
1377
+ }
1378
+ return this.coList;
1379
+ }
1380
+ /**
1381
+ * Given an already loaded `CoList`, ensure that items are loaded to the specified depth.
1382
+ *
1383
+ * Works like `CoList.load()`, but you don't need to pass the ID or the account to load as again.
1384
+ *
1385
+ * @category Subscription & Loading
1386
+ */
1387
+ ensureLoaded(options) {
1388
+ return ensureCoValueLoaded(this.coList, options);
1389
+ }
1390
+ subscribe(...args) {
1391
+ const { options, listener } = parseSubscribeRestArgs(args);
1392
+ return subscribeToExistingCoValue(this.coList, options, listener);
1393
+ }
1394
+ /**
1395
+ * Wait for the `CoList` to be uploaded to the other peers.
1396
+ *
1397
+ * @category Subscription & Loading
1398
+ */
1399
+ async waitForSync(options) {
1400
+ await this.raw.core.waitForSync(options);
1401
+ }
1402
+ /**
1403
+ * Get the descriptor for the items in the `CoList`
1404
+ * @internal
1405
+ */
1406
+ getItemsDescriptor() {
1407
+ return this.schema[ItemsSym];
1408
+ }
1409
+ /**
1410
+ * If a `CoList`'s items are a `coField.ref(...)`, you can use `coList.$jazz.refs[i]` to access
1411
+ * the `Ref` instead of the potentially loaded/null value.
1412
+ *
1413
+ * This allows you to always get the ID or load the value manually.
1414
+ *
1415
+ * @example
1416
+ * ```ts
1417
+ * animals.$jazz.refs[0].id; // => ID<Animal>
1418
+ * animals.$jazz.refs[0].value;
1419
+ * // => Animal | null
1420
+ * const animal = await animals.$jazz.refs[0].load();
1421
+ * ```
1422
+ *
1423
+ * @category Content
1424
+ **/
1425
+ get refs() {
1426
+ return makeRefs(
1427
+ this.coList,
1428
+ (idx) => this.raw.get(idx),
1429
+ () => Array.from({ length: this.raw.entries().length }, (_, idx) => idx),
1430
+ this.loadedAs,
1431
+ (_idx) => this.schema[ItemsSym]
1432
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1433
+ );
1434
+ }
1435
+ /**
1436
+ * Get the edits made to the CoList.
1437
+ *
1438
+ * @category Collaboration
1439
+ */
1440
+ getEdits() {
1441
+ throw new Error("Not implemented");
1442
+ }
1443
+ /** @internal */
1444
+ get raw() {
1445
+ return this.getRaw();
1446
+ }
1447
+ /** @internal */
1448
+ get schema() {
1449
+ return this.coList.constructor._schema;
1450
+ }
1451
+ };
1452
+ function toRawItems(items, itemDescriptor, owner) {
1453
+ let rawItems = [];
1454
+ if (itemDescriptor === "json") {
1455
+ rawItems = items;
1456
+ } else if ("encoded" in itemDescriptor) {
1457
+ rawItems = items?.map((e) => itemDescriptor.encoded.encode(e));
1458
+ } else if (isRefEncoded(itemDescriptor)) {
1459
+ rawItems = items?.map((value) => {
1460
+ if (value == null) {
1461
+ return null;
1462
+ }
1463
+ let refId = value.$jazz?.id;
1464
+ if (!refId) {
1465
+ const coValue = instantiateRefEncodedWithInit(
1466
+ itemDescriptor,
1467
+ value,
1468
+ owner
1469
+ );
1470
+ refId = coValue.$jazz.id;
1471
+ }
1472
+ return refId;
1473
+ });
1474
+ } else {
1475
+ throw new Error("Invalid element descriptor");
1476
+ }
1477
+ return rawItems;
1478
+ }
1479
+ var CoListProxyHandler = {
1480
+ get(target, key, receiver) {
1481
+ if (typeof key === "string" && !isNaN(+key)) {
1482
+ const itemDescriptor = target.$jazz.schema[ItemsSym];
1483
+ const rawValue = target.$jazz.raw.get(Number(key));
1484
+ if (itemDescriptor === "json") {
1485
+ return rawValue;
1486
+ } else if ("encoded" in itemDescriptor) {
1487
+ return rawValue === void 0 ? void 0 : itemDescriptor.encoded.decode(rawValue);
1488
+ } else if (isRefEncoded(itemDescriptor)) {
1489
+ return rawValue === void 0 || rawValue === null ? void 0 : accessChildByKey(target, rawValue, key);
1490
+ }
1491
+ } else if (key === "length") {
1492
+ return target.$jazz.raw.entries().length;
1493
+ } else {
1494
+ return Reflect.get(target, key, receiver);
1495
+ }
1496
+ },
1497
+ set(target, key, value, receiver) {
1498
+ if (key === ItemsSym && typeof value === "object" && SchemaInit in value) {
1499
+ target.constructor._schema ||= {};
1500
+ target.constructor._schema[ItemsSym] = value[SchemaInit];
1501
+ return true;
1502
+ }
1503
+ if (typeof key === "string" && !isNaN(+key)) {
1504
+ throw Error("Cannot update a CoList directly. Use `$jazz.set` instead.");
1505
+ } else {
1506
+ return Reflect.set(target, key, value, receiver);
1507
+ }
1508
+ },
1509
+ defineProperty(target, key, descriptor) {
1510
+ if (descriptor.value && key === ItemsSym && typeof descriptor.value === "object" && SchemaInit in descriptor.value) {
1511
+ target.constructor._schema ||= {};
1512
+ target.constructor._schema[ItemsSym] = descriptor.value[SchemaInit];
1513
+ return true;
1514
+ } else {
1515
+ return Reflect.defineProperty(target, key, descriptor);
1516
+ }
1517
+ },
1518
+ has(target, key) {
1519
+ if (typeof key === "string" && !isNaN(+key)) {
1520
+ return Number(key) < target.$jazz.raw.entries().length;
1521
+ } else {
1522
+ return Reflect.has(target, key);
1523
+ }
1524
+ }
1525
+ };
1526
+
1527
+ // src/tools/coValues/coFeed.ts
1528
+ import { cojsonInternals as cojsonInternals3 } from "cojson";
1529
+ var _CoFeed = class _CoFeed extends CoValueBase {
1530
+ /**
1531
+ * Declare a `CoFeed` by subclassing `CoFeed.Of(...)` and passing the item schema using a `co` primitive or a `coField.ref`.
1532
+ *
1533
+ * @example
1534
+ * ```ts
1535
+ * class ColorFeed extends CoFeed.Of(coField.string) {}
1536
+ * class AnimalFeed extends CoFeed.Of(coField.ref(Animal)) {}
1537
+ * ```
1538
+ *
1539
+ * @category Declaration
1540
+ */
1541
+ static Of(item) {
1542
+ var _a2, _b;
1543
+ const cls = class CoFeedOf extends (_b = _CoFeed, _a2 = coField.items, _b) {
1544
+ constructor() {
1545
+ super(...arguments);
1546
+ this[_a2] = item;
1547
+ }
1548
+ };
1549
+ cls._schema ||= {};
1550
+ cls._schema[ItemsSym] = item[SchemaInit];
1551
+ return cls;
1552
+ }
1553
+ /**
1554
+ * The current account's view of this `CoFeed`
1555
+ * @category Content
1556
+ */
1557
+ get byMe() {
1558
+ if (this.$jazz.loadedAs[TypeSym] === "Account") {
1559
+ return this.perAccount[this.$jazz.loadedAs.$jazz.id];
1560
+ } else {
1561
+ return void 0;
1562
+ }
1563
+ }
1564
+ /**
1565
+ * The per-account view of this `CoFeed`
1566
+ *
1567
+ * @example
1568
+ * ```ts
1569
+ * // Access entries directly by account ID
1570
+ * const aliceEntries = feed[aliceAccount.id];
1571
+ * console.log(aliceEntries.value); // Latest value from Alice
1572
+ *
1573
+ * // Iterate through all accounts' entries
1574
+ * for (const [accountId, entries] of Object.entries(feed)) {
1575
+ * console.log(`Latest entry from ${accountId}:`, entries.value);
1576
+ *
1577
+ * // Access all entries from this account
1578
+ * for (const entry of entries.all) {
1579
+ * console.log(`Entry made at ${entry.madeAt}:`, entry.value);
1580
+ * }
1581
+ * }
1582
+ * ```
1583
+ *
1584
+ * @category Content
1585
+ */
1586
+ get perAccount() {
1587
+ return new Proxy({}, CoStreamPerAccountProxyHandler(this));
1588
+ }
1589
+ /**
1590
+ * The per-session view of this `CoFeed`
1591
+ * @category Content
1592
+ */
1593
+ get perSession() {
1594
+ return new Proxy(
1595
+ {},
1596
+ CoStreamPerSessionProxyHandler(this, this)
1597
+ );
1598
+ }
1599
+ /**
1600
+ * The current session's view of this `CoFeed`
1601
+ *
1602
+ * This is a shortcut for `this.perSession` where the session ID is the current session ID.
1603
+ *
1604
+ * @category Content
1605
+ */
1606
+ get inCurrentSession() {
1607
+ if (this.$jazz.loadedAs[TypeSym] === "Account") {
1608
+ return this.perSession[this.$jazz.loadedAs.$jazz.sessionID];
1609
+ } else {
1610
+ return void 0;
1611
+ }
1612
+ }
1613
+ /** @internal */
1614
+ constructor(options) {
1615
+ super();
1616
+ Object.defineProperties(this, {
1617
+ $jazz: {
1618
+ value: new CoFeedJazzApi(this, options.fromRaw),
1619
+ enumerable: false
1620
+ }
1621
+ });
1622
+ return this;
1623
+ }
1624
+ /**
1625
+ * Create a new `CoFeed`
1626
+ * @category Creation
1627
+ * @deprecated Use `co.feed(...).create` instead.
1628
+ */
1629
+ static create(init, options) {
1630
+ const { owner } = parseCoValueCreateOptions(options);
1631
+ const raw = owner.$jazz.raw.createStream();
1632
+ const instance = new this({ fromRaw: raw });
1633
+ if (init) {
1634
+ instance.$jazz.push(...init);
1635
+ }
1636
+ return instance;
1637
+ }
1638
+ /**
1639
+ * Get a JSON representation of the `CoFeed`
1640
+ * @category
1641
+ */
1642
+ toJSON() {
1643
+ const itemDescriptor = this.$jazz.schema[ItemsSym];
1644
+ const mapper = itemDescriptor === "json" ? (v) => v : "encoded" in itemDescriptor ? itemDescriptor.encoded.encode : (v) => v && v.$jazz.id;
1645
+ return {
1646
+ ...Object.fromEntries(
1647
+ Object.entries(this).map(([account, entry]) => [
1648
+ account,
1649
+ mapper(entry.value)
1650
+ ])
1651
+ ),
1652
+ in: Object.fromEntries(
1653
+ Object.entries(this.perSession).map(([session, entry]) => [
1654
+ session,
1655
+ mapper(entry.value)
1656
+ ])
1657
+ )
1658
+ };
1659
+ }
1660
+ /** @internal */
1661
+ [(ItemsSym, inspect2)]() {
1662
+ return this.toJSON();
1663
+ }
1664
+ /** @internal */
1665
+ static schema(def) {
1666
+ this._schema ||= {};
1667
+ Object.assign(this._schema, def);
1668
+ }
1669
+ /**
1670
+ * Load a `CoFeed`
1671
+ * @category Subscription & Loading
1672
+ * @deprecated Use `co.feed(...).load` instead.
1673
+ */
1674
+ static load(id, options) {
1675
+ return loadCoValueWithoutMe(this, id, options);
1676
+ }
1677
+ static subscribe(id, ...args) {
1678
+ const { options, listener } = parseSubscribeRestArgs(args);
1679
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
1680
+ }
1681
+ };
1682
+ _CoFeed.prototype[TypeSym] = "CoStream";
1683
+ var CoFeed = _CoFeed;
1684
+ var CoFeedJazzApi = class extends CoValueJazzApi {
1685
+ constructor(coFeed, raw) {
1686
+ super(coFeed);
1687
+ this.coFeed = coFeed;
1688
+ this.raw = raw;
1689
+ }
1690
+ /**
1691
+ * The ID of this `CoFeed`
1692
+ * @category Content
1693
+ */
1694
+ get id() {
1695
+ return this.raw.id;
1696
+ }
1697
+ get owner() {
1698
+ return getCoValueOwner(this.coFeed);
1699
+ }
1700
+ /**
1701
+ * Push items to this `CoFeed`
1702
+ *
1703
+ * Items are appended to the current session's log. Each session (tab, device, app instance)
1704
+ * maintains its own append-only log, which is then aggregated into the per-account view.
1705
+ *
1706
+ * @example
1707
+ * ```ts
1708
+ * // Adds items to current session's log
1709
+ * feed.$jazz.push("item1", "item2");
1710
+ *
1711
+ * // View items from current session
1712
+ * console.log(feed.inCurrentSession);
1713
+ *
1714
+ * // View aggregated items from all sessions for current account
1715
+ * console.log(feed.byMe);
1716
+ * ```
1717
+ *
1718
+ * @category Content
1719
+ */
1720
+ push(...items) {
1721
+ for (const item of items) {
1722
+ this.pushItem(item);
1723
+ }
1724
+ }
1725
+ pushItem(item) {
1726
+ const itemDescriptor = this.schema[ItemsSym];
1727
+ if (itemDescriptor === "json") {
1728
+ this.raw.push(item);
1729
+ } else if ("encoded" in itemDescriptor) {
1730
+ this.raw.push(itemDescriptor.encoded.encode(item));
1731
+ } else if (isRefEncoded(itemDescriptor)) {
1732
+ let refId = item.$jazz?.id;
1733
+ if (!refId) {
1734
+ const coValue = instantiateRefEncodedWithInit(
1735
+ itemDescriptor,
1736
+ item,
1737
+ this.owner
1738
+ );
1739
+ refId = coValue.$jazz.id;
1740
+ }
1741
+ this.raw.push(refId);
1742
+ }
1743
+ }
1744
+ /**
1745
+ * Ensure a `CoFeed` is loaded to the specified depth
1746
+ *
1747
+ * @returns A new instance of the same CoFeed that's loaded to the specified depth
1748
+ * @category Subscription & Loading
1749
+ */
1750
+ ensureLoaded(options) {
1751
+ return ensureCoValueLoaded(this.coFeed, options);
1752
+ }
1753
+ subscribe(...args) {
1754
+ const { options, listener } = parseSubscribeRestArgs(args);
1755
+ return subscribeToExistingCoValue(this.coFeed, options, listener);
1756
+ }
1757
+ /**
1758
+ * Wait for the `CoFeed` to be uploaded to the other peers.
1759
+ *
1760
+ * @category Subscription & Loading
1761
+ */
1762
+ waitForSync(options) {
1763
+ return this.raw.core.waitForSync(options);
1764
+ }
1765
+ /**
1766
+ * Get the descriptor for the items in the `CoFeed`
1767
+ * @internal
1768
+ */
1769
+ getItemsDescriptor() {
1770
+ return this.schema[ItemsSym];
1771
+ }
1772
+ /** @internal */
1773
+ get schema() {
1774
+ return this.coFeed.constructor._schema;
1775
+ }
1776
+ };
1777
+ function entryFromRawEntry(accessFrom, rawEntry, loadedAs, accountID, itemField) {
1778
+ return {
1779
+ get value() {
1780
+ if (itemField === "json") {
1781
+ return rawEntry.value;
1782
+ } else if ("encoded" in itemField) {
1783
+ return itemField.encoded.decode(rawEntry.value);
1784
+ } else if (isRefEncoded(itemField)) {
1785
+ return accessChildById(
1786
+ accessFrom,
1787
+ rawEntry.value,
1788
+ itemField
1789
+ );
1790
+ } else {
1791
+ throw new Error("Invalid item field schema");
1792
+ }
1793
+ },
1794
+ get ref() {
1795
+ if (itemField !== "json" && isRefEncoded(itemField)) {
1796
+ const rawId = rawEntry.value;
1797
+ return new Ref(
1798
+ rawId,
1799
+ loadedAs,
1800
+ itemField,
1801
+ accessFrom
1802
+ );
1803
+ } else {
1804
+ return void 0;
1805
+ }
1806
+ },
1807
+ get by() {
1808
+ return accountID && accessChildById(accessFrom, accountID, {
1809
+ ref: Account,
1810
+ optional: false
1811
+ });
1812
+ },
1813
+ madeAt: rawEntry.at,
1814
+ tx: rawEntry.tx
1815
+ };
1816
+ }
1817
+ var CoStreamPerAccountProxyHandler = (innerTarget) => ({
1818
+ get(_target, key, receiver) {
1819
+ if (typeof key === "string" && key.startsWith("co_")) {
1820
+ const rawEntry = innerTarget.$jazz.raw.lastItemBy(key);
1821
+ if (!rawEntry) return;
1822
+ const entry = entryFromRawEntry(
1823
+ receiver,
1824
+ rawEntry,
1825
+ innerTarget.$jazz.loadedAs,
1826
+ key,
1827
+ innerTarget.$jazz.schema[ItemsSym]
1828
+ );
1829
+ Object.defineProperty(entry, "all", {
1830
+ get: () => {
1831
+ const allRawEntries = innerTarget.$jazz.raw.itemsBy(
1832
+ key
1833
+ );
1834
+ return function* () {
1835
+ while (true) {
1836
+ const rawEntry2 = allRawEntries.next();
1837
+ if (rawEntry2.done) return;
1838
+ yield entryFromRawEntry(
1839
+ receiver,
1840
+ rawEntry2.value,
1841
+ innerTarget.$jazz.loadedAs,
1842
+ key,
1843
+ innerTarget.$jazz.schema[ItemsSym]
1844
+ );
1845
+ }
1846
+ }();
1847
+ }
1848
+ });
1849
+ return entry;
1850
+ } else {
1851
+ return Reflect.get(innerTarget, key, receiver);
1852
+ }
1853
+ },
1854
+ ownKeys(_target) {
1855
+ return Array.from(innerTarget.$jazz.raw.accounts());
1856
+ },
1857
+ getOwnPropertyDescriptor(_target, key) {
1858
+ if (typeof key === "string" && key.startsWith("co_")) {
1859
+ return {
1860
+ configurable: true,
1861
+ enumerable: true,
1862
+ writable: false
1863
+ };
1864
+ } else {
1865
+ return Reflect.getOwnPropertyDescriptor(innerTarget, key);
1866
+ }
1867
+ }
1868
+ });
1869
+ var CoStreamPerSessionProxyHandler = (innerTarget, accessFrom) => ({
1870
+ get(_target, key, receiver) {
1871
+ if (typeof key === "string" && key.includes("session")) {
1872
+ const sessionID = key;
1873
+ const rawEntry = innerTarget.$jazz.raw.lastItemIn(sessionID);
1874
+ if (!rawEntry) return;
1875
+ const by = cojsonInternals3.accountOrAgentIDfromSessionID(sessionID);
1876
+ const entry = entryFromRawEntry(
1877
+ accessFrom,
1878
+ rawEntry,
1879
+ innerTarget.$jazz.loadedAs,
1880
+ cojsonInternals3.isAccountID(by) ? by : void 0,
1881
+ innerTarget.$jazz.schema[ItemsSym]
1882
+ );
1883
+ Object.defineProperty(entry, "all", {
1884
+ get: () => {
1885
+ const allRawEntries = innerTarget.$jazz.raw.itemsIn(sessionID);
1886
+ return function* () {
1887
+ while (true) {
1888
+ const rawEntry2 = allRawEntries.next();
1889
+ if (rawEntry2.done) return;
1890
+ yield entryFromRawEntry(
1891
+ accessFrom,
1892
+ rawEntry2.value,
1893
+ innerTarget.$jazz.loadedAs,
1894
+ cojsonInternals3.isAccountID(by) ? by : void 0,
1895
+ innerTarget.$jazz.schema[ItemsSym]
1896
+ );
1897
+ }
1898
+ }();
1899
+ }
1900
+ });
1901
+ return entry;
1902
+ } else {
1903
+ return Reflect.get(innerTarget, key, receiver);
1904
+ }
1905
+ },
1906
+ ownKeys() {
1907
+ return innerTarget.$jazz.raw.sessions();
1908
+ },
1909
+ getOwnPropertyDescriptor(target, key) {
1910
+ if (typeof key === "string" && key.startsWith("co_")) {
1911
+ return {
1912
+ configurable: true,
1913
+ enumerable: true,
1914
+ writable: false
1915
+ };
1916
+ } else {
1917
+ return Reflect.getOwnPropertyDescriptor(target, key);
1918
+ }
1919
+ }
1920
+ });
1921
+ var FileStream = class extends CoValueBase {
1922
+ constructor(options) {
1923
+ super();
1924
+ let raw;
1925
+ if ("fromRaw" in options) {
1926
+ raw = options.fromRaw;
1927
+ } else {
1928
+ const rawOwner = options.owner.$jazz.raw;
1929
+ raw = rawOwner.createBinaryStream();
1930
+ }
1931
+ Object.defineProperties(this, {
1932
+ [TypeSym]: { value: "BinaryCoStream", enumerable: false },
1933
+ $jazz: {
1934
+ value: new FileStreamJazzApi(this, raw),
1935
+ enumerable: false
1936
+ }
1937
+ });
1938
+ }
1939
+ /**
1940
+ * Create a new empty `FileStream` instance.
1941
+ *
1942
+ * @param options - Configuration options for the new FileStream
1943
+ * @param options.owner - The Account or Group that will own this FileStream and control access rights
1944
+ *
1945
+ * @example
1946
+ * ```typescript
1947
+ * // Create owned by an account
1948
+ * const stream = FileStream.create({ owner: myAccount });
1949
+ *
1950
+ * // Create owned by a group
1951
+ * const stream = FileStream.create({ owner: teamGroup });
1952
+ *
1953
+ * // Create with implicit owner
1954
+ * const stream = FileStream.create(myAccount);
1955
+ * ```
1956
+ *
1957
+ * @remarks
1958
+ * For uploading an existing file or blob, use {@link FileStream.createFromBlob} instead.
1959
+ *
1960
+ * @category Creation
1961
+ * @deprecated Use `co.fileStream(...).create` instead.
1962
+ */
1963
+ static create(options) {
1964
+ return new this(parseCoValueCreateOptions(options));
1965
+ }
1966
+ getMetadata() {
1967
+ return this.$jazz.raw.getBinaryStreamInfo();
1968
+ }
1969
+ getChunks(options) {
1970
+ return this.$jazz.raw.getBinaryChunks(options?.allowUnfinished);
1971
+ }
1972
+ isBinaryStreamEnded() {
1973
+ return this.$jazz.raw.isBinaryStreamEnded();
1974
+ }
1975
+ start(options) {
1976
+ this.$jazz.raw.startBinaryStream(options);
1977
+ }
1978
+ push(data) {
1979
+ this.$jazz.raw.pushBinaryStreamChunk(data);
1980
+ }
1981
+ end() {
1982
+ this.$jazz.raw.endBinaryStream();
1983
+ }
1984
+ toBlob(options) {
1985
+ const chunks = this.getChunks({
1986
+ allowUnfinished: options?.allowUnfinished
1987
+ });
1988
+ if (!chunks) {
1989
+ return void 0;
1990
+ }
1991
+ return new Blob(chunks.chunks, { type: chunks.mimeType });
1992
+ }
1993
+ /**
1994
+ * Load a `FileStream` as a `Blob`
1995
+ *
1996
+ * @category Content
1997
+ * @deprecated Use `co.fileStream(...).loadAsBlob` instead.
1998
+ */
1999
+ static async loadAsBlob(id, options) {
2000
+ let stream = await this.load(id, options);
2001
+ return stream?.toBlob({
2002
+ allowUnfinished: options?.allowUnfinished
2003
+ });
2004
+ }
2005
+ static async loadAsBase64(id, options) {
2006
+ const stream = await this.load(id, options);
2007
+ return stream?.asBase64(options);
2008
+ }
2009
+ asBase64(options) {
2010
+ const chunks = this.getChunks(options);
2011
+ if (!chunks) return void 0;
2012
+ const output = [];
2013
+ for (const chunk of chunks.chunks) {
2014
+ for (const byte of chunk) {
2015
+ output.push(String.fromCharCode(byte));
2016
+ }
2017
+ }
2018
+ const base642 = btoa(output.join(""));
2019
+ if (options?.dataURL) {
2020
+ return `data:${chunks.mimeType};base64,${base642}`;
2021
+ }
2022
+ return base642;
2023
+ }
2024
+ /**
2025
+ * Create a `FileStream` from a `Blob` or `File`
2026
+ *
2027
+ * @example
2028
+ * ```ts
2029
+ * import { coField, FileStream } from "jazz-tools";
2030
+ *
2031
+ * const fileStream = await FileStream.createFromBlob(file, {owner: group})
2032
+ * ```
2033
+ * @category Content
2034
+ * @deprecated Use `co.fileStream(...).createFromBlob` instead.
2035
+ */
2036
+ static async createFromBlob(blob, options) {
2037
+ const arrayBuffer = await blob.arrayBuffer();
2038
+ return this.createFromArrayBuffer(
2039
+ arrayBuffer,
2040
+ blob.type,
2041
+ blob instanceof File ? blob.name : void 0,
2042
+ options
2043
+ );
2044
+ }
2045
+ /**
2046
+ * Create a `FileStream` from a `Blob` or `File`
2047
+ *
2048
+ * @example
2049
+ * ```ts
2050
+ * import { coField, FileStream } from "jazz-tools";
2051
+ *
2052
+ * const fileStream = await FileStream.createFromBlob(file, {owner: group})
2053
+ * ```
2054
+ * @category Content
2055
+ * @deprecated Use `co.fileStream(...).createFromArrayBuffer` instead.
2056
+ */
2057
+ static async createFromArrayBuffer(arrayBuffer, mimeType, fileName, options) {
2058
+ const stream = this.create(options);
2059
+ const onProgress = options && "onProgress" in options ? options.onProgress : void 0;
2060
+ const start = Date.now();
2061
+ const data = new Uint8Array(arrayBuffer);
2062
+ stream.start({
2063
+ mimeType,
2064
+ totalSizeBytes: arrayBuffer.byteLength,
2065
+ fileName
2066
+ });
2067
+ const chunkSize = cojsonInternals3.TRANSACTION_CONFIG.MAX_RECOMMENDED_TX_SIZE;
2068
+ let lastProgressUpdate = Date.now();
2069
+ for (let idx = 0; idx < data.length; idx += chunkSize) {
2070
+ stream.push(data.slice(idx, idx + chunkSize));
2071
+ if (Date.now() - lastProgressUpdate > 100) {
2072
+ onProgress?.(idx / data.length);
2073
+ lastProgressUpdate = Date.now();
2074
+ }
2075
+ await new Promise((resolve) => setTimeout(resolve, 0));
2076
+ }
2077
+ stream.end();
2078
+ const end = Date.now();
2079
+ console.debug(
2080
+ "Finished creating binary stream in",
2081
+ (end - start) / 1e3,
2082
+ "s - Throughput in MB/s",
2083
+ 1e3 * (arrayBuffer.byteLength / (end - start)) / (1024 * 1024)
2084
+ );
2085
+ onProgress?.(1);
2086
+ return stream;
2087
+ }
2088
+ /**
2089
+ * Get a JSON representation of the `FileStream`
2090
+ * @category Content
2091
+ */
2092
+ toJSON() {
2093
+ return {
2094
+ ...this.getChunks()
2095
+ };
2096
+ }
2097
+ /** @internal */
2098
+ [inspect2]() {
2099
+ return this.toJSON();
2100
+ }
2101
+ /**
2102
+ * Load a `FileStream`
2103
+ * @category Subscription & Loading
2104
+ * @deprecated Use `co.fileStream(...).load` instead.
2105
+ */
2106
+ static async load(id, options) {
2107
+ const stream = await loadCoValueWithoutMe(this, id, options);
2108
+ if (!options?.allowUnfinished && !stream?.isBinaryStreamEnded()) {
2109
+ return new Promise((resolve) => {
2110
+ subscribeToCoValueWithoutMe(
2111
+ this,
2112
+ id,
2113
+ options || {},
2114
+ (value, unsubscribe) => {
2115
+ if (value.isBinaryStreamEnded()) {
2116
+ unsubscribe();
2117
+ resolve(value);
2118
+ }
2119
+ }
2120
+ );
2121
+ });
2122
+ }
2123
+ return stream;
2124
+ }
2125
+ static subscribe(id, ...args) {
2126
+ const { options, listener } = parseSubscribeRestArgs(args);
2127
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
2128
+ }
2129
+ };
2130
+ var FileStreamJazzApi = class extends CoValueJazzApi {
2131
+ constructor(fileStream, raw) {
2132
+ super(fileStream);
2133
+ this.fileStream = fileStream;
2134
+ this.raw = raw;
2135
+ }
2136
+ /**
2137
+ * The ID of this `FileStream`
2138
+ * @category Content
2139
+ */
2140
+ get id() {
2141
+ return this.raw.id;
2142
+ }
2143
+ get owner() {
2144
+ return getCoValueOwner(this.fileStream);
2145
+ }
2146
+ /**
2147
+ * An instance method to subscribe to an existing `FileStream`
2148
+ * @category Subscription & Loading
2149
+ */
2150
+ subscribe(listener) {
2151
+ return subscribeToExistingCoValue(this.fileStream, {}, listener);
2152
+ }
2153
+ /**
2154
+ * Wait for the `FileStream` to be uploaded to the other peers.
2155
+ *
2156
+ * @category Subscription & Loading
2157
+ */
2158
+ waitForSync(options) {
2159
+ return this.raw.core.waitForSync(options);
2160
+ }
2161
+ };
2162
+
2163
+ // src/tools/coValues/account.ts
2164
+ import {
2165
+ ControlledAccount as RawControlledAccount,
2166
+ LocalNode as LocalNode2,
2167
+ cojsonInternals as cojsonInternals4
2168
+ } from "cojson";
2169
+ var Account = class extends CoValueBase {
2170
+ constructor(options) {
2171
+ super();
2172
+ if (!("fromRaw" in options)) {
2173
+ throw new Error("Can only construct account from raw or with .create()");
2174
+ }
2175
+ const proxy = new Proxy(
2176
+ this,
2177
+ AccountAndGroupProxyHandler
2178
+ );
2179
+ Object.defineProperties(this, {
2180
+ [TypeSym]: { value: "Account", enumerable: false },
2181
+ $jazz: {
2182
+ value: new AccountJazzApi(proxy, options.fromRaw),
2183
+ enumerable: false
2184
+ }
2185
+ });
2186
+ return proxy;
2187
+ }
2188
+ /**
2189
+ * Whether this account is the currently active account.
2190
+ */
2191
+ get isMe() {
2192
+ return activeAccountContext.get().$jazz.id === this.$jazz.id;
2193
+ }
2194
+ /**
2195
+ * Accept an invite to a `CoValue` or `Group`.
2196
+ *
2197
+ * @param valueID The ID of the `CoValue` or `Group` to accept the invite to.
2198
+ * @param inviteSecret The secret of the invite to accept.
2199
+ * @param coValueClass The class of the `CoValue` or `Group` to accept the invite to.
2200
+ * @returns The loaded `CoValue` or `Group`.
2201
+ */
2202
+ async acceptInvite(valueID, inviteSecret, coValueClass) {
2203
+ if (!this.$jazz.isLocalNodeOwner) {
2204
+ throw new Error("Only a controlled account can accept invites");
2205
+ }
2206
+ await this.$jazz.localNode.acceptInvite(
2207
+ valueID,
2208
+ inviteSecret
2209
+ );
2210
+ return loadCoValue(
2211
+ coValueClassFromCoValueClassOrSchema(coValueClass),
2212
+ valueID,
2213
+ {
2214
+ loadAs: this
2215
+ }
2216
+ );
2217
+ }
2218
+ getRoleOf(member) {
2219
+ if (member === "me") {
2220
+ return this.isMe ? "admin" : void 0;
2221
+ }
2222
+ if (member === this.$jazz.id) {
2223
+ return "admin";
2224
+ }
2225
+ return void 0;
2226
+ }
2227
+ canRead(value) {
2228
+ const valueOwner = value.$jazz.owner;
2229
+ if (!valueOwner) {
2230
+ return true;
2231
+ }
2232
+ const role = valueOwner.getRoleOf(this.$jazz.id);
2233
+ return role === "admin" || role === "writer" || role === "reader" || role === "writeOnly";
2234
+ }
2235
+ canWrite(value) {
2236
+ const valueOwner = value.$jazz.owner;
2237
+ if (!valueOwner) {
2238
+ if (value[TypeSym] === "Group") {
2239
+ const roleInGroup = value.getRoleOf(this.$jazz.id);
2240
+ return roleInGroup === "admin" || roleInGroup === "writer";
2241
+ }
2242
+ if (value[TypeSym] === "Account") {
2243
+ return value.$jazz.id === this.$jazz.id;
2244
+ }
2245
+ return false;
2246
+ }
2247
+ const role = valueOwner.getRoleOf(this.$jazz.id);
2248
+ return role === "admin" || role === "writer" || role === "writeOnly";
2249
+ }
2250
+ canAdmin(value) {
2251
+ const valueOwner = value.$jazz.owner;
2252
+ if (!valueOwner) {
2253
+ if (value[TypeSym] === "Group") {
2254
+ const roleInGroup = value.getRoleOf(this.$jazz.id);
2255
+ return roleInGroup === "admin";
2256
+ }
2257
+ if (value[TypeSym] === "Account") {
2258
+ return value.$jazz.id === this.$jazz.id;
2259
+ }
2260
+ return false;
2261
+ }
2262
+ return valueOwner.getRoleOf(this.$jazz.id) === "admin";
2263
+ }
2264
+ /** @private */
2265
+ static async create(options) {
2266
+ const { node } = await LocalNode2.withNewlyCreatedAccount({
2267
+ ...options,
2268
+ migration: async (rawAccount, _node, creationProps) => {
2269
+ const account = new this({
2270
+ fromRaw: rawAccount
2271
+ });
2272
+ await account.applyMigration?.(creationProps);
2273
+ }
2274
+ });
2275
+ return this.fromNode(node);
2276
+ }
2277
+ static getMe() {
2278
+ return activeAccountContext.get();
2279
+ }
2280
+ /**
2281
+ * @deprecated Use `co.account(...).createAs` instead.
2282
+ */
2283
+ static async createAs(as, options) {
2284
+ const connectedPeers = cojsonInternals4.connectedPeers(
2285
+ "creatingAccount",
2286
+ "createdAccount",
2287
+ { peer1role: "server", peer2role: "client" }
2288
+ );
2289
+ as.$jazz.localNode.syncManager.addPeer(connectedPeers[1]);
2290
+ const account = await this.create({
2291
+ creationProps: options.creationProps,
2292
+ crypto: as.$jazz.localNode.crypto,
2293
+ peersToLoadFrom: [connectedPeers[0]]
2294
+ });
2295
+ await account.$jazz.waitForAllCoValuesSync();
2296
+ return account;
2297
+ }
2298
+ static fromNode(node) {
2299
+ return new this({
2300
+ fromRaw: node.expectCurrentAccount("jazz-tools/Account.fromNode")
2301
+ });
2302
+ }
2303
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2304
+ toJSON() {
2305
+ return {};
2306
+ }
2307
+ [inspect2]() {
2308
+ return this.toJSON();
2309
+ }
2310
+ async applyMigration(creationProps) {
2311
+ await this.migrate(creationProps);
2312
+ if (this.profile === void 0 && creationProps) {
2313
+ const profileGroup = RegisteredSchemas["Group"].create({ owner: this });
2314
+ this.$jazz.set(
2315
+ "profile",
2316
+ Profile.create({ name: creationProps.name }, profileGroup)
2317
+ );
2318
+ profileGroup.addMember("everyone", "reader");
2319
+ }
2320
+ const profile = this.$jazz.localNode.expectCoValueLoaded(this.$jazz.raw.get("profile")).getCurrentContent();
2321
+ if (!profile.get("inbox")) {
2322
+ const inboxRoot = createInboxRoot(this);
2323
+ profile.set("inbox", inboxRoot.id);
2324
+ profile.set("inboxInvite", inboxRoot.inviteLink);
2325
+ }
2326
+ }
2327
+ // Placeholder method for subclasses to override
2328
+ migrate(creationProps) {
2329
+ creationProps;
2330
+ }
2331
+ /**
2332
+ * Load an `Account`
2333
+ * @category Subscription & Loading
2334
+ * @deprecated Use `co.account(...).load` instead.
2335
+ */
2336
+ static load(id, options) {
2337
+ return loadCoValueWithoutMe(this, id, options);
2338
+ }
2339
+ static subscribe(id, ...args) {
2340
+ const { options, listener } = parseSubscribeRestArgs(args);
2341
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
2342
+ }
2343
+ };
2344
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2345
+ Account._schema = {
2346
+ profile: {
2347
+ ref: () => Profile,
2348
+ optional: false
2349
+ },
2350
+ root: {
2351
+ ref: () => RegisteredSchemas["CoMap"],
2352
+ optional: true
2353
+ }
2354
+ };
2355
+ var AccountJazzApi = class extends CoValueJazzApi {
2356
+ constructor(account, raw) {
2357
+ super(account);
2358
+ this.account = account;
2359
+ this.raw = raw;
2360
+ this.isLocalNodeOwner = this.raw.id === this.localNode.getCurrentAgent().id;
2361
+ if (this.isLocalNodeOwner) {
2362
+ this.sessionID = this.localNode.currentSessionID;
2363
+ }
2364
+ }
2365
+ /**
2366
+ * The ID of this `Account`
2367
+ * @category Content
2368
+ */
2369
+ get id() {
2370
+ return this.raw.id;
2371
+ }
2372
+ /**
2373
+ * Accounts have no owner. They can be accessed by everyone.
2374
+ */
2375
+ get owner() {
2376
+ return void 0;
2377
+ }
2378
+ /**
2379
+ * Set the value of a key in the account.
2380
+ *
2381
+ * @param key The key to set.
2382
+ * @param value The value to set.
2383
+ *
2384
+ * @category Content
2385
+ */
2386
+ set(key, value) {
2387
+ if (value) {
2388
+ let refId = value.$jazz?.id;
2389
+ if (!refId) {
2390
+ const descriptor = this.schema[key];
2391
+ const coValue = instantiateRefEncodedWithInit(
2392
+ descriptor,
2393
+ value,
2394
+ accountOrGroupToGroup(this.account)
2395
+ );
2396
+ refId = coValue.$jazz.id;
2397
+ }
2398
+ this.raw.set(key, refId, "trusting");
2399
+ }
2400
+ }
2401
+ has(key) {
2402
+ const entry = this.raw.getRaw(key);
2403
+ return entry?.change !== void 0 && entry.change.op !== "del";
2404
+ }
2405
+ /**
2406
+ * Get the descriptor for a given key
2407
+ * @internal
2408
+ */
2409
+ getDescriptor(key) {
2410
+ if (key === "profile") {
2411
+ return this.schema.profile;
2412
+ } else if (key === "root") {
2413
+ return this.schema.root;
2414
+ }
2415
+ return void 0;
2416
+ }
2417
+ /**
2418
+ * If property `prop` is a `coField.ref(...)`, you can use `account.$jazz.refs.prop` to access
2419
+ * the `Ref` instead of the potentially loaded/null value.
2420
+ *
2421
+ * This allows you to always get the ID or load the value manually.
2422
+ *
2423
+ * @category Content
2424
+ */
2425
+ get refs() {
2426
+ const profileID = this.raw.get("profile");
2427
+ const rootID = this.raw.get("root");
2428
+ return {
2429
+ profile: profileID ? new Ref(
2430
+ profileID,
2431
+ this.loadedAs,
2432
+ this.schema.profile,
2433
+ this.account
2434
+ ) : void 0,
2435
+ root: rootID ? new Ref(
2436
+ rootID,
2437
+ this.loadedAs,
2438
+ this.schema.root,
2439
+ this.account
2440
+ ) : void 0
2441
+ };
2442
+ }
2443
+ /** @category Subscription & Loading */
2444
+ ensureLoaded(options) {
2445
+ return ensureCoValueLoaded(this.account, options);
2446
+ }
2447
+ subscribe(...args) {
2448
+ const { options, listener } = parseSubscribeRestArgs(args);
2449
+ return subscribeToExistingCoValue(this.account, options, listener);
2450
+ }
2451
+ /**
2452
+ * Wait for the `Account` to be uploaded to the other peers.
2453
+ *
2454
+ * @category Subscription & Loading
2455
+ */
2456
+ waitForSync(options) {
2457
+ return this.raw.core.waitForSync(options);
2458
+ }
2459
+ /**
2460
+ * Wait for all the available `CoValues` to be uploaded to the other peers.
2461
+ *
2462
+ * @category Subscription & Loading
2463
+ */
2464
+ waitForAllCoValuesSync(options) {
2465
+ return this.localNode.syncManager.waitForAllCoValuesSync(options?.timeout);
2466
+ }
2467
+ /** @internal */
2468
+ get schema() {
2469
+ return this.account.constructor._schema;
2470
+ }
2471
+ get loadedAs() {
2472
+ if (this.isLocalNodeOwner) return this.account;
2473
+ const agent = this.localNode.getCurrentAgent();
2474
+ if (agent instanceof RawControlledAccount) {
2475
+ return coValuesCache.get(
2476
+ agent.account,
2477
+ () => Account.fromRaw(agent.account)
2478
+ );
2479
+ }
2480
+ return new AnonymousJazzAgent2(this.localNode);
2481
+ }
2482
+ };
2483
+ var AccountAndGroupProxyHandler = {
2484
+ get(target, key, receiver) {
2485
+ if (key === "profile" || key === "root") {
2486
+ const id = target.$jazz.raw.get(key);
2487
+ if (id) {
2488
+ return accessChildByKey(target, id, key);
2489
+ } else {
2490
+ return void 0;
2491
+ }
2492
+ } else {
2493
+ return Reflect.get(target, key, receiver);
2494
+ }
2495
+ },
2496
+ set(target, key, value, receiver) {
2497
+ if (target instanceof Account && (key === "profile" || key === "root") && typeof value === "object" && SchemaInit in value) {
2498
+ target.constructor._schema ||= {};
2499
+ target.constructor._schema[key] = value[SchemaInit];
2500
+ return true;
2501
+ } else if (target instanceof Account && (key === "profile" || key === "root")) {
2502
+ if (value) {
2503
+ target.$jazz.set(key, value);
2504
+ }
2505
+ return true;
2506
+ } else {
2507
+ return Reflect.set(target, key, value, receiver);
2508
+ }
2509
+ },
2510
+ defineProperty(target, key, descriptor) {
2511
+ if ((key === "profile" || key === "root") && typeof descriptor.value === "object" && SchemaInit in descriptor.value) {
2512
+ target.constructor._schema ||= {};
2513
+ target.constructor._schema[key] = descriptor.value[SchemaInit];
2514
+ return true;
2515
+ } else {
2516
+ return Reflect.defineProperty(target, key, descriptor);
2517
+ }
2518
+ }
2519
+ };
2520
+ function isControlledAccount(account) {
2521
+ return account.$jazz.isLocalNodeOwner;
2522
+ }
2523
+ RegisteredSchemas["Account"] = Account;
2524
+
2525
+ // src/tools/coValues/group.ts
2526
+ var _Group = class _Group extends CoValueBase {
2527
+ /** @deprecated Don't use constructor directly, use .create */
2528
+ constructor(options) {
2529
+ super();
2530
+ let raw;
2531
+ if (options && "fromRaw" in options) {
2532
+ raw = options.fromRaw;
2533
+ } else {
2534
+ const initOwner = options.owner;
2535
+ if (!initOwner) throw new Error("No owner provided");
2536
+ if (initOwner[TypeSym] === "Account" && isControlledAccount(initOwner)) {
2537
+ const rawOwner = initOwner.$jazz.raw;
2538
+ raw = rawOwner.core.node.createGroup();
2539
+ } else {
2540
+ throw new Error("Can only construct group as a controlled account");
2541
+ }
2542
+ }
2543
+ const proxy = new Proxy(
2544
+ this,
2545
+ AccountAndGroupProxyHandler
2546
+ );
2547
+ Object.defineProperties(this, {
2548
+ $jazz: {
2549
+ value: new GroupJazzApi(proxy, raw),
2550
+ enumerable: false
2551
+ }
2552
+ });
2553
+ return proxy;
2554
+ }
2555
+ static create(options) {
2556
+ return new this(parseGroupCreateOptions(options));
2557
+ }
2558
+ myRole() {
2559
+ return this.$jazz.raw.myRole();
2560
+ }
2561
+ addMember(member, role) {
2562
+ if (member !== "everyone" && member[TypeSym] === "Group") {
2563
+ if (role === "writeOnly")
2564
+ throw new Error("Cannot add group as member with write-only role");
2565
+ this.$jazz.raw.extend(member.$jazz.raw, role);
2566
+ } else if (role !== void 0 && role !== "inherit") {
2567
+ this.$jazz.raw.addMember(
2568
+ member === "everyone" ? member : member.$jazz.raw,
2569
+ role
2570
+ );
2571
+ }
2572
+ }
2573
+ removeMember(member) {
2574
+ if (member !== "everyone" && member[TypeSym] === "Group") {
2575
+ this.$jazz.raw.revokeExtend(member.$jazz.raw);
2576
+ } else {
2577
+ return this.$jazz.raw.removeMember(
2578
+ member === "everyone" ? member : member.$jazz.raw
2579
+ );
2580
+ }
2581
+ }
2582
+ getMembersFromKeys(accountIDs) {
2583
+ const members = [];
2584
+ const refEncodedAccountSchema = {
2585
+ ref: () => Account,
2586
+ optional: false
2587
+ };
2588
+ for (const accountID of accountIDs) {
2589
+ if (!isAccountID(accountID)) continue;
2590
+ const role = this.$jazz.raw.roleOf(accountID);
2591
+ if (role === "admin" || role === "writer" || role === "reader" || role === "writeOnly") {
2592
+ const ref2 = new Ref(
2593
+ accountID,
2594
+ this.$jazz.loadedAs,
2595
+ refEncodedAccountSchema,
2596
+ this
2597
+ );
2598
+ const group = this;
2599
+ members.push({
2600
+ id: accountID,
2601
+ role,
2602
+ ref: ref2,
2603
+ get account() {
2604
+ return accessChildById(group, accountID, refEncodedAccountSchema);
2605
+ }
2606
+ });
2607
+ }
2608
+ }
2609
+ return members;
2610
+ }
2611
+ /**
2612
+ * Returns all members of the group, including inherited members from parent
2613
+ * groups.
2614
+ *
2615
+ * If you need only the direct members of the group, use
2616
+ * {@link getDirectMembers} instead.
2617
+ *
2618
+ * @returns The members of the group.
2619
+ */
2620
+ get members() {
2621
+ return this.getMembersFromKeys(this.$jazz.raw.getAllMemberKeysSet());
2622
+ }
2623
+ /**
2624
+ * Returns the direct members of the group.
2625
+ *
2626
+ * If you need all members of the group, including inherited members from
2627
+ * parent groups, use {@link Group.members|members} instead.
2628
+ * @returns The direct members of the group.
2629
+ */
2630
+ getDirectMembers() {
2631
+ return this.getMembersFromKeys(this.$jazz.raw.getMemberKeys());
2632
+ }
2633
+ getRoleOf(member) {
2634
+ const accountId = member === "me" ? activeAccountContext.get().$jazz.id : member === "everyone" ? member : member;
2635
+ return this.$jazz.raw.roleOf(accountId);
2636
+ }
2637
+ /**
2638
+ * Make the group public, so that everyone can read it.
2639
+ * Alias for `addMember("everyone", role)`.
2640
+ *
2641
+ * @param role - Optional: the role to grant to everyone. Defaults to "reader".
2642
+ * @returns The group itself.
2643
+ */
2644
+ makePublic(role = "reader") {
2645
+ this.addMember("everyone", role);
2646
+ return this;
2647
+ }
2648
+ getParentGroups() {
2649
+ return this.$jazz.raw.getParentGroups().map((group) => _Group.fromRaw(group));
2650
+ }
2651
+ /** @category Identity & Permissions
2652
+ * Gives members of a parent group membership in this group.
2653
+ * @deprecated Use `addMember` instead.
2654
+ * @param parent The group that will gain access to this group.
2655
+ * @param roleMapping The role all members of the parent group should have in this group.
2656
+ * @returns This group.
2657
+ */
2658
+ extend(parent, roleMapping) {
2659
+ this.$jazz.raw.extend(parent.$jazz.raw, roleMapping);
2660
+ return this;
2661
+ }
2662
+ /** @category Identity & Permissions
2663
+ * Revokes membership from members a parent group.
2664
+ * @deprecated Use `removeMember` instead.
2665
+ * @param parent The group that will lose access to this group.
2666
+ * @returns This group.
2667
+ */
2668
+ async revokeExtend(parent) {
2669
+ await this.$jazz.raw.revokeExtend(parent.$jazz.raw);
2670
+ return this;
2671
+ }
2672
+ /** @category Subscription & Loading */
2673
+ static load(id, options) {
2674
+ return loadCoValueWithoutMe(this, id, options);
2675
+ }
2676
+ static subscribe(id, ...args) {
2677
+ const { options, listener } = parseSubscribeRestArgs(args);
2678
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
2679
+ }
2680
+ };
2681
+ _Group.prototype[TypeSym] = "Group";
2682
+ var Group6 = _Group;
2683
+ var GroupJazzApi = class extends CoValueJazzApi {
2684
+ constructor(group, raw) {
2685
+ super(group);
2686
+ this.group = group;
2687
+ this.raw = raw;
2688
+ }
2689
+ /**
2690
+ * The ID of this `Group`
2691
+ * @category Content
2692
+ */
2693
+ get id() {
2694
+ return this.raw.id;
2695
+ }
2696
+ /**
2697
+ * Groups have no owner. They can be accessed by everyone.
2698
+ */
2699
+ get owner() {
2700
+ return void 0;
2701
+ }
2702
+ /** @category Subscription & Loading */
2703
+ ensureLoaded(options) {
2704
+ return ensureCoValueLoaded(this.group, options);
2705
+ }
2706
+ subscribe(...args) {
2707
+ const { options, listener } = parseSubscribeRestArgs(args);
2708
+ return subscribeToExistingCoValue(this.group, options, listener);
2709
+ }
2710
+ /**
2711
+ * Wait for the `Group` to be uploaded to the other peers.
2712
+ *
2713
+ * @category Subscription & Loading
2714
+ */
2715
+ waitForSync(options) {
2716
+ return this.raw.core.waitForSync(options);
2717
+ }
2718
+ };
2719
+ RegisteredSchemas["Group"] = Group6;
2720
+ function isAccountID(id) {
2721
+ return id.startsWith("co_");
2722
+ }
2723
+ function getCoValueOwner(coValue) {
2724
+ const group = accessChildById(coValue, coValue.$jazz.raw.group.id, {
2725
+ ref: RegisteredSchemas["Group"],
2726
+ optional: false
2727
+ });
2728
+ if (!group) {
2729
+ throw new Error("CoValue has no owner");
2730
+ }
2731
+ return group;
2732
+ }
2733
+
2734
+ // src/tools/coValues/profile.ts
2735
+ var Profile = class extends CoMap {
2736
+ constructor() {
2737
+ super(...arguments);
2738
+ this.name = coField.string;
2739
+ this.inbox = coField.optional.string;
2740
+ this.inboxInvite = coField.optional.string;
2741
+ }
2742
+ /**
2743
+ * Creates a new profile with the given initial values and owner.
2744
+ *
2745
+ * The owner (a Group) determines access rights to the Profile.
2746
+ *
2747
+ * @category Creation
2748
+ * @deprecated Use `co.profile(...).create` instead.
2749
+ */
2750
+ static create(init, options) {
2751
+ const owner = options !== void 0 && "owner" in options ? options.owner : options;
2752
+ if (owner?.[TypeSym] === "Account") {
2753
+ throw new Error("Profiles should be owned by a group");
2754
+ }
2755
+ return super.create(init, options);
2756
+ }
2757
+ };
2758
+
2759
+ // src/tools/coValues/inbox.ts
2760
+ import { RawAccount as RawAccount2 } from "cojson";
2761
+ function createInboxRoot(account) {
2762
+ if (!account.$jazz.isLocalNodeOwner) {
2763
+ throw new Error("Account is not controlled");
2764
+ }
2765
+ const rawAccount = account.$jazz.raw;
2766
+ const group = rawAccount.core.node.createGroup();
2767
+ const messagesFeed = group.createStream();
2768
+ const inboxRoot = rawAccount.createMap();
2769
+ const processedFeed = rawAccount.createStream();
2770
+ const failedFeed = rawAccount.createStream();
2771
+ const inviteLink = `${messagesFeed.id}/${group.createInvite("writeOnly")}`;
2772
+ inboxRoot.set("messages", messagesFeed.id);
2773
+ inboxRoot.set("processed", processedFeed.id);
2774
+ inboxRoot.set("failed", failedFeed.id);
2775
+ return {
2776
+ id: inboxRoot.id,
2777
+ inviteLink
2778
+ };
2779
+ }
2780
+
2781
+ // src/tools/coValues/coPlainText.ts
2782
+ import { stringifyOpID } from "cojson";
2783
+ import { calcPatch as calcPatch2 } from "fast-myers-diff";
2784
+ var CoPlainText = class extends String {
2785
+ /** @internal */
2786
+ constructor(options) {
2787
+ if (!options) {
2788
+ super("");
2789
+ return;
2790
+ }
2791
+ if ("fromRaw" in options) {
2792
+ super(options.fromRaw.toString());
2793
+ const raw = options.fromRaw;
2794
+ Object.defineProperties(this, {
2795
+ [TypeSym]: { value: "CoPlainText", enumerable: false },
2796
+ $jazz: {
2797
+ value: new CoTextJazzApi(this, raw),
2798
+ enumerable: false
2799
+ }
2800
+ });
2801
+ return;
2802
+ }
2803
+ if ("text" in options && "owner" in options) {
2804
+ super(options.text);
2805
+ const raw = options.owner.$jazz.raw.createPlainText(options.text);
2806
+ Object.defineProperties(this, {
2807
+ [TypeSym]: { value: "CoPlainText", enumerable: false },
2808
+ $jazz: {
2809
+ value: new CoTextJazzApi(this, raw),
2810
+ enumerable: false
2811
+ }
2812
+ });
2813
+ return;
2814
+ }
2815
+ throw new Error("Invalid constructor arguments");
2816
+ }
2817
+ /**
2818
+ * Create a new `CoPlainText` with the given text and owner.
2819
+ *
2820
+ * The owner (a Group or Account) determines access rights to the CoPlainText.
2821
+ *
2822
+ * The CoPlainText will immediately be persisted and synced to connected peers.
2823
+ *
2824
+ * @example
2825
+ * ```ts
2826
+ * const text = CoPlainText.create("Hello, world!", { owner: me });
2827
+ * ```
2828
+ *
2829
+ * @category Creation
2830
+ * @deprecated Use `co.plainText(...).create` instead.
2831
+ */
2832
+ static create(text, options) {
2833
+ const { owner } = parseCoValueCreateOptions(options);
2834
+ return new this({ text, owner });
2835
+ }
2836
+ get length() {
2837
+ return this.$jazz.raw.toString().length;
2838
+ }
2839
+ toString() {
2840
+ return this.$jazz.raw.toString();
2841
+ }
2842
+ valueOf() {
2843
+ return this.$jazz.raw.toString();
2844
+ }
2845
+ toJSON() {
2846
+ return this.$jazz.raw.toString();
2847
+ }
2848
+ [inspect2]() {
2849
+ return this.toJSON();
2850
+ }
2851
+ insertBefore(idx, text) {
2852
+ this.$jazz.raw.insertBefore(idx, text);
2853
+ }
2854
+ insertAfter(idx, text) {
2855
+ this.$jazz.raw.insertAfter(idx, text);
2856
+ }
2857
+ deleteRange(range) {
2858
+ this.$jazz.raw.deleteRange(range);
2859
+ }
2860
+ posBefore(idx) {
2861
+ return this.$jazz.raw.mapping.opIDbeforeIdx[idx];
2862
+ }
2863
+ posAfter(idx) {
2864
+ return this.$jazz.raw.mapping.opIDafterIdx[idx];
2865
+ }
2866
+ idxBefore(pos) {
2867
+ return this.$jazz.raw.mapping.idxBeforeOpID[stringifyOpID(pos)];
2868
+ }
2869
+ idxAfter(pos) {
2870
+ return this.$jazz.raw.mapping.idxAfterOpID[stringifyOpID(pos)];
2871
+ }
2872
+ /** @category Internals */
2873
+ static fromRaw(raw) {
2874
+ return new this({ fromRaw: raw });
2875
+ }
2876
+ /**
2877
+ * Load a `CoPlainText` with a given ID, as a given account.
2878
+ *
2879
+ * @category Subscription & Loading
2880
+ * @deprecated Use `co.plainText(...).load` instead.
2881
+ */
2882
+ static load(id, options) {
2883
+ return loadCoValueWithoutMe(this, id, options);
2884
+ }
2885
+ static subscribe(id, ...args) {
2886
+ const { options, listener } = parseSubscribeRestArgs(args);
2887
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
2888
+ }
2889
+ /**
2890
+ * Allow CoPlainText to behave like a primitive string in most contexts (e.g.,
2891
+ * string concatenation, template literals, React rendering, etc.) by implementing
2892
+ * Symbol.toPrimitive. This eliminates the need to call .toString() explicitly.
2893
+ *
2894
+ * The 'hint' parameter indicates the preferred type of conversion:
2895
+ * - 'string': prefer string conversion
2896
+ * - 'number': prefer number conversion (attempt to parse the text as a number)
2897
+ * - 'default': usually treat as string
2898
+ */
2899
+ [Symbol.toPrimitive](hint) {
2900
+ if (hint === "number") {
2901
+ return Number(this.$jazz.raw.toString());
2902
+ }
2903
+ return this.$jazz.raw.toString();
2904
+ }
2905
+ };
2906
+ var CoTextJazzApi = class extends CoValueJazzApi {
2907
+ constructor(coText, raw) {
2908
+ super(coText);
2909
+ this.coText = coText;
2910
+ this.raw = raw;
2911
+ }
2912
+ get id() {
2913
+ return this.raw.id;
2914
+ }
2915
+ get owner() {
2916
+ return getCoValueOwner(this.coText);
2917
+ }
2918
+ /**
2919
+ * Apply text, modifying the text in place. Calculates the diff and applies it to the CoValue.
2920
+ *
2921
+ * @category Mutation
2922
+ */
2923
+ applyDiff(other) {
2924
+ const current = this.raw.toString();
2925
+ const currentGraphemes = this.raw.toGraphemes(current);
2926
+ const otherGraphemes = this.raw.toGraphemes(other);
2927
+ const patches = [...calcPatch2(currentGraphemes, otherGraphemes)];
2928
+ for (const [from, to, insert] of patches.reverse()) {
2929
+ if (to > from) {
2930
+ this.coText.deleteRange({ from, to });
2931
+ }
2932
+ if (insert.length > 0) {
2933
+ this.coText.insertBefore(from, this.raw.fromGraphemes(insert));
2934
+ }
2935
+ }
2936
+ }
2937
+ /**
2938
+ * Given an already loaded `CoPlainText`, subscribe to updates to the `CoPlainText` and ensure that the specified fields are loaded to the specified depth.
2939
+ *
2940
+ * Works like `CoPlainText.subscribe()`, but you don't need to pass the ID or the account to load as again.
2941
+ *
2942
+ * Returns an unsubscribe function that you should call when you no longer need updates.
2943
+ *
2944
+ * @category Subscription & Loading
2945
+ **/
2946
+ subscribe(listener) {
2947
+ return subscribeToExistingCoValue(this.coText, {}, listener);
2948
+ }
2949
+ };
2950
+
2951
+ // src/tools/coValues/coRichText.ts
2952
+ var CoRichText = class extends CoPlainText {
2953
+ };
2954
+
2955
+ // src/tools/coValues/schemaUnion.ts
2956
+ var SchemaUnion = class _SchemaUnion extends CoValueBase {
2957
+ /**
2958
+ * Create a new union type from a discriminator function.
2959
+ *
2960
+ * The discriminator function receives the raw data and should return the appropriate concrete class to use for that data.
2961
+ *
2962
+ * When loading a SchemaUnion, the correct subclass will be instantiated based on the discriminator.
2963
+ *
2964
+ * @param discriminator - Function that determines which concrete type to use
2965
+ * @returns A new class that can create/load instances of the union type
2966
+ *
2967
+ * @example
2968
+ * ```ts
2969
+ * const WidgetUnion = SchemaUnion.Of<BaseWidget>((raw) => {
2970
+ * switch (raw.get("type")) {
2971
+ * case "button": return ButtonWidget;
2972
+ * case "slider": return SliderWidget;
2973
+ * default: throw new Error("Unknown widget type");
2974
+ * }
2975
+ * });
2976
+ *
2977
+ * const widget = await loadCoValue(WidgetUnion, id, me, {});
2978
+ *
2979
+ * // You can narrow the returned instance to a subclass by using `instanceof`
2980
+ * if (widget instanceof ButtonWidget) {
2981
+ * console.log(widget.label);
2982
+ * } else if (widget instanceof SliderWidget) {
2983
+ * console.log(widget.min, widget.max);
2984
+ * }
2985
+ * ```
2986
+ *
2987
+ * @category Declaration
2988
+ **/
2989
+ static Of(discriminator) {
2990
+ return class SchemaUnionClass extends _SchemaUnion {
2991
+ static create(init, owner) {
2992
+ const ResolvedClass = discriminator(new Map(Object.entries(init)));
2993
+ return ResolvedClass.create(init, owner);
2994
+ }
2995
+ static fromRaw(raw) {
2996
+ const ResolvedClass = discriminator(
2997
+ raw
2998
+ );
2999
+ return ResolvedClass.fromRaw(raw);
3000
+ }
3001
+ };
3002
+ }
3003
+ static create(init, owner) {
3004
+ throw new Error("Not implemented");
3005
+ }
3006
+ /**
3007
+ * Create an instance from raw data. This is called internally and should not be used directly.
3008
+ * Use {@link SchemaUnion.Of} to create a union type instead.
3009
+ *
3010
+ * @internal
3011
+ */
3012
+ static fromRaw(raw) {
3013
+ throw new Error("Not implemented");
3014
+ }
3015
+ /**
3016
+ * Load a `SchemaUnion` with a given ID, as a given account.
3017
+ *
3018
+ * Note: The `resolve` option is not supported for `SchemaUnion`s due to https://github.com/garden-co/jazz/issues/2639
3019
+ *
3020
+ * @category Subscription & Loading
3021
+ */
3022
+ static load(id, options) {
3023
+ return loadCoValueWithoutMe(this, id, options);
3024
+ }
3025
+ static subscribe(id, ...args) {
3026
+ const { options, listener } = parseSubscribeRestArgs(args);
3027
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
3028
+ }
3029
+ };
3030
+
3031
+ // src/tools/implementation/anonymousJazzAgent.ts
3032
+ var _a;
3033
+ _a = TypeSym;
3034
+ var AnonymousJazzAgent2 = class {
3035
+ constructor(node) {
3036
+ this.node = node;
3037
+ this[_a] = "Anonymous";
3038
+ }
3039
+ };
3040
+
3041
+ // src/tools/implementation/activeAccountContext.ts
3042
+ var ActiveAccountContext = class {
3043
+ constructor() {
3044
+ this.activeAccount = null;
3045
+ this.guestMode = false;
3046
+ }
3047
+ set(account) {
3048
+ this.activeAccount = account;
3049
+ this.guestMode = false;
3050
+ }
3051
+ setGuestMode() {
3052
+ this.activeAccount = null;
3053
+ this.guestMode = true;
3054
+ }
3055
+ maybeGet() {
3056
+ return this.activeAccount;
3057
+ }
3058
+ get() {
3059
+ if (!this.activeAccount) {
3060
+ if (this.guestMode) {
3061
+ throw new Error(
3062
+ "Something that expects a full active account was called in guest mode."
3063
+ );
3064
+ }
3065
+ throw new Error("No active account");
3066
+ }
3067
+ return this.activeAccount;
3068
+ }
3069
+ };
3070
+ var activeAccountContext = new ActiveAccountContext();
3071
+
3072
+ // src/tools/implementation/refs.ts
3073
+ var Ref = class {
3074
+ constructor(id, controlledAccount, schema, parent) {
3075
+ this.id = id;
3076
+ this.controlledAccount = controlledAccount;
3077
+ this.schema = schema;
3078
+ this.parent = parent;
3079
+ if (!isRefEncoded(schema)) {
3080
+ throw new Error("Ref must be constructed with a ref schema");
3081
+ }
3082
+ }
3083
+ async load() {
3084
+ const subscriptionScope = getSubscriptionScope(this.parent);
3085
+ subscriptionScope.subscribeToId(this.id, this.schema);
3086
+ const node = subscriptionScope.childNodes.get(this.id);
3087
+ if (!node) {
3088
+ return null;
3089
+ }
3090
+ const value = node.value;
3091
+ if (value?.type === "loaded") {
3092
+ return value.value;
3093
+ } else {
3094
+ return new Promise((resolve) => {
3095
+ const unsubscribe = node.subscribe((value2) => {
3096
+ if (value2?.type === "loaded") {
3097
+ unsubscribe();
3098
+ resolve(value2.value);
3099
+ } else if (value2?.type === "unavailable") {
3100
+ unsubscribe();
3101
+ resolve(null);
3102
+ } else if (value2?.type === "unauthorized") {
3103
+ unsubscribe();
3104
+ resolve(null);
3105
+ }
3106
+ });
3107
+ });
3108
+ }
3109
+ }
3110
+ get value() {
3111
+ return accessChildById(this.parent, this.id, this.schema);
3112
+ }
3113
+ };
3114
+ function makeRefs(parent, getIdForKey, getKeysWithIds, controlledAccount, refSchemaForKey) {
3115
+ const refs = {};
3116
+ return new Proxy(refs, {
3117
+ get(_target, key) {
3118
+ if (key === Symbol.iterator) {
3119
+ return function* () {
3120
+ for (const key2 of getKeysWithIds()) {
3121
+ yield new Ref(
3122
+ getIdForKey(key2),
3123
+ controlledAccount,
3124
+ refSchemaForKey(key2),
3125
+ parent
3126
+ );
3127
+ }
3128
+ };
3129
+ }
3130
+ if (typeof key === "symbol") return void 0;
3131
+ if (key === "length") {
3132
+ return getKeysWithIds().length;
3133
+ }
3134
+ const id = getIdForKey(key);
3135
+ if (!id) return void 0;
3136
+ return new Ref(
3137
+ id,
3138
+ controlledAccount,
3139
+ refSchemaForKey(key),
3140
+ parent
3141
+ );
3142
+ },
3143
+ ownKeys() {
3144
+ return getKeysWithIds().map((key) => key.toString());
3145
+ },
3146
+ getOwnPropertyDescriptor(target, key) {
3147
+ const id = getIdForKey(key);
3148
+ if (id) {
3149
+ return {
3150
+ enumerable: true,
3151
+ configurable: true,
3152
+ writable: true
3153
+ };
3154
+ } else {
3155
+ return Reflect.getOwnPropertyDescriptor(target, key);
3156
+ }
3157
+ }
3158
+ });
3159
+ }
3160
+
3161
+ // src/tools/implementation/schema.ts
3162
+ var Encoders = {
3163
+ Date: {
3164
+ encode: (value) => value.toISOString(),
3165
+ decode: (value) => new Date(value)
3166
+ },
3167
+ OptionalDate: {
3168
+ encode: (value) => value?.toISOString() || null,
3169
+ decode: (value) => value === null ? void 0 : new Date(value)
3170
+ }
3171
+ };
3172
+ var optional = {
3173
+ ref: optionalRef,
3174
+ json() {
3175
+ return { [SchemaInit]: "json" };
3176
+ },
3177
+ encoded(arg) {
3178
+ return { [SchemaInit]: { encoded: arg } };
3179
+ },
3180
+ string: {
3181
+ [SchemaInit]: "json"
3182
+ },
3183
+ number: {
3184
+ [SchemaInit]: "json"
3185
+ },
3186
+ boolean: {
3187
+ [SchemaInit]: "json"
3188
+ },
3189
+ null: {
3190
+ [SchemaInit]: "json"
3191
+ },
3192
+ Date: {
3193
+ [SchemaInit]: { encoded: Encoders.OptionalDate }
3194
+ },
3195
+ literal(..._lit) {
3196
+ return { [SchemaInit]: "json" };
3197
+ }
3198
+ };
3199
+ var coField = {
3200
+ string: {
3201
+ [SchemaInit]: "json"
3202
+ },
3203
+ number: {
3204
+ [SchemaInit]: "json"
3205
+ },
3206
+ boolean: {
3207
+ [SchemaInit]: "json"
3208
+ },
3209
+ null: {
3210
+ [SchemaInit]: "json"
3211
+ },
3212
+ Date: {
3213
+ [SchemaInit]: { encoded: Encoders.Date }
3214
+ },
3215
+ literal(..._lit) {
3216
+ return { [SchemaInit]: "json" };
3217
+ },
3218
+ json() {
3219
+ return { [SchemaInit]: "json" };
3220
+ },
3221
+ encoded(arg) {
3222
+ return { [SchemaInit]: { encoded: arg } };
3223
+ },
3224
+ ref,
3225
+ items: ItemsSym,
3226
+ optional
3227
+ };
3228
+ function optionalRef(arg) {
3229
+ return ref(arg, { optional: true });
3230
+ }
3231
+ function ref(arg, options) {
3232
+ return {
3233
+ [SchemaInit]: {
3234
+ ref: arg,
3235
+ optional: options?.optional || false
3236
+ }
3237
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3238
+ };
3239
+ }
3240
+ function isRefEncoded(schema) {
3241
+ return typeof schema === "object" && "ref" in schema && "optional" in schema && typeof schema.ref === "function";
3242
+ }
3243
+ function instantiateRefEncodedFromRaw(schema, raw) {
3244
+ return isCoValueClass(schema.ref) ? schema.ref.fromRaw(raw) : schema.ref(
3245
+ raw
3246
+ ).fromRaw(raw);
3247
+ }
3248
+ function instantiateRefEncodedWithInit(schema, init, parentOwner) {
3249
+ if (!isCoValueClass(schema.ref)) {
3250
+ throw Error(
3251
+ `Cannot automatically create CoValue from value: ${JSON.stringify(init)}. Use the CoValue schema's create() method instead.`
3252
+ );
3253
+ }
3254
+ const node = parentOwner.$jazz.localNode;
3255
+ const rawGroup = node.createGroup();
3256
+ const owner = new Group6({ fromRaw: rawGroup });
3257
+ owner.addMember(parentOwner);
3258
+ return schema.ref.create(init, owner);
3259
+ }
3260
+
3261
+ // src/tools/lib/migration.ts
3262
+ function applyCoValueMigrations(instance) {
3263
+ const node = instance.$jazz.raw.core.node;
3264
+ const migratedCoValues = node._migratedCoValues ??= /* @__PURE__ */ new Set();
3265
+ if ("migrate" in instance && typeof instance.migrate === "function" && instance[TypeSym] !== "Account" && !migratedCoValues.has(instance.$jazz.id)) {
3266
+ migratedCoValues.add(instance.$jazz.id);
3267
+ const result = instance.migrate?.(instance);
3268
+ if (result && "then" in result) {
3269
+ throw new Error("Migration function cannot be async");
3270
+ }
3271
+ }
3272
+ }
3273
+
3274
+ // src/tools/subscribe/CoValueCoreSubscription.ts
3275
+ var CoValueCoreSubscription = class {
3276
+ constructor(node, id, listener, skipRetry) {
3277
+ this.node = node;
3278
+ this.id = id;
3279
+ this.listener = listener;
3280
+ this.skipRetry = skipRetry;
3281
+ this._unsubscribe = () => {
3282
+ };
3283
+ this.unsubscribed = false;
3284
+ const entry = this.node.getCoValue(this.id);
3285
+ if (entry?.isAvailable()) {
3286
+ this.subscribe(entry.getCurrentContent());
3287
+ } else {
3288
+ this.node.loadCoValueCore(this.id, void 0, skipRetry).then((value) => {
3289
+ if (this.unsubscribed) return;
3290
+ if (value.isAvailable()) {
3291
+ this.subscribe(value.getCurrentContent());
3292
+ } else {
3293
+ this.subscribeToState();
3294
+ this.listener("unavailable");
3295
+ }
3296
+ }).catch((error) => {
3297
+ console.error("Unexpected error loading CoValue: ", error);
3298
+ this.listener("unavailable");
3299
+ });
3300
+ }
3301
+ }
3302
+ subscribeToState() {
3303
+ const entry = this.node.getCoValue(this.id);
3304
+ const handleStateChange = (core2, unsubFromStateChange2) => {
3305
+ if (this.unsubscribed) {
3306
+ unsubFromStateChange2();
3307
+ return;
3308
+ }
3309
+ if (core2.isAvailable()) {
3310
+ this.subscribe(core2.getCurrentContent());
3311
+ unsubFromStateChange2();
3312
+ }
3313
+ };
3314
+ const unsubFromStateChange = entry.subscribe(handleStateChange);
3315
+ this._unsubscribe = () => {
3316
+ unsubFromStateChange();
3317
+ };
3318
+ }
3319
+ subscribe(value) {
3320
+ if (this.unsubscribed) return;
3321
+ this._unsubscribe = value.subscribe((value2) => {
3322
+ this.listener(value2);
3323
+ });
3324
+ this.listener(value);
3325
+ }
3326
+ unsubscribe() {
3327
+ if (this.unsubscribed) return;
3328
+ this.unsubscribed = true;
3329
+ this._unsubscribe();
3330
+ }
3331
+ };
3332
+
3333
+ // src/tools/subscribe/JazzError.ts
3334
+ var JazzError = class _JazzError {
3335
+ constructor(id, type, issues) {
3336
+ this.id = id;
3337
+ this.type = type;
3338
+ this.issues = issues;
3339
+ }
3340
+ toString() {
3341
+ return this.issues.map((issue) => {
3342
+ let message = `${issue.message}`;
3343
+ if (this.id) {
3344
+ message += ` from ${this.id}`;
3345
+ }
3346
+ if (issue.path.length > 0) {
3347
+ message += ` on path ${issue.path.join(".")}`;
3348
+ }
3349
+ return message;
3350
+ }).join("\n");
3351
+ }
3352
+ prependPath(item) {
3353
+ if (this.issues.length === 0) {
3354
+ return this;
3355
+ }
3356
+ const issues = this.issues.map((issue) => {
3357
+ return {
3358
+ ...issue,
3359
+ path: [item].concat(issue.path)
3360
+ };
3361
+ });
3362
+ return new _JazzError(this.id, this.type, issues);
3363
+ }
3364
+ };
3365
+
3366
+ // src/tools/subscribe/utils.ts
3367
+ import { RawAccount as RawAccount3 } from "cojson";
3368
+
3369
+ // src/tools/lib/cache.ts
3370
+ var weakMap = /* @__PURE__ */ new WeakMap();
3371
+ var coValuesCache = {
3372
+ get: (raw, compute) => {
3373
+ const cached = weakMap.get(raw);
3374
+ if (cached) {
3375
+ return cached;
3376
+ }
3377
+ const computed = compute();
3378
+ weakMap.set(raw, computed);
3379
+ return computed;
3380
+ }
3381
+ };
3382
+
3383
+ // src/tools/subscribe/utils.ts
3384
+ function myRoleForRawValue(raw) {
3385
+ const rawOwner = raw.group;
3386
+ const owner = coValuesCache.get(
3387
+ rawOwner,
3388
+ () => rawOwner instanceof RawAccount3 ? RegisteredSchemas["Account"].fromRaw(rawOwner) : RegisteredSchemas["Group"].fromRaw(rawOwner)
3389
+ );
3390
+ return accountOrGroupToGroup(owner).myRole();
3391
+ }
3392
+ function createCoValue(ref2, raw, subscriptionScope) {
3393
+ const freshValueInstance = instantiateRefEncodedFromRaw(ref2, raw);
3394
+ Object.defineProperty(freshValueInstance.$jazz, "_subscriptionScope", {
3395
+ value: subscriptionScope,
3396
+ writable: false,
3397
+ enumerable: false,
3398
+ configurable: false
3399
+ });
3400
+ return {
3401
+ type: "loaded",
3402
+ value: freshValueInstance,
3403
+ id: subscriptionScope.id
3404
+ };
3405
+ }
3406
+
3407
+ // src/tools/subscribe/SubscriptionScope.ts
3408
+ var SubscriptionScope = class _SubscriptionScope {
3409
+ constructor(node, resolve, id, schema, skipRetry = false, bestEffortResolution = false) {
3410
+ this.node = node;
3411
+ this.id = id;
3412
+ this.schema = schema;
3413
+ this.skipRetry = skipRetry;
3414
+ this.bestEffortResolution = bestEffortResolution;
3415
+ this.childNodes = /* @__PURE__ */ new Map();
3416
+ this.childValues = /* @__PURE__ */ new Map();
3417
+ this.childErrors = /* @__PURE__ */ new Map();
3418
+ this.validationErrors = /* @__PURE__ */ new Map();
3419
+ this.dirty = false;
3420
+ this.idsSubscribed = /* @__PURE__ */ new Set();
3421
+ this.autoloaded = /* @__PURE__ */ new Set();
3422
+ this.autoloadedKeys = /* @__PURE__ */ new Set();
3423
+ this.skipInvalidKeys = /* @__PURE__ */ new Set();
3424
+ this.totalValidTransactions = 0;
3425
+ this.migrated = false;
3426
+ this.migrating = false;
3427
+ this.silenceUpdates = false;
3428
+ this.handleChildUpdate = (id, value, key) => {
3429
+ if (value.type === "unloaded") {
3430
+ return;
3431
+ }
3432
+ this.childValues.set(id, value);
3433
+ if (value.type === "unavailable" || value.type === "unauthorized") {
3434
+ this.childErrors.set(id, value.prependPath(key ?? id));
3435
+ this.errorFromChildren = this.computeChildErrors();
3436
+ } else if (this.errorFromChildren && this.childErrors.has(id)) {
3437
+ this.childErrors.delete(id);
3438
+ this.errorFromChildren = this.computeChildErrors();
3439
+ }
3440
+ if (this.shouldSendUpdates()) {
3441
+ if (this.value.type === "loaded") {
3442
+ this.updateValue(
3443
+ createCoValue(this.schema, this.value.value.$jazz.raw, this)
3444
+ );
3445
+ }
3446
+ }
3447
+ this.triggerUpdate();
3448
+ };
3449
+ this.subscribers = /* @__PURE__ */ new Set();
3450
+ this.resolve = resolve;
3451
+ this.value = { type: "unloaded", id };
3452
+ let lastUpdate;
3453
+ this.subscription = new CoValueCoreSubscription(
3454
+ node,
3455
+ id,
3456
+ (value) => {
3457
+ lastUpdate = value;
3458
+ if (skipRetry && value === "unavailable") {
3459
+ this.handleUpdate(value);
3460
+ this.destroy();
3461
+ return;
3462
+ }
3463
+ if (!this.migrated && value !== "unavailable") {
3464
+ if (this.migrating) {
3465
+ return;
3466
+ }
3467
+ this.migrating = true;
3468
+ applyCoValueMigrations(
3469
+ instantiateRefEncodedFromRaw(this.schema, value)
3470
+ );
3471
+ this.migrated = true;
3472
+ this.handleUpdate(lastUpdate);
3473
+ return;
3474
+ }
3475
+ this.handleUpdate(value);
3476
+ },
3477
+ skipRetry
3478
+ );
3479
+ }
3480
+ updateValue(value) {
3481
+ this.value = value;
3482
+ this.dirty = true;
3483
+ }
3484
+ handleUpdate(update) {
3485
+ if (update === "unavailable") {
3486
+ if (this.value.type === "unloaded") {
3487
+ this.updateValue(
3488
+ new JazzError(this.id, "unavailable", [
3489
+ {
3490
+ code: "unavailable",
3491
+ message: "The value is unavailable",
3492
+ params: {
3493
+ id: this.id
3494
+ },
3495
+ path: []
3496
+ }
3497
+ ])
3498
+ );
3499
+ }
3500
+ this.triggerUpdate();
3501
+ return;
3502
+ }
3503
+ const ruleset = update.core.verified.header.ruleset;
3504
+ const hasAccess = ruleset.type !== "ownedByGroup" || myRoleForRawValue(update) !== void 0;
3505
+ if (!hasAccess) {
3506
+ if (this.value.type !== "unauthorized") {
3507
+ this.updateValue(
3508
+ new JazzError(this.id, "unauthorized", [
3509
+ {
3510
+ code: "unauthorized",
3511
+ message: `The current user (${this.node.getCurrentAgent().id}) is not authorized to access this value`,
3512
+ params: {
3513
+ id: this.id
3514
+ },
3515
+ path: []
3516
+ }
3517
+ ])
3518
+ );
3519
+ this.triggerUpdate();
3520
+ }
3521
+ return;
3522
+ }
3523
+ this.silenceUpdates = true;
3524
+ if (this.value.type !== "loaded") {
3525
+ this.updateValue(createCoValue(this.schema, update, this));
3526
+ this.loadChildren();
3527
+ } else {
3528
+ const hasChanged = update.totalValidTransactions !== this.totalValidTransactions || // Checking the identity of the raw value makes us cover the cases where the group
3529
+ // has been updated and the coValues that don't update the totalValidTransactions value (e.g. FileStream)
3530
+ this.value.value.$jazz.raw !== update;
3531
+ if (this.loadChildren()) {
3532
+ this.updateValue(createCoValue(this.schema, update, this));
3533
+ } else if (hasChanged) {
3534
+ this.updateValue(createCoValue(this.schema, update, this));
3535
+ }
3536
+ }
3537
+ this.totalValidTransactions = update.totalValidTransactions;
3538
+ this.silenceUpdates = false;
3539
+ this.triggerUpdate();
3540
+ }
3541
+ computeChildErrors() {
3542
+ let issues = [];
3543
+ let errorType = "unavailable";
3544
+ if (this.childErrors.size === 0 && this.validationErrors.size === 0) {
3545
+ return void 0;
3546
+ }
3547
+ if (this.bestEffortResolution) {
3548
+ return void 0;
3549
+ }
3550
+ for (const [key, value] of this.childErrors.entries()) {
3551
+ if (this.autoloaded.has(key)) {
3552
+ continue;
3553
+ }
3554
+ if (this.skipInvalidKeys.has(key)) {
3555
+ continue;
3556
+ }
3557
+ errorType = value.type;
3558
+ if (value.issues) {
3559
+ issues.push(...value.issues);
3560
+ }
3561
+ }
3562
+ for (const [key, value] of this.validationErrors.entries()) {
3563
+ if (this.skipInvalidKeys.has(key)) {
3564
+ continue;
3565
+ }
3566
+ errorType = value.type;
3567
+ if (value.issues) {
3568
+ issues.push(...value.issues);
3569
+ }
3570
+ }
3571
+ if (issues.length) {
3572
+ return new JazzError(this.id, errorType, issues);
3573
+ }
3574
+ return void 0;
3575
+ }
3576
+ shouldSendUpdates() {
3577
+ if (this.value.type === "unloaded") return false;
3578
+ if (this.value.type !== "loaded") return true;
3579
+ if (this.isStreaming() && !this.isFileStream()) {
3580
+ return false;
3581
+ }
3582
+ for (const value of this.childValues.values()) {
3583
+ if (value.type === "unloaded" && !this.autoloaded.has(value.id)) {
3584
+ return false;
3585
+ }
3586
+ }
3587
+ return true;
3588
+ }
3589
+ getCurrentValue() {
3590
+ if (this.value.type === "unauthorized" || this.value.type === "unavailable") {
3591
+ console.error(this.value.toString());
3592
+ return null;
3593
+ }
3594
+ if (!this.shouldSendUpdates()) {
3595
+ return void 0;
3596
+ }
3597
+ if (this.errorFromChildren) {
3598
+ console.error(this.errorFromChildren.toString());
3599
+ return null;
3600
+ }
3601
+ if (this.value.type === "loaded") {
3602
+ return this.value.value;
3603
+ }
3604
+ return void 0;
3605
+ }
3606
+ isStreaming() {
3607
+ if (this.value.type !== "loaded") {
3608
+ return false;
3609
+ }
3610
+ return this.value.value.$jazz.raw.core.verified.isStreaming();
3611
+ }
3612
+ isFileStream() {
3613
+ if (this.value.type !== "loaded") {
3614
+ return false;
3615
+ }
3616
+ return this.value.value.$jazz.raw.core.verified.header.meta?.type === "binary";
3617
+ }
3618
+ triggerUpdate() {
3619
+ if (!this.shouldSendUpdates()) return;
3620
+ if (!this.dirty) return;
3621
+ if (this.subscribers.size === 0) return;
3622
+ if (this.silenceUpdates) return;
3623
+ const error = this.errorFromChildren;
3624
+ const value = this.value;
3625
+ if (error) {
3626
+ this.subscribers.forEach((listener) => listener(error));
3627
+ } else if (value.type !== "unloaded") {
3628
+ this.subscribers.forEach((listener) => listener(value));
3629
+ }
3630
+ this.dirty = false;
3631
+ }
3632
+ subscribe(listener) {
3633
+ this.subscribers.add(listener);
3634
+ return () => {
3635
+ this.subscribers.delete(listener);
3636
+ };
3637
+ }
3638
+ setListener(listener) {
3639
+ this.subscribers.add(listener);
3640
+ this.triggerUpdate();
3641
+ }
3642
+ subscribeToKey(key) {
3643
+ if (this.resolve === true || !this.resolve) {
3644
+ this.resolve = {};
3645
+ }
3646
+ if (!this.resolve.$each && !(key in this.resolve)) {
3647
+ const resolve = this.resolve;
3648
+ resolve[key] = true;
3649
+ this.autoloadedKeys.add(key);
3650
+ }
3651
+ if (this.value.type !== "loaded") {
3652
+ return;
3653
+ }
3654
+ const value = this.value.value;
3655
+ this.silenceUpdates = true;
3656
+ if (value[TypeSym] === "CoMap" || value[TypeSym] === "Account") {
3657
+ const map = value;
3658
+ this.loadCoMapKey(map, key, true);
3659
+ } else if (value[TypeSym] === "CoList") {
3660
+ const list = value;
3661
+ this.loadCoListKey(list, key, true);
3662
+ }
3663
+ this.silenceUpdates = false;
3664
+ }
3665
+ subscribeToId(id, descriptor) {
3666
+ if (this.idsSubscribed.has(id) || this.childValues.has(id)) {
3667
+ return;
3668
+ }
3669
+ this.idsSubscribed.add(id);
3670
+ this.autoloaded.add(id);
3671
+ this.silenceUpdates = true;
3672
+ this.childValues.set(id, { type: "unloaded", id });
3673
+ const child = new _SubscriptionScope(
3674
+ this.node,
3675
+ true,
3676
+ id,
3677
+ descriptor,
3678
+ this.skipRetry,
3679
+ this.bestEffortResolution
3680
+ );
3681
+ this.childNodes.set(id, child);
3682
+ child.setListener((value) => this.handleChildUpdate(id, value));
3683
+ this.silenceUpdates = false;
3684
+ }
3685
+ loadChildren() {
3686
+ const { resolve } = this;
3687
+ if (this.value.type !== "loaded") {
3688
+ return false;
3689
+ }
3690
+ const value = this.value.value;
3691
+ const depth = typeof resolve !== "object" || resolve === null ? {} : resolve;
3692
+ let hasChanged = false;
3693
+ const idsToLoad = new Set(this.idsSubscribed);
3694
+ const coValueType = value[TypeSym];
3695
+ if (Object.keys(depth).length > 0) {
3696
+ if (coValueType === "CoMap" || coValueType === "Account" || coValueType === "Group") {
3697
+ const map = value;
3698
+ const keys = "$each" in depth ? map.$jazz.raw.keys() : Object.keys(depth);
3699
+ for (const key of keys) {
3700
+ const id = this.loadCoMapKey(map, key, depth[key] ?? depth.$each);
3701
+ if (id) {
3702
+ idsToLoad.add(id);
3703
+ }
3704
+ }
3705
+ } else if (value[TypeSym] === "CoList") {
3706
+ const list = value;
3707
+ const descriptor = list.$jazz.getItemsDescriptor();
3708
+ if (descriptor && isRefEncoded(descriptor)) {
3709
+ list.$jazz.raw.processNewTransactions();
3710
+ const entries = list.$jazz.raw.entries();
3711
+ const keys = "$each" in depth ? Object.keys(entries) : Object.keys(depth);
3712
+ for (const key of keys) {
3713
+ const id = this.loadCoListKey(list, key, depth[key] ?? depth.$each);
3714
+ if (id) {
3715
+ idsToLoad.add(id);
3716
+ }
3717
+ }
3718
+ }
3719
+ } else if (value[TypeSym] === "CoStream") {
3720
+ const stream = value;
3721
+ const descriptor = stream.$jazz.getItemsDescriptor();
3722
+ if (descriptor && isRefEncoded(descriptor)) {
3723
+ for (const session of stream.$jazz.raw.sessions()) {
3724
+ const values = stream.$jazz.raw.items[session] ?? [];
3725
+ for (const [i, item] of values.entries()) {
3726
+ const key = `${session}/${i}`;
3727
+ if (!depth.$each && !depth[key]) {
3728
+ continue;
3729
+ }
3730
+ const id = item.value;
3731
+ if (id) {
3732
+ idsToLoad.add(id);
3733
+ this.loadChildNode(id, depth[key] ?? depth.$each, descriptor);
3734
+ this.validationErrors.delete(key);
3735
+ } else if (!descriptor.optional) {
3736
+ this.validationErrors.set(
3737
+ key,
3738
+ new JazzError(void 0, "unavailable", [
3739
+ {
3740
+ code: "validationError",
3741
+ message: `The ref on position ${key} requested on ${stream.constructor.name} is missing`,
3742
+ params: {},
3743
+ path: [key]
3744
+ }
3745
+ ])
3746
+ );
3747
+ }
3748
+ }
3749
+ }
3750
+ }
3751
+ }
3752
+ }
3753
+ this.errorFromChildren = this.computeChildErrors();
3754
+ for (const id of this.childNodes.keys()) {
3755
+ if (!idsToLoad.has(id)) {
3756
+ hasChanged = true;
3757
+ const childNode = this.childNodes.get(id);
3758
+ if (childNode) {
3759
+ childNode.destroy();
3760
+ }
3761
+ this.childNodes.delete(id);
3762
+ this.childValues.delete(id);
3763
+ }
3764
+ }
3765
+ return hasChanged;
3766
+ }
3767
+ loadCoMapKey(map, key, depth) {
3768
+ if (key === "$onError") {
3769
+ return void 0;
3770
+ }
3771
+ const id = map.$jazz.raw.get(key);
3772
+ const descriptor = map.$jazz.getDescriptor(key);
3773
+ if (!descriptor) {
3774
+ this.childErrors.set(
3775
+ key,
3776
+ new JazzError(void 0, "unavailable", [
3777
+ {
3778
+ code: "validationError",
3779
+ message: `The ref ${key} requested on ${map.constructor.name} is not defined in the schema`,
3780
+ params: {},
3781
+ path: [key]
3782
+ }
3783
+ ])
3784
+ );
3785
+ return void 0;
3786
+ }
3787
+ if (isRefEncoded(descriptor)) {
3788
+ if (id) {
3789
+ this.loadChildNode(id, depth, descriptor, key);
3790
+ this.validationErrors.delete(key);
3791
+ return id;
3792
+ } else if (!descriptor.optional) {
3793
+ this.validationErrors.set(
3794
+ key,
3795
+ new JazzError(void 0, "unavailable", [
3796
+ {
3797
+ code: "validationError",
3798
+ message: `The ref ${key} requested on ${map.constructor.name} is missing`,
3799
+ params: {},
3800
+ path: [key]
3801
+ }
3802
+ ])
3803
+ );
3804
+ }
3805
+ }
3806
+ return void 0;
3807
+ }
3808
+ loadCoListKey(list, key, depth) {
3809
+ const descriptor = list.$jazz.getItemsDescriptor();
3810
+ if (!descriptor || !isRefEncoded(descriptor)) {
3811
+ return void 0;
3812
+ }
3813
+ const entries = list.$jazz.raw.entries();
3814
+ const entry = entries[Number(key)];
3815
+ if (!entry) {
3816
+ return void 0;
3817
+ }
3818
+ const id = entry.value;
3819
+ if (id) {
3820
+ this.loadChildNode(id, depth, descriptor, key);
3821
+ this.validationErrors.delete(key);
3822
+ return id;
3823
+ } else if (!descriptor.optional) {
3824
+ this.validationErrors.set(
3825
+ key,
3826
+ new JazzError(void 0, "unavailable", [
3827
+ {
3828
+ code: "validationError",
3829
+ message: `The ref on position ${key} requested on ${list.constructor.name} is missing`,
3830
+ params: {},
3831
+ path: [key]
3832
+ }
3833
+ ])
3834
+ );
3835
+ }
3836
+ return void 0;
3837
+ }
3838
+ loadChildNode(id, query, descriptor, key) {
3839
+ if (this.childValues.has(id)) {
3840
+ return;
3841
+ }
3842
+ if (key && this.autoloadedKeys.has(key)) {
3843
+ this.autoloaded.add(id);
3844
+ }
3845
+ const skipInvalid = typeof query === "object" && query.$onError === null;
3846
+ if (skipInvalid) {
3847
+ if (key) {
3848
+ this.skipInvalidKeys.add(key);
3849
+ }
3850
+ this.skipInvalidKeys.add(id);
3851
+ }
3852
+ const resolve = typeof query === "object" && query !== null ? { ...query } : query;
3853
+ this.childValues.set(id, { type: "unloaded", id });
3854
+ const child = new _SubscriptionScope(
3855
+ this.node,
3856
+ resolve,
3857
+ id,
3858
+ descriptor,
3859
+ this.skipRetry,
3860
+ this.bestEffortResolution
3861
+ );
3862
+ this.childNodes.set(id, child);
3863
+ child.setListener((value) => this.handleChildUpdate(id, value, key));
3864
+ }
3865
+ destroy() {
3866
+ this.subscription.unsubscribe();
3867
+ this.subscribers.clear();
3868
+ this.childNodes.forEach((child) => child.destroy());
3869
+ }
3870
+ };
3871
+
3872
+ // src/tools/subscribe/index.ts
3873
+ function getSubscriptionScope(value) {
3874
+ const subscriptionScope = value.$jazz._subscriptionScope;
3875
+ if (subscriptionScope) {
3876
+ return subscriptionScope;
3877
+ }
3878
+ const node = value.$jazz.raw.core.node;
3879
+ const resolve = true;
3880
+ const id = value.$jazz.id;
3881
+ const newSubscriptionScope = new SubscriptionScope(node, resolve, id, {
3882
+ ref: value.constructor,
3883
+ optional: false
3884
+ });
3885
+ Object.defineProperty(value.$jazz, "_subscriptionScope", {
3886
+ value: subscriptionScope,
3887
+ writable: false,
3888
+ enumerable: false,
3889
+ configurable: false
3890
+ });
3891
+ return newSubscriptionScope;
3892
+ }
3893
+ function accessChildByKey(parent, childId, key) {
3894
+ const subscriptionScope = getSubscriptionScope(parent);
3895
+ if (!subscriptionScope.childValues.has(childId)) {
3896
+ subscriptionScope.subscribeToKey(key);
3897
+ }
3898
+ const value = subscriptionScope.childValues.get(childId);
3899
+ if (value?.type === "loaded") {
3900
+ return value.value;
3901
+ } else {
3902
+ return null;
3903
+ }
3904
+ }
3905
+ function accessChildById(parent, childId, schema) {
3906
+ const subscriptionScope = getSubscriptionScope(parent);
3907
+ subscriptionScope.subscribeToId(childId, schema);
3908
+ const value = subscriptionScope.childValues.get(childId);
3909
+ if (value?.type === "loaded") {
3910
+ return value.value;
3911
+ } else {
3912
+ return null;
3913
+ }
3914
+ }
3915
+
3916
+ // src/tools/implementation/createContext.ts
3917
+ import {
3918
+ LocalNode as LocalNode3
3919
+ } from "cojson";
3920
+
3921
+ // src/tools/implementation/schemaUtils.ts
3922
+ function removeGetters(obj) {
3923
+ const result = {};
3924
+ for (const key of Object.keys(obj)) {
3925
+ const descriptor = Object.getOwnPropertyDescriptor(obj, key);
3926
+ if (!descriptor?.get) {
3927
+ result[key] = obj[key];
3928
+ }
3929
+ }
3930
+ return result;
3931
+ }
3932
+
3933
+ // src/tools/implementation/zodSchema/schemaTypes/CoDiscriminatedUnionSchema.ts
3934
+ var CoDiscriminatedUnionSchema = class {
3935
+ constructor(coreSchema, coValueClass) {
3936
+ this.coValueClass = coValueClass;
3937
+ this.collaborative = true;
3938
+ this.builtin = "CoDiscriminatedUnion";
3939
+ this.getDefinition = coreSchema.getDefinition;
3940
+ }
3941
+ load(id, options) {
3942
+ return this.coValueClass.load(id, options);
3943
+ }
3944
+ subscribe(id, options, listener) {
3945
+ return this.coValueClass.subscribe(id, options, listener);
3946
+ }
3947
+ getCoValueClass() {
3948
+ return this.coValueClass;
3949
+ }
3950
+ optional() {
3951
+ return coOptionalDefiner(this);
3952
+ }
3953
+ };
3954
+
3955
+ // src/tools/implementation/zodSchema/schemaTypes/CoOptionalSchema.ts
3956
+ var CoOptionalSchema = class {
3957
+ constructor(innerType) {
3958
+ this.innerType = innerType;
3959
+ this.collaborative = true;
3960
+ this.builtin = "CoOptional";
3961
+ this.getDefinition = () => ({
3962
+ innerType: this.innerType
3963
+ });
3964
+ }
3965
+ getCoValueClass() {
3966
+ return this.innerType.getCoValueClass();
3967
+ }
3968
+ };
3969
+
3970
+ // src/tools/implementation/zodSchema/schemaTypes/RichTextSchema.ts
3971
+ var RichTextSchema = class {
3972
+ constructor(coValueClass) {
3973
+ this.coValueClass = coValueClass;
3974
+ this.collaborative = true;
3975
+ this.builtin = "CoRichText";
3976
+ }
3977
+ create(text, options) {
3978
+ return this.coValueClass.create(text, options);
3979
+ }
3980
+ load(id, options) {
3981
+ return this.coValueClass.load(id, options);
3982
+ }
3983
+ subscribe(...args) {
3984
+ return this.coValueClass.subscribe(...args);
3985
+ }
3986
+ getCoValueClass() {
3987
+ return this.coValueClass;
3988
+ }
3989
+ optional() {
3990
+ return coOptionalDefiner(this);
3991
+ }
3992
+ };
3993
+
3994
+ // src/tools/implementation/zodSchema/zodReExport.ts
3995
+ import {
3996
+ object as zodObject,
3997
+ strictObject as zodStrictObject
3998
+ } from "zod/v4";
3999
+ import {
4000
+ string,
4001
+ number,
4002
+ boolean,
4003
+ templateLiteral,
4004
+ json,
4005
+ date,
4006
+ emoji,
4007
+ base64,
4008
+ base64url,
4009
+ nanoid,
4010
+ cuid,
4011
+ cuid2,
4012
+ ulid,
4013
+ ipv4,
4014
+ ipv6,
4015
+ email,
4016
+ url,
4017
+ uuid,
4018
+ literal,
4019
+ enum as enum2,
4020
+ cidrv4,
4021
+ cidrv6,
4022
+ iso,
4023
+ int32,
4024
+ union,
4025
+ discriminatedUnion,
4026
+ int,
4027
+ optional as optional2,
4028
+ array,
4029
+ tuple,
4030
+ z
4031
+ } from "zod/v4";
4032
+
4033
+ // src/tools/implementation/zodSchema/zodCo.ts
4034
+ var isZodV4Schema = (schema) => {
4035
+ return typeof schema === "object" && schema !== null && "_zod" in schema;
4036
+ };
4037
+ var isValidShape = (shape) => {
4038
+ return Object.values(removeGetters(shape)).every(
4039
+ (schema) => isZodV4Schema(schema) || isAnyCoValueSchema(schema) || isCoValueClass(schema)
4040
+ );
4041
+ };
4042
+ var validateCoMapShape = (shape) => {
4043
+ if (isAnyCoValueSchema(shape)) {
4044
+ throw new Error(
4045
+ "co.map() expects an object as its argument, not a CoValue schema"
4046
+ );
4047
+ } else if (!isValidShape(shape)) {
4048
+ throw new Error(
4049
+ "co.map() supports only Zod v4 schemas and CoValue schemas"
4050
+ );
4051
+ }
4052
+ };
4053
+ var coMapDefiner = (shape) => {
4054
+ validateCoMapShape(shape);
4055
+ const coreSchema = createCoreCoMapSchema(shape);
4056
+ return hydrateCoreCoValueSchema(coreSchema);
4057
+ };
4058
+ var coFileStreamDefiner = () => {
4059
+ const coreSchema = createCoreFileStreamSchema();
4060
+ return hydrateCoreCoValueSchema(coreSchema);
4061
+ };
4062
+ var coOptionalDefiner = (schema) => {
4063
+ return new CoOptionalSchema(schema);
4064
+ };
4065
+
4066
+ // src/tools/implementation/zodSchema/schemaTypes/CoMapSchema.ts
4067
+ function createCoreCoMapSchema(shape, catchAll) {
4068
+ return {
4069
+ collaborative: true,
4070
+ builtin: "CoMap",
4071
+ shape,
4072
+ catchAll,
4073
+ getDefinition: () => ({
4074
+ get shape() {
4075
+ return shape;
4076
+ },
4077
+ get catchall() {
4078
+ return catchAll;
4079
+ },
4080
+ get discriminatorMap() {
4081
+ const propValues = {};
4082
+ for (const key in removeGetters(shape)) {
4083
+ if (isAnyCoValueSchema(shape[key])) {
4084
+ continue;
4085
+ }
4086
+ const field = shape[key]._zod;
4087
+ if (field.values) {
4088
+ propValues[key] ??= /* @__PURE__ */ new Set();
4089
+ for (const v of field.values) propValues[key].add(v);
4090
+ }
4091
+ }
4092
+ return propValues;
4093
+ }
4094
+ })
4095
+ };
4096
+ }
4097
+ function enrichCoMapSchema(schema, coValueClass) {
4098
+ const coValueSchema = Object.assign(schema, {
4099
+ create: (...args) => {
4100
+ return coValueClass.create(...args);
4101
+ },
4102
+ load: (...args) => {
4103
+ return coValueClass.load(...args);
4104
+ },
4105
+ subscribe: (...args) => {
4106
+ return coValueClass.subscribe(...args);
4107
+ },
4108
+ findUnique: (...args) => {
4109
+ return coValueClass.findUnique(...args);
4110
+ },
4111
+ upsertUnique: (...args) => {
4112
+ return coValueClass.upsertUnique(...args);
4113
+ },
4114
+ loadUnique: (...args) => {
4115
+ return coValueClass.loadUnique(...args);
4116
+ },
4117
+ catchall: (catchAll) => {
4118
+ const schemaWithCatchAll = createCoreCoMapSchema(
4119
+ coValueSchema.getDefinition().shape,
4120
+ catchAll
4121
+ );
4122
+ return hydrateCoreCoValueSchema(schemaWithCatchAll);
4123
+ },
4124
+ withMigration: (migration) => {
4125
+ coValueClass.prototype.migrate = migration;
4126
+ return coValueSchema;
4127
+ },
4128
+ getCoValueClass: () => {
4129
+ return coValueClass;
4130
+ },
4131
+ optional: () => {
4132
+ return coOptionalDefiner(coValueSchema);
4133
+ },
4134
+ pick: (keys) => {
4135
+ const keysSet = new Set(Object.keys(keys));
4136
+ const pickedShape = {};
4137
+ for (const [key, value] of Object.entries(coValueSchema.shape)) {
4138
+ if (keysSet.has(key)) {
4139
+ pickedShape[key] = value;
4140
+ }
4141
+ }
4142
+ return coMapDefiner(pickedShape);
4143
+ },
4144
+ partial: () => {
4145
+ const partialShape = {};
4146
+ for (const [key, value] of Object.entries(coValueSchema.shape)) {
4147
+ if (isAnyCoValueSchema(value)) {
4148
+ partialShape[key] = coOptionalDefiner(value);
4149
+ } else {
4150
+ partialShape[key] = z.optional(coValueSchema.shape[key]);
4151
+ }
4152
+ }
4153
+ const partialCoMapSchema = coMapDefiner(partialShape);
4154
+ if (coValueSchema.catchAll) {
4155
+ return partialCoMapSchema.catchall(
4156
+ coValueSchema.catchAll
4157
+ );
4158
+ }
4159
+ return partialCoMapSchema;
4160
+ }
4161
+ });
4162
+ return coValueSchema;
4163
+ }
4164
+
4165
+ // src/tools/implementation/zodSchema/schemaTypes/CoListSchema.ts
4166
+ var CoListSchema = class {
4167
+ constructor(element, coValueClass) {
4168
+ this.element = element;
4169
+ this.coValueClass = coValueClass;
4170
+ this.collaborative = true;
4171
+ this.builtin = "CoList";
4172
+ }
4173
+ create(items, options) {
4174
+ return this.coValueClass.create(items, options);
4175
+ }
4176
+ load(id, options) {
4177
+ return this.coValueClass.load(id, options);
4178
+ }
4179
+ subscribe(id, options, listener) {
4180
+ return this.coValueClass.subscribe(id, options, listener);
4181
+ }
4182
+ getCoValueClass() {
4183
+ return this.coValueClass;
4184
+ }
4185
+ /** @deprecated Use `CoList.upsertUnique` and `CoList.loadUnique` instead. */
4186
+ findUnique(unique, ownerID, as) {
4187
+ return this.coValueClass.findUnique(unique, ownerID, as);
4188
+ }
4189
+ upsertUnique(options) {
4190
+ return this.coValueClass.upsertUnique(options);
4191
+ }
4192
+ loadUnique(unique, ownerID, options) {
4193
+ return this.coValueClass.loadUnique(unique, ownerID, options);
4194
+ }
4195
+ optional() {
4196
+ return coOptionalDefiner(this);
4197
+ }
4198
+ };
4199
+
4200
+ // src/tools/implementation/zodSchema/schemaTypes/CoFeedSchema.ts
4201
+ var CoFeedSchema = class {
4202
+ constructor(element, coValueClass) {
4203
+ this.element = element;
4204
+ this.coValueClass = coValueClass;
4205
+ this.collaborative = true;
4206
+ this.builtin = "CoFeed";
4207
+ }
4208
+ create(init, options) {
4209
+ return this.coValueClass.create(init, options);
4210
+ }
4211
+ load(id, options) {
4212
+ return this.coValueClass.load(id, options);
4213
+ }
4214
+ subscribe(...args) {
4215
+ return this.coValueClass.subscribe(...args);
4216
+ }
4217
+ getCoValueClass() {
4218
+ return this.coValueClass;
4219
+ }
4220
+ optional() {
4221
+ return coOptionalDefiner(this);
4222
+ }
4223
+ };
4224
+
4225
+ // src/tools/implementation/zodSchema/schemaTypes/PlainTextSchema.ts
4226
+ var PlainTextSchema = class {
4227
+ constructor(coValueClass) {
4228
+ this.coValueClass = coValueClass;
4229
+ this.collaborative = true;
4230
+ this.builtin = "CoPlainText";
4231
+ }
4232
+ create(text, options) {
4233
+ return this.coValueClass.create(text, options);
4234
+ }
4235
+ load(id, options) {
4236
+ return this.coValueClass.load(id, options);
4237
+ }
4238
+ subscribe(...args) {
4239
+ return this.coValueClass.subscribe(...args);
4240
+ }
4241
+ fromRaw(raw) {
4242
+ return this.coValueClass.fromRaw(raw);
4243
+ }
4244
+ getCoValueClass() {
4245
+ return this.coValueClass;
4246
+ }
4247
+ optional() {
4248
+ return coOptionalDefiner(this);
4249
+ }
4250
+ };
4251
+
4252
+ // src/tools/implementation/zodSchema/schemaTypes/FileStreamSchema.ts
4253
+ function createCoreFileStreamSchema() {
4254
+ return {
4255
+ collaborative: true,
4256
+ builtin: "FileStream"
4257
+ };
4258
+ }
4259
+ var FileStreamSchema = class {
4260
+ constructor(coValueClass) {
4261
+ this.coValueClass = coValueClass;
4262
+ this.collaborative = true;
4263
+ this.builtin = "FileStream";
4264
+ }
4265
+ create(options) {
4266
+ return this.coValueClass.create(options);
4267
+ }
4268
+ createFromBlob(blob, options) {
4269
+ return this.coValueClass.createFromBlob(blob, options);
4270
+ }
4271
+ createFromArrayBuffer(...args) {
4272
+ return this.coValueClass.createFromArrayBuffer(...args);
4273
+ }
4274
+ loadAsBlob(id, options) {
4275
+ return this.coValueClass.loadAsBlob(id, options);
4276
+ }
4277
+ load(id, options) {
4278
+ return this.coValueClass.load(id, options);
4279
+ }
4280
+ subscribe(...args) {
4281
+ return this.coValueClass.subscribe(...args);
4282
+ }
4283
+ getCoValueClass() {
4284
+ return this.coValueClass;
4285
+ }
4286
+ optional() {
4287
+ return coOptionalDefiner(this);
4288
+ }
4289
+ };
4290
+
4291
+ // src/tools/implementation/zodSchema/schemaTypes/AccountSchema.ts
4292
+ function enrichAccountSchema(schema, coValueClass) {
4293
+ const enrichedSchema = Object.assign(schema, {
4294
+ create: (...args) => {
4295
+ return coValueClass.create(...args);
4296
+ },
4297
+ createAs: (...args) => {
4298
+ return coValueClass.createAs(...args);
4299
+ },
4300
+ getMe: (...args) => {
4301
+ return coValueClass.getMe(...args);
4302
+ },
4303
+ load: (...args) => {
4304
+ return coValueClass.load(...args);
4305
+ },
4306
+ subscribe: (...args) => {
4307
+ return coValueClass.subscribe(...args);
4308
+ },
4309
+ fromRaw: (...args) => {
4310
+ return coValueClass.fromRaw(...args);
4311
+ },
4312
+ withMigration: (migration) => {
4313
+ coValueClass.prototype.migrate = async function(creationProps) {
4314
+ await migration(this, creationProps);
4315
+ };
4316
+ return enrichedSchema;
4317
+ },
4318
+ getCoValueClass: () => {
4319
+ return coValueClass;
4320
+ }
4321
+ });
4322
+ return enrichedSchema;
4323
+ }
4324
+
4325
+ // src/tools/implementation/zodSchema/unionUtils.ts
4326
+ function schemaUnionDiscriminatorFor(schema) {
4327
+ if (isUnionOfCoMapsDeeply(schema)) {
4328
+ const definition = schema.getDefinition();
4329
+ const { discriminatorMap, discriminator, options } = definition;
4330
+ const field = discriminatorMap[discriminator];
4331
+ if (!field) {
4332
+ throw new Error(
4333
+ "co.discriminatedUnion() of collaborative types with non-existent discriminator key is not supported"
4334
+ );
4335
+ }
4336
+ for (const value of field) {
4337
+ if (typeof value !== "string" && typeof value !== "number") {
4338
+ throw new Error(
4339
+ "co.discriminatedUnion() of collaborative types with non-string or non-number discriminator value is not supported"
4340
+ );
4341
+ }
4342
+ }
4343
+ const availableOptions = [];
4344
+ for (const option of options) {
4345
+ if (option.builtin === "CoMap") {
4346
+ availableOptions.push(option);
4347
+ } else if (option.builtin === "CoDiscriminatedUnion") {
4348
+ for (const subOption of option.getDefinition().options) {
4349
+ if (!options.includes(subOption)) {
4350
+ options.push(subOption);
4351
+ }
4352
+ }
4353
+ } else {
4354
+ throw new Error(
4355
+ "Unsupported zod type in co.discriminatedUnion() of collaborative types"
4356
+ );
4357
+ }
4358
+ }
4359
+ const determineSchema = (discriminable) => {
4360
+ for (const option of availableOptions) {
4361
+ let match = true;
4362
+ for (const key of Object.keys(discriminatorMap)) {
4363
+ const discriminatorDef = option.getDefinition().shape[key];
4364
+ const discriminatorValue = discriminable.get(key);
4365
+ if (discriminatorValue && typeof discriminatorValue === "object") {
4366
+ throw new Error("Discriminator must be a primitive value");
4367
+ }
4368
+ if (!discriminatorDef) {
4369
+ if (key === discriminator) {
4370
+ match = false;
4371
+ break;
4372
+ } else {
4373
+ continue;
4374
+ }
4375
+ }
4376
+ if (discriminatorDef._zod?.def.type !== "literal") {
4377
+ break;
4378
+ }
4379
+ const literalDef = discriminatorDef._zod.def;
4380
+ if (!Array.from(literalDef.values).includes(discriminatorValue)) {
4381
+ match = false;
4382
+ break;
4383
+ }
4384
+ }
4385
+ if (match) {
4386
+ const coValueSchema = hydrateCoreCoValueSchema(option);
4387
+ return coValueSchema.getCoValueClass();
4388
+ }
4389
+ }
4390
+ throw new Error(
4391
+ "co.discriminatedUnion() of collaborative types with no matching discriminator value found"
4392
+ );
4393
+ };
4394
+ return determineSchema;
4395
+ } else {
4396
+ throw new Error(
4397
+ "co.discriminatedUnion() of non-collaborative types is not supported"
4398
+ );
4399
+ }
4400
+ }
4401
+ function isUnionOfCoMapsDeeply(schema) {
4402
+ return schema.getDefinition().options.every(isCoMapOrUnionOfCoMapsDeeply);
4403
+ }
4404
+ function isCoMapOrUnionOfCoMapsDeeply(schema) {
4405
+ if (schema.builtin === "CoMap") {
4406
+ return true;
4407
+ } else if (schema.builtin === "CoDiscriminatedUnion") {
4408
+ return schema.getDefinition().options.every(isCoMapOrUnionOfCoMapsDeeply);
4409
+ } else {
4410
+ return false;
4411
+ }
4412
+ }
4413
+ function isUnionOfPrimitivesDeeply(schema) {
4414
+ if (schema instanceof z.core.$ZodUnion) {
4415
+ return schema._zod.def.options.every(isUnionOfPrimitivesDeeply);
4416
+ } else {
4417
+ return !isAnyCoValueSchema(schema);
4418
+ }
4419
+ }
4420
+
4421
+ // src/tools/implementation/zodSchema/runtimeConverters/schemaFieldToCoFieldDef.ts
4422
+ function schemaFieldToCoFieldDef(schema) {
4423
+ if (isCoValueClass(schema)) {
4424
+ return coField.ref(schema);
4425
+ } else if (isCoValueSchema(schema)) {
4426
+ if (schema.builtin === "CoOptional") {
4427
+ return coField.ref(schema.getCoValueClass(), {
4428
+ optional: true
4429
+ });
4430
+ }
4431
+ return coField.ref(schema.getCoValueClass());
4432
+ } else {
4433
+ if ("_zod" in schema) {
4434
+ const zodSchemaDef = schema._zod.def;
4435
+ if (zodSchemaDef.type === "optional" || zodSchemaDef.type === "nullable") {
4436
+ const inner = zodSchemaDef.innerType;
4437
+ const coFieldDef = schemaFieldToCoFieldDef(inner);
4438
+ if (zodSchemaDef.type === "nullable" && coFieldDef === coField.optional.Date) {
4439
+ throw new Error("Nullable z.date() is not supported");
4440
+ }
4441
+ return coFieldDef;
4442
+ } else if (zodSchemaDef.type === "string") {
4443
+ return coField.string;
4444
+ } else if (zodSchemaDef.type === "number") {
4445
+ return coField.number;
4446
+ } else if (zodSchemaDef.type === "boolean") {
4447
+ return coField.boolean;
4448
+ } else if (zodSchemaDef.type === "null") {
4449
+ return coField.null;
4450
+ } else if (zodSchemaDef.type === "enum") {
4451
+ return coField.string;
4452
+ } else if (zodSchemaDef.type === "readonly") {
4453
+ return schemaFieldToCoFieldDef(
4454
+ schema.def.innerType
4455
+ );
4456
+ } else if (zodSchemaDef.type === "date") {
4457
+ return coField.optional.Date;
4458
+ } else if (zodSchemaDef.type === "template_literal") {
4459
+ return coField.string;
4460
+ } else if (zodSchemaDef.type === "lazy") {
4461
+ return schemaFieldToCoFieldDef(
4462
+ schema.unwrap()
4463
+ );
4464
+ } else if (zodSchemaDef.type === "default" || zodSchemaDef.type === "catch") {
4465
+ console.warn(
4466
+ "z.default()/z.catch() are not supported in collaborative schemas. They will be ignored."
4467
+ );
4468
+ return schemaFieldToCoFieldDef(
4469
+ schema.def.innerType
4470
+ );
4471
+ } else if (zodSchemaDef.type === "literal") {
4472
+ if (zodSchemaDef.values.some((literal2) => typeof literal2 === "undefined")) {
4473
+ throw new Error("z.literal() with undefined is not supported");
4474
+ }
4475
+ if (zodSchemaDef.values.some((literal2) => literal2 === null)) {
4476
+ throw new Error("z.literal() with null is not supported");
4477
+ }
4478
+ if (zodSchemaDef.values.some((literal2) => typeof literal2 === "bigint")) {
4479
+ throw new Error("z.literal() with bigint is not supported");
4480
+ }
4481
+ return coField.literal(
4482
+ ...zodSchemaDef.values
4483
+ );
4484
+ } else if (zodSchemaDef.type === "object" || zodSchemaDef.type === "array" || zodSchemaDef.type === "tuple") {
4485
+ return coField.json();
4486
+ } else if (zodSchemaDef.type === "union") {
4487
+ if (isUnionOfPrimitivesDeeply(schema)) {
4488
+ return coField.json();
4489
+ } else {
4490
+ throw new Error(
4491
+ "z.union()/z.discriminatedUnion() of collaborative types is not supported. Use co.discriminatedUnion() instead."
4492
+ );
4493
+ }
4494
+ } else {
4495
+ throw new Error(
4496
+ `Unsupported zod type: ${schema._zod?.def?.type || JSON.stringify(schema)}`
4497
+ );
4498
+ }
4499
+ } else {
4500
+ throw new Error(`Unsupported zod type: ${schema}`);
4501
+ }
4502
+ }
4503
+ }
4504
+
4505
+ // src/tools/implementation/zodSchema/runtimeConverters/coValueSchemaTransformation.ts
4506
+ function isAnyCoValueSchema(schema) {
4507
+ return typeof schema === "object" && schema !== null && "collaborative" in schema && schema.collaborative === true;
4508
+ }
4509
+ function isCoValueSchema(schema) {
4510
+ return isAnyCoValueSchema(schema) && "getCoValueClass" in schema;
4511
+ }
4512
+ function hydrateCoreCoValueSchema(schema) {
4513
+ if (isCoValueSchema(schema)) {
4514
+ return schema;
4515
+ }
4516
+ if (schema.builtin === "CoOptional") {
4517
+ throw new Error(
4518
+ `co.optional() of collaborative types is not supported as top-level schema: ${JSON.stringify(schema)}`
4519
+ );
4520
+ } else if (schema.builtin === "CoMap" || schema.builtin === "Account") {
4521
+ const def = schema.getDefinition();
4522
+ const ClassToExtend = schema.builtin === "Account" ? Account : CoMap;
4523
+ const coValueClass = class ZCoMap extends ClassToExtend {
4524
+ constructor(options) {
4525
+ super(options);
4526
+ for (const [fieldName, fieldType] of Object.entries(def.shape)) {
4527
+ this[fieldName] = schemaFieldToCoFieldDef(
4528
+ fieldType
4529
+ );
4530
+ }
4531
+ if (def.catchall) {
4532
+ this[coField.items] = schemaFieldToCoFieldDef(
4533
+ def.catchall
4534
+ );
4535
+ }
4536
+ }
4537
+ };
4538
+ const coValueSchema = ClassToExtend === Account ? enrichAccountSchema(schema, coValueClass) : enrichCoMapSchema(schema, coValueClass);
4539
+ return coValueSchema;
4540
+ } else if (schema.builtin === "CoList") {
4541
+ const element = schema.element;
4542
+ const coValueClass = class ZCoList extends CoList {
4543
+ constructor(options) {
4544
+ super(options);
4545
+ this[coField.items] = schemaFieldToCoFieldDef(
4546
+ element
4547
+ );
4548
+ }
4549
+ };
4550
+ const coValueSchema = new CoListSchema(element, coValueClass);
4551
+ return coValueSchema;
4552
+ } else if (schema.builtin === "CoFeed") {
4553
+ const coValueClass = CoFeed.Of(
4554
+ schemaFieldToCoFieldDef(schema.element)
4555
+ );
4556
+ const coValueSchema = new CoFeedSchema(schema.element, coValueClass);
4557
+ return coValueSchema;
4558
+ } else if (schema.builtin === "FileStream") {
4559
+ const coValueClass = FileStream;
4560
+ return new FileStreamSchema(coValueClass);
4561
+ } else if (schema.builtin === "CoPlainText") {
4562
+ const coValueClass = CoPlainText;
4563
+ return new PlainTextSchema(coValueClass);
4564
+ } else if (schema.builtin === "CoRichText") {
4565
+ const coValueClass = CoRichText;
4566
+ return new RichTextSchema(coValueClass);
4567
+ } else if (schema.builtin === "CoDiscriminatedUnion") {
4568
+ const coValueClass = SchemaUnion.Of(schemaUnionDiscriminatorFor(schema));
4569
+ const coValueSchema = new CoDiscriminatedUnionSchema(schema, coValueClass);
4570
+ return coValueSchema;
4571
+ } else {
4572
+ const notReachable = schema;
4573
+ throw new Error(
4574
+ `Unsupported zod CoValue type for top-level schema: ${JSON.stringify(notReachable, void 0, 2)}`
4575
+ );
4576
+ }
4577
+ }
4578
+ function coValueClassFromCoValueClassOrSchema(schema) {
4579
+ if (isCoValueClass(schema)) {
4580
+ return schema;
4581
+ } else if (isCoValueSchema(schema)) {
4582
+ return schema.getCoValueClass();
4583
+ }
4584
+ throw new Error(`Unsupported schema: ${JSON.stringify(schema)}`);
4585
+ }
4586
+
4587
+ // src/tools/coValues/extensions/imageDef.ts
4588
+ var ImageDefinitionBase = coMapDefiner({
4589
+ original: coFileStreamDefiner(),
4590
+ originalSize: z.tuple([z.number(), z.number()]),
4591
+ placeholderDataURL: z.string().optional(),
4592
+ progressive: z.boolean()
4593
+ }).catchall(coFileStreamDefiner());
4594
+
4595
+ // src/tools/implementation/ContextManager.ts
4596
+ import { cojsonInternals as cojsonInternals5 } from "cojson";
4597
+ import { PureJSCrypto } from "cojson/dist/crypto/PureJSCrypto";
4598
+
4599
+ // src/tools/implementation/devtoolsFormatters.ts
4600
+ globalThis.devtoolsFormatters = [
4601
+ {
4602
+ header: (object) => {
4603
+ if (object[TypeSym] === "CoMap") {
4604
+ return ["div", {}, ["span", {}, object.constructor.name]];
4605
+ } else if (object[TypeSym] === "CoList") {
4606
+ return [
4607
+ "div",
4608
+ {},
4609
+ ["span", {}, object.constructor.name + "(" + object.length + ") "]
4610
+ ];
4611
+ } else if (object[TypeSym] === "Account") {
4612
+ return [
4613
+ "div",
4614
+ {},
4615
+ [
4616
+ "span",
4617
+ {},
4618
+ object.constructor.name + "(" + object.$jazz.refs.profile.value?.name + (object.isMe ? " ME" : "") + ")"
4619
+ ]
4620
+ ];
4621
+ } else {
4622
+ return null;
4623
+ }
4624
+ },
4625
+ hasBody: function() {
4626
+ return true;
4627
+ },
4628
+ body: function(object) {
4629
+ if (object[TypeSym] === "CoMap" || object[TypeSym] === "Account") {
4630
+ return [
4631
+ "div",
4632
+ { style: "margin-left: 15px" },
4633
+ ["div", "id: ", ["object", { object: object.id }]],
4634
+ ...Object.entries(object).map(([k, v]) => [
4635
+ "div",
4636
+ { style: "white-space: nowrap;" },
4637
+ ["span", { style: "font-weight: bold; opacity: 0.6" }, k, ": "],
4638
+ ["object", { object: v }],
4639
+ ...typeof object._schema[k] === "function" ? v === null ? [
4640
+ [
4641
+ "span",
4642
+ { style: "opacity: 0.5" },
4643
+ ` (pending ${object._schema[k].name} `,
4644
+ ["object", { object: object.$jazz.refs[k] }],
4645
+ ")"
4646
+ ]
4647
+ ] : [] : []
4648
+ ])
4649
+ ];
4650
+ } else if (object[TypeSym] === "CoList") {
4651
+ return [
4652
+ "div",
4653
+ { style: "margin-left: 15px" },
4654
+ ["div", "id: ", ["object", { object: object.id }]],
4655
+ ...object.map((v, i) => [
4656
+ "div",
4657
+ { style: "white-space: nowrap;" },
4658
+ ["span", { style: "font-weight: bold; opacity: 0.6" }, i, ": "],
4659
+ ["object", { object: v }],
4660
+ ...typeof object._schema[ItemsSym] === "function" ? v === null ? [
4661
+ [
4662
+ "span",
4663
+ { style: "opacity: 0.5" },
4664
+ ` (pending ${object._schema[ItemsSym].name} `,
4665
+ ["object", { object: object.$jazz.refs[i] }],
4666
+ ")"
4667
+ ]
4668
+ ] : [] : []
4669
+ ])
4670
+ ];
4671
+ }
4672
+ }
4673
+ }
4674
+ ];
4675
+
30
4676
  // src/react-core/hooks.ts
31
4677
  function useJazzContext() {
32
4678
  const value = useContext(JazzContext);
@@ -68,7 +4714,7 @@ function useIsAuthenticated() {
68
4714
  () => authSecretStorage.isAuthenticated
69
4715
  );
70
4716
  }
71
- function useCoValueSubscription(Schema, id, options) {
4717
+ function useCoValueSubscription(Schema4, id, options) {
72
4718
  const contextManager = useJazzContextManager();
73
4719
  const createSubscription = () => {
74
4720
  if (!id) {
@@ -76,16 +4722,16 @@ function useCoValueSubscription(Schema, id, options) {
76
4722
  subscription: null,
77
4723
  contextManager,
78
4724
  id,
79
- Schema
4725
+ Schema: Schema4
80
4726
  };
81
4727
  }
82
4728
  const node = contextManager.getCurrentValue().node;
83
- const subscription2 = new SubscriptionScope(
4729
+ const subscription2 = new SubscriptionScope2(
84
4730
  node,
85
4731
  options?.resolve ?? true,
86
4732
  id,
87
4733
  {
88
- ref: coValueClassFromCoValueClassOrSchema(Schema),
4734
+ ref: coValueClassFromCoValueClassOrSchema2(Schema4),
89
4735
  optional: true
90
4736
  }
91
4737
  );
@@ -93,12 +4739,12 @@ function useCoValueSubscription(Schema, id, options) {
93
4739
  subscription: subscription2,
94
4740
  contextManager,
95
4741
  id,
96
- Schema
4742
+ Schema: Schema4
97
4743
  };
98
4744
  };
99
4745
  const [subscription, setSubscription] = React.useState(createSubscription);
100
4746
  React.useLayoutEffect(() => {
101
- if (subscription.contextManager !== contextManager || subscription.id !== id || subscription.Schema !== Schema) {
4747
+ if (subscription.contextManager !== contextManager || subscription.id !== id || subscription.Schema !== Schema4) {
102
4748
  subscription.subscription?.destroy();
103
4749
  setSubscription(createSubscription());
104
4750
  }
@@ -106,11 +4752,11 @@ function useCoValueSubscription(Schema, id, options) {
106
4752
  subscription.subscription?.destroy();
107
4753
  setSubscription(createSubscription());
108
4754
  });
109
- }, [Schema, id, contextManager]);
4755
+ }, [Schema4, id, contextManager]);
110
4756
  return subscription.subscription;
111
4757
  }
112
- function useCoState(Schema, id, options) {
113
- const subscription = useCoValueSubscription(Schema, id, options);
4758
+ function useCoState(Schema4, id, options) {
4759
+ const subscription = useCoValueSubscription(Schema4, id, options);
114
4760
  const value = React.useSyncExternalStore(
115
4761
  React.useCallback(
116
4762
  (callback) => {
@@ -127,11 +4773,11 @@ function useCoState(Schema, id, options) {
127
4773
  );
128
4774
  return value;
129
4775
  }
130
- function useAccountSubscription(Schema, options) {
4776
+ function useAccountSubscription(Schema4, options) {
131
4777
  const contextManager = useJazzContextManager();
132
4778
  const createSubscription = () => {
133
4779
  const agent = getCurrentAccountFromContextManager(contextManager);
134
- if (agent._type === "Anonymous") {
4780
+ if (agent[TypeSym] === "Anonymous") {
135
4781
  return {
136
4782
  subscription: null,
137
4783
  contextManager,
@@ -140,19 +4786,24 @@ function useAccountSubscription(Schema, options) {
140
4786
  }
141
4787
  const resolve = options?.resolve ?? true;
142
4788
  const node = contextManager.getCurrentValue().node;
143
- const subscription2 = new SubscriptionScope(node, resolve, agent.id, {
144
- ref: coValueClassFromCoValueClassOrSchema(Schema),
145
- optional: true
146
- });
4789
+ const subscription2 = new SubscriptionScope2(
4790
+ node,
4791
+ resolve,
4792
+ agent.$jazz.id,
4793
+ {
4794
+ ref: coValueClassFromCoValueClassOrSchema2(Schema4),
4795
+ optional: true
4796
+ }
4797
+ );
147
4798
  return {
148
4799
  subscription: subscription2,
149
4800
  contextManager,
150
- Schema
4801
+ Schema: Schema4
151
4802
  };
152
4803
  };
153
4804
  const [subscription, setSubscription] = React.useState(createSubscription);
154
4805
  React.useLayoutEffect(() => {
155
- if (subscription.contextManager !== contextManager || subscription.Schema !== Schema) {
4806
+ if (subscription.contextManager !== contextManager || subscription.Schema !== Schema4) {
156
4807
  subscription.subscription?.destroy();
157
4808
  setSubscription(createSubscription());
158
4809
  }
@@ -160,12 +4811,12 @@ function useAccountSubscription(Schema, options) {
160
4811
  subscription.subscription?.destroy();
161
4812
  setSubscription(createSubscription());
162
4813
  });
163
- }, [Schema, contextManager]);
4814
+ }, [Schema4, contextManager]);
164
4815
  return subscription.subscription;
165
4816
  }
166
- function useAccount(AccountSchema = Account, options) {
4817
+ function useAccount(AccountSchema2 = Account13, options) {
167
4818
  const contextManager = useJazzContextManager();
168
- const subscription = useAccountSubscription(AccountSchema, options);
4819
+ const subscription = useAccountSubscription(AccountSchema2, options);
169
4820
  const agent = getCurrentAccountFromContextManager(contextManager);
170
4821
  const value = React.useSyncExternalStore(
171
4822
  React.useCallback(
@@ -297,4 +4948,5 @@ export {
297
4948
  useJazzContextManager,
298
4949
  usePassphraseAuth
299
4950
  };
4951
+ /* istanbul ignore file -- @preserve */
300
4952
  //# sourceMappingURL=index.js.map