jazz-tools 0.13.0 → 0.13.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +5 -5
- package/CHANGELOG.md +14 -0
- package/dist/{chunk-FKK4CPZZ.js → chunk-YZW2QELD.js} +90 -42
- package/dist/chunk-YZW2QELD.js.map +1 -0
- package/dist/coValues/deepLoading.d.ts +8 -2
- package/dist/coValues/deepLoading.d.ts.map +1 -1
- package/dist/coValues/interfaces.d.ts +1 -1
- package/dist/coValues/interfaces.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/testing.js +1 -1
- package/package.json +2 -2
- package/src/coValues/deepLoading.ts +89 -39
- package/src/coValues/interfaces.ts +17 -5
- package/src/tests/deepLoading.test.ts +104 -4
- package/vitest.config.ts +10 -0
- package/dist/chunk-FKK4CPZZ.js.map +0 -1
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../src/implementation/activeAccountContext.ts","../src/implementation/anonymousJazzAgent.ts","../src/coValues/interfaces.ts","../src/implementation/inspect.ts","../src/implementation/symbols.ts","../src/coValues/deepLoading.ts","../src/implementation/refs.ts","../src/lib/cache.ts","../src/implementation/schema.ts","../src/implementation/subscriptionScope.ts","../src/implementation/createContext.ts","../src/coValues/registeredSchemas.ts","../src/implementation/devtoolsFormatters.ts","../src/coValues/inbox.ts","../src/coValues/coMap.ts","../src/coValues/profile.ts","../src/coValues/account.ts","../src/coValues/coFeed.ts","../src/coValues/coList.ts","../src/coValues/group.ts","../src/coValues/coPlainText.ts","../src/coValues/coRichText.ts","../src/coValues/extensions/imageDef.ts","../src/coValues/schemaUnion.ts","../src/auth/KvStoreContext.ts","../src/auth/AuthSecretStorage.ts","../src/auth/InMemoryKVStore.ts","../src/implementation/ContextManager.ts","../src/auth/DemoAuth.ts","../src/auth/PassphraseAuth.ts","../src/implementation/invites.ts"],"sourcesContent":["import type { Account } from \"../coValues/account.js\";\n\nclass ActiveAccountContext {\n private activeAccount: Account | null = null;\n private guestMode: boolean = false;\n\n set(account: Account | null) {\n this.activeAccount = account;\n this.guestMode = false;\n }\n\n setGuestMode() {\n this.activeAccount = null;\n this.guestMode = true;\n }\n\n maybeGet() {\n return this.activeAccount;\n }\n\n get() {\n if (!this.activeAccount) {\n if (this.guestMode) {\n throw new Error(\n \"Something that expects a full active account was called in guest mode.\",\n );\n }\n\n throw new Error(\"No active account\");\n }\n\n return this.activeAccount;\n }\n}\n\nexport type { ActiveAccountContext };\n\nexport const activeAccountContext = new ActiveAccountContext();\n","import { LocalNode } from \"cojson\";\n\nexport class AnonymousJazzAgent {\n _type = \"Anonymous\" as const;\n constructor(public node: LocalNode) {}\n}\n","import type {\n CoValueUniqueness,\n CojsonInternalTypes,\n RawCoValue,\n} from \"cojson\";\nimport { RawAccount } from \"cojson\";\nimport { activeAccountContext } from \"../implementation/activeAccountContext.js\";\nimport { AnonymousJazzAgent } from \"../implementation/anonymousJazzAgent.js\";\nimport {\n Ref,\n SubscriptionScope,\n inspect,\n subscriptionsScopes,\n} from \"../internal.js\";\nimport { coValuesCache } from \"../lib/cache.js\";\nimport { type Account } from \"./account.js\";\nimport {\n RefsToResolve,\n RefsToResolveStrict,\n Resolved,\n fulfillsDepth,\n} from \"./deepLoading.js\";\nimport { type Group } from \"./group.js\";\nimport { RegisteredSchemas } from \"./registeredSchemas.js\";\n\n/** @category Abstract interfaces */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface CoValueClass<Value extends CoValue = CoValue> {\n /** @ignore */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (...args: any[]): Value;\n}\n\nexport interface CoValueFromRaw<V extends CoValue> {\n fromRaw(raw: V[\"_raw\"]): V;\n}\n\n/** @category Abstract interfaces */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface CoValue {\n /** @category Content */\n readonly id: ID<this>;\n /** @category Type Helpers */\n _type: string;\n /** @category Collaboration */\n _owner: Account | Group;\n /** @category Internals */\n _raw: RawCoValue;\n /** @internal */\n readonly _loadedAs: Account | AnonymousJazzAgent;\n /** @category Stringifying & Inspection */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(key?: string, seenAbove?: ID<CoValue>[]): any[] | object | string;\n /** @category Stringifying & Inspection */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [inspect](): any;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isCoValue(value: any): value is CoValue {\n return value && value._type !== undefined;\n}\n\nexport function isCoValueClass<V extends CoValue>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n value: any,\n): value is CoValueClass<V> & CoValueFromRaw<V> {\n return typeof value === \"function\" && value.fromRaw !== undefined;\n}\n\n/**\n * IDs are unique identifiers for `CoValue`s.\n * Can be used with a type argument to refer to a specific `CoValue` type.\n *\n * @example\n *\n * ```ts\n * type AccountID = ID<Account>;\n * ```\n *\n * @category CoValues\n */\nexport type ID<T> = CojsonInternalTypes.RawCoID & IDMarker<T>;\n\ntype IDMarker<out T> = { __type(_: never): T };\n\n/** @internal */\nexport class CoValueBase implements CoValue {\n declare id: ID<this>;\n declare _type: string;\n declare _raw: RawCoValue;\n /** @category Internals */\n declare _instanceID: string;\n\n get _owner(): Account | Group {\n const owner =\n this._raw.group instanceof RawAccount\n ? RegisteredSchemas[\"Account\"].fromRaw(this._raw.group)\n : RegisteredSchemas[\"Group\"].fromRaw(this._raw.group);\n\n const subScope = subscriptionsScopes.get(this);\n if (subScope) {\n subScope.onRefAccessedOrSet(this.id, owner.id);\n subscriptionsScopes.set(owner, subScope);\n }\n\n return owner;\n }\n\n /** @private */\n get _loadedAs() {\n const rawAccount = this._raw.core.node.account;\n\n if (rawAccount instanceof RawAccount) {\n return coValuesCache.get(rawAccount, () =>\n RegisteredSchemas[\"Account\"].fromRaw(rawAccount),\n );\n }\n\n return new AnonymousJazzAgent(this._raw.core.node);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(..._args: any) {\n Object.defineProperty(this, \"_instanceID\", {\n value: `instance-${Math.random().toString(36).slice(2)}`,\n enumerable: false,\n });\n }\n\n /** @category Internals */\n static fromRaw<V extends CoValue>(this: CoValueClass<V>, raw: RawCoValue): V {\n return new this({ fromRaw: raw });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(): object | any[] | string {\n return {\n id: this.id,\n type: this._type,\n error: \"unknown CoValue class\",\n };\n }\n\n [inspect]() {\n return this.toJSON();\n }\n\n /** @category Type Helpers */\n castAs<Cl extends CoValueClass & CoValueFromRaw<CoValue>>(\n cl: Cl,\n ): InstanceType<Cl> {\n const casted = cl.fromRaw(this._raw) as InstanceType<Cl>;\n const subscriptionScope = subscriptionsScopes.get(this);\n if (subscriptionScope) {\n subscriptionsScopes.set(casted, subscriptionScope);\n }\n return casted;\n }\n}\n\nexport function loadCoValueWithoutMe<\n V extends CoValue,\n const R extends RefsToResolve<V>,\n>(\n cls: CoValueClass<V>,\n id: ID<CoValue>,\n options?: {\n resolve?: RefsToResolveStrict<V, R>;\n loadAs?: Account | AnonymousJazzAgent;\n },\n): Promise<Resolved<V, R> | null> {\n return loadCoValue(cls, id, {\n ...options,\n loadAs: options?.loadAs ?? activeAccountContext.get(),\n });\n}\n\nexport function loadCoValue<\n V extends CoValue,\n const R extends RefsToResolve<V>,\n>(\n cls: CoValueClass<V>,\n id: ID<CoValue>,\n options: {\n resolve?: RefsToResolveStrict<V, R>;\n loadAs: Account | AnonymousJazzAgent;\n },\n): Promise<Resolved<V, R> | null> {\n return new Promise((resolve) => {\n subscribeToCoValue<V, R>(\n cls,\n id,\n {\n resolve: options.resolve,\n loadAs: options.loadAs,\n onUnavailable: () => {\n resolve(null);\n },\n onUnauthorized: () => {\n resolve(null);\n },\n },\n (value, unsubscribe) => {\n resolve(value);\n unsubscribe();\n },\n );\n });\n}\n\nexport async function ensureCoValueLoaded<\n V extends CoValue,\n const R extends RefsToResolve<V>,\n>(\n existing: V,\n options?: { resolve?: RefsToResolveStrict<V, R> } | undefined,\n): Promise<Resolved<V, R>> {\n const response = await loadCoValue(\n existing.constructor as CoValueClass<V>,\n existing.id,\n {\n loadAs: existing._loadedAs,\n resolve: options?.resolve,\n },\n );\n\n if (!response) {\n throw new Error(\"Failed to deeply load CoValue \" + existing.id);\n }\n\n return response;\n}\n\ntype SubscribeListener<V extends CoValue, R extends RefsToResolve<V>> = (\n value: Resolved<V, R>,\n unsubscribe: () => void,\n) => void;\n\nexport type SubscribeListenerOptions<\n V extends CoValue,\n R extends RefsToResolve<V>,\n> = {\n resolve?: RefsToResolveStrict<V, R>;\n loadAs?: Account | AnonymousJazzAgent;\n onUnauthorized?: () => void;\n onUnavailable?: () => void;\n};\n\nexport type SubscribeRestArgs<V extends CoValue, R extends RefsToResolve<V>> =\n | [options: SubscribeListenerOptions<V, R>, listener: SubscribeListener<V, R>]\n | [listener: SubscribeListener<V, R>];\n\nexport function parseSubscribeRestArgs<\n V extends CoValue,\n R extends RefsToResolve<V>,\n>(\n args: SubscribeRestArgs<V, R>,\n): {\n options: SubscribeListenerOptions<V, R>;\n listener: SubscribeListener<V, R>;\n} {\n if (args.length === 2) {\n if (\n typeof args[0] === \"object\" &&\n args[0] &&\n typeof args[1] === \"function\"\n ) {\n return {\n options: {\n resolve: args[0].resolve,\n loadAs: args[0].loadAs,\n onUnauthorized: args[0].onUnauthorized,\n onUnavailable: args[0].onUnavailable,\n },\n listener: args[1],\n };\n } else {\n throw new Error(\"Invalid arguments\");\n }\n } else {\n if (typeof args[0] === \"function\") {\n return { options: {}, listener: args[0] };\n } else {\n throw new Error(\"Invalid arguments\");\n }\n }\n}\n\nexport function subscribeToCoValueWithoutMe<\n V extends CoValue,\n const R extends RefsToResolve<V>,\n>(\n cls: CoValueClass<V>,\n id: ID<CoValue>,\n options: SubscribeListenerOptions<V, R>,\n listener: SubscribeListener<V, R>,\n) {\n return subscribeToCoValue(\n cls,\n id,\n {\n ...options,\n loadAs: options.loadAs ?? activeAccountContext.get(),\n },\n listener,\n );\n}\n\nexport function subscribeToCoValue<\n V extends CoValue,\n const R extends RefsToResolve<V>,\n>(\n cls: CoValueClass<V>,\n id: ID<CoValue>,\n options: {\n resolve?: RefsToResolveStrict<V, R>;\n loadAs: Account | AnonymousJazzAgent;\n onUnavailable?: () => void;\n onUnauthorized?: (errorPath: string[]) => void;\n syncResolution?: boolean;\n },\n listener: SubscribeListener<V, R>,\n): () => void {\n const ref = new Ref(id, options.loadAs, { ref: cls, optional: false });\n\n let unsubscribed = false;\n let unsubscribe: (() => void) | undefined;\n\n function subscribe() {\n const value = ref.getValueWithoutAccessCheck();\n\n if (!value) {\n options.onUnavailable?.();\n return;\n }\n\n if (unsubscribed) return;\n\n const subscription = new SubscriptionScope(\n value,\n cls as CoValueClass<V> & CoValueFromRaw<V>,\n (update, subscription) => {\n if (subscription.syncResolution) return;\n\n if (!ref.hasReadAccess()) {\n console.error(\n \"Not enough permissions to load / subscribe to CoValue\",\n id,\n );\n options.onUnauthorized?.([]);\n return;\n }\n\n let result;\n\n try {\n subscription.syncResolution = true;\n result = fulfillsDepth(options.resolve, update);\n } catch (e) {\n console.error(\n \"Failed to load / subscribe to CoValue\",\n e,\n e instanceof Error ? e.stack : undefined,\n );\n options.onUnavailable?.();\n return;\n } finally {\n subscription.syncResolution = false;\n }\n\n if (result.status === \"unauthorized\") {\n console.error(\n \"Not enough permissions to load / subscribe to CoValue\",\n id,\n \"on path\",\n result.path.join(\".\"),\n \"unaccessible value:\",\n result.id,\n );\n options.onUnauthorized?.(result.path);\n return;\n }\n\n if (result.status === \"fulfilled\") {\n listener(update as Resolved<V, R>, subscription.unsubscribeAll);\n }\n },\n );\n\n unsubscribe = subscription.unsubscribeAll;\n }\n\n const sync = options.syncResolution ? ref.syncLoad() : undefined;\n\n if (sync) {\n subscribe();\n } else {\n ref\n .load()\n .then(() => subscribe())\n .catch((e) => {\n console.error(\n \"Failed to load / subscribe to CoValue\",\n e,\n e instanceof Error ? e.stack : undefined,\n );\n options.onUnavailable?.();\n });\n }\n\n return function unsubscribeAtAnyPoint() {\n unsubscribed = true;\n unsubscribe && unsubscribe();\n };\n}\n\nexport function createCoValueObservable<\n V extends CoValue,\n const R extends RefsToResolve<V>,\n>(initialValue: undefined | null = undefined) {\n let currentValue: Resolved<V, R> | undefined | null = initialValue;\n let subscriberCount = 0;\n\n function subscribe(\n cls: CoValueClass<V>,\n id: ID<CoValue>,\n options: {\n loadAs: Account | AnonymousJazzAgent;\n resolve?: RefsToResolveStrict<V, R>;\n onUnavailable?: () => void;\n onUnauthorized?: () => void;\n syncResolution?: boolean;\n },\n listener: () => void,\n ) {\n subscriberCount++;\n\n const unsubscribe = subscribeToCoValue(\n cls,\n id,\n {\n loadAs: options.loadAs,\n resolve: options.resolve,\n onUnavailable: () => {\n currentValue = null;\n options.onUnavailable?.();\n },\n onUnauthorized: () => {\n currentValue = null;\n options.onUnauthorized?.();\n },\n syncResolution: options.syncResolution,\n },\n (value) => {\n currentValue = value;\n listener();\n },\n );\n\n return () => {\n unsubscribe();\n subscriberCount--;\n if (subscriberCount === 0) {\n currentValue = undefined;\n }\n };\n }\n\n const observable = {\n getCurrentValue: () => currentValue,\n subscribe,\n };\n\n return observable;\n}\n\nexport function subscribeToExistingCoValue<\n V extends CoValue,\n const R extends RefsToResolve<V>,\n>(\n existing: V,\n options:\n | {\n resolve?: RefsToResolveStrict<V, R>;\n onUnavailable?: () => void;\n onUnauthorized?: () => void;\n }\n | undefined,\n listener: SubscribeListener<V, R>,\n): () => void {\n return subscribeToCoValue(\n existing.constructor as CoValueClass<V>,\n existing.id,\n {\n loadAs: existing._loadedAs,\n resolve: options?.resolve,\n onUnavailable: options?.onUnavailable,\n onUnauthorized: options?.onUnauthorized,\n },\n listener,\n );\n}\n\nexport function isAccountInstance(instance: unknown): instance is Account {\n if (typeof instance !== \"object\" || instance === null) {\n return false;\n }\n\n return \"_type\" in instance && instance._type === \"Account\";\n}\n\nexport function isAnonymousAgentInstance(\n instance: unknown,\n): instance is AnonymousJazzAgent {\n if (typeof instance !== \"object\" || instance === null) {\n return false;\n }\n\n return \"_type\" in instance && instance._type === \"Anonymous\";\n}\n\nexport function parseCoValueCreateOptions(\n options:\n | {\n owner?: Account | Group;\n unique?: CoValueUniqueness[\"uniqueness\"];\n }\n | Account\n | Group\n | undefined,\n) {\n const Group = RegisteredSchemas[\"Group\"];\n\n if (!options) {\n return { owner: Group.create(), uniqueness: undefined };\n }\n\n if (\"_type\" in options) {\n if (options._type === \"Account\" || options._type === \"Group\") {\n return { owner: options, uniqueness: undefined };\n }\n }\n\n const uniqueness = options.unique\n ? { uniqueness: options.unique }\n : undefined;\n\n return {\n owner: options.owner ?? Group.create(),\n uniqueness,\n };\n}\n\nexport function parseGroupCreateOptions(\n options:\n | {\n owner?: Account;\n }\n | Account\n | undefined,\n) {\n if (!options) {\n return { owner: activeAccountContext.get() };\n }\n\n return \"_type\" in options && isAccountInstance(options)\n ? { owner: options }\n : { owner: options.owner ?? activeAccountContext.get() };\n}\n","export const inspect = Symbol.for(\"nodejs.util.inspect.custom\");\nexport type inspect = typeof inspect;\n","export type JazzToolsSymbol = SchemaInit | ItemsSym | MembersSym;\n\nexport const SchemaInit = \"$SchemaInit$\";\nexport type SchemaInit = typeof SchemaInit;\n\nexport const ItemsSym = \"$items$\";\nexport type ItemsSym = typeof ItemsSym;\n\nexport const MembersSym = \"$members$\";\nexport type MembersSym = typeof MembersSym;\n","import { JsonValue, RawCoList, SessionID } from \"cojson\";\nimport { ItemsSym, type Ref, RefEncoded, UnCo } from \"../internal.js\";\nimport { type Account } from \"./account.js\";\nimport { type CoFeed, CoFeedEntry } from \"./coFeed.js\";\nimport { type CoList } from \"./coList.js\";\nimport { type CoKeys, type CoMap } from \"./coMap.js\";\nimport { type CoValue, type ID } from \"./interfaces.js\";\n\nfunction hasRefValue(value: CoValue, key: string | number) {\n return Boolean(\n (\n value as unknown as {\n _refs: { [key: string]: Ref<CoValue> | undefined };\n }\n )._refs?.[key],\n );\n}\n\nfunction hasReadAccess(value: CoValue, key: string | number) {\n return Boolean(\n (\n value as unknown as {\n _refs: { [key: string]: Ref<CoValue> | undefined };\n }\n )._refs?.[key]?.hasReadAccess(),\n );\n}\n\nfunction isOptionalField(value: CoValue, key: string): boolean {\n return (\n ((value as CoMap)._schema[key] as RefEncoded<CoValue>)?.optional ?? false\n );\n}\n\ntype FulfillsDepthResult =\n | {\n status: \"fulfilled\" | \"unfulfilled\";\n }\n | {\n status: \"unauthorized\";\n path: string[];\n id: JsonValue;\n };\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function fulfillsDepth(depth: any, value: CoValue): FulfillsDepthResult {\n if (depth === true || depth === undefined) {\n return {\n status: \"fulfilled\",\n };\n }\n\n if (\n value._type === \"CoMap\" ||\n value._type === \"Group\" ||\n value._type === \"Account\"\n ) {\n const map = value as CoMap;\n\n if (\"$each\" in depth) {\n const result: FulfillsDepthResult = { status: \"fulfilled\" };\n\n for (const [key, item] of Object.entries(value)) {\n const rawValue = map._raw.get(key);\n\n if (rawValue !== undefined) {\n if (!item) {\n if (hasReadAccess(map, key)) {\n result.status = \"unfulfilled\";\n continue;\n } else {\n return {\n status: \"unauthorized\",\n path: [key],\n id: rawValue,\n };\n }\n }\n\n const innerResult = fulfillsDepth(depth.$each, item);\n\n if (innerResult.status === \"unfulfilled\") {\n result.status = \"unfulfilled\";\n } else if (\n innerResult.status === \"unauthorized\" &&\n !isOptionalField(value, ItemsSym)\n ) {\n innerResult.path.unshift(key);\n\n return innerResult; // If any item is unauthorized, the whole thing is unauthorized\n }\n } else if (!isOptionalField(value, ItemsSym)) {\n return {\n status: \"unfulfilled\",\n };\n }\n }\n\n return result;\n } else {\n const result: FulfillsDepthResult = { status: \"fulfilled\" };\n\n for (const key of Object.keys(depth)) {\n const rawValue = map._raw.get(key);\n\n if (rawValue === undefined || rawValue === null) {\n if (!map._schema?.[key]) {\n // Field not defined in schema\n if (map._schema?.[ItemsSym]) {\n // CoMap.Record\n if (isOptionalField(map, ItemsSym)) {\n continue;\n } else {\n // All fields are required, so the returned type is not optional and we must comply\n throw new Error(\n `The ref ${key} requested on ${map.constructor.name} is missing`,\n );\n }\n } else {\n // Field not defined in CoMap schema\n throw new Error(\n `The ref ${key} requested on ${map.constructor.name} is not defined in the schema`,\n );\n }\n } else if (isOptionalField(map, key)) {\n continue;\n } else {\n // Field is required but has never been set\n throw new Error(\n `The ref ${key} on ${map.constructor.name} is required but missing`,\n );\n }\n } else {\n const item = (value as Record<string, any>)[key];\n\n if (!item) {\n if (hasReadAccess(map, key)) {\n result.status = \"unfulfilled\";\n continue;\n } else {\n return {\n status: \"unauthorized\",\n path: [key],\n id: rawValue,\n };\n }\n }\n\n const innerResult = fulfillsDepth(depth[key], item);\n\n if (innerResult.status === \"unfulfilled\") {\n result.status = \"unfulfilled\";\n } else if (\n innerResult.status === \"unauthorized\" &&\n !isOptionalField(value, key)\n ) {\n innerResult.path.unshift(key);\n\n return innerResult; // If any item is unauthorized, the whole thing is unauthorized\n }\n }\n }\n\n return result;\n }\n } else if (value._type === \"CoList\") {\n if (\"$each\" in depth) {\n const result: FulfillsDepthResult = { status: \"fulfilled\" };\n\n for (const [key, item] of (value as CoList).entries()) {\n if (hasRefValue(value, key)) {\n if (!item) {\n if (hasReadAccess(value, key)) {\n result.status = \"unfulfilled\";\n continue;\n } else {\n return {\n status: \"unauthorized\",\n path: [key.toString()],\n id: (value._raw as RawCoList).get(key) ?? \"undefined\",\n };\n }\n }\n\n const innerResult = fulfillsDepth(depth.$each, item);\n\n if (innerResult.status === \"unfulfilled\") {\n result.status = \"unfulfilled\";\n } else if (\n innerResult.status === \"unauthorized\" &&\n !isOptionalField(value, ItemsSym)\n ) {\n innerResult.path.unshift(key.toString());\n\n return innerResult; // If any item is unauthorized, the whole thing is unauthorized\n }\n } else if (!isOptionalField(value, ItemsSym)) {\n return {\n status: \"unfulfilled\",\n };\n }\n }\n\n return result;\n }\n\n return {\n status: \"fulfilled\",\n };\n } else if (value._type === \"CoStream\") {\n if (\"$each\" in depth) {\n const result: FulfillsDepthResult = { status: \"fulfilled\" };\n\n for (const item of Object.values((value as CoFeed).perSession)) {\n if (item.ref) {\n if (!item.value) {\n if (item.ref.hasReadAccess()) {\n result.status = \"unfulfilled\";\n continue;\n } else {\n return {\n status: \"unauthorized\",\n path: [item.ref.id],\n id: item.ref.id,\n };\n }\n }\n\n const innerResult = fulfillsDepth(depth.$each, item.value);\n\n if (innerResult.status === \"unfulfilled\") {\n result.status = \"unfulfilled\";\n } else if (\n innerResult.status === \"unauthorized\" &&\n !isOptionalField(value, ItemsSym)\n ) {\n innerResult.path.unshift(item.ref.id);\n\n return innerResult; // If any item is unauthorized, the whole thing is unauthorized\n }\n } else if (!isOptionalField(value, ItemsSym)) {\n return {\n status: \"unfulfilled\",\n };\n }\n }\n\n return result;\n }\n\n return {\n status: \"fulfilled\",\n };\n } else if (\n value._type === \"BinaryCoStream\" ||\n value._type === \"CoPlainText\"\n ) {\n return {\n status: \"fulfilled\",\n };\n } else {\n console.error(value);\n throw new Error(\"Unexpected value type: \" + value._type);\n }\n}\n\ntype UnCoNotNull<T> = UnCo<Exclude<T, null>>;\nexport type Clean<T> = UnCo<NonNullable<T>>;\n\nexport type RefsToResolve<\n V,\n DepthLimit extends number = 10,\n CurrentDepth extends number[] = [],\n> =\n | boolean\n | (DepthLimit extends CurrentDepth[\"length\"]\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n : // Basically V extends CoList - but if we used that we'd introduce circularity into the definition of CoList itself\n V extends Array<infer Item>\n ?\n | {\n $each: RefsToResolve<\n UnCoNotNull<Item>,\n DepthLimit,\n [0, ...CurrentDepth]\n >;\n }\n | boolean\n : // Basically V extends CoMap | Group | Account - but if we used that we'd introduce circularity into the definition of CoMap itself\n V extends { _type: \"CoMap\" | \"Group\" | \"Account\" }\n ?\n | {\n [Key in CoKeys<V> as Clean<V[Key]> extends CoValue\n ? Key\n : never]?: RefsToResolve<\n Clean<V[Key]>,\n DepthLimit,\n [0, ...CurrentDepth]\n >;\n }\n | (ItemsSym extends keyof V\n ? {\n $each: RefsToResolve<\n Clean<V[ItemsSym]>,\n DepthLimit,\n [0, ...CurrentDepth]\n >;\n }\n : never)\n | boolean\n : V extends {\n _type: \"CoStream\";\n byMe: CoFeedEntry<infer Item> | undefined;\n }\n ?\n | {\n $each: RefsToResolve<\n UnCoNotNull<Item>,\n DepthLimit,\n [0, ...CurrentDepth]\n >;\n }\n | boolean\n : boolean);\n\nexport type RefsToResolveStrict<T, V> = V extends RefsToResolve<T>\n ? RefsToResolve<T>\n : V;\n\nexport type Resolved<T, R extends RefsToResolve<T> | undefined> = DeeplyLoaded<\n T,\n R,\n 10,\n []\n>;\n\nexport type DeeplyLoaded<\n V,\n Depth,\n DepthLimit extends number = 10,\n CurrentDepth extends number[] = [],\n> = DepthLimit extends CurrentDepth[\"length\"]\n ? V\n : Depth extends boolean | undefined // Checking against boolean instead of true because the inference from RefsToResolveStrict transforms true into boolean\n ? V\n : // Basically V extends CoList - but if we used that we'd introduce circularity into the definition of CoList itself\n [V] extends [Array<infer Item>]\n ? UnCoNotNull<Item> extends CoValue\n ? Depth extends { $each: infer ItemDepth }\n ? // Deeply loaded CoList\n (UnCoNotNull<Item> &\n DeeplyLoaded<\n UnCoNotNull<Item>,\n ItemDepth,\n DepthLimit,\n [0, ...CurrentDepth]\n >)[] &\n V // the CoList base type needs to be intersected after so that built-in methods return the correct narrowed array type\n : never\n : V\n : // Basically V extends CoMap | Group | Account - but if we used that we'd introduce circularity into the definition of CoMap itself\n [V] extends [{ _type: \"CoMap\" | \"Group\" | \"Account\" }]\n ? ItemsSym extends keyof V\n ? Depth extends { $each: infer ItemDepth }\n ? // Deeply loaded Record-like CoMap\n {\n [key: string]: DeeplyLoaded<\n Clean<V[ItemsSym]>,\n ItemDepth,\n DepthLimit,\n [0, ...CurrentDepth]\n >;\n } & V // same reason as in CoList\n : never\n : keyof Depth extends never // Depth = {}\n ? V\n : // Deeply loaded CoMap\n {\n -readonly [Key in keyof Depth]-?: Key extends CoKeys<V>\n ? Clean<V[Key]> extends CoValue\n ?\n | DeeplyLoaded<\n Clean<V[Key]>,\n Depth[Key],\n DepthLimit,\n [0, ...CurrentDepth]\n >\n | (undefined extends V[Key] ? undefined : never)\n : never\n : never;\n } & V // same reason as in CoList\n : [V] extends [\n {\n _type: \"CoStream\";\n byMe: CoFeedEntry<infer Item> | undefined;\n },\n ]\n ? // Deeply loaded CoStream\n {\n byMe?: { value: UnCoNotNull<Item> };\n inCurrentSession?: { value: UnCoNotNull<Item> };\n perSession: {\n [key: SessionID]: { value: UnCoNotNull<Item> };\n };\n } & { [key: ID<Account>]: { value: UnCoNotNull<Item> } } & V // same reason as in CoList\n : [V] extends [\n {\n _type: \"BinaryCoStream\";\n },\n ]\n ? V\n : [V] extends [\n {\n _type: \"CoPlainText\";\n },\n ]\n ? V\n : never;\n","import { type CoID, RawAccount, type RawCoValue, RawGroup } from \"cojson\";\nimport { type Account } from \"../coValues/account.js\";\nimport type {\n AnonymousJazzAgent,\n CoValue,\n ID,\n RefEncoded,\n UnCo,\n} from \"../internal.js\";\nimport {\n instantiateRefEncoded,\n isRefEncoded,\n subscriptionsScopes,\n} from \"../internal.js\";\nimport { coValuesCache } from \"../lib/cache.js\";\n\nconst TRACE_ACCESSES = false;\n\nexport class Ref<out V extends CoValue> {\n constructor(\n readonly id: ID<V>,\n readonly controlledAccount: Account | AnonymousJazzAgent,\n readonly schema: RefEncoded<V>,\n ) {\n if (!isRefEncoded(schema)) {\n throw new Error(\"Ref must be constructed with a ref schema\");\n }\n }\n\n private getNode() {\n return \"node\" in this.controlledAccount\n ? this.controlledAccount.node\n : this.controlledAccount._raw.core.node;\n }\n\n hasReadAccess() {\n const node = this.getNode();\n\n const raw = node.getLoaded(this.id as unknown as CoID<RawCoValue>);\n\n if (!raw) {\n return true;\n }\n\n if (raw instanceof RawAccount || raw instanceof RawGroup) {\n return true;\n }\n\n const group = raw.core.getGroup();\n\n if (group instanceof RawAccount) {\n if (node.account.id !== group.id) {\n return false;\n }\n } else if (group.myRole() === undefined) {\n return false;\n }\n\n return true;\n }\n\n getValueWithoutAccessCheck() {\n const node = this.getNode();\n const raw = node.getLoaded(this.id as unknown as CoID<RawCoValue>);\n\n if (raw) {\n return coValuesCache.get(raw, () =>\n instantiateRefEncoded(this.schema, raw),\n );\n } else {\n return null;\n }\n }\n\n get value() {\n if (!this.hasReadAccess()) {\n return null;\n }\n\n return this.getValueWithoutAccessCheck();\n }\n\n private async loadHelper(): Promise<V | \"unavailable\"> {\n const node =\n \"node\" in this.controlledAccount\n ? this.controlledAccount.node\n : this.controlledAccount._raw.core.node;\n const raw = await node.load(this.id as unknown as CoID<RawCoValue>);\n if (raw === \"unavailable\") {\n return \"unavailable\";\n } else {\n return new Ref(this.id, this.controlledAccount, this.schema).value!;\n }\n }\n\n syncLoad(): V | undefined {\n const node =\n \"node\" in this.controlledAccount\n ? this.controlledAccount.node\n : this.controlledAccount._raw.core.node;\n\n const entry = node.coValuesStore.get(\n this.id as unknown as CoID<RawCoValue>,\n );\n\n if (entry.state.type === \"available\") {\n return new Ref(this.id, this.controlledAccount, this.schema).value!;\n }\n\n return undefined;\n }\n\n async load(): Promise<V | undefined> {\n const result = await this.loadHelper();\n if (result === \"unavailable\") {\n return undefined;\n } else {\n return result;\n }\n }\n\n accessFrom(fromScopeValue: CoValue, key: string | number | symbol): V | null {\n const subScope = subscriptionsScopes.get(fromScopeValue);\n\n subScope?.onRefAccessedOrSet(fromScopeValue.id, this.id);\n TRACE_ACCESSES &&\n console.log(subScope?.scopeID, \"accessing\", fromScopeValue, key, this.id);\n\n if (this.value && subScope) {\n subscriptionsScopes.set(this.value, subScope);\n }\n\n if (subScope) {\n const cached = subScope.cachedValues[this.id];\n if (cached) {\n TRACE_ACCESSES && console.log(\"cached\", cached);\n return cached as V;\n } else if (this.value !== null) {\n const freshValueInstance = instantiateRefEncoded(\n this.schema,\n this.value._raw,\n );\n TRACE_ACCESSES && console.log(\"freshValueInstance\", freshValueInstance);\n subScope.cachedValues[this.id] = freshValueInstance;\n subscriptionsScopes.set(freshValueInstance, subScope);\n return freshValueInstance as V;\n } else {\n return null;\n }\n } else {\n return this.value;\n }\n }\n}\n\nexport function makeRefs<Keys extends string | number>(\n getIdForKey: (key: Keys) => ID<CoValue> | undefined,\n getKeysWithIds: () => Keys[],\n controlledAccount: Account | AnonymousJazzAgent,\n refSchemaForKey: (key: Keys) => RefEncoded<CoValue>,\n): { [K in Keys]: Ref<CoValue> } & {\n [Symbol.iterator]: () => IterableIterator<Ref<CoValue>>;\n length: number;\n} {\n const refs = {} as { [K in Keys]: Ref<CoValue> } & {\n [Symbol.iterator]: () => IterableIterator<Ref<CoValue>>;\n length: number;\n };\n return new Proxy(refs, {\n get(_target, key) {\n if (key === Symbol.iterator) {\n return function* () {\n for (const key of getKeysWithIds()) {\n yield new Ref(\n getIdForKey(key)!,\n controlledAccount,\n refSchemaForKey(key),\n );\n }\n };\n }\n if (typeof key === \"symbol\") return undefined;\n if (key === \"length\") {\n return getKeysWithIds().length;\n }\n const id = getIdForKey(key as Keys);\n if (!id) return undefined;\n return new Ref(\n id as ID<CoValue>,\n controlledAccount,\n refSchemaForKey(key as Keys),\n );\n },\n ownKeys() {\n return getKeysWithIds().map((key) => key.toString());\n },\n getOwnPropertyDescriptor(target, key) {\n const id = getIdForKey(key as Keys);\n if (id) {\n return {\n enumerable: true,\n configurable: true,\n writable: true,\n };\n } else {\n return Reflect.getOwnPropertyDescriptor(target, key);\n }\n },\n });\n}\n\nexport type RefIfCoValue<V> = NonNullable<V> extends CoValue\n ? Ref<UnCo<NonNullable<V>>>\n : never;\n","import { RawCoValue } from \"cojson\";\nimport { CoValue } from \"../internal.js\";\n\nconst weakMap = new WeakMap<RawCoValue, CoValue>();\n\nexport const coValuesCache = {\n get: <V extends CoValue>(raw: RawCoValue, compute: () => V) => {\n const cached = weakMap.get(raw);\n if (cached) {\n return cached as V;\n }\n const computed = compute();\n weakMap.set(raw, computed);\n return computed;\n },\n};\n","import type { JsonValue, RawCoValue } from \"cojson\";\nimport { CojsonInternalTypes } from \"cojson\";\nimport {\n type CoValue,\n type CoValueClass,\n CoValueFromRaw,\n ItemsSym,\n JazzToolsSymbol,\n SchemaInit,\n isCoValueClass,\n} from \"../internal.js\";\n\n/** @category Schema definition */\nexport const Encoders = {\n Date: {\n encode: (value: Date) => value.toISOString(),\n decode: (value: JsonValue) => new Date(value as string),\n },\n OptionalDate: {\n encode: (value: Date | undefined) => value?.toISOString() || null,\n decode: (value: JsonValue) =>\n value === null ? undefined : new Date(value as string),\n },\n};\n\nexport type CoMarker = { readonly __co: unique symbol };\n/** @category Schema definition */\nexport type co<T> = T | (T & CoMarker);\nexport type IfCo<C, R> = C extends infer _A | infer B\n ? B extends CoMarker\n ? R extends JazzToolsSymbol // Exclude symbol properties like co.items from the refs/init types\n ? never\n : R\n : never\n : never;\nexport type UnCo<T> = T extends co<infer A> ? A : T;\n\nconst optional = {\n ref: optionalRef,\n json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T | undefined> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return { [SchemaInit]: \"json\" satisfies Schema } as any;\n },\n encoded<T>(arg: OptionalEncoder<T>): co<T | undefined> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return { [SchemaInit]: { encoded: arg } satisfies Schema } as any;\n },\n string: {\n [SchemaInit]: \"json\" satisfies Schema,\n } as unknown as co<string | undefined>,\n number: {\n [SchemaInit]: \"json\" satisfies Schema,\n } as unknown as co<number | undefined>,\n boolean: {\n [SchemaInit]: \"json\" satisfies Schema,\n } as unknown as co<boolean | undefined>,\n null: {\n [SchemaInit]: \"json\" satisfies Schema,\n } as unknown as co<null | undefined>,\n Date: {\n [SchemaInit]: { encoded: Encoders.OptionalDate } satisfies Schema,\n } as unknown as co<Date | undefined>,\n literal<T extends (string | number | boolean)[]>(\n ..._lit: T\n ): co<T[number] | undefined> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return { [SchemaInit]: \"json\" satisfies Schema } as any;\n },\n};\n\n/** @category Schema definition */\nexport const co = {\n string: {\n [SchemaInit]: \"json\" satisfies Schema,\n } as unknown as co<string>,\n number: {\n [SchemaInit]: \"json\" satisfies Schema,\n } as unknown as co<number>,\n boolean: {\n [SchemaInit]: \"json\" satisfies Schema,\n } as unknown as co<boolean>,\n null: {\n [SchemaInit]: \"json\" satisfies Schema,\n } as unknown as co<null>,\n Date: {\n [SchemaInit]: { encoded: Encoders.Date } satisfies Schema,\n } as unknown as co<Date>,\n literal<T extends (string | number | boolean)[]>(..._lit: T): co<T[number]> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return { [SchemaInit]: \"json\" satisfies Schema } as any;\n },\n json<T extends CojsonInternalTypes.CoJsonValue<T>>(): co<T> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return { [SchemaInit]: \"json\" satisfies Schema } as any;\n },\n encoded<T>(arg: Encoder<T>): co<T> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return { [SchemaInit]: { encoded: arg } satisfies Schema } as any;\n },\n ref,\n items: ItemsSym as ItemsSym,\n optional,\n};\n\nfunction optionalRef<C extends CoValueClass>(\n arg: C | ((_raw: InstanceType<C>[\"_raw\"]) => C),\n): co<InstanceType<C> | null | undefined> {\n return ref(arg, { optional: true });\n}\n\nfunction ref<C extends CoValueClass>(\n arg: C | ((_raw: InstanceType<C>[\"_raw\"]) => C),\n options?: never,\n): co<InstanceType<C> | null>;\nfunction ref<C extends CoValueClass>(\n arg: C | ((_raw: InstanceType<C>[\"_raw\"]) => C),\n options: { optional: true },\n): co<InstanceType<C> | null | undefined>;\nfunction ref<\n C extends CoValueClass,\n Options extends { optional?: boolean } | undefined,\n>(\n arg: C | ((_raw: InstanceType<C>[\"_raw\"]) => C),\n options?: Options,\n): Options extends { optional: true }\n ? co<InstanceType<C> | null | undefined>\n : co<InstanceType<C> | null> {\n return {\n [SchemaInit]: {\n ref: arg,\n optional: options?.optional || false,\n } satisfies Schema,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n}\n\nexport type JsonEncoded = \"json\";\nexport type EncodedAs<V> = { encoded: Encoder<V> | OptionalEncoder<V> };\nexport type RefEncoded<V extends CoValue> = {\n ref: CoValueClass<V> | ((raw: RawCoValue) => CoValueClass<V>);\n optional: boolean;\n};\n\nexport function isRefEncoded<V extends CoValue>(\n schema: Schema,\n): schema is RefEncoded<V> {\n return (\n typeof schema === \"object\" &&\n \"ref\" in schema &&\n \"optional\" in schema &&\n typeof schema.ref === \"function\"\n );\n}\n\nexport function instantiateRefEncoded<V extends CoValue>(\n schema: RefEncoded<V>,\n raw: RawCoValue,\n): V {\n return isCoValueClass<V>(schema.ref)\n ? schema.ref.fromRaw(raw)\n : (schema.ref as (raw: RawCoValue) => CoValueClass<V> & CoValueFromRaw<V>)(\n raw,\n ).fromRaw(raw);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Schema = JsonEncoded | RefEncoded<CoValue> | EncodedAs<any>;\n\nexport type SchemaFor<Field> = NonNullable<Field> extends CoValue\n ? RefEncoded<NonNullable<Field>>\n : NonNullable<Field> extends JsonValue\n ? JsonEncoded\n : EncodedAs<NonNullable<Field>>;\n\nexport type Encoder<V> = {\n encode: (value: V) => JsonValue;\n decode: (value: JsonValue) => V;\n};\nexport type OptionalEncoder<V> =\n | Encoder<V>\n | {\n encode: (value: V | undefined) => JsonValue;\n decode: (value: JsonValue) => V | undefined;\n };\n","import type { CoValueCore, LocalNode, RawCoValue } from \"cojson\";\nimport { type Account } from \"../coValues/account.js\";\nimport type {\n AnonymousJazzAgent,\n CoValue,\n CoValueClass,\n CoValueFromRaw,\n ID,\n} from \"../internal.js\";\n\nexport const subscriptionsScopes = new WeakMap<\n CoValue,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n SubscriptionScope<any>\n>();\n\nexport class SubscriptionScope<Root extends CoValue> {\n scopeID: string = `scope-${Math.random().toString(36).slice(2)}`;\n subscriber: Account | AnonymousJazzAgent;\n entries = new Map<\n ID<CoValue>,\n | { state: \"loading\"; immediatelyUnsub?: boolean }\n | { state: \"loaded\"; rawUnsub: () => void }\n >();\n rootEntry: {\n state: \"loaded\";\n value: RawCoValue;\n rawUnsub: () => void;\n };\n scheduleUpdate: () => void;\n scheduledUpdate: boolean = false;\n cachedValues: { [id: ID<CoValue>]: CoValue } = {};\n parents: { [id: ID<CoValue>]: Set<ID<CoValue>> } = {};\n syncResolution: boolean = false;\n\n constructor(\n root: Root,\n rootSchema: CoValueClass<Root> & CoValueFromRaw<Root>,\n onUpdate: (newRoot: Root, scope: SubscriptionScope<Root>) => void,\n ) {\n this.rootEntry = {\n state: \"loaded\" as const,\n value: root._raw,\n rawUnsub: () => {}, // placeholder\n };\n this.entries.set(root.id, this.rootEntry);\n\n subscriptionsScopes.set(root, this);\n\n this.subscriber = root._loadedAs;\n\n this.scheduleUpdate = () => {\n const value = rootSchema.fromRaw(this.rootEntry.value) as Root;\n subscriptionsScopes.set(value, this);\n onUpdate(value, this);\n };\n\n this.rootEntry.rawUnsub = root._raw.core.subscribe(\n (rawUpdate: RawCoValue | undefined) => {\n if (!rawUpdate) return;\n this.rootEntry.value = rawUpdate;\n this.scheduleUpdate();\n },\n );\n }\n\n onRefAccessedOrSet(\n fromId: ID<CoValue>,\n accessedOrSetId: ID<CoValue> | undefined,\n ) {\n // console.log(\"onRefAccessedOrSet\", this.scopeID, accessedOrSetId);\n if (!accessedOrSetId) {\n return;\n }\n\n this.parents[accessedOrSetId] = this.parents[accessedOrSetId] || new Set();\n this.parents[accessedOrSetId]!.add(fromId);\n\n if (!this.entries.has(accessedOrSetId)) {\n const loadingEntry = {\n state: \"loading\",\n immediatelyUnsub: false,\n } as const;\n this.entries.set(accessedOrSetId, loadingEntry);\n const node =\n this.subscriber._type === \"Account\"\n ? this.subscriber._raw.core.node\n : this.subscriber.node;\n\n loadCoValue(\n node,\n accessedOrSetId,\n (core) => {\n if (\n loadingEntry.state === \"loading\" &&\n loadingEntry.immediatelyUnsub\n ) {\n return;\n }\n if (core !== \"unavailable\") {\n const entry = {\n state: \"loaded\" as const,\n rawUnsub: () => {}, // placeholder\n };\n this.entries.set(accessedOrSetId, entry);\n\n const rawUnsub = core.subscribe((rawUpdate) => {\n if (!rawUpdate) return;\n\n this.invalidate(accessedOrSetId);\n this.scheduleUpdate();\n });\n\n entry.rawUnsub = rawUnsub;\n }\n },\n this.syncResolution,\n );\n }\n }\n\n invalidate(id: ID<CoValue>, seen: Set<ID<CoValue>> = new Set()) {\n if (seen.has(id)) return;\n\n delete this.cachedValues[id];\n seen.add(id);\n for (const parent of this.parents[id] || []) {\n this.invalidate(parent, seen);\n }\n }\n\n unsubscribeAll = () => {\n for (const entry of this.entries.values()) {\n if (entry.state === \"loaded\") {\n entry.rawUnsub();\n } else {\n entry.immediatelyUnsub = true;\n }\n }\n this.entries.clear();\n };\n}\n\n/**\n * Loads a CoValue from the node and calls the callback with the result.\n\n * If the CoValue is already loaded, the callback is called synchronously.\n * If the CoValue is not loaded, the callback is called asynchronously.\n */\nfunction loadCoValue(\n node: LocalNode,\n id: ID<CoValue>,\n callback: (value: CoValueCore | \"unavailable\") => void,\n syncResolution: boolean,\n) {\n const entry = node.coValuesStore.get(id);\n\n if (entry.state.type === \"available\" && syncResolution) {\n callback(entry.state.coValue);\n } else {\n void node.loadCoValueCore(id).then((core) => {\n callback(core);\n });\n }\n}\n","import {\n AgentSecret,\n CoID,\n ControlledAgent,\n CryptoProvider,\n LocalNode,\n Peer,\n RawAccount,\n RawAccountID,\n SessionID,\n} from \"cojson\";\nimport { AuthSecretStorage } from \"../auth/AuthSecretStorage.js\";\nimport { type Account, type AccountClass } from \"../coValues/account.js\";\nimport { RegisteredSchemas } from \"../coValues/registeredSchemas.js\";\nimport type { ID } from \"../internal.js\";\nimport { AuthCredentials, NewAccountProps } from \"../types.js\";\nimport { activeAccountContext } from \"./activeAccountContext.js\";\nimport { AnonymousJazzAgent } from \"./anonymousJazzAgent.js\";\n\nexport type Credentials = {\n accountID: ID<Account>;\n secret: AgentSecret;\n};\n\ntype SessionProvider = (\n accountID: ID<Account>,\n crypto: CryptoProvider,\n) => Promise<{ sessionID: SessionID; sessionDone: () => void }>;\n\nexport type AuthResult =\n | {\n type: \"existing\";\n username?: string;\n credentials: Credentials;\n saveCredentials?: (credentials: Credentials) => Promise<void>;\n onSuccess: () => void;\n onError: (error: string | Error) => void;\n logOut: () => Promise<void>;\n }\n | {\n type: \"new\";\n creationProps: {\n name: string;\n anonymous?: boolean;\n other?: Record<string, unknown>;\n };\n initialSecret?: AgentSecret;\n saveCredentials: (credentials: Credentials) => Promise<void>;\n onSuccess: () => void;\n onError: (error: string | Error) => void;\n logOut: () => Promise<void>;\n };\n\nexport async function randomSessionProvider(\n accountID: ID<Account>,\n crypto: CryptoProvider,\n) {\n return {\n sessionID: crypto.newRandomSessionID(accountID as unknown as RawAccountID),\n sessionDone: () => {},\n };\n}\n\nexport type JazzContextWithAccount<Acc extends Account> = {\n node: LocalNode;\n account: Acc;\n done: () => void;\n logOut: () => Promise<void>;\n};\n\nexport type JazzContextWithAgent = {\n agent: AnonymousJazzAgent;\n done: () => void;\n logOut: () => Promise<void>;\n};\n\nexport type JazzContext<Acc extends Account> =\n | JazzContextWithAccount<Acc>\n | JazzContextWithAgent;\n\nexport async function createJazzContextFromExistingCredentials<\n Acc extends Account,\n>({\n credentials,\n peersToLoadFrom,\n crypto,\n AccountSchema: PropsAccountSchema,\n sessionProvider,\n onLogOut,\n}: {\n credentials: Credentials;\n peersToLoadFrom: Peer[];\n crypto: CryptoProvider;\n AccountSchema?: AccountClass<Acc>;\n sessionProvider: SessionProvider;\n onLogOut?: () => void;\n}): Promise<JazzContextWithAccount<Acc>> {\n const { sessionID, sessionDone } = await sessionProvider(\n credentials.accountID,\n crypto,\n );\n\n const CurrentAccountSchema =\n PropsAccountSchema ??\n (RegisteredSchemas[\"Account\"] as unknown as AccountClass<Acc>);\n\n const node = await LocalNode.withLoadedAccount({\n accountID: credentials.accountID as unknown as CoID<RawAccount>,\n accountSecret: credentials.secret,\n sessionID: sessionID,\n peersToLoadFrom: peersToLoadFrom,\n crypto: crypto,\n migration: async (rawAccount, _node, creationProps) => {\n const account = new CurrentAccountSchema({\n fromRaw: rawAccount,\n }) as Acc;\n activeAccountContext.set(account);\n\n await account.applyMigration(creationProps);\n },\n });\n\n const account = CurrentAccountSchema.fromNode(node);\n activeAccountContext.set(account);\n\n return {\n node,\n account,\n done: () => {\n node.gracefulShutdown();\n sessionDone();\n },\n logOut: async () => {\n node.gracefulShutdown();\n sessionDone();\n await onLogOut?.();\n },\n };\n}\n\nexport async function createJazzContextForNewAccount<Acc extends Account>({\n creationProps,\n initialAgentSecret,\n peersToLoadFrom,\n crypto,\n AccountSchema: PropsAccountSchema,\n onLogOut,\n}: {\n creationProps: { name: string };\n initialAgentSecret?: AgentSecret;\n peersToLoadFrom: Peer[];\n crypto: CryptoProvider;\n AccountSchema?: AccountClass<Acc>;\n onLogOut?: () => Promise<void>;\n}): Promise<JazzContextWithAccount<Acc>> {\n const CurrentAccountSchema =\n PropsAccountSchema ??\n (RegisteredSchemas[\"Account\"] as unknown as AccountClass<Acc>);\n\n const { node } = await LocalNode.withNewlyCreatedAccount({\n creationProps,\n peersToLoadFrom,\n crypto,\n initialAgentSecret,\n migration: async (rawAccount, _node, creationProps) => {\n const account = new CurrentAccountSchema({\n fromRaw: rawAccount,\n }) as Acc;\n activeAccountContext.set(account);\n\n await account.applyMigration(creationProps);\n },\n });\n\n const account = CurrentAccountSchema.fromNode(node);\n activeAccountContext.set(account);\n\n return {\n node,\n account,\n done: () => {\n node.gracefulShutdown();\n },\n logOut: async () => {\n node.gracefulShutdown();\n await onLogOut?.();\n },\n };\n}\n\nexport async function createJazzContext<Acc extends Account>(options: {\n credentials?: AuthCredentials;\n newAccountProps?: NewAccountProps;\n peersToLoadFrom: Peer[];\n crypto: CryptoProvider;\n defaultProfileName?: string;\n AccountSchema?: AccountClass<Acc>;\n sessionProvider: SessionProvider;\n authSecretStorage: AuthSecretStorage;\n}) {\n const crypto = options.crypto;\n\n let context: JazzContextWithAccount<Acc>;\n\n const authSecretStorage = options.authSecretStorage;\n\n await authSecretStorage.migrate();\n\n const credentials = options.credentials ?? (await authSecretStorage.get());\n\n if (credentials && !options.newAccountProps) {\n context = await createJazzContextFromExistingCredentials({\n credentials: {\n accountID: credentials.accountID,\n secret: credentials.accountSecret,\n },\n peersToLoadFrom: options.peersToLoadFrom,\n crypto,\n AccountSchema: options.AccountSchema,\n sessionProvider: options.sessionProvider,\n onLogOut: () => {\n authSecretStorage.clearWithoutNotify();\n },\n });\n } else {\n const secretSeed = options.crypto.newRandomSecretSeed();\n\n const initialAgentSecret =\n options.newAccountProps?.secret ??\n crypto.agentSecretFromSecretSeed(secretSeed);\n\n const creationProps = options.newAccountProps?.creationProps ?? {\n name: options.defaultProfileName ?? \"Anonymous user\",\n };\n\n context = await createJazzContextForNewAccount({\n creationProps,\n initialAgentSecret,\n peersToLoadFrom: options.peersToLoadFrom,\n crypto,\n AccountSchema: options.AccountSchema,\n onLogOut: async () => {\n await authSecretStorage.clearWithoutNotify();\n },\n });\n\n if (!options.newAccountProps) {\n await authSecretStorage.setWithoutNotify({\n accountID: context.account.id,\n secretSeed,\n accountSecret: context.node.account.agentSecret,\n provider: \"anonymous\",\n });\n }\n }\n\n return {\n ...context,\n authSecretStorage,\n };\n}\n\nexport async function createAnonymousJazzContext({\n peersToLoadFrom,\n crypto,\n}: {\n peersToLoadFrom: Peer[];\n crypto: CryptoProvider;\n}): Promise<JazzContextWithAgent> {\n const agentSecret = crypto.newRandomAgentSecret();\n const rawAgent = new ControlledAgent(agentSecret, crypto);\n\n const node = new LocalNode(\n rawAgent,\n crypto.newRandomSessionID(rawAgent.id),\n crypto,\n );\n\n for (const peer of peersToLoadFrom) {\n node.syncManager.addPeer(peer);\n }\n\n activeAccountContext.setGuestMode();\n\n return {\n agent: new AnonymousJazzAgent(node),\n done: () => {},\n logOut: async () => {},\n };\n}\n","import type { Account } from \"./account.js\";\nimport type { CoMap } from \"./coMap.js\";\nimport type { Group } from \"./group.js\";\n\n/**\n * Regisering schemas into this Record to avoid circular dependencies.\n */\nexport const RegisteredSchemas = {} as {\n Account: typeof Account;\n Group: typeof Group;\n CoMap: typeof CoMap;\n};\n","/* istanbul ignore file -- @preserve */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { ItemsSym } from \"./symbols.js\";\n\n(globalThis as any).devtoolsFormatters = [\n {\n header: (object: any) => {\n if (object._type === \"CoMap\") {\n return [\"div\", {}, [\"span\", {}, object.constructor.name]];\n } else if (object._type === \"CoList\") {\n return [\n \"div\",\n {},\n [\"span\", {}, object.constructor.name + \"(\" + object.length + \") \"],\n ];\n } else if (object._type === \"Account\") {\n return [\n \"div\",\n {},\n [\n \"span\",\n {},\n object.constructor.name +\n \"(\" +\n object._refs.profile.value?.name +\n (object.isMe ? \" ME\" : \"\") +\n \")\",\n ],\n ];\n } else {\n return null;\n }\n },\n hasBody: function () {\n return true;\n },\n body: function (object: any) {\n if (object._type === \"CoMap\" || object._type === \"Account\") {\n return [\n \"div\",\n { style: \"margin-left: 15px\" },\n [\"div\", \"id: \", [\"object\", { object: object.id }]],\n ...Object.entries(object).map(([k, v]) => [\n \"div\",\n { style: \"white-space: nowrap;\" },\n [\"span\", { style: \"font-weight: bold; opacity: 0.6\" }, k, \": \"],\n [\"object\", { object: v }],\n ...(typeof object._schema[k] === \"function\"\n ? v === null\n ? [\n [\n \"span\",\n { style: \"opacity: 0.5\" },\n ` (pending ${object._schema[k].name} `,\n [\"object\", { object: object._refs[k] }],\n \")\",\n ],\n ]\n : []\n : []),\n ]),\n ];\n } else if (object._type === \"CoList\") {\n return [\n \"div\",\n { style: \"margin-left: 15px\" },\n [\"div\", \"id: \", [\"object\", { object: object.id }]],\n ...(object as any[]).map((v, i) => [\n \"div\",\n { style: \"white-space: nowrap;\" },\n [\"span\", { style: \"font-weight: bold; opacity: 0.6\" }, i, \": \"],\n [\"object\", { object: v }],\n ...(typeof object._schema[ItemsSym] === \"function\"\n ? v === null\n ? [\n [\n \"span\",\n { style: \"opacity: 0.5\" },\n ` (pending ${object._schema[ItemsSym].name} `,\n [\"object\", { object: object._refs[i] }],\n \")\",\n ],\n ]\n : []\n : []),\n ]),\n ];\n }\n },\n },\n];\n","import {\n CoID,\n InviteSecret,\n RawAccount,\n RawCoMap,\n RawControlledAccount,\n SessionID,\n} from \"cojson\";\nimport { CoStreamItem, RawCoStream } from \"cojson\";\nimport { activeAccountContext } from \"../implementation/activeAccountContext.js\";\nimport { type Account } from \"./account.js\";\nimport { CoValue, CoValueClass, ID, loadCoValue } from \"./interfaces.js\";\n\nexport type InboxInvite = `${CoID<MessagesStream>}/${InviteSecret}`;\ntype TxKey = `${SessionID}/${number}`;\n\ntype MessagesStream = RawCoStream<CoID<InboxMessage<CoValue, any>>>;\ntype FailedMessagesStream = RawCoStream<{\n errors: string[];\n value: CoID<InboxMessage<CoValue, any>>;\n}>;\ntype TxKeyStream = RawCoStream<TxKey>;\nexport type InboxRoot = RawCoMap<{\n messages: CoID<MessagesStream>;\n processed: CoID<TxKeyStream>;\n failed: CoID<FailedMessagesStream>;\n inviteLink: InboxInvite;\n}>;\n\nexport function createInboxRoot(account: Account) {\n if (!account.isLocalNodeOwner) {\n throw new Error(\"Account is not controlled\");\n }\n\n const rawAccount = account._raw as RawControlledAccount;\n\n const group = rawAccount.createGroup();\n const messagesFeed = group.createStream<MessagesStream>();\n\n const inboxRoot = rawAccount.createMap<InboxRoot>();\n const processedFeed = rawAccount.createStream<TxKeyStream>();\n const failedFeed = rawAccount.createStream<FailedMessagesStream>();\n\n const inviteLink =\n `${messagesFeed.id}/${group.createInvite(\"writeOnly\")}` as const;\n\n inboxRoot.set(\"messages\", messagesFeed.id);\n inboxRoot.set(\"processed\", processedFeed.id);\n inboxRoot.set(\"failed\", failedFeed.id);\n\n return {\n id: inboxRoot.id,\n inviteLink,\n };\n}\n\ntype InboxMessage<I extends CoValue, O extends CoValue | undefined> = RawCoMap<{\n payload: ID<I>;\n result: ID<O> | undefined;\n processed: boolean;\n error: string | undefined;\n}>;\n\nfunction createInboxMessage<I extends CoValue, O extends CoValue | undefined>(\n payload: I,\n inboxOwner: RawAccount,\n) {\n const group = payload._raw.group;\n\n if (group instanceof RawAccount) {\n throw new Error(\"Inbox messages should be owned by a group\");\n }\n\n group.addMember(inboxOwner, \"writer\");\n\n const message = group.createMap<InboxMessage<I, O>>({\n payload: payload.id,\n result: undefined,\n processed: false,\n error: undefined,\n });\n\n return message;\n}\n\nexport class Inbox {\n account: Account;\n messages: MessagesStream;\n processed: TxKeyStream;\n failed: FailedMessagesStream;\n root: InboxRoot;\n processing = new Set<`${SessionID}/${number}`>();\n\n private constructor(\n account: Account,\n root: InboxRoot,\n messages: MessagesStream,\n processed: TxKeyStream,\n failed: FailedMessagesStream,\n ) {\n this.account = account;\n this.root = root;\n this.messages = messages;\n this.processed = processed;\n this.failed = failed;\n }\n\n subscribe<I extends CoValue, O extends CoValue | undefined>(\n Schema: CoValueClass<I>,\n callback: (\n message: I,\n senderAccountID: ID<Account>,\n ) => Promise<O | undefined | void>,\n options: { retries?: number } = {},\n ) {\n const processed = new Set<`${SessionID}/${number}`>();\n const failed = new Map<`${SessionID}/${number}`, string[]>();\n const node = this.account._raw.core.node;\n\n this.processed.subscribe((stream) => {\n for (const items of Object.values(stream.items)) {\n for (const item of items) {\n processed.add(item.value as TxKey);\n }\n }\n });\n\n const { account } = this;\n const { retries = 3 } = options;\n\n let failTimer: ReturnType<typeof setTimeout> | number | undefined =\n undefined;\n\n const clearFailTimer = () => {\n clearTimeout(failTimer);\n failTimer = undefined;\n };\n\n const handleNewMessages = (stream: MessagesStream) => {\n clearFailTimer(); // Stop the failure timers, we're going to process the failed entries anyway\n\n for (const [sessionID, items] of Object.entries(stream.items) as [\n SessionID,\n CoStreamItem<CoID<InboxMessage<I, O>>>[],\n ][]) {\n const accountID = getAccountIDfromSessionID(sessionID);\n\n if (!accountID) {\n console.warn(\"Received message from unknown account\", sessionID);\n continue;\n }\n\n for (const item of items) {\n const txKey = `${sessionID}/${item.tx.txIndex}` as const;\n\n if (!processed.has(txKey) && !this.processing.has(txKey)) {\n this.processing.add(txKey);\n\n const id = item.value;\n\n node\n .load(id)\n .then((message) => {\n if (message === \"unavailable\") {\n return Promise.reject(\n new Error(\"Unable to load inbox message \" + id),\n );\n }\n\n return loadCoValue(Schema, message.get(\"payload\") as ID<I>, {\n loadAs: account,\n });\n })\n .then((value) => {\n if (!value) {\n return Promise.reject(\n new Error(\"Unable to load inbox message \" + id),\n );\n }\n\n return callback(value, accountID);\n })\n .then((result) => {\n const inboxMessage = node\n .expectCoValueLoaded(item.value)\n .getCurrentContent() as RawCoMap;\n\n if (result) {\n inboxMessage.set(\"result\", result.id);\n }\n\n inboxMessage.set(\"processed\", true);\n\n this.processed.push(txKey);\n this.processing.delete(txKey);\n })\n .catch((error) => {\n console.error(\"Error processing inbox message\", error);\n this.processing.delete(txKey);\n const errors = failed.get(txKey) ?? [];\n\n const stringifiedError = String(error);\n errors.push(stringifiedError);\n\n const inboxMessage = node\n .expectCoValueLoaded(item.value)\n .getCurrentContent() as RawCoMap;\n\n inboxMessage.set(\"error\", stringifiedError);\n\n if (errors.length > retries) {\n inboxMessage.set(\"processed\", true);\n this.processed.push(txKey);\n this.failed.push({ errors, value: item.value });\n } else {\n failed.set(txKey, errors);\n if (!failTimer) {\n failTimer = setTimeout(\n () => handleNewMessages(stream),\n 100,\n );\n }\n }\n });\n }\n }\n }\n };\n\n return this.messages.subscribe(handleNewMessages);\n }\n\n static async load(account: Account) {\n const profile = account.profile;\n\n if (!profile) {\n throw new Error(\"Account profile should already be loaded\");\n }\n\n if (!profile.inbox) {\n throw new Error(\"The account has not set up their inbox\");\n }\n\n const node = account._raw.core.node;\n\n const root = await node.load(profile.inbox as CoID<InboxRoot>);\n\n if (root === \"unavailable\") {\n throw new Error(\"Inbox not found\");\n }\n\n const [messages, processed, failed] = await Promise.all([\n node.load(root.get(\"messages\")!),\n node.load(root.get(\"processed\")!),\n node.load(root.get(\"failed\")!),\n ]);\n\n if (\n messages === \"unavailable\" ||\n processed === \"unavailable\" ||\n failed === \"unavailable\"\n ) {\n throw new Error(\"Inbox not found\");\n }\n\n return new Inbox(account, root, messages, processed, failed);\n }\n}\n\nexport class InboxSender<I extends CoValue, O extends CoValue | undefined> {\n currentAccount: Account;\n owner: RawAccount;\n messages: MessagesStream;\n\n private constructor(\n currentAccount: Account,\n owner: RawAccount,\n messages: MessagesStream,\n ) {\n this.currentAccount = currentAccount;\n this.owner = owner;\n this.messages = messages;\n }\n\n getOwnerAccount() {\n return this.owner;\n }\n\n sendMessage(message: I): Promise<O extends CoValue ? ID<O> : undefined> {\n const inboxMessage = createInboxMessage<I, O>(message, this.owner);\n\n this.messages.push(inboxMessage.id);\n\n return new Promise((resolve, reject) => {\n inboxMessage.subscribe((message) => {\n if (message.get(\"processed\")) {\n const error = message.get(\"error\");\n if (error) {\n reject(new Error(error));\n } else {\n resolve(\n message.get(\"result\") as O extends CoValue ? ID<O> : undefined,\n );\n }\n }\n });\n });\n }\n\n static async load<\n I extends CoValue,\n O extends CoValue | undefined = undefined,\n >(inboxOwnerID: ID<Account>, currentAccount?: Account) {\n currentAccount ||= activeAccountContext.get();\n\n const node = currentAccount._raw.core.node;\n\n const inboxOwnerRaw = await node.load(\n inboxOwnerID as unknown as CoID<RawAccount>,\n );\n\n if (inboxOwnerRaw === \"unavailable\") {\n throw new Error(\"Failed to load the inbox owner\");\n }\n\n const inboxOwnerProfileRaw = await node.load(inboxOwnerRaw.get(\"profile\")!);\n\n if (inboxOwnerProfileRaw === \"unavailable\") {\n throw new Error(\"Failed to load the inbox owner profile\");\n }\n\n if (\n inboxOwnerProfileRaw.group.roleOf(currentAccount._raw.id) !== \"reader\" &&\n inboxOwnerProfileRaw.group.roleOf(currentAccount._raw.id) !== \"writer\" &&\n inboxOwnerProfileRaw.group.roleOf(currentAccount._raw.id) !== \"admin\"\n ) {\n throw new Error(\n \"Insufficient permissions to access the inbox, make sure its user profile is publicly readable.\",\n );\n }\n\n const inboxInvite = inboxOwnerProfileRaw.get(\"inboxInvite\");\n\n if (!inboxInvite) {\n throw new Error(\"The user has not set up their inbox\");\n }\n\n const id = await acceptInvite(inboxInvite as InboxInvite, currentAccount);\n\n const messages = await node.load(id);\n\n if (messages === \"unavailable\") {\n throw new Error(\"Inbox not found\");\n }\n\n return new InboxSender<I, O>(currentAccount, inboxOwnerRaw, messages);\n }\n}\n\nasync function acceptInvite(invite: string, account?: Account) {\n account ||= activeAccountContext.get();\n\n const id = invite.slice(0, invite.indexOf(\"/\")) as CoID<MessagesStream>;\n\n const inviteSecret = invite.slice(invite.indexOf(\"/\") + 1) as InviteSecret;\n\n if (!id?.startsWith(\"co_z\") || !inviteSecret.startsWith(\"inviteSecret_\")) {\n throw new Error(\"Invalid inbox ticket\");\n }\n\n if (!account.isLocalNodeOwner) {\n throw new Error(\"Account is not controlled\");\n }\n\n await (account._raw as RawControlledAccount).acceptInvite(id, inviteSecret);\n\n return id;\n}\n\nfunction getAccountIDfromSessionID(sessionID: SessionID) {\n const until = sessionID.indexOf(\"_session\");\n const accountID = sessionID.slice(0, until);\n\n if (accountID.startsWith(\"co_z\")) {\n return accountID as ID<Account>;\n }\n\n return;\n}\n","import {\n AgentID,\n type CoValueUniqueness,\n CojsonInternalTypes,\n type JsonValue,\n RawAccountID,\n type RawCoMap,\n cojsonInternals,\n} from \"cojson\";\nimport { activeAccountContext } from \"../implementation/activeAccountContext.js\";\nimport type {\n AnonymousJazzAgent,\n CoValue,\n CoValueClass,\n ID,\n IfCo,\n RefEncoded,\n RefIfCoValue,\n RefsToResolve,\n RefsToResolveStrict,\n Resolved,\n Schema,\n SubscribeListenerOptions,\n SubscribeRestArgs,\n co,\n} from \"../internal.js\";\nimport {\n CoValueBase,\n ItemsSym,\n Ref,\n SchemaInit,\n ensureCoValueLoaded,\n inspect,\n isRefEncoded,\n loadCoValueWithoutMe,\n makeRefs,\n parseCoValueCreateOptions,\n parseSubscribeRestArgs,\n subscribeToCoValueWithoutMe,\n subscribeToExistingCoValue,\n subscriptionsScopes,\n} from \"../internal.js\";\nimport { RegisteredAccount } from \"../types.js\";\nimport { type Account } from \"./account.js\";\nimport { type Group } from \"./group.js\";\nimport { RegisteredSchemas } from \"./registeredSchemas.js\";\n\ntype CoMapEdit<V> = {\n value?: V;\n ref?: RefIfCoValue<V>;\n by?: RegisteredAccount;\n madeAt: Date;\n key?: string;\n};\n\ntype LastAndAllCoMapEdits<V> = CoMapEdit<V> & { all: CoMapEdit<V>[] };\n\nexport type Simplify<A> = {\n [K in keyof A]: A[K];\n} extends infer B\n ? B\n : never;\n\n/**\n * CoMaps are collaborative versions of plain objects, mapping string-like keys to values.\n *\n * @categoryDescription Declaration\n * Declare your own CoMap schemas by subclassing `CoMap` and assigning field schemas with `co`.\n *\n * Optional `co.ref(...)` fields must be marked with `{ optional: true }`.\n *\n * ```ts\n * import { co, CoMap } from \"jazz-tools\";\n *\n * class Person extends CoMap {\n * name = co.string;\n * age = co.number;\n * pet = co.ref(Animal);\n * car = co.ref(Car, { optional: true });\n * }\n * ```\n *\n * @categoryDescription Content\n * You can access properties you declare on a `CoMap` (using `co`) as if they were normal properties on a plain object, using dot notation, `Object.keys()`, etc.\n *\n * ```ts\n * person.name;\n * person[\"age\"];\n * person.age = 42;\n * person.pet?.name;\n * Object.keys(person);\n * // => [\"name\", \"age\", \"pet\"]\n * ```\n *\n * @category CoValues\n * */\nexport class CoMap extends CoValueBase implements CoValue {\n /**\n * The ID of this `CoMap`\n * @category Content */\n declare id: ID<this>;\n /** @category Type Helpers */\n declare _type: \"CoMap\";\n static {\n this.prototype._type = \"CoMap\";\n }\n /** @category Internals */\n declare _raw: RawCoMap;\n\n /** @internal */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static _schema: any;\n /** @internal */\n get _schema() {\n return (this.constructor as typeof CoMap)._schema as {\n [key: string]: Schema;\n } & { [ItemsSym]?: Schema };\n }\n\n /**\n * If property `prop` is a `co.ref(...)`, you can use `coMaps._refs.prop` to access\n * the `Ref` instead of the potentially loaded/null value.\n *\n * This allows you to always get the ID or load the value manually.\n *\n * @example\n * ```ts\n * person._refs.pet.id; // => ID<Animal>\n * person._refs.pet.value;\n * // => Animal | null\n * const pet = await person._refs.pet.load();\n * ```\n *\n * @category Content\n **/\n get _refs(): {\n [Key in CoKeys<this>]: IfCo<this[Key], RefIfCoValue<this[Key]>>;\n } {\n return makeRefs<CoKeys<this>>(\n (key) => this._raw.get(key as string) as unknown as ID<CoValue>,\n () => {\n const keys = this._raw.keys().filter((key) => {\n const schema =\n this._schema[key as keyof typeof this._schema] ||\n (this._schema[ItemsSym] as Schema | undefined);\n return schema && schema !== \"json\" && isRefEncoded(schema);\n }) as CoKeys<this>[];\n\n return keys;\n },\n this._loadedAs,\n (key) =>\n (this._schema[key] || this._schema[ItemsSym]) as RefEncoded<CoValue>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) as any;\n }\n\n /** @internal */\n public getEditFromRaw(\n target: CoMap,\n rawEdit: {\n by: RawAccountID | AgentID;\n tx: CojsonInternalTypes.TransactionID;\n at: Date;\n value?: JsonValue | undefined;\n },\n descriptor: Schema,\n key: string,\n ) {\n return {\n value:\n descriptor === \"json\"\n ? rawEdit.value\n : \"encoded\" in descriptor\n ? rawEdit.value === null || rawEdit.value === undefined\n ? rawEdit.value\n : descriptor.encoded.decode(rawEdit.value)\n : new Ref(\n rawEdit.value as ID<CoValue>,\n target._loadedAs,\n descriptor,\n ).accessFrom(target, \"_edits.\" + key + \".value\"),\n ref:\n descriptor !== \"json\" && isRefEncoded(descriptor)\n ? new Ref(rawEdit.value as ID<CoValue>, target._loadedAs, descriptor)\n : undefined,\n by:\n rawEdit.by &&\n new Ref<Account>(rawEdit.by as ID<Account>, target._loadedAs, {\n ref: RegisteredSchemas[\"Account\"],\n optional: false,\n }).accessFrom(target, \"_edits.\" + key + \".by\"),\n madeAt: rawEdit.at,\n key,\n };\n }\n\n /** @category Collaboration */\n get _edits() {\n const map = this;\n return new Proxy(\n {},\n {\n get(_target, key) {\n const rawEdit = map._raw.lastEditAt(key as string);\n if (!rawEdit) return undefined;\n\n const descriptor = map._schema[\n key as keyof typeof map._schema\n ] as Schema;\n\n return {\n ...map.getEditFromRaw(map, rawEdit, descriptor, key as string),\n get all() {\n return [...map._raw.editsAt(key as string)].map((rawEdit) =>\n map.getEditFromRaw(map, rawEdit, descriptor, key as string),\n );\n },\n };\n },\n ownKeys(_target) {\n return map._raw.keys();\n },\n getOwnPropertyDescriptor(target, key) {\n return {\n value: Reflect.get(target, key),\n writable: false,\n enumerable: true,\n configurable: true,\n };\n },\n },\n ) as {\n [Key in CoKeys<this>]: IfCo<this[Key], LastAndAllCoMapEdits<this[Key]>>;\n };\n }\n\n /** @internal */\n constructor(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n options: { fromRaw: RawCoMap } | undefined,\n ) {\n super();\n\n if (options) {\n if (\"fromRaw\" in options) {\n Object.defineProperties(this, {\n id: {\n value: options.fromRaw.id as unknown as ID<this>,\n enumerable: false,\n },\n _raw: { value: options.fromRaw, enumerable: false },\n });\n } else {\n throw new Error(\"Invalid CoMap constructor arguments\");\n }\n }\n\n return new Proxy(this, CoMapProxyHandler as ProxyHandler<this>);\n }\n\n /**\n * Create a new CoMap with the given initial values and owner.\n *\n * The owner (a Group or Account) determines access rights to the CoMap.\n *\n * The CoMap will immediately be persisted and synced to connected peers.\n *\n * @example\n * ```ts\n * const person = Person.create({\n * name: \"Alice\",\n * age: 42,\n * pet: cat,\n * }, { owner: friendGroup });\n * ```\n *\n * @category Creation\n **/\n static create<M extends CoMap>(\n this: CoValueClass<M>,\n init: Simplify<CoMapInit<M>>,\n options?:\n | {\n owner: Account | Group;\n unique?: CoValueUniqueness[\"uniqueness\"];\n }\n | Account\n | Group,\n ) {\n const instance = new this();\n\n const { owner, uniqueness } = parseCoValueCreateOptions(options);\n const raw = instance.rawFromInit(init, owner, uniqueness);\n\n Object.defineProperties(instance, {\n id: {\n value: raw.id,\n enumerable: false,\n },\n _raw: { value: raw, enumerable: false },\n });\n return instance;\n }\n\n /**\n * Return a JSON representation of the `CoMap`\n * @category Content\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(_key?: string, seenAbove?: ID<CoValue>[]): any[] {\n const jsonedFields = this._raw.keys().map((key) => {\n const tKey = key as CoKeys<this>;\n const descriptor = (this._schema[tKey] ||\n this._schema[ItemsSym]) as Schema;\n\n if (descriptor == \"json\" || \"encoded\" in descriptor) {\n return [key, this._raw.get(key)];\n } else if (isRefEncoded(descriptor)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (seenAbove?.includes((this as any)[tKey]?.id)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return [key, { _circular: (this as any)[tKey]?.id }];\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const jsonedRef = (this as any)[tKey]?.toJSON(tKey, [\n ...(seenAbove || []),\n this.id,\n ]);\n return [key, jsonedRef];\n } else {\n return [key, undefined];\n }\n });\n\n return {\n id: this.id,\n _type: this._type,\n ...Object.fromEntries(jsonedFields),\n };\n }\n\n [inspect]() {\n return this.toJSON();\n }\n\n /**\n * Create a new `RawCoMap` from an initialization object\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rawFromInit<Fields extends object = Record<string, any>>(\n init: Simplify<CoMapInit<Fields>> | undefined,\n owner: Account | Group,\n uniqueness?: CoValueUniqueness,\n ) {\n const rawOwner = owner._raw;\n\n const rawInit = {} as {\n [key in keyof Fields]: JsonValue | undefined;\n };\n\n if (init)\n for (const key of Object.keys(init) as (keyof Fields)[]) {\n const initValue = init[key as keyof typeof init];\n\n const descriptor = (this._schema[key as keyof typeof this._schema] ||\n this._schema[ItemsSym]) as Schema;\n\n if (!descriptor) {\n continue;\n }\n\n if (descriptor === \"json\") {\n rawInit[key] = initValue as JsonValue;\n } else if (isRefEncoded(descriptor)) {\n if (initValue) {\n rawInit[key] = (initValue as unknown as CoValue).id;\n }\n } else if (\"encoded\" in descriptor) {\n rawInit[key] = descriptor.encoded.encode(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n initValue as any,\n );\n }\n }\n\n return rawOwner.createMap(rawInit, null, \"private\", uniqueness);\n }\n\n /**\n * Declare a Record-like CoMap schema, by extending `CoMap.Record(...)` and passing the value schema using `co`. Keys are always `string`.\n *\n * @example\n * ```ts\n * import { co, CoMap } from \"jazz-tools\";\n *\n * class ColorToFruitMap extends CoMap.Record(\n * co.ref(Fruit)\n * ) {}\n *\n * // assume we have map: ColorToFruitMap\n * // and strawberry: Fruit\n * map[\"red\"] = strawberry;\n * ```\n *\n * @category Declaration\n */\n static Record<Value>(value: IfCo<Value, Value>) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\n class RecordLikeCoMap extends CoMap {\n [ItemsSym] = value;\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\n interface RecordLikeCoMap extends Record<string, Value> {}\n\n return RecordLikeCoMap;\n }\n\n /**\n * Load a `CoMap` with a given ID, as a given account.\n *\n * `depth` specifies which (if any) fields that reference other CoValues to load as well before resolving.\n * The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth.\n *\n * You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues.\n *\n * Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.\n *\n * @example\n * ```ts\n * const person = await Person.load(\n * \"co_zdsMhHtfG6VNKt7RqPUPvUtN2Ax\",\n * { pet: {} }\n * );\n * ```\n *\n * @category Subscription & Loading\n */\n static load<M extends CoMap, const R extends RefsToResolve<M> = true>(\n this: CoValueClass<M>,\n id: ID<M>,\n options?: {\n resolve?: RefsToResolveStrict<M, R>;\n loadAs?: Account | AnonymousJazzAgent;\n },\n ): Promise<Resolved<M, R> | null> {\n return loadCoValueWithoutMe(this, id, options);\n }\n\n /**\n * Load and subscribe to a `CoMap` with a given ID, as a given account.\n *\n * Automatically also subscribes to updates to all referenced/nested CoValues as soon as they are accessed in the listener.\n *\n * `depth` specifies which (if any) fields that reference other CoValues to load as well before calling `listener` for the first time.\n * The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth.\n *\n * You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues.\n *\n * Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.\n *\n * Returns an unsubscribe function that you should call when you no longer need updates.\n *\n * Also see the `useCoState` hook to reactively subscribe to a CoValue in a React component.\n *\n * @example\n * ```ts\n * const unsub = Person.subscribe(\n * \"co_zdsMhHtfG6VNKt7RqPUPvUtN2Ax\",\n * { pet: {} },\n * (person) => console.log(person)\n * );\n * ```\n *\n * @category Subscription & Loading\n */\n static subscribe<M extends CoMap, const R extends RefsToResolve<M> = true>(\n this: CoValueClass<M>,\n id: ID<M>,\n listener: (value: Resolved<M, R>, unsubscribe: () => void) => void,\n ): () => void;\n static subscribe<M extends CoMap, const R extends RefsToResolve<M> = true>(\n this: CoValueClass<M>,\n id: ID<M>,\n options: SubscribeListenerOptions<M, R>,\n listener: (value: Resolved<M, R>, unsubscribe: () => void) => void,\n ): () => void;\n static subscribe<M extends CoMap, const R extends RefsToResolve<M>>(\n this: CoValueClass<M>,\n id: ID<M>,\n ...args: SubscribeRestArgs<M, R>\n ): () => void {\n const { options, listener } = parseSubscribeRestArgs(args);\n return subscribeToCoValueWithoutMe<M, R>(this, id, options, listener);\n }\n\n static findUnique<M extends CoMap>(\n this: CoValueClass<M>,\n unique: CoValueUniqueness[\"uniqueness\"],\n ownerID: ID<Account> | ID<Group>,\n as?: Account | Group | AnonymousJazzAgent,\n ) {\n as ||= activeAccountContext.get();\n\n const header = {\n type: \"comap\" as const,\n ruleset: {\n type: \"ownedByGroup\" as const,\n group: ownerID,\n },\n meta: null,\n uniqueness: unique,\n };\n const crypto =\n as._type === \"Anonymous\" ? as.node.crypto : as._raw.core.crypto;\n return cojsonInternals.idforHeader(header, crypto) as ID<M>;\n }\n\n /**\n * Given an already loaded `CoMap`, ensure that the specified fields are loaded to the specified depth.\n *\n * Works like `CoMap.load()`, but you don't need to pass the ID or the account to load as again.\n *\n * @category Subscription & Loading\n */\n ensureLoaded<M extends CoMap, const R extends RefsToResolve<M>>(\n this: M,\n options: { resolve: RefsToResolveStrict<M, R> },\n ): Promise<Resolved<M, R>> {\n return ensureCoValueLoaded(this, options);\n }\n\n /**\n * Given an already loaded `CoMap`, subscribe to updates to the `CoMap` and ensure that the specified fields are loaded to the specified depth.\n *\n * Works like `CoMap.subscribe()`, but you don't need to pass the ID or the account to load as again.\n *\n * Returns an unsubscribe function that you should call when you no longer need updates.\n *\n * @category Subscription & Loading\n **/\n subscribe<M extends CoMap, const R extends RefsToResolve<M> = true>(\n this: M,\n listener: (value: Resolved<M, R>, unsubscribe: () => void) => void,\n ): () => void;\n subscribe<M extends CoMap, const R extends RefsToResolve<M> = true>(\n this: M,\n options: { resolve?: RefsToResolveStrict<M, R> },\n listener: (value: Resolved<M, R>, unsubscribe: () => void) => void,\n ): () => void;\n subscribe<M extends CoMap, const R extends RefsToResolve<M>>(\n this: M,\n ...args: SubscribeRestArgs<M, R>\n ): () => void {\n const { options, listener } = parseSubscribeRestArgs(args);\n return subscribeToExistingCoValue<M, R>(this, options, listener);\n }\n\n applyDiff<N extends Partial<CoMapInit<this>>>(newValues: N) {\n for (const key in newValues) {\n if (Object.prototype.hasOwnProperty.call(newValues, key)) {\n const tKey = key as keyof typeof newValues & keyof this;\n const descriptor = (this._schema[tKey as string] ||\n this._schema[ItemsSym]) as Schema;\n\n if (tKey in this._schema) {\n const newValue = newValues[tKey];\n const currentValue = (this as unknown as N)[tKey];\n\n if (descriptor === \"json\" || \"encoded\" in descriptor) {\n if (currentValue !== newValue) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any)[tKey] = newValue;\n }\n } else if (isRefEncoded(descriptor)) {\n const currentId = (currentValue as CoValue | undefined)?.id;\n const newId = (newValue as CoValue | undefined)?.id;\n if (currentId !== newId) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any)[tKey] = newValue;\n }\n }\n }\n }\n }\n return this;\n }\n\n /**\n * Wait for the `CoMap` to be uploaded to the other peers.\n *\n * @category Subscription & Loading\n */\n waitForSync(options?: { timeout?: number }) {\n return this._raw.core.waitForSync(options);\n }\n}\n\nexport type CoKeys<Map extends object> = Exclude<\n keyof Map & string,\n keyof CoMap\n>;\n\n/**\n * Force required ref fields to be non nullable\n *\n * Considering that:\n * - Optional refs are typed as co<InstanceType<CoValueClass> | null | undefined>\n * - Required refs are typed as co<InstanceType<CoValueClass> | null>\n *\n * This type works in two steps:\n * - Remove the null from both types\n * - Then we check if the input type accepts undefined, if positive we put the null union back\n *\n * So the optional refs stays unchanged while we safely remove the null union\n * from required refs\n *\n * This way required refs can be marked as required in the CoMapInit while\n * staying a nullable property for value access.\n *\n * Example:\n *\n * const map = MyCoMap.create({\n * requiredRef: NestedMap.create({}) // null is not valid here\n * })\n *\n * map.requiredRef // this value is still nullable\n */\ntype ForceRequiredRef<V> = V extends co<InstanceType<CoValueClass> | null>\n ? NonNullable<V>\n : V extends co<InstanceType<CoValueClass> | undefined>\n ? V | null\n : V;\n\nexport type CoMapInit<Map extends object> = {\n [Key in CoKeys<Map> as undefined extends Map[Key]\n ? never\n : IfCo<Map[Key], Key>]: ForceRequiredRef<Map[Key]>;\n} & {\n [Key in CoKeys<Map> as IfCo<Map[Key], Key>]?: ForceRequiredRef<Map[Key]>;\n};\n\n// TODO: cache handlers per descriptor for performance?\nconst CoMapProxyHandler: ProxyHandler<CoMap> = {\n get(target, key, receiver) {\n if (key === \"_schema\") {\n return Reflect.get(target, key);\n } else if (key in target) {\n return Reflect.get(target, key, receiver);\n } else {\n const schema = target._schema;\n\n if (!schema) {\n return undefined;\n }\n\n const descriptor = (schema[key as keyof CoMap[\"_schema\"]] ||\n schema[ItemsSym]) as Schema;\n if (descriptor && typeof key === \"string\") {\n const raw = target._raw.get(key);\n\n if (descriptor === \"json\") {\n return raw;\n } else if (\"encoded\" in descriptor) {\n return raw === undefined ? undefined : descriptor.encoded.decode(raw);\n } else if (isRefEncoded(descriptor)) {\n return raw === undefined\n ? undefined\n : new Ref(\n raw as unknown as ID<CoValue>,\n target._loadedAs,\n descriptor,\n ).accessFrom(receiver, key);\n }\n } else {\n return undefined;\n }\n }\n },\n set(target, key, value, receiver) {\n if (\n (typeof key === \"string\" || ItemsSym) &&\n typeof value === \"object\" &&\n value !== null &&\n SchemaInit in value\n ) {\n (target.constructor as typeof CoMap)._schema ||= {};\n (target.constructor as typeof CoMap)._schema[key] = value[SchemaInit];\n return true;\n }\n\n const descriptor = (target._schema[key as keyof CoMap[\"_schema\"]] ||\n target._schema[ItemsSym]) as Schema;\n if (descriptor && typeof key === \"string\") {\n if (descriptor === \"json\") {\n target._raw.set(key, value);\n } else if (\"encoded\" in descriptor) {\n target._raw.set(key, descriptor.encoded.encode(value));\n } else if (isRefEncoded(descriptor)) {\n if (value === null) {\n if (descriptor.optional) {\n target._raw.set(key, null);\n } else {\n throw new Error(`Cannot set required reference ${key} to null`);\n }\n } else if (value?.id) {\n target._raw.set(key, value.id);\n subscriptionsScopes\n .get(target)\n ?.onRefAccessedOrSet(target.id, value.id);\n } else {\n throw new Error(\n `Cannot set reference ${key} to a non-CoValue. Got ${value}`,\n );\n }\n }\n return true;\n } else {\n return Reflect.set(target, key, value, receiver);\n }\n },\n defineProperty(target, key, attributes) {\n if (\n \"value\" in attributes &&\n typeof attributes.value === \"object\" &&\n SchemaInit in attributes.value\n ) {\n (target.constructor as typeof CoMap)._schema ||= {};\n (target.constructor as typeof CoMap)._schema[key as string] =\n attributes.value[SchemaInit];\n return true;\n } else {\n return Reflect.defineProperty(target, key, attributes);\n }\n },\n ownKeys(target) {\n const keys = Reflect.ownKeys(target).filter((k) => k !== ItemsSym);\n // for (const key of Reflect.ownKeys(target._schema)) {\n // if (key !== ItemsSym && !keys.includes(key)) {\n // keys.push(key);\n // }\n // }\n for (const key of target._raw.keys()) {\n if (!keys.includes(key)) {\n keys.push(key);\n }\n }\n\n return keys;\n },\n getOwnPropertyDescriptor(target, key) {\n if (key in target) {\n return Reflect.getOwnPropertyDescriptor(target, key);\n } else {\n const descriptor = (target._schema[key as keyof CoMap[\"_schema\"]] ||\n target._schema[ItemsSym]) as Schema;\n if (descriptor || key in target._raw.latest) {\n return {\n enumerable: true,\n configurable: true,\n writable: true,\n };\n }\n }\n },\n has(target, key) {\n const descriptor = (target._schema?.[key as keyof CoMap[\"_schema\"]] ||\n target._schema?.[ItemsSym]) as Schema;\n\n if (target._raw && typeof key === \"string\" && descriptor) {\n return target._raw.get(key) !== undefined;\n } else {\n return Reflect.has(target, key);\n }\n },\n deleteProperty(target, key) {\n const descriptor = (target._schema[key as keyof CoMap[\"_schema\"]] ||\n target._schema[ItemsSym]) as Schema;\n if (typeof key === \"string\" && descriptor) {\n target._raw.delete(key);\n return true;\n } else {\n return Reflect.deleteProperty(target, key);\n }\n },\n};\n\nRegisteredSchemas[\"CoMap\"] = CoMap;\n","import { CoID } from \"cojson\";\nimport { CoValueClass, co } from \"../internal.js\";\nimport { Account } from \"./account.js\";\nimport { CoMap, CoMapInit, Simplify } from \"./coMap.js\";\nimport { Group } from \"./group.js\";\nimport { InboxInvite, InboxRoot } from \"./inbox.js\";\n\n/** @category Identity & Permissions */\nexport class Profile extends CoMap {\n name = co.string;\n inbox = co.optional.json<CoID<InboxRoot>>();\n inboxInvite = co.optional.json<InboxInvite>();\n\n override get _owner(): Group {\n return super._owner as Group;\n }\n\n /**\n * Creates a new profile with the given initial values and owner.\n *\n * The owner (a Group) determines access rights to the Profile.\n *\n * @category Creation\n */\n static override create<M extends CoMap>(\n this: CoValueClass<M>,\n init: Simplify<CoMapInit<M>>,\n options?:\n | {\n owner: Group;\n }\n | Group,\n ) {\n const owner =\n options !== undefined && \"owner\" in options ? options.owner : options;\n\n // We add some guardrails to ensure that the owner of a profile is a group\n if ((owner as Group | Account | undefined)?._type === \"Account\") {\n throw new Error(\"Profiles should be owned by a group\");\n }\n\n return super.create<M>(init, options);\n }\n}\n","import {\n AgentSecret,\n CoID,\n CryptoProvider,\n Everyone,\n InviteSecret,\n LocalNode,\n Peer,\n RawAccount,\n RawCoMap,\n RawCoValue,\n RawControlledAccount,\n Role,\n SessionID,\n cojsonInternals,\n} from \"cojson\";\nimport { activeAccountContext } from \"../implementation/activeAccountContext.js\";\nimport {\n AnonymousJazzAgent,\n type CoValue,\n CoValueBase,\n CoValueClass,\n ID,\n Ref,\n type RefEncoded,\n RefIfCoValue,\n RefsToResolve,\n RefsToResolveStrict,\n Resolved,\n type Schema,\n SchemaInit,\n SubscribeListenerOptions,\n SubscribeRestArgs,\n ensureCoValueLoaded,\n inspect,\n loadCoValue,\n loadCoValueWithoutMe,\n parseSubscribeRestArgs,\n subscribeToCoValueWithoutMe,\n subscribeToExistingCoValue,\n subscriptionsScopes,\n} from \"../internal.js\";\nimport { coValuesCache } from \"../lib/cache.js\";\nimport { RegisteredAccount } from \"../types.js\";\nimport { type CoMap } from \"./coMap.js\";\nimport { type Group } from \"./group.js\";\nimport { createInboxRoot } from \"./inbox.js\";\nimport { Profile } from \"./profile.js\";\nimport { RegisteredSchemas } from \"./registeredSchemas.js\";\n\nexport type AccountCreationProps = {\n name: string;\n onboarding?: boolean;\n};\n\n/** @category Identity & Permissions */\nexport class Account extends CoValueBase implements CoValue {\n declare id: ID<this>;\n declare _type: \"Account\";\n declare _raw: RawAccount | RawControlledAccount;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static _schema: any;\n get _schema(): {\n profile: Schema;\n root: Schema;\n } {\n return (this.constructor as typeof Account)._schema;\n }\n static {\n this._schema = {\n profile: {\n ref: () => Profile,\n optional: false,\n } satisfies RefEncoded<Profile>,\n root: {\n ref: () => RegisteredSchemas[\"CoMap\"],\n optional: true,\n } satisfies RefEncoded<CoMap>,\n };\n }\n\n get _owner(): Account {\n return this as Account;\n }\n get _loadedAs(): Account | AnonymousJazzAgent {\n if (this.isLocalNodeOwner) return this;\n\n const rawAccount = this._raw.core.node.account;\n\n if (rawAccount instanceof RawAccount) {\n return coValuesCache.get(rawAccount, () => Account.fromRaw(rawAccount));\n }\n\n return new AnonymousJazzAgent(this._raw.core.node);\n }\n\n declare profile: Profile | null;\n declare root: CoMap | null;\n\n get _refs(): {\n profile: RefIfCoValue<Profile> | undefined;\n root: RefIfCoValue<CoMap> | undefined;\n } {\n const profileID = this._raw.get(\"profile\") as unknown as\n | ID<NonNullable<this[\"profile\"]>>\n | undefined;\n const rootID = this._raw.get(\"root\") as unknown as\n | ID<NonNullable<this[\"root\"]>>\n | undefined;\n\n return {\n profile:\n profileID &&\n (new Ref(\n profileID,\n this._loadedAs,\n this._schema.profile as RefEncoded<\n NonNullable<this[\"profile\"]> & CoValue\n >,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) as any as RefIfCoValue<this[\"profile\"]>),\n root:\n rootID &&\n (new Ref(\n rootID,\n this._loadedAs,\n this._schema.root as RefEncoded<NonNullable<this[\"root\"]> & CoValue>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) as any as RefIfCoValue<this[\"root\"]>),\n };\n }\n\n /**\n * Whether this account is the currently active account.\n */\n get isMe() {\n return activeAccountContext.get().id === this.id;\n }\n\n /**\n * Whether this account is the owner of the local node.\n */\n isLocalNodeOwner: boolean;\n sessionID: SessionID | undefined;\n\n constructor(options: { fromRaw: RawAccount | RawControlledAccount }) {\n super();\n if (!(\"fromRaw\" in options)) {\n throw new Error(\"Can only construct account from raw or with .create()\");\n }\n this.isLocalNodeOwner =\n options.fromRaw.id == options.fromRaw.core.node.account.id;\n\n Object.defineProperties(this, {\n id: {\n value: options.fromRaw.id,\n enumerable: false,\n },\n _raw: { value: options.fromRaw, enumerable: false },\n _type: { value: \"Account\", enumerable: false },\n });\n\n if (this.isLocalNodeOwner) {\n this.sessionID = options.fromRaw.core.node.currentSessionID;\n }\n\n return new Proxy(this, AccountAndGroupProxyHandler as ProxyHandler<this>);\n }\n\n myRole(): \"admin\" | undefined {\n if (this.isLocalNodeOwner) {\n return \"admin\";\n }\n }\n\n getRoleOf(member: Everyone | ID<Account> | \"me\") {\n if (member === \"me\") {\n return this.isMe ? \"admin\" : undefined;\n }\n\n if (member === this.id) {\n return \"admin\";\n }\n\n return undefined;\n }\n\n getParentGroups(): Array<Group> {\n return [];\n }\n\n get members(): Array<{\n id: ID<RegisteredAccount> | \"everyone\";\n role: Role;\n ref: Ref<RegisteredAccount> | undefined;\n account: RegisteredAccount | null | undefined;\n }> {\n const ref = new Ref<RegisteredAccount>(this.id, this._loadedAs, {\n ref: () => this.constructor as typeof Account,\n optional: false,\n });\n\n return [{ id: this.id, role: \"admin\", ref, account: this }];\n }\n\n canRead(value: CoValue) {\n const role = value._owner.getRoleOf(this.id);\n\n return (\n role === \"admin\" ||\n role === \"writer\" ||\n role === \"reader\" ||\n role === \"writeOnly\"\n );\n }\n\n canWrite(value: CoValue) {\n const role = value._owner.getRoleOf(this.id);\n\n return role === \"admin\" || role === \"writer\" || role === \"writeOnly\";\n }\n\n canAdmin(value: CoValue) {\n return value._owner.getRoleOf(this.id) === \"admin\";\n }\n\n async acceptInvite<V extends CoValue>(\n valueID: ID<V>,\n inviteSecret: InviteSecret,\n coValueClass: CoValueClass<V>,\n ): Promise<Resolved<V, true> | null> {\n if (!this.isLocalNodeOwner) {\n throw new Error(\"Only a controlled account can accept invites\");\n }\n\n await (this._raw as RawControlledAccount).acceptInvite(\n valueID as unknown as CoID<RawCoValue>,\n inviteSecret,\n );\n\n return loadCoValue(coValueClass, valueID, {\n loadAs: this,\n });\n }\n\n /** @private */\n static async create<A extends Account>(\n this: CoValueClass<A> & typeof Account,\n options: {\n creationProps: { name: string };\n initialAgentSecret?: AgentSecret;\n peersToLoadFrom?: Peer[];\n crypto: CryptoProvider;\n },\n ): Promise<A> {\n const { node } = await LocalNode.withNewlyCreatedAccount({\n ...options,\n migration: async (rawAccount, _node, creationProps) => {\n const account = new this({\n fromRaw: rawAccount,\n }) as A;\n\n await account.applyMigration?.(creationProps);\n },\n });\n\n return this.fromNode(node) as A;\n }\n\n static getMe<A extends Account>(this: CoValueClass<A> & typeof Account) {\n return activeAccountContext.get() as A;\n }\n\n static async createAs<A extends Account>(\n this: CoValueClass<A> & typeof Account,\n as: Account,\n options: {\n creationProps: { name: string };\n },\n ) {\n // TODO: is there a cleaner way to do this?\n const connectedPeers = cojsonInternals.connectedPeers(\n \"creatingAccount\",\n \"createdAccount\",\n { peer1role: \"server\", peer2role: \"client\" },\n );\n\n as._raw.core.node.syncManager.addPeer(connectedPeers[1]);\n\n return this.create<A>({\n creationProps: options.creationProps,\n crypto: as._raw.core.node.crypto,\n peersToLoadFrom: [connectedPeers[0]],\n });\n }\n\n static fromNode<A extends Account>(\n this: CoValueClass<A>,\n node: LocalNode,\n ): A {\n return new this({\n fromRaw: node.account as RawControlledAccount,\n }) as A;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(): object | any[] {\n return {\n id: this.id,\n _type: this._type,\n };\n }\n\n [inspect]() {\n return this.toJSON();\n }\n\n async applyMigration(creationProps?: AccountCreationProps) {\n await this.migrate(creationProps);\n\n // if the user has not defined a profile themselves, we create one\n if (this.profile === undefined && creationProps) {\n const profileGroup = RegisteredSchemas[\"Group\"].create({ owner: this });\n\n this.profile = Profile.create({ name: creationProps.name }, profileGroup);\n this.profile._owner.addMember(\"everyone\", \"reader\");\n } else if (this.profile && creationProps) {\n if (this.profile._owner._type !== \"Group\") {\n throw new Error(\"Profile must be owned by a Group\", {\n cause: `The profile of the account \"${this.id}\" was created with an Account as owner, which is not allowed.`,\n });\n }\n }\n\n const node = this._raw.core.node;\n const profile = node\n .expectCoValueLoaded(this._raw.get(\"profile\")!)\n .getCurrentContent() as RawCoMap;\n\n if (!profile.get(\"inbox\")) {\n const inboxRoot = createInboxRoot(this);\n profile.set(\"inbox\", inboxRoot.id);\n profile.set(\"inboxInvite\", inboxRoot.inviteLink);\n }\n }\n\n // Placeholder method for subclasses to override\n migrate(creationProps?: AccountCreationProps) {\n creationProps; // To avoid unused parameter warning\n }\n\n /** @category Subscription & Loading */\n static load<A extends Account, const R extends RefsToResolve<A> = true>(\n this: CoValueClass<A>,\n id: ID<A>,\n options?: {\n resolve?: RefsToResolveStrict<A, R>;\n loadAs?: Account | AnonymousJazzAgent;\n },\n ): Promise<Resolved<A, R> | null> {\n return loadCoValueWithoutMe(this, id, options);\n }\n\n /** @category Subscription & Loading */\n static subscribe<A extends Account, const R extends RefsToResolve<A> = true>(\n this: CoValueClass<A>,\n id: ID<A>,\n listener: (value: Resolved<A, R>, unsubscribe: () => void) => void,\n ): () => void;\n static subscribe<A extends Account, const R extends RefsToResolve<A> = true>(\n this: CoValueClass<A>,\n id: ID<A>,\n options: SubscribeListenerOptions<A, R>,\n listener: (value: Resolved<A, R>, unsubscribe: () => void) => void,\n ): () => void;\n static subscribe<A extends Account, const R extends RefsToResolve<A>>(\n this: CoValueClass<A>,\n id: ID<A>,\n ...args: SubscribeRestArgs<A, R>\n ): () => void {\n const { options, listener } = parseSubscribeRestArgs(args);\n return subscribeToCoValueWithoutMe<A, R>(this, id, options, listener);\n }\n\n /** @category Subscription & Loading */\n ensureLoaded<A extends Account, const R extends RefsToResolve<A>>(\n this: A,\n options: { resolve: RefsToResolveStrict<A, R> },\n ): Promise<Resolved<A, R>> {\n return ensureCoValueLoaded(this, options);\n }\n\n /** @category Subscription & Loading */\n subscribe<A extends Account, const R extends RefsToResolve<A>>(\n this: A,\n listener: (value: Resolved<A, R>, unsubscribe: () => void) => void,\n ): () => void;\n subscribe<A extends Account, const R extends RefsToResolve<A>>(\n this: A,\n options: { resolve?: RefsToResolveStrict<A, R> },\n listener: (value: Resolved<A, R>, unsubscribe: () => void) => void,\n ): () => void;\n subscribe<A extends Account, const R extends RefsToResolve<A>>(\n this: A,\n ...args: SubscribeRestArgs<A, R>\n ): () => void {\n const { options, listener } = parseSubscribeRestArgs(args);\n return subscribeToExistingCoValue(this, options, listener);\n }\n\n /**\n * Wait for the `Account` to be uploaded to the other peers.\n *\n * @category Subscription & Loading\n */\n waitForSync(options?: {\n timeout?: number;\n }) {\n return this._raw.core.waitForSync(options);\n }\n\n /**\n * Wait for all the available `CoValues` to be uploaded to the other peers.\n *\n * @category Subscription & Loading\n */\n waitForAllCoValuesSync(options?: {\n timeout?: number;\n }) {\n return this._raw.core.node.syncManager.waitForAllCoValuesSync(\n options?.timeout,\n );\n }\n}\n\nexport const AccountAndGroupProxyHandler: ProxyHandler<Account | Group> = {\n get(target, key, receiver) {\n if (key === \"profile\") {\n const ref = target._refs.profile;\n return ref\n ? ref.accessFrom(receiver, \"profile\")\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (undefined as any);\n } else if (key === \"root\") {\n const ref = target._refs.root;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return ref ? ref.accessFrom(receiver, \"root\") : (undefined as any);\n } else {\n return Reflect.get(target, key, receiver);\n }\n },\n set(target, key, value, receiver) {\n if (\n (key === \"profile\" || key === \"root\") &&\n typeof value === \"object\" &&\n SchemaInit in value\n ) {\n (target.constructor as typeof CoMap)._schema ||= {};\n (target.constructor as typeof CoMap)._schema[key] = value[SchemaInit];\n return true;\n } else if (key === \"profile\") {\n if (value) {\n target._raw.set(\n \"profile\",\n value.id as unknown as CoID<RawCoMap>,\n \"trusting\",\n );\n }\n subscriptionsScopes\n .get(receiver)\n ?.onRefAccessedOrSet(target.id, value.id);\n return true;\n } else if (key === \"root\") {\n if (value) {\n target._raw.set(\"root\", value.id as unknown as CoID<RawCoMap>);\n }\n subscriptionsScopes\n .get(receiver)\n ?.onRefAccessedOrSet(target.id, value.id);\n return true;\n } else {\n return Reflect.set(target, key, value, receiver);\n }\n },\n defineProperty(target, key, descriptor) {\n if (\n (key === \"profile\" || key === \"root\") &&\n typeof descriptor.value === \"object\" &&\n SchemaInit in descriptor.value\n ) {\n (target.constructor as typeof CoMap)._schema ||= {};\n (target.constructor as typeof CoMap)._schema[key] =\n descriptor.value[SchemaInit];\n return true;\n } else {\n return Reflect.defineProperty(target, key, descriptor);\n }\n },\n};\n\n/** @category Identity & Permissions */\nexport function isControlledAccount(account: Account): account is Account & {\n isLocalNodeOwner: true;\n sessionID: SessionID;\n _raw: RawControlledAccount;\n} {\n return account.isLocalNodeOwner;\n}\n\nexport type AccountClass<Acc extends Account> = CoValueClass<Acc> & {\n fromNode: (typeof Account)[\"fromNode\"];\n};\n\nRegisteredSchemas[\"Account\"] = Account;\n","/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport type {\n AgentID,\n BinaryStreamInfo,\n CojsonInternalTypes,\n JsonValue,\n RawAccountID,\n RawBinaryCoStream,\n RawCoStream,\n SessionID,\n} from \"cojson\";\nimport { MAX_RECOMMENDED_TX_SIZE, cojsonInternals } from \"cojson\";\nimport type {\n AnonymousJazzAgent,\n CoValue,\n CoValueClass,\n ID,\n IfCo,\n RefsToResolve,\n RefsToResolveStrict,\n Resolved,\n Schema,\n SchemaFor,\n SubscribeListenerOptions,\n SubscribeRestArgs,\n UnCo,\n} from \"../internal.js\";\nimport {\n CoValueBase,\n ItemsSym,\n Ref,\n SchemaInit,\n co,\n ensureCoValueLoaded,\n inspect,\n isRefEncoded,\n loadCoValueWithoutMe,\n parseCoValueCreateOptions,\n parseSubscribeRestArgs,\n subscribeToCoValueWithoutMe,\n subscribeToExistingCoValue,\n} from \"../internal.js\";\nimport { RegisteredAccount } from \"../types.js\";\nimport { type Account } from \"./account.js\";\nimport { type Group } from \"./group.js\";\nimport { RegisteredSchemas } from \"./registeredSchemas.js\";\n\n/** @deprecated Use CoFeedEntry instead */\nexport type CoStreamEntry<Item> = CoFeedEntry<Item>;\n\nexport type CoFeedEntry<Item> = SingleCoFeedEntry<Item> & {\n all: IterableIterator<SingleCoFeedEntry<Item>>;\n};\n\n/** @deprecated Use SingleCoFeedEntry instead */\nexport type SingleCoStreamEntry<Item> = SingleCoFeedEntry<Item>;\n\nexport type SingleCoFeedEntry<Item> = {\n value: NonNullable<Item> extends CoValue ? NonNullable<Item> | null : Item;\n ref: NonNullable<Item> extends CoValue ? Ref<NonNullable<Item>> : never;\n by?: RegisteredAccount | null;\n madeAt: Date;\n tx: CojsonInternalTypes.TransactionID;\n};\n\n/** @deprecated Use CoFeed instead */\nexport { CoFeed as CoStream };\n\n/**\n * CoFeeds are collaborative logs of data.\n *\n * @categoryDescription Content\n * They are similar to `CoList`s, but with a few key differences:\n * - They are append-only\n * - They consist of several internal append-only logs, one per account session (tab, device, app instance, etc.)\n * - They expose those as a per-account aggregated view (default) or a precise per-session view\n *\n * ```ts\n * favDog.push(\"Poodle\");\n * favDog.push(\"Schnowzer\");\n * ```\n *\n * @category CoValues\n */\nexport class CoFeed<Item = any> extends CoValueBase implements CoValue {\n /**\n * Declare a `CoFeed` by subclassing `CoFeed.Of(...)` and passing the item schema using a `co` primitive or a `co.ref`.\n *\n * @example\n * ```ts\n * class ColorFeed extends CoFeed.Of(co.string) {}\n * class AnimalFeed extends CoFeed.Of(co.ref(Animal)) {}\n * ```\n *\n * @category Declaration\n */\n static Of<Item>(item: IfCo<Item, Item>): typeof CoFeed<Item> {\n return class CoFeedOf extends CoFeed<Item> {\n [co.items] = item;\n };\n }\n\n /**\n * The ID of this `CoFeed`\n * @category Content */\n declare id: ID<this>;\n /** @category Type Helpers */\n declare _type: \"CoStream\";\n static {\n this.prototype._type = \"CoStream\";\n }\n /** @category Internals */\n declare _raw: RawCoStream;\n\n /** @internal This is only a marker type and doesn't exist at runtime */\n [ItemsSym]!: Item;\n /** @internal */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static _schema: any;\n /** @internal */\n get _schema(): {\n [ItemsSym]: SchemaFor<Item>;\n } {\n return (this.constructor as typeof CoFeed)._schema;\n }\n\n /**\n * The per-account view of this `CoFeed`\n *\n * @example\n * ```ts\n * // Access entries directly by account ID\n * const aliceEntries = feed[aliceAccount.id];\n * console.log(aliceEntries.value); // Latest value from Alice\n *\n * // Iterate through all accounts' entries\n * for (const [accountId, entries] of Object.entries(feed)) {\n * console.log(`Latest entry from ${accountId}:`, entries.value);\n *\n * // Access all entries from this account\n * for (const entry of entries.all) {\n * console.log(`Entry made at ${entry.madeAt}:`, entry.value);\n * }\n * }\n * ```\n *\n * @category Content\n */\n [key: ID<Account>]: CoFeedEntry<Item>;\n\n /**\n * The current account's view of this `CoFeed`\n * @category Content\n */\n get byMe(): CoFeedEntry<Item> | undefined {\n if (this._loadedAs._type === \"Account\") {\n return this[this._loadedAs.id];\n } else {\n return undefined;\n }\n }\n\n /**\n * The per-session view of this `CoFeed`\n * @category Content\n */\n perSession!: {\n [key: SessionID]: CoFeedEntry<Item>;\n };\n\n /**\n * The current session's view of this `CoFeed`\n *\n * This is a shortcut for `this.perSession` where the session ID is the current session ID.\n *\n * @category Content\n */\n get inCurrentSession(): CoFeedEntry<Item> | undefined {\n if (this._loadedAs._type === \"Account\") {\n return this.perSession[this._loadedAs.sessionID!];\n } else {\n return undefined;\n }\n }\n\n constructor(\n options:\n | { init: Item[]; owner: Account | Group }\n | { fromRaw: RawCoStream },\n ) {\n super();\n\n if (options && \"fromRaw\" in options) {\n Object.defineProperties(this, {\n id: {\n value: options.fromRaw.id,\n enumerable: false,\n },\n _raw: { value: options.fromRaw, enumerable: false },\n });\n }\n\n return new Proxy(this, CoStreamProxyHandler as ProxyHandler<this>);\n }\n\n /**\n * Create a new `CoFeed`\n * @category Creation\n */\n static create<S extends CoFeed>(\n this: CoValueClass<S>,\n init: S extends CoFeed<infer Item> ? UnCo<Item>[] : never,\n options?: { owner: Account | Group } | Account | Group,\n ) {\n const { owner } = parseCoValueCreateOptions(options);\n const instance = new this({ init, owner });\n const raw = owner._raw.createStream();\n\n Object.defineProperties(instance, {\n id: {\n value: raw.id,\n enumerable: false,\n },\n _raw: { value: raw, enumerable: false },\n });\n\n if (init) {\n instance.push(...init);\n }\n return instance;\n }\n\n /**\n * Push items to this `CoFeed`\n *\n * Items are appended to the current session's log. Each session (tab, device, app instance)\n * maintains its own append-only log, which is then aggregated into the per-account view.\n *\n * @example\n * ```ts\n * // Adds items to current session's log\n * feed.push(\"item1\", \"item2\");\n *\n * // View items from current session\n * console.log(feed.inCurrentSession);\n *\n * // View aggregated items from all sessions for current account\n * console.log(feed.byMe);\n * ```\n *\n * @category Content\n */\n push(...items: Item[]) {\n for (const item of items) {\n this.pushItem(item);\n }\n }\n\n private pushItem(item: Item) {\n const itemDescriptor = this._schema[ItemsSym] as Schema;\n\n if (itemDescriptor === \"json\") {\n this._raw.push(item as JsonValue);\n } else if (\"encoded\" in itemDescriptor) {\n this._raw.push(itemDescriptor.encoded.encode(item));\n } else if (isRefEncoded(itemDescriptor)) {\n this._raw.push((item as unknown as CoValue).id);\n }\n }\n\n /**\n * Get a JSON representation of the `CoFeed`\n * @category\n */\n toJSON(): {\n id: string;\n _type: \"CoStream\";\n [key: string]: unknown;\n in: { [key: string]: unknown };\n } {\n const itemDescriptor = this._schema[ItemsSym] as Schema;\n const mapper =\n itemDescriptor === \"json\"\n ? (v: unknown) => v\n : \"encoded\" in itemDescriptor\n ? itemDescriptor.encoded.encode\n : (v: unknown) => v && (v as CoValue).id;\n\n return {\n id: this.id,\n _type: this._type,\n ...Object.fromEntries(\n Object.entries(this).map(([account, entry]) => [\n account,\n mapper(entry.value),\n ]),\n ),\n in: Object.fromEntries(\n Object.entries(this.perSession).map(([session, entry]) => [\n session,\n mapper(entry.value),\n ]),\n ),\n };\n }\n\n /** @internal */\n [inspect](): {\n id: string;\n _type: \"CoStream\";\n [key: string]: unknown;\n in: { [key: string]: unknown };\n } {\n return this.toJSON();\n }\n\n /** @internal */\n static schema<V extends CoFeed>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: { new (...args: any): V } & typeof CoFeed,\n def: { [ItemsSym]: V[\"_schema\"][ItemsSym] },\n ) {\n this._schema ||= {};\n Object.assign(this._schema, def);\n }\n\n /**\n * Load a `CoFeed`\n * @category Subscription & Loading\n */\n static load<F extends CoFeed, const R extends RefsToResolve<F> = true>(\n this: CoValueClass<F>,\n id: ID<F>,\n options: {\n resolve?: RefsToResolveStrict<F, R>;\n loadAs?: Account | AnonymousJazzAgent;\n },\n ): Promise<Resolved<F, R> | null> {\n return loadCoValueWithoutMe(this, id, options);\n }\n\n /**\n * Subscribe to a `CoFeed`, when you have an ID but don't have a `CoFeed` instance yet\n * @category Subscription & Loading\n */\n static subscribe<F extends CoFeed, const R extends RefsToResolve<F> = true>(\n this: CoValueClass<F>,\n id: ID<F>,\n listener: (value: Resolved<F, R>, unsubscribe: () => void) => void,\n ): () => void;\n static subscribe<F extends CoFeed, const R extends RefsToResolve<F> = true>(\n this: CoValueClass<F>,\n id: ID<F>,\n options: SubscribeListenerOptions<F, R>,\n listener: (value: Resolved<F, R>, unsubscribe: () => void) => void,\n ): () => void;\n static subscribe<F extends CoFeed, const R extends RefsToResolve<F>>(\n this: CoValueClass<F>,\n id: ID<F>,\n ...args: SubscribeRestArgs<F, R>\n ): () => void {\n const { options, listener } = parseSubscribeRestArgs(args);\n return subscribeToCoValueWithoutMe<F, R>(this, id, options, listener);\n }\n\n /**\n * Ensure a `CoFeed` is loaded to the specified depth\n *\n * @returns A new instance of the same CoFeed that's loaded to the specified depth\n * @category Subscription & Loading\n */\n ensureLoaded<F extends CoFeed, const R extends RefsToResolve<F>>(\n this: F,\n options?: { resolve?: RefsToResolveStrict<F, R> },\n ): Promise<Resolved<F, R>> {\n return ensureCoValueLoaded(this, options);\n }\n\n /**\n * An instance method to subscribe to an existing `CoFeed`\n *\n * No need to provide an ID or Account since they're already part of the instance.\n * @category Subscription & Loading\n */\n subscribe<F extends CoFeed, const R extends RefsToResolve<F>>(\n this: F,\n listener: (value: Resolved<F, R>, unsubscribe: () => void) => void,\n ): () => void;\n subscribe<F extends CoFeed, const R extends RefsToResolve<F>>(\n this: F,\n options: { resolve?: RefsToResolveStrict<F, R> },\n listener: (value: Resolved<F, R>, unsubscribe: () => void) => void,\n ): () => void;\n subscribe<F extends CoFeed, const R extends RefsToResolve<F>>(\n this: F,\n ...args: SubscribeRestArgs<F, R>\n ): () => void {\n const { options, listener } = parseSubscribeRestArgs(args);\n return subscribeToExistingCoValue(this, options, listener);\n }\n\n /**\n * Wait for the `CoFeed` to be uploaded to the other peers.\n *\n * @category Subscription & Loading\n */\n waitForSync(options?: {\n timeout?: number;\n }) {\n return this._raw.core.waitForSync(options);\n }\n}\n\n/**\n * Converts a raw stream entry into a formatted CoFeed entry with proper typing and accessors.\n * @internal\n */\nfunction entryFromRawEntry<Item>(\n accessFrom: CoValue,\n rawEntry: {\n by: RawAccountID | AgentID;\n tx: CojsonInternalTypes.TransactionID;\n at: Date;\n value: JsonValue;\n },\n loadedAs: Account | AnonymousJazzAgent,\n accountID: ID<Account> | undefined,\n itemField: Schema,\n): Omit<CoFeedEntry<Item>, \"all\"> {\n return {\n get value(): NonNullable<Item> extends CoValue\n ? (CoValue & Item) | null\n : Item {\n if (itemField === \"json\") {\n return rawEntry.value as NonNullable<Item> extends CoValue\n ? (CoValue & Item) | null\n : Item;\n } else if (\"encoded\" in itemField) {\n return itemField.encoded.decode(rawEntry.value);\n } else if (isRefEncoded(itemField)) {\n return this.ref?.accessFrom(\n accessFrom,\n rawEntry.by + rawEntry.tx.sessionID + rawEntry.tx.txIndex + \".value\",\n ) as NonNullable<Item> extends CoValue ? (CoValue & Item) | null : Item;\n } else {\n throw new Error(\"Invalid item field schema\");\n }\n },\n get ref(): NonNullable<Item> extends CoValue\n ? Ref<NonNullable<Item>>\n : never {\n if (itemField !== \"json\" && isRefEncoded(itemField)) {\n const rawId = rawEntry.value;\n return new Ref(\n rawId as unknown as ID<CoValue>,\n loadedAs,\n itemField,\n ) as NonNullable<Item> extends CoValue ? Ref<NonNullable<Item>> : never;\n } else {\n return undefined as never;\n }\n },\n get by() {\n return (\n accountID &&\n new Ref<Account>(accountID as unknown as ID<Account>, loadedAs, {\n ref: RegisteredSchemas[\"Account\"],\n optional: false,\n })?.accessFrom(\n accessFrom,\n rawEntry.by + rawEntry.tx.sessionID + rawEntry.tx.txIndex + \".by\",\n )\n );\n },\n madeAt: rawEntry.at,\n tx: rawEntry.tx,\n };\n}\n\n/**\n * The proxy handler for `CoFeed` instances\n * @internal\n */\nexport const CoStreamProxyHandler: ProxyHandler<CoFeed> = {\n get(target, key, receiver) {\n if (typeof key === \"string\" && key.startsWith(\"co_\")) {\n const rawEntry = target._raw.lastItemBy(key as RawAccountID);\n\n if (!rawEntry) return;\n const entry = entryFromRawEntry(\n receiver,\n rawEntry,\n target._loadedAs,\n key as unknown as ID<Account>,\n target._schema[ItemsSym],\n );\n\n Object.defineProperty(entry, \"all\", {\n get: () => {\n const allRawEntries = target._raw.itemsBy(key as RawAccountID);\n return (function* () {\n while (true) {\n const rawEntry = allRawEntries.next();\n if (rawEntry.done) return;\n yield entryFromRawEntry(\n receiver,\n rawEntry.value,\n target._loadedAs,\n key as unknown as ID<Account>,\n target._schema[ItemsSym],\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n })() satisfies IterableIterator<SingleCoFeedEntry<any>>;\n },\n });\n\n return entry;\n } else if (key === \"perSession\") {\n return new Proxy({}, CoStreamPerSessionProxyHandler(target, receiver));\n } else {\n return Reflect.get(target, key, receiver);\n }\n },\n set(target, key, value, receiver) {\n if (key === ItemsSym && typeof value === \"object\" && SchemaInit in value) {\n (target.constructor as typeof CoFeed)._schema ||= {};\n (target.constructor as typeof CoFeed)._schema[ItemsSym] =\n value[SchemaInit];\n return true;\n } else {\n return Reflect.set(target, key, value, receiver);\n }\n },\n defineProperty(target, key, descriptor) {\n if (\n descriptor.value &&\n key === ItemsSym &&\n typeof descriptor.value === \"object\" &&\n SchemaInit in descriptor.value\n ) {\n (target.constructor as typeof CoFeed)._schema ||= {};\n (target.constructor as typeof CoFeed)._schema[ItemsSym] =\n descriptor.value[SchemaInit];\n return true;\n } else {\n return Reflect.defineProperty(target, key, descriptor);\n }\n },\n ownKeys(target) {\n const keys = Reflect.ownKeys(target);\n\n for (const accountID of target._raw.accounts()) {\n keys.push(accountID);\n }\n\n return keys;\n },\n getOwnPropertyDescriptor(target, key) {\n if (typeof key === \"string\" && key.startsWith(\"co_\")) {\n return {\n configurable: true,\n enumerable: true,\n writable: false,\n };\n } else {\n return Reflect.getOwnPropertyDescriptor(target, key);\n }\n },\n};\n\n/**\n * The proxy handler for the per-session view of a `CoFeed`\n * @internal\n */\nconst CoStreamPerSessionProxyHandler = (\n innerTarget: CoFeed,\n accessFrom: CoFeed,\n): ProxyHandler<Record<string, never>> => ({\n get(_target, key, receiver) {\n if (typeof key === \"string\" && key.includes(\"session\")) {\n const sessionID = key as SessionID;\n const rawEntry = innerTarget._raw.lastItemIn(sessionID);\n\n if (!rawEntry) return;\n const by = cojsonInternals.accountOrAgentIDfromSessionID(sessionID);\n\n const entry = entryFromRawEntry(\n accessFrom,\n rawEntry,\n innerTarget._loadedAs,\n cojsonInternals.isAccountID(by)\n ? (by as unknown as ID<Account>)\n : undefined,\n innerTarget._schema[ItemsSym],\n );\n\n Object.defineProperty(entry, \"all\", {\n get: () => {\n const allRawEntries = innerTarget._raw.itemsIn(sessionID);\n return (function* () {\n while (true) {\n const rawEntry = allRawEntries.next();\n if (rawEntry.done) return;\n yield entryFromRawEntry(\n accessFrom,\n rawEntry.value,\n innerTarget._loadedAs,\n cojsonInternals.isAccountID(by)\n ? (by as unknown as ID<Account>)\n : undefined,\n innerTarget._schema[ItemsSym],\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n })() satisfies IterableIterator<SingleCoFeedEntry<any>>;\n },\n });\n\n return entry;\n } else {\n return Reflect.get(innerTarget, key, receiver);\n }\n },\n ownKeys() {\n return innerTarget._raw.sessions();\n },\n getOwnPropertyDescriptor(target, key) {\n if (typeof key === \"string\" && key.startsWith(\"co_\")) {\n return {\n configurable: true,\n enumerable: true,\n writable: false,\n };\n } else {\n return Reflect.getOwnPropertyDescriptor(target, key);\n }\n },\n});\n\n/** @deprecated Use FileStream instead */\nexport { FileStream as BinaryCoStream };\n\n/**\n * FileStreams are `CoFeed`s that contain binary data, collaborative versions of `Blob`s.\n *\n * @categoryDescription Declaration\n * `FileStream` can be referenced in schemas.\n *\n * ```ts\n * import { co, FileStream } from \"jazz-tools\";\n *\n * class MyCoMap extends CoMap {\n * file = co.ref(FileStream);\n * }\n * ```\n *\n * @category CoValues\n */\nexport class FileStream extends CoValueBase implements CoValue {\n /**\n * The ID of this `FileStream`\n * @category Content\n */\n declare id: ID<this>;\n /** @category Type Helpers */\n declare _type: \"BinaryCoStream\";\n /** @internal */\n declare _raw: RawBinaryCoStream;\n\n constructor(\n options:\n | {\n owner: Account | Group;\n }\n | {\n fromRaw: RawBinaryCoStream;\n },\n ) {\n super();\n\n let raw: RawBinaryCoStream;\n\n if (\"fromRaw\" in options) {\n raw = options.fromRaw;\n } else {\n const rawOwner = options.owner._raw;\n raw = rawOwner.createBinaryStream();\n }\n\n Object.defineProperties(this, {\n id: {\n value: raw.id,\n enumerable: false,\n },\n _type: { value: \"BinaryCoStream\", enumerable: false },\n _raw: { value: raw, enumerable: false },\n });\n }\n\n /**\n * Create a new empty `FileStream` instance.\n *\n * @param options - Configuration options for the new FileStream\n * @param options.owner - The Account or Group that will own this FileStream and control access rights\n *\n * @example\n * ```typescript\n * // Create owned by an account\n * const stream = FileStream.create({ owner: myAccount });\n *\n * // Create owned by a group\n * const stream = FileStream.create({ owner: teamGroup });\n *\n * // Create with implicit owner\n * const stream = FileStream.create(myAccount);\n * ```\n *\n * @remarks\n * For uploading an existing file or blob, use {@link FileStream.createFromBlob} instead.\n *\n * @category Creation\n */\n static create<S extends FileStream>(\n this: CoValueClass<S>,\n options?: { owner?: Account | Group } | Account | Group,\n ) {\n return new this(parseCoValueCreateOptions(options));\n }\n\n getChunks(options?: {\n allowUnfinished?: boolean;\n }):\n | (BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean })\n | undefined {\n return this._raw.getBinaryChunks(options?.allowUnfinished);\n }\n\n isBinaryStreamEnded(): boolean {\n return this._raw.isBinaryStreamEnded();\n }\n\n start(options: BinaryStreamInfo): void {\n this._raw.startBinaryStream(options);\n }\n\n push(data: Uint8Array): void {\n this._raw.pushBinaryStreamChunk(data);\n }\n\n end(): void {\n this._raw.endBinaryStream();\n }\n\n toBlob(options?: { allowUnfinished?: boolean }): Blob | undefined {\n const chunks = this.getChunks({\n allowUnfinished: options?.allowUnfinished,\n });\n\n if (!chunks) {\n return undefined;\n }\n\n // @ts-ignore\n return new Blob(chunks.chunks, { type: chunks.mimeType });\n }\n\n /**\n * Load a `FileStream` as a `Blob`\n *\n * @category Content\n */\n static async loadAsBlob(\n id: ID<FileStream>,\n options?: {\n allowUnfinished?: boolean;\n loadAs?: Account | AnonymousJazzAgent;\n },\n ): Promise<Blob | undefined> {\n let stream = await this.load(id, options);\n\n /**\n * If the user hasn't requested an incomplete blob and the\n * stream isn't complete wait for the stream download before progressing\n */\n if (!options?.allowUnfinished && !stream?.isBinaryStreamEnded()) {\n stream = await new Promise<FileStream>((resolve) => {\n subscribeToCoValueWithoutMe(\n this,\n id,\n options || {},\n (value, unsubscribe) => {\n if (value.isBinaryStreamEnded()) {\n unsubscribe();\n resolve(value);\n }\n },\n );\n });\n }\n\n return stream?.toBlob({\n allowUnfinished: options?.allowUnfinished,\n });\n }\n\n /**\n * Create a `FileStream` from a `Blob` or `File`\n *\n * @example\n * ```ts\n * import { co, FileStream } from \"jazz-tools\";\n *\n * const fileStream = await FileStream.createFromBlob(file, {owner: group})\n * ```\n * @category Content\n */\n static async createFromBlob(\n blob: Blob | File,\n options?:\n | {\n owner?: Group | Account;\n onProgress?: (progress: number) => void;\n }\n | Account\n | Group,\n ): Promise<FileStream> {\n const stream = this.create(options);\n const onProgress =\n options && \"onProgress\" in options ? options.onProgress : undefined;\n\n const start = Date.now();\n\n const data = new Uint8Array(await blob.arrayBuffer());\n stream.start({\n mimeType: blob.type,\n totalSizeBytes: blob.size,\n fileName: blob instanceof File ? blob.name : undefined,\n });\n const chunkSize = MAX_RECOMMENDED_TX_SIZE;\n\n let lastProgressUpdate = Date.now();\n\n for (let idx = 0; idx < data.length; idx += chunkSize) {\n stream.push(data.slice(idx, idx + chunkSize));\n\n if (Date.now() - lastProgressUpdate > 100) {\n onProgress?.(idx / data.length);\n lastProgressUpdate = Date.now();\n }\n\n await new Promise((resolve) => setTimeout(resolve, 0));\n }\n stream.end();\n const end = Date.now();\n\n console.debug(\n \"Finished creating binary stream in\",\n (end - start) / 1000,\n \"s - Throughput in MB/s\",\n (1000 * (blob.size / (end - start))) / (1024 * 1024),\n );\n onProgress?.(1);\n\n return stream;\n }\n\n /**\n * Get a JSON representation of the `FileStream`\n * @category Content\n */\n toJSON(): {\n id: string;\n _type: \"BinaryCoStream\";\n mimeType?: string;\n totalSizeBytes?: number;\n fileName?: string;\n chunks?: Uint8Array[];\n finished?: boolean;\n } {\n return {\n id: this.id,\n _type: this._type,\n ...this.getChunks(),\n };\n }\n\n /** @internal */\n [inspect]() {\n return this.toJSON();\n }\n\n /**\n * Load a `FileStream`\n * @category Subscription & Loading\n */\n static load<C extends FileStream>(\n this: CoValueClass<C>,\n id: ID<C>,\n options?: { loadAs?: Account | AnonymousJazzAgent },\n ): Promise<Resolved<C, true> | null> {\n return loadCoValueWithoutMe(this, id, options);\n }\n\n /**\n * Subscribe to a `FileStream`, when you have an ID but don't have a `FileStream` instance yet\n * @category Subscription & Loading\n */\n static subscribe<C extends FileStream>(\n this: CoValueClass<C>,\n id: ID<C>,\n options: { loadAs?: Account | AnonymousJazzAgent },\n listener: (value: Resolved<C, true>) => void,\n ): () => void {\n return subscribeToCoValueWithoutMe<C, true>(this, id, options, listener);\n }\n\n /**\n * An instance method to subscribe to an existing `FileStream`\n * @category Subscription & Loading\n */\n subscribe<B extends FileStream>(\n this: B,\n listener: (value: Resolved<B, true>) => void,\n ): () => void {\n return subscribeToExistingCoValue(this, {}, listener);\n }\n\n /**\n * Wait for the `FileStream` to be uploaded to the other peers.\n *\n * @category Subscription & Loading\n */\n waitForSync(options?: { timeout?: number }) {\n return this._raw.core.waitForSync(options);\n }\n}\n","import type { JsonValue, RawCoList } from \"cojson\";\nimport { RawAccount } from \"cojson\";\nimport { calcPatch } from \"fast-myers-diff\";\nimport type {\n CoValue,\n CoValueClass,\n CoValueFromRaw,\n ID,\n RefEncoded,\n RefsToResolve,\n RefsToResolveStrict,\n Resolved,\n Schema,\n SchemaFor,\n SubscribeListenerOptions,\n SubscribeRestArgs,\n UnCo,\n} from \"../internal.js\";\nimport {\n AnonymousJazzAgent,\n ItemsSym,\n Ref,\n SchemaInit,\n co,\n ensureCoValueLoaded,\n inspect,\n isRefEncoded,\n loadCoValueWithoutMe,\n makeRefs,\n parseCoValueCreateOptions,\n parseSubscribeRestArgs,\n subscribeToCoValueWithoutMe,\n subscribeToExistingCoValue,\n subscriptionsScopes,\n} from \"../internal.js\";\nimport { coValuesCache } from \"../lib/cache.js\";\nimport { RegisteredAccount } from \"../types.js\";\nimport { type Account } from \"./account.js\";\nimport { type Group } from \"./group.js\";\nimport { RegisteredSchemas } from \"./registeredSchemas.js\";\n\n/**\n * CoLists are collaborative versions of plain arrays.\n *\n * @categoryDescription Content\n * You can access items on a `CoList` as if they were normal items on a plain array, using `[]` notation, etc.\n *\n * Since `CoList` is a subclass of `Array`, you can use all the normal array methods like `push`, `pop`, `splice`, etc.\n *\n * ```ts\n * colorList[0];\n * colorList[3] = \"yellow\";\n * colorList.push(\"Kawazaki Green\");\n * colorList.splice(1, 1);\n * ```\n *\n * @category CoValues\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class CoList<Item = any> extends Array<Item> implements CoValue {\n /**\n * Declare a `CoList` by subclassing `CoList.Of(...)` and passing the item schema using `co`.\n *\n * @example\n * ```ts\n * class ColorList extends CoList.Of(\n * co.string\n * ) {}\n * class AnimalList extends CoList.Of(\n * co.ref(Animal)\n * ) {}\n * ```\n *\n * @category Declaration\n */\n static Of<Item>(item: Item): typeof CoList<Item> {\n // TODO: cache superclass for item class\n return class CoListOf extends CoList<Item> {\n [co.items] = item;\n };\n }\n\n /**\n * @ignore\n * @deprecated Use UPPERCASE `CoList.Of` instead! */\n static of(..._args: never): never {\n throw new Error(\"Can't use Array.of with CoLists\");\n }\n\n /**\n * The ID of this `CoList`\n * @category Content */\n declare id: ID<this>;\n /** @category Type Helpers */\n declare _type: \"CoList\";\n static {\n this.prototype._type = \"CoList\";\n }\n /** @category Internals */\n declare _raw: RawCoList;\n /** @category Internals */\n declare _instanceID: string;\n\n /** @internal This is only a marker type and doesn't exist at runtime */\n [ItemsSym]!: Item;\n /** @internal */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static _schema: any;\n /** @internal */\n get _schema(): {\n [ItemsSym]: SchemaFor<Item>;\n } {\n return (this.constructor as typeof CoList)._schema;\n }\n\n /** @category Collaboration */\n get _owner(): Account | Group {\n return this._raw.group instanceof RawAccount\n ? RegisteredSchemas[\"Account\"].fromRaw(this._raw.group)\n : RegisteredSchemas[\"Group\"].fromRaw(this._raw.group);\n }\n\n /**\n * If a `CoList`'s items are a `co.ref(...)`, you can use `coList._refs[i]` to access\n * the `Ref` instead of the potentially loaded/null value.\n *\n * This allows you to always get the ID or load the value manually.\n *\n * @example\n * ```ts\n * animals._refs[0].id; // => ID<Animal>\n * animals._refs[0].value;\n * // => Animal | null\n * const animal = await animals._refs[0].load();\n * ```\n *\n * @category Content\n **/\n get _refs(): {\n [idx: number]: Exclude<Item, null> extends CoValue\n ? Ref<UnCo<Exclude<Item, null>>>\n : never;\n } & {\n length: number;\n [Symbol.iterator](): IterableIterator<\n Exclude<Item, null> extends CoValue ? Ref<Exclude<Item, null>> : never\n >;\n } {\n return makeRefs<number>(\n (idx) => this._raw.get(idx) as unknown as ID<CoValue>,\n () => Array.from({ length: this._raw.entries().length }, (_, idx) => idx),\n this._loadedAs,\n (_idx) => this._schema[ItemsSym] as RefEncoded<CoValue>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) as any;\n }\n\n get _edits(): {\n [idx: number]: {\n value?: Item;\n ref?: Item extends CoValue ? Ref<Item> : never;\n by?: RegisteredAccount;\n madeAt: Date;\n };\n } {\n throw new Error(\"Not implemented\");\n }\n\n get _loadedAs() {\n const rawAccount = this._raw.core.node.account;\n\n if (rawAccount instanceof RawAccount) {\n return coValuesCache.get(rawAccount, () =>\n RegisteredSchemas[\"Account\"].fromRaw(rawAccount),\n );\n }\n\n return new AnonymousJazzAgent(this._raw.core.node);\n }\n\n static get [Symbol.species]() {\n return Array;\n }\n\n constructor(options: { fromRaw: RawCoList } | undefined) {\n super();\n\n Object.defineProperty(this, \"_instanceID\", {\n value: `instance-${Math.random().toString(36).slice(2)}`,\n enumerable: false,\n });\n\n if (options && \"fromRaw\" in options) {\n Object.defineProperties(this, {\n id: {\n value: options.fromRaw.id,\n enumerable: false,\n },\n _raw: { value: options.fromRaw, enumerable: false },\n });\n }\n\n return new Proxy(this, CoListProxyHandler as ProxyHandler<this>);\n }\n\n /**\n * Create a new CoList with the given initial values and owner.\n *\n * The owner (a Group or Account) determines access rights to the CoMap.\n *\n * The CoList will immediately be persisted and synced to connected peers.\n *\n * @example\n * ```ts\n * const colours = ColorList.create(\n * [\"red\", \"green\", \"blue\"],\n * { owner: me }\n * );\n * const animals = AnimalList.create(\n * [cat, dog, fish],\n * { owner: me }\n * );\n * ```\n *\n * @category Creation\n **/\n static create<L extends CoList>(\n this: CoValueClass<L>,\n items: UnCo<L[number]>[],\n options?: { owner: Account | Group } | Account | Group,\n ) {\n const { owner } = parseCoValueCreateOptions(options);\n const instance = new this({ init: items, owner });\n const raw = owner._raw.createList(\n toRawItems(items, instance._schema[ItemsSym]),\n );\n\n Object.defineProperties(instance, {\n id: {\n value: raw.id,\n enumerable: false,\n },\n _raw: { value: raw, enumerable: false },\n });\n\n return instance;\n }\n\n push(...items: Item[]): number {\n this._raw.appendItems(\n toRawItems(items, this._schema[ItemsSym]),\n undefined,\n \"private\",\n );\n\n return this._raw.entries().length;\n }\n\n unshift(...items: Item[]): number {\n for (const item of toRawItems(items as Item[], this._schema[ItemsSym])) {\n this._raw.prepend(item);\n }\n\n return this._raw.entries().length;\n }\n\n pop(): Item | undefined {\n const last = this[this.length - 1];\n\n this._raw.delete(this.length - 1);\n\n return last;\n }\n\n shift(): Item | undefined {\n const first = this[0];\n\n this._raw.delete(0);\n\n return first;\n }\n\n /**\n * Splice the `CoList` at a given index.\n *\n * @param start - The index to start the splice.\n * @param deleteCount - The number of items to delete.\n * @param items - The items to insert.\n */\n splice(start: number, deleteCount: number, ...items: Item[]): Item[] {\n const deleted = this.slice(start, start + deleteCount);\n\n for (\n let idxToDelete = start + deleteCount - 1;\n idxToDelete >= start;\n idxToDelete--\n ) {\n this._raw.delete(idxToDelete);\n }\n\n const rawItems = toRawItems(items as Item[], this._schema[ItemsSym]);\n\n // If there are no items to insert, return the deleted items\n if (rawItems.length === 0) {\n return deleted;\n }\n\n // Fast path for single item insertion\n if (rawItems.length === 1) {\n const item = rawItems[0];\n if (item === undefined) return deleted;\n if (start === 0) {\n this._raw.prepend(item);\n } else {\n this._raw.append(item, Math.max(start - 1, 0));\n }\n return deleted;\n }\n\n // Handle multiple items\n if (start === 0) {\n // Iterate in reverse order without creating a new array\n for (let i = rawItems.length - 1; i >= 0; i--) {\n const item = rawItems[i];\n if (item === undefined) continue;\n this._raw.prepend(item);\n }\n } else {\n let appendAfter = Math.max(start - 1, 0);\n for (const item of rawItems) {\n if (item === undefined) continue;\n this._raw.append(item, appendAfter);\n appendAfter++;\n }\n }\n\n return deleted;\n }\n\n /**\n * Modify the `CoList` to match another list, where the changes are managed internally.\n *\n * @param result - The resolved list of items.\n */\n applyDiff(result: Item[]) {\n const current = this._raw.asArray() as Item[];\n const comparator = isRefEncoded(this._schema[ItemsSym])\n ? (aIdx: number, bIdx: number) => {\n return (\n (current[aIdx] as CoValue)?.id === (result[bIdx] as CoValue)?.id\n );\n }\n : undefined;\n\n const patches = [...calcPatch(current, result, comparator)];\n for (const [from, to, insert] of patches.reverse()) {\n this.splice(from, to - from, ...insert);\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(_key?: string, seenAbove?: ID<CoValue>[]): any[] {\n const itemDescriptor = this._schema[ItemsSym] as Schema;\n if (itemDescriptor === \"json\") {\n return this._raw.asArray();\n } else if (\"encoded\" in itemDescriptor) {\n return this._raw.asArray().map((e) => itemDescriptor.encoded.encode(e));\n } else if (isRefEncoded(itemDescriptor)) {\n return this.map((item, idx) =>\n seenAbove?.includes((item as CoValue)?.id)\n ? { _circular: (item as CoValue).id }\n : (item as unknown as CoValue)?.toJSON(idx + \"\", [\n ...(seenAbove || []),\n this.id,\n ]),\n );\n } else {\n return [];\n }\n }\n\n [inspect]() {\n return this.toJSON();\n }\n\n /** @category Internals */\n static fromRaw<V extends CoList>(\n this: CoValueClass<V> & typeof CoList,\n raw: RawCoList,\n ) {\n return new this({ fromRaw: raw });\n }\n\n /** @internal */\n static schema<V extends CoList>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: { new (...args: any): V } & typeof CoList,\n def: { [ItemsSym]: V[\"_schema\"][ItemsSym] },\n ) {\n this._schema ||= {};\n Object.assign(this._schema, def);\n }\n\n /**\n * Load a `CoList` with a given ID, as a given account.\n *\n * `depth` specifies if item CoValue references should be loaded as well before resolving.\n * The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth.\n *\n * You can pass `[]` or for shallowly loading only this CoList, or `[itemDepth]` for recursively loading referenced CoValues.\n *\n * Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.\n *\n * @example\n * ```ts\n * const animalsWithVets =\n * await ListOfAnimals.load(\n * \"co_zdsMhHtfG6VNKt7RqPUPvUtN2Ax\",\n * me,\n * [{ vet: {} }]\n * );\n * ```\n *\n * @category Subscription & Loading\n */\n static load<L extends CoList, const R extends RefsToResolve<L> = true>(\n this: CoValueClass<L>,\n id: ID<L>,\n options?: {\n resolve?: RefsToResolveStrict<L, R>;\n loadAs?: Account | AnonymousJazzAgent;\n },\n ): Promise<Resolved<L, R> | null> {\n return loadCoValueWithoutMe(this, id, options);\n }\n\n /**\n * Load and subscribe to a `CoList` with a given ID, as a given account.\n *\n * Automatically also subscribes to updates to all referenced/nested CoValues as soon as they are accessed in the listener.\n *\n * `depth` specifies if item CoValue references should be loaded as well before calling `listener` for the first time.\n * The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth.\n *\n * You can pass `[]` or for shallowly loading only this CoList, or `[itemDepth]` for recursively loading referenced CoValues.\n *\n * Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.\n *\n * Returns an unsubscribe function that you should call when you no longer need updates.\n *\n * Also see the `useCoState` hook to reactively subscribe to a CoValue in a React component.\n *\n * @example\n * ```ts\n * const unsub = ListOfAnimals.subscribe(\n * \"co_zdsMhHtfG6VNKt7RqPUPvUtN2Ax\",\n * me,\n * { vet: {} },\n * (animalsWithVets) => console.log(animalsWithVets)\n * );\n * ```\n *\n * @category Subscription & Loading\n */\n static subscribe<L extends CoList, const R extends RefsToResolve<L> = true>(\n this: CoValueClass<L>,\n id: ID<L>,\n listener: (value: Resolved<L, R>, unsubscribe: () => void) => void,\n ): () => void;\n static subscribe<L extends CoList, const R extends RefsToResolve<L> = true>(\n this: CoValueClass<L>,\n id: ID<L>,\n options: SubscribeListenerOptions<L, R>,\n listener: (value: Resolved<L, R>, unsubscribe: () => void) => void,\n ): () => void;\n static subscribe<L extends CoList, const R extends RefsToResolve<L>>(\n this: CoValueClass<L>,\n id: ID<L>,\n ...args: SubscribeRestArgs<L, R>\n ): () => void {\n const { options, listener } = parseSubscribeRestArgs(args);\n return subscribeToCoValueWithoutMe<L, R>(this, id, options, listener);\n }\n\n /**\n * Given an already loaded `CoList`, ensure that items are loaded to the specified depth.\n *\n * Works like `CoList.load()`, but you don't need to pass the ID or the account to load as again.\n *\n * @category Subscription & Loading\n */\n ensureLoaded<L extends CoList, const R extends RefsToResolve<L>>(\n this: L,\n options: { resolve: RefsToResolveStrict<L, R> },\n ): Promise<Resolved<L, R>> {\n return ensureCoValueLoaded(this, options);\n }\n\n /**\n * Given an already loaded `CoList`, subscribe to updates to the `CoList` and ensure that items are loaded to the specified depth.\n *\n * Works like `CoList.subscribe()`, but you don't need to pass the ID or the account to load as again.\n *\n * Returns an unsubscribe function that you should call when you no longer need updates.\n *\n * @category Subscription & Loading\n **/\n subscribe<L extends CoList, const R extends RefsToResolve<L> = true>(\n this: L,\n listener: (value: Resolved<L, R>, unsubscribe: () => void) => void,\n ): () => void;\n subscribe<L extends CoList, const R extends RefsToResolve<L> = true>(\n this: L,\n options: { resolve?: RefsToResolveStrict<L, R> },\n listener: (value: Resolved<L, R>, unsubscribe: () => void) => void,\n ): () => void;\n subscribe<L extends CoList, const R extends RefsToResolve<L>>(\n this: L,\n ...args: SubscribeRestArgs<L, R>\n ): () => void {\n const { options, listener } = parseSubscribeRestArgs(args);\n return subscribeToExistingCoValue(this, options, listener);\n }\n\n /** @category Type Helpers */\n castAs<Cl extends CoValueClass & CoValueFromRaw<CoValue>>(\n cl: Cl,\n ): InstanceType<Cl> {\n const casted = cl.fromRaw(this._raw) as InstanceType<Cl>;\n const subscriptionScope = subscriptionsScopes.get(this);\n if (subscriptionScope) {\n subscriptionsScopes.set(casted, subscriptionScope);\n }\n return casted;\n }\n\n /**\n * Wait for the `CoList` to be uploaded to the other peers.\n *\n * @category Subscription & Loading\n */\n waitForSync(options?: { timeout?: number }) {\n return this._raw.core.waitForSync(options);\n }\n}\n\n/**\n * Convert an array of items to a raw array of items.\n * @param items - The array of items to convert.\n * @param itemDescriptor - The descriptor of the items.\n * @returns The raw array of items.\n */\nfunction toRawItems<Item>(items: Item[], itemDescriptor: Schema) {\n const rawItems =\n itemDescriptor === \"json\"\n ? (items as JsonValue[])\n : \"encoded\" in itemDescriptor\n ? items?.map((e) => itemDescriptor.encoded.encode(e))\n : isRefEncoded(itemDescriptor)\n ? items?.map((v) => (v as unknown as CoValue).id)\n : (() => {\n throw new Error(\"Invalid element descriptor\");\n })();\n return rawItems;\n}\n\nconst CoListProxyHandler: ProxyHandler<CoList> = {\n get(target, key, receiver) {\n if (typeof key === \"string\" && !isNaN(+key)) {\n const itemDescriptor = target._schema[ItemsSym] as Schema;\n const rawValue = target._raw.get(Number(key));\n if (itemDescriptor === \"json\") {\n return rawValue;\n } else if (\"encoded\" in itemDescriptor) {\n return rawValue === undefined\n ? undefined\n : itemDescriptor.encoded.decode(rawValue);\n } else if (isRefEncoded(itemDescriptor)) {\n return rawValue === undefined\n ? undefined\n : new Ref(\n rawValue as unknown as ID<CoValue>,\n target._loadedAs,\n itemDescriptor,\n ).accessFrom(receiver, Number(key));\n }\n } else if (key === \"length\") {\n return target._raw.entries().length;\n } else {\n return Reflect.get(target, key, receiver);\n }\n },\n set(target, key, value, receiver) {\n if (key === ItemsSym && typeof value === \"object\" && SchemaInit in value) {\n (target.constructor as typeof CoList)._schema ||= {};\n (target.constructor as typeof CoList)._schema[ItemsSym] =\n value[SchemaInit];\n return true;\n }\n if (typeof key === \"string\" && !isNaN(+key)) {\n const itemDescriptor = target._schema[ItemsSym] as Schema;\n let rawValue;\n if (itemDescriptor === \"json\") {\n rawValue = value;\n } else if (\"encoded\" in itemDescriptor) {\n rawValue = itemDescriptor.encoded.encode(value);\n } else if (isRefEncoded(itemDescriptor)) {\n if (value === null) {\n if (itemDescriptor.optional) {\n rawValue = null;\n } else {\n throw new Error(`Cannot set required reference ${key} to null`);\n }\n } else if (value?.id) {\n rawValue = value.id;\n } else {\n throw new Error(\n `Cannot set reference ${key} to a non-CoValue. Got ${value}`,\n );\n }\n }\n target._raw.replace(Number(key), rawValue);\n return true;\n } else {\n return Reflect.set(target, key, value, receiver);\n }\n },\n defineProperty(target, key, descriptor) {\n if (\n descriptor.value &&\n key === ItemsSym &&\n typeof descriptor.value === \"object\" &&\n SchemaInit in descriptor.value\n ) {\n (target.constructor as typeof CoList)._schema ||= {};\n (target.constructor as typeof CoList)._schema[ItemsSym] =\n descriptor.value[SchemaInit];\n return true;\n } else {\n return Reflect.defineProperty(target, key, descriptor);\n }\n },\n has(target, key) {\n if (typeof key === \"string\" && !isNaN(+key)) {\n return Number(key) < target._raw.entries().length;\n } else {\n return Reflect.has(target, key);\n }\n },\n};\n","import type {\n AccountRole,\n AgentID,\n Everyone,\n RawAccountID,\n RawGroup,\n Role,\n} from \"cojson\";\nimport { activeAccountContext } from \"../implementation/activeAccountContext.js\";\nimport type {\n CoValue,\n CoValueClass,\n ID,\n RefEncoded,\n RefsToResolve,\n RefsToResolveStrict,\n Resolved,\n Schema,\n SubscribeListenerOptions,\n SubscribeRestArgs,\n} from \"../internal.js\";\nimport {\n CoValueBase,\n Ref,\n co,\n ensureCoValueLoaded,\n loadCoValueWithoutMe,\n parseGroupCreateOptions,\n parseSubscribeRestArgs,\n subscribeToCoValueWithoutMe,\n subscribeToExistingCoValue,\n} from \"../internal.js\";\nimport { RegisteredAccount } from \"../types.js\";\nimport { AccountAndGroupProxyHandler, isControlledAccount } from \"./account.js\";\nimport { type Account } from \"./account.js\";\nimport { type CoMap } from \"./coMap.js\";\nimport { type Profile } from \"./profile.js\";\nimport { RegisteredSchemas } from \"./registeredSchemas.js\";\n\n/** @category Identity & Permissions */\nexport class Group extends CoValueBase implements CoValue {\n declare id: ID<this>;\n declare _type: \"Group\";\n static {\n this.prototype._type = \"Group\";\n }\n declare _raw: RawGroup;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static _schema: any;\n get _schema(): {\n profile: Schema;\n root: Schema;\n } {\n return (this.constructor as typeof Group)._schema;\n }\n static {\n this._schema = {\n profile: \"json\" satisfies Schema,\n root: \"json\" satisfies Schema,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n Object.defineProperty(this.prototype, \"_schema\", {\n get: () => this._schema,\n });\n }\n\n declare profile: Profile | null;\n declare root: CoMap | null;\n\n get _refs(): {\n profile: Ref<Profile> | undefined;\n root: Ref<CoMap> | undefined;\n } {\n const profileID = this._raw.get(\"profile\") as unknown as\n | ID<NonNullable<this[\"profile\"]>>\n | undefined;\n const rootID = this._raw.get(\"root\") as unknown as\n | ID<NonNullable<this[\"root\"]>>\n | undefined;\n return {\n profile:\n profileID &&\n (new Ref(\n profileID,\n this._loadedAs,\n this._schema.profile as RefEncoded<NonNullable<this[\"profile\"]>>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) as any as this[\"profile\"] extends Profile\n ? Ref<this[\"profile\"]>\n : never),\n root:\n rootID &&\n (new Ref(\n rootID,\n this._loadedAs,\n this._schema.root as RefEncoded<NonNullable<this[\"root\"]>>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) as any as this[\"root\"] extends CoMap ? Ref<this[\"root\"]> : never),\n };\n }\n\n /** @deprecated Don't use constructor directly, use .create */\n constructor(options: { fromRaw: RawGroup } | { owner: Account | Group }) {\n super();\n let raw: RawGroup;\n\n if (options && \"fromRaw\" in options) {\n raw = options.fromRaw;\n } else {\n const initOwner = options.owner;\n if (!initOwner) throw new Error(\"No owner provided\");\n if (initOwner._type === \"Account\" && isControlledAccount(initOwner)) {\n const rawOwner = initOwner._raw;\n raw = rawOwner.createGroup();\n } else {\n throw new Error(\"Can only construct group as a controlled account\");\n }\n }\n\n Object.defineProperties(this, {\n id: {\n value: raw.id,\n enumerable: false,\n },\n _raw: { value: raw, enumerable: false },\n });\n\n return new Proxy(this, AccountAndGroupProxyHandler as ProxyHandler<this>);\n }\n\n static create<G extends Group>(\n this: CoValueClass<G>,\n options?: { owner: Account } | Account,\n ) {\n return new this(parseGroupCreateOptions(options));\n }\n\n myRole(): Role | undefined {\n return this._raw.myRole();\n }\n\n addMember(member: Everyone, role: \"writer\" | \"reader\"): void;\n addMember(member: Account, role: AccountRole): void;\n addMember(member: Everyone | Account, role: AccountRole) {\n this._raw.addMember(member === \"everyone\" ? member : member._raw, role);\n }\n\n removeMember(member: Everyone | Account) {\n return this._raw.removeMember(member === \"everyone\" ? member : member._raw);\n }\n\n get members(): Array<{\n id: ID<RegisteredAccount>;\n role: AccountRole;\n ref: Ref<RegisteredAccount>;\n account: RegisteredAccount;\n }> {\n const members = [];\n\n const BaseAccountSchema =\n (activeAccountContext.maybeGet()?.constructor as typeof Account) ||\n RegisteredSchemas[\"Account\"];\n const refEncodedAccountSchema = {\n ref: () => BaseAccountSchema,\n optional: false,\n } satisfies RefEncoded<RegisteredAccount>;\n\n for (const accountID of this._raw.getAllMemberKeysSet()) {\n if (!isAccountID(accountID)) continue;\n\n const role = this._raw.roleOf(accountID);\n\n if (\n role === \"admin\" ||\n role === \"writer\" ||\n role === \"reader\" ||\n role === \"writeOnly\"\n ) {\n const ref = new Ref<RegisteredAccount>(\n accountID as unknown as ID<RegisteredAccount>,\n this._loadedAs,\n refEncodedAccountSchema,\n );\n const accessRef = () => ref.accessFrom(this, \"members.\" + accountID);\n\n if (!ref.syncLoad()) {\n console.warn(\"Account not loaded\", accountID);\n }\n\n members.push({\n id: accountID as unknown as ID<Account>,\n role,\n ref,\n get account() {\n // Accounts values are non-nullable because are loaded as dependencies\n return accessRef() as RegisteredAccount;\n },\n });\n }\n }\n\n return members;\n }\n\n getRoleOf(member: Everyone | ID<Account> | \"me\") {\n if (member === \"me\") {\n return this._raw.roleOf(\n activeAccountContext.get().id as unknown as RawAccountID,\n );\n }\n\n return this._raw.roleOf(\n member === \"everyone\" ? member : (member as unknown as RawAccountID),\n );\n }\n\n getParentGroups(): Array<Group> {\n return this._raw.getParentGroups().map((group) => Group.fromRaw(group));\n }\n\n extend(\n parent: Group,\n roleMapping?: \"reader\" | \"writer\" | \"admin\" | \"inherit\",\n ) {\n this._raw.extend(parent._raw, roleMapping);\n return this;\n }\n\n async revokeExtend(parent: Group) {\n await this._raw.revokeExtend(parent._raw);\n return this;\n }\n\n /** @category Subscription & Loading */\n static load<G extends Group, const R extends RefsToResolve<G>>(\n this: CoValueClass<G>,\n id: ID<G>,\n options?: { resolve?: RefsToResolveStrict<G, R>; loadAs?: Account },\n ): Promise<Resolved<G, R> | null> {\n return loadCoValueWithoutMe(this, id, options);\n }\n\n /** @category Subscription & Loading */\n static subscribe<G extends Group, const R extends RefsToResolve<G>>(\n this: CoValueClass<G>,\n id: ID<G>,\n listener: (value: Resolved<G, R>, unsubscribe: () => void) => void,\n ): () => void;\n static subscribe<G extends Group, const R extends RefsToResolve<G>>(\n this: CoValueClass<G>,\n id: ID<G>,\n options: SubscribeListenerOptions<G, R>,\n listener: (value: Resolved<G, R>, unsubscribe: () => void) => void,\n ): () => void;\n static subscribe<G extends Group, const R extends RefsToResolve<G>>(\n this: CoValueClass<G>,\n id: ID<G>,\n ...args: SubscribeRestArgs<G, R>\n ): () => void {\n const { options, listener } = parseSubscribeRestArgs(args);\n return subscribeToCoValueWithoutMe<G, R>(this, id, options, listener);\n }\n\n /** @category Subscription & Loading */\n ensureLoaded<G extends Group, const R extends RefsToResolve<G>>(\n this: G,\n options?: { resolve?: RefsToResolveStrict<G, R> },\n ): Promise<Resolved<G, R>> {\n return ensureCoValueLoaded(this, options);\n }\n\n /** @category Subscription & Loading */\n subscribe<G extends Group, const R extends RefsToResolve<G>>(\n this: G,\n listener: (value: Resolved<G, R>, unsubscribe: () => void) => void,\n ): () => void;\n subscribe<G extends Group, const R extends RefsToResolve<G>>(\n this: G,\n options: { resolve?: RefsToResolveStrict<G, R> },\n listener: (value: Resolved<G, R>, unsubscribe: () => void) => void,\n ): () => void;\n subscribe<G extends Group, const R extends RefsToResolve<G>>(\n this: G,\n ...args: SubscribeRestArgs<G, R>\n ): () => void {\n const { options, listener } = parseSubscribeRestArgs(args);\n return subscribeToExistingCoValue(this, options, listener);\n }\n\n /**\n * Wait for the `Group` to be uploaded to the other peers.\n *\n * @category Subscription & Loading\n */\n waitForSync(options?: { timeout?: number }) {\n return this._raw.core.waitForSync(options);\n }\n}\n\nRegisteredSchemas[\"Group\"] = Group;\n\nexport function isAccountID(id: RawAccountID | AgentID): id is RawAccountID {\n return id.startsWith(\"co_\");\n}\n","import {\n type OpID,\n RawAccount,\n type RawCoPlainText,\n stringifyOpID,\n} from \"cojson\";\nimport type {\n AnonymousJazzAgent,\n CoValue,\n CoValueClass,\n ID,\n Resolved,\n SubscribeListenerOptions,\n SubscribeRestArgs,\n} from \"../internal.js\";\nimport {\n inspect,\n loadCoValueWithoutMe,\n parseSubscribeRestArgs,\n subscribeToCoValueWithoutMe,\n subscribeToExistingCoValue,\n} from \"../internal.js\";\nimport { Account } from \"./account.js\";\nimport { Group } from \"./group.js\";\n\nexport type TextPos = OpID;\n\nexport class CoPlainText extends String implements CoValue {\n declare id: ID<this>;\n declare _type: \"CoPlainText\";\n declare _raw: RawCoPlainText;\n\n get _owner(): Account | Group {\n return this._raw.group instanceof RawAccount\n ? Account.fromRaw(this._raw.group)\n : Group.fromRaw(this._raw.group);\n }\n\n get _loadedAs() {\n return Account.fromNode(this._raw.core.node);\n }\n\n constructor(\n options:\n | { fromRaw: RawCoPlainText }\n | { text: string; owner: Account | Group },\n ) {\n super();\n\n let raw;\n\n if (\"fromRaw\" in options) {\n raw = options.fromRaw;\n } else {\n raw = options.owner._raw.createPlainText(options.text);\n }\n\n Object.defineProperties(this, {\n id: { value: raw.id, enumerable: false },\n _type: { value: \"CoPlainText\", enumerable: false },\n _raw: { value: raw, enumerable: false },\n });\n }\n\n static create<T extends CoPlainText>(\n this: CoValueClass<T>,\n text: string,\n options: { owner: Account | Group },\n ) {\n return new this({ text, owner: options.owner });\n }\n\n get length() {\n return this._raw.toString().length;\n }\n\n toString() {\n return this._raw.toString();\n }\n\n valueOf() {\n return this._raw.toString();\n }\n\n toJSON(): string {\n return this._raw.toString();\n }\n\n [inspect]() {\n return this.toJSON();\n }\n\n insertAfter(idx: number, text: string) {\n this._raw.insertAfter(idx, text);\n }\n\n deleteRange(range: { from: number; to: number }) {\n this._raw.deleteRange(range);\n }\n\n posBefore(idx: number): TextPos | undefined {\n return this._raw.mapping.opIDbeforeIdx[idx];\n }\n\n posAfter(idx: number): TextPos | undefined {\n return this._raw.mapping.opIDafterIdx[idx];\n }\n\n idxBefore(pos: TextPos): number | undefined {\n return this._raw.mapping.idxBeforeOpID[stringifyOpID(pos)];\n }\n\n idxAfter(pos: TextPos): number | undefined {\n return this._raw.mapping.idxAfterOpID[stringifyOpID(pos)];\n }\n\n static fromRaw<V extends CoPlainText>(\n this: CoValueClass<V> & typeof CoPlainText,\n raw: RawCoPlainText,\n ) {\n return new this({ fromRaw: raw });\n }\n\n /**\n * Load a `CoPlainText` with a given ID, as a given account.\n *\n * @category Subscription & Loading\n */\n static load<T extends CoPlainText>(\n this: CoValueClass<T>,\n id: ID<T>,\n options?: { loadAs?: Account | AnonymousJazzAgent },\n ): Promise<T | null> {\n return loadCoValueWithoutMe(this, id, options);\n }\n\n // /**\n // * Effectful version of `CoMap.load()`.\n // *\n // * Needs to be run inside an `AccountCtx` context.\n // *\n // * @category Subscription & Loading\n // */\n // static loadEf<T extends CoPlainText>(\n // this: CoValueClass<T>,\n // id: ID<T>,\n // ): Effect.Effect<T, UnavailableError, AccountCtx> {\n // return loadCoValueEf(this, id, []);\n // }\n\n /**\n * Load and subscribe to a `CoPlainText` with a given ID, as a given account.\n *\n * Automatically also subscribes to updates to all referenced/nested CoValues as soon as they are accessed in the listener.\n *\n * Check out the `load` methods on `CoMap`/`CoList`/`CoStream`/`Group`/`Account` to see which depth structures are valid to nest.\n *\n * Returns an unsubscribe function that you should call when you no longer need updates.\n *\n * Also see the `useCoState` hook to reactively subscribe to a CoValue in a React component.\n *\n * @category Subscription & Loading\n */\n static subscribe<T extends CoPlainText>(\n this: CoValueClass<T>,\n id: ID<T>,\n listener: (value: Resolved<T, true>, unsubscribe: () => void) => void,\n ): () => void;\n static subscribe<T extends CoPlainText>(\n this: CoValueClass<T>,\n id: ID<T>,\n options: Omit<SubscribeListenerOptions<T, true>, \"resolve\">,\n listener: (value: Resolved<T, true>, unsubscribe: () => void) => void,\n ): () => void;\n static subscribe<T extends CoPlainText>(\n this: CoValueClass<T>,\n id: ID<T>,\n ...args: SubscribeRestArgs<T, true>\n ): () => void {\n const { options, listener } = parseSubscribeRestArgs(args);\n return subscribeToCoValueWithoutMe<T, true>(this, id, options, listener);\n }\n\n /**\n * Given an already loaded `CoPlainText`, subscribe to updates to the `CoPlainText` and ensure that the specified fields are loaded to the specified depth.\n *\n * Works like `CoPlainText.subscribe()`, but you don't need to pass the ID or the account to load as again.\n *\n * Returns an unsubscribe function that you should call when you no longer need updates.\n *\n * @category Subscription & Loading\n **/\n subscribe<T extends CoPlainText>(\n this: T,\n listener: (value: Resolved<T, true>, unsubscribe: () => void) => void,\n ): () => void {\n return subscribeToExistingCoValue(this, {}, listener);\n }\n}\n","import { co } from \"../internal.js\";\nimport type { Account } from \"./account.js\";\nimport { CoList } from \"./coList.js\";\nimport { CoMap, type CoMapInit } from \"./coMap.js\";\nimport { CoPlainText, type TextPos } from \"./coPlainText.js\";\nimport type { Group } from \"./group.js\";\n\n/**\n * Base class for text annotations and formatting marks.\n * Represents a mark with start and end positions in text.\n *\n * Example text: \"Hello world! How are you?\"\n * If we want to mark \"world\" with bold:\n *\n * ```\n * uncertainty region\n * ↓\n * Hello [····]world[····]! How are you?\n * ↑ ↑ ↑ ↑\n * | | | |\n * startAfter | | endBefore\n * startBefore endAfter\n * ```\n *\n * - startAfter: Position after \"Hello \" (exclusive boundary)\n * - startBefore: Position before \"world\" (inclusive boundary)\n * - endAfter: Position after \"world\" (inclusive boundary)\n * - endBefore: Position before \"!\" (exclusive boundary)\n *\n * The regions marked with [····] are \"uncertainty regions\" where:\n * - Text inserted in the left uncertainty region may or may not be part of the mark\n * - Text inserted in the right uncertainty region may or may not be part of the mark\n * - Text inserted between startBefore and endAfter is definitely part of the mark\n *\n * Positions must satisfy:\n * 0 ≤ startAfter ≤ startBefore < endAfter ≤ endBefore ≤ textLength\n * A mark cannot be zero-length, so endAfter must be greater than startBefore.\n */\nexport class Mark extends CoMap {\n startAfter = co.json<TextPos | null>();\n startBefore = co.json<TextPos>();\n endAfter = co.json<TextPos>();\n endBefore = co.json<TextPos | null>();\n tag = co.string;\n\n /**\n * Validates and clamps mark positions to ensure they are in the correct order\n * @returns Normalized positions or null if invalid\n */\n validatePositions(\n textLength: number,\n idxAfter: (pos: TextPos) => number | undefined,\n idxBefore: (pos: TextPos) => number | undefined,\n ) {\n if (!textLength) {\n console.error(\"Cannot validate positions for empty text\");\n return null;\n }\n\n // Get positions with fallbacks\n const positions = {\n startAfter: this.startAfter ? (idxBefore(this.startAfter) ?? 0) : 0,\n startBefore: this.startBefore ? (idxAfter(this.startBefore) ?? 0) : 0,\n endAfter: this.endAfter\n ? (idxBefore(this.endAfter) ?? textLength)\n : textLength,\n endBefore: this.endBefore\n ? (idxAfter(this.endBefore) ?? textLength)\n : textLength,\n };\n\n // Clamp and ensure proper ordering in one step\n return {\n startAfter: Math.max(0, positions.startAfter),\n startBefore: Math.max(positions.startAfter + 1, positions.startBefore),\n endAfter: Math.min(textLength - 1, positions.endAfter),\n endBefore: Math.min(textLength, positions.endBefore),\n };\n }\n}\n\n/**\n * A mark with resolved numeric positions in text.\n * Contains both position information and reference to the source mark.\n * @template R Type extending Mark, defaults to Mark\n */\nexport type ResolvedMark<R extends Mark = Mark> = {\n startAfter: number;\n startBefore: number;\n endAfter: number;\n endBefore: number;\n sourceMark: R;\n};\n\n/**\n * A mark that has been resolved and diffused with certainty information.\n * Includes start/end positions and indication of boundary certainty.\n * @template R Type extending Mark, defaults to Mark\n */\nexport type ResolvedAndDiffusedMark<R extends Mark = Mark> = {\n start: number;\n end: number;\n side: \"uncertainStart\" | \"certainMiddle\" | \"uncertainEnd\";\n sourceMark: R;\n};\n\n/**\n * Defines how marks should be focused when resolving positions.\n * - 'far': Positions marks at furthest valid positions\n * - 'close': Positions marks at nearest valid positions\n * - 'closestWhitespace': Positions marks at nearest whitespace\n */\nexport type FocusBias = \"far\" | \"close\" | \"closestWhitespace\";\n\n/**\n * A mark that has been resolved and focused to specific positions.\n * Contains simplified position information and reference to source mark.\n * @template R Type extending Mark, defaults to Mark\n */\nexport type ResolvedAndFocusedMark<R extends Mark = Mark> = {\n start: number;\n end: number;\n sourceMark: R;\n};\n\n/**\n * Main class for handling rich text content with marks.\n * Combines plain text with a list of marks for formatting and annotations.\n * Provides methods for text manipulation, mark insertion, and tree conversion.\n */\nexport class CoRichText extends CoMap {\n text = co.ref(CoPlainText);\n marks = co.ref(CoList.Of(co.ref(Mark)));\n\n /**\n * Create a CoRichText from plain text.\n */\n static createFromPlainText(\n text: string,\n options: { owner: Account | Group },\n ) {\n return this.create(\n {\n text: CoPlainText.create(text, { owner: options.owner }),\n marks: CoList.Of(co.ref(Mark)).create([], {\n owner: options.owner,\n }),\n },\n { owner: options.owner },\n );\n }\n\n /**\n * Create a CoRichText from plain text and a mark.\n */\n static createFromPlainTextAndMark<\n MarkClass extends {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (...args: any[]): Mark;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n create(init: any, options: { owner: Account | Group }): Mark;\n },\n >(\n text: string,\n WrapIn: MarkClass,\n extraArgs: Omit<\n CoMapInit<InstanceType<MarkClass>>,\n \"startAfter\" | \"startBefore\" | \"endAfter\" | \"endBefore\"\n >,\n options: { owner: Account | Group },\n ) {\n const richtext = this.createFromPlainText(text, options);\n\n richtext.insertMark(0, text.length, WrapIn, extraArgs);\n\n return richtext;\n }\n\n /**\n * Insert text at a specific index.\n */\n insertAfter(idx: number, text: string) {\n if (!this.text)\n throw new Error(\"Cannot insert into a CoRichText without loaded text\");\n this.text.insertAfter(idx, text);\n }\n\n /**\n * Delete a range of text.\n */\n deleteRange(range: { from: number; to: number }) {\n if (!this.text)\n throw new Error(\"Cannot delete from a CoRichText without loaded text\");\n this.text.deleteRange(range);\n }\n\n /**\n * Get the position of a specific index.\n */\n posBefore(idx: number): TextPos | undefined {\n if (!this.text)\n throw new Error(\n \"Cannot get posBefore in a CoRichText without loaded text\",\n );\n return this.text.posBefore(idx);\n }\n\n /**\n * Get the position of a specific index.\n */\n posAfter(idx: number): TextPos | undefined {\n if (!this.text)\n throw new Error(\n \"Cannot get posAfter in a CoRichText without loaded text\",\n );\n return this.text.posAfter(idx);\n }\n\n /**\n * Get the index of a specific position.\n */\n idxBefore(pos: TextPos): number | undefined {\n if (!this.text)\n throw new Error(\n \"Cannot get idxBefore in a CoRichText without loaded text\",\n );\n return this.text.idxBefore(pos);\n }\n\n /**\n * Get the index of a specific position.\n */\n idxAfter(pos: TextPos): number | undefined {\n if (!this.text)\n throw new Error(\n \"Cannot get idxAfter in a CoRichText without loaded text\",\n );\n return this.text.idxAfter(pos);\n }\n\n /**\n * Insert a mark at a specific range.\n */\n insertMark<\n MarkClass extends {\n new (...args: any[]): Mark;\n create(init: any, options: { owner: Account | Group }): Mark;\n },\n >(\n start: number,\n end: number,\n RangeClass: MarkClass,\n extraArgs: Omit<\n CoMapInit<InstanceType<MarkClass>>,\n \"startAfter\" | \"startBefore\" | \"endAfter\" | \"endBefore\"\n >,\n options?: { markOwner?: Account | Group },\n ) {\n if (!this.text || !this.marks) {\n throw new Error(\"Cannot insert a range without loaded ranges\");\n }\n\n const textLength = this.length;\n\n // Clamp positions to text bounds\n start = Math.max(start, 0);\n end = Math.min(end, textLength);\n\n const owner = options?.markOwner || this._owner;\n if (!owner) {\n throw new Error(\"No owner specified for mark\");\n }\n\n const range = RangeClass.create(\n {\n ...extraArgs,\n startAfter: this.posBefore(start),\n startBefore: this.posAfter(start),\n endAfter: this.posBefore(end),\n endBefore: this.posAfter(end),\n },\n { owner },\n );\n\n this.marks.push(range);\n }\n\n /**\n * Remove a mark at a specific range.\n */\n removeMark<\n MarkClass extends {\n new (...args: any[]): Mark;\n create(init: any, options: { owner: Account | Group }): Mark;\n },\n >(\n start: number,\n end: number,\n RangeClass: MarkClass,\n options: { tag: string },\n ) {\n if (!this.marks) {\n throw new Error(\"Cannot remove marks without loaded marks\");\n }\n\n // Find marks of the given class that overlap with the range\n const resolvedMarks = this.resolveMarks();\n\n for (const mark of resolvedMarks) {\n // If mark is outside the range, we'll skip it\n if (mark.endBefore < start || mark.startAfter > end) {\n continue;\n }\n\n // If mark is wrong type, we'll skip it\n if (options.tag && mark.sourceMark.tag !== options.tag) {\n continue;\n }\n\n const markIndex = this.marks.findIndex((m) => m === mark.sourceMark);\n if (markIndex === -1) {\n continue;\n }\n\n // If mark is completely inside the range, we'll remove it\n if (mark.startBefore >= start && mark.endAfter <= end) {\n // Remove the mark\n this.marks.splice(markIndex, 1);\n continue;\n }\n\n // If mark starts before and extends after the removal range, update end positions to start of removal\n if (\n mark.startBefore < start &&\n mark.endAfter >= start &&\n mark.endAfter <= end\n ) {\n const endAfterPos = this.posBefore(start);\n const endBeforePos = this.posBefore(start);\n if (endAfterPos && endBeforePos) {\n mark.sourceMark.endAfter = endAfterPos;\n mark.sourceMark.endBefore = endBeforePos;\n }\n continue;\n }\n\n // If mark starts in removal range and extends beyond it, update start positions to end of removal\n if (\n mark.startBefore >= start &&\n mark.startBefore <= end &&\n mark.endAfter > end\n ) {\n const startAfterPos = this.posAfter(end);\n const startBeforePos = this.posAfter(end);\n if (startAfterPos && startBeforePos) {\n mark.sourceMark.startAfter = startAfterPos;\n mark.sourceMark.startBefore = startBeforePos;\n }\n continue;\n }\n\n // If removal is inside the mark, we'll split the mark\n if (mark.startBefore <= start && mark.endAfter >= end) {\n // Split the mark by shortening it at the start and adding a new mark at the end\n const endAfterPos = this.posBefore(start);\n const endBeforePos = this.posBefore(start);\n if (endAfterPos && endBeforePos) {\n mark.sourceMark.endAfter = endAfterPos;\n mark.sourceMark.endBefore = endBeforePos;\n }\n this.insertMark(\n end + 1,\n mark.endBefore,\n RangeClass,\n // @ts-ignore Some Typescript versions flag this as an error\n {},\n {\n markOwner: mark.sourceMark._owner || this._owner,\n },\n );\n continue;\n }\n }\n }\n\n /**\n * Resolve the positions of all marks.\n */\n resolveMarks(): ResolvedMark[] {\n if (!this.text || !this.marks) {\n throw new Error(\"Cannot resolve ranges without loaded text and ranges\");\n }\n\n const textLength = this.length;\n\n return this.marks.flatMap((mark) => {\n if (!mark) return [];\n\n const positions = mark.validatePositions(\n textLength,\n (pos) => this.idxAfter(pos),\n (pos) => this.idxBefore(pos),\n );\n if (!positions) return [];\n\n return [\n {\n sourceMark: mark,\n ...positions,\n tag: mark.tag,\n },\n ];\n });\n }\n\n /**\n * Resolve and diffuse the positions of all marks.\n */\n resolveAndDiffuseMarks(): ResolvedAndDiffusedMark[] {\n return this.resolveMarks().flatMap((range) => [\n ...(range.startAfter < range.startBefore - 1\n ? [\n {\n start: range.startAfter,\n end: range.startBefore - 1,\n side: \"uncertainStart\" as const,\n sourceMark: range.sourceMark,\n },\n ]\n : []),\n {\n start: range.startBefore - 1,\n end: range.endAfter + 1,\n side: \"certainMiddle\" as const,\n sourceMark: range.sourceMark,\n },\n ...(range.endAfter + 1 < range.endBefore\n ? [\n {\n start: range.endAfter + 1,\n end: range.endBefore,\n side: \"uncertainEnd\" as const,\n sourceMark: range.sourceMark,\n },\n ]\n : []),\n ]);\n }\n\n /**\n * Resolve, diffuse, and focus the positions of all marks.\n */\n resolveAndDiffuseAndFocusMarks(): ResolvedAndFocusedMark[] {\n // for now we only keep the certainMiddle ranges\n return this.resolveAndDiffuseMarks().filter(\n (range) => range.side === \"certainMiddle\",\n );\n }\n\n /**\n * Convert a CoRichText to a tree structure useful for client libraries.\n */\n toTree(tagPrecedence: string[]): TreeNode {\n const ranges = this.resolveAndDiffuseAndFocusMarks();\n\n // Convert a bunch of (potentially overlapping) ranges into a tree\n // - make sure we include all text in leaves, even if it's not covered by a range\n // - we split overlapping ranges in a way where the higher precedence (tag earlier in tagPrecedence)\n // stays intact and the lower precedence tag is split into two ranges, one inside and one outside the higher precedence range\n\n const text = this.text?.toString() || \"\";\n\n let currentNodes: (TreeLeaf | TreeNode)[] = [\n {\n type: \"leaf\",\n start: 0,\n end: text.length,\n },\n ];\n\n const rangesSortedLowToHighPrecedence = ranges.sort((a, b) => {\n const aPrecedence = tagPrecedence.indexOf(a.sourceMark.tag);\n const bPrecedence = tagPrecedence.indexOf(b.sourceMark.tag);\n return bPrecedence - aPrecedence;\n });\n\n // for each range, split the current nodes where necessary (no matter if leaf or already a node), wrapping the resulting \"inside\" parts in a node with the range's tag\n for (const range of rangesSortedLowToHighPrecedence) {\n // console.log(\"currentNodes\", currentNodes);\n const newNodes = currentNodes.flatMap((node) => {\n const [before, inOrAfter] = splitNode(node, range.start);\n const [inside, after] = inOrAfter\n ? splitNode(inOrAfter, range.end)\n : [undefined, undefined];\n\n return [\n ...(before ? [before] : []),\n ...(inside\n ? [\n {\n type: \"node\" as const,\n tag: range.sourceMark.tag,\n start: inside.start,\n end: inside.end,\n children: [inside],\n },\n ]\n : []),\n ...(after ? [after] : []),\n ];\n });\n\n currentNodes = newNodes;\n }\n\n return {\n type: \"node\",\n tag: \"root\",\n start: 0,\n end: text.length,\n children: currentNodes,\n };\n }\n\n get length() {\n return this.text?.toString().length || 0;\n }\n\n /**\n * Convert a CoRichText to plain text.\n */\n toString() {\n if (!this.text) return \"\";\n return this.text.toString();\n }\n}\n\n/**\n * Represents a leaf node in the rich text tree structure.\n * Contains plain text without any marks.\n */\nexport type TreeLeaf = {\n type: \"leaf\";\n start: number;\n end: number;\n};\n\n/**\n * Represents a node in the rich text tree structure.\n * Can contain other nodes or leaves, and includes formatting information.\n */\nexport type TreeNode = {\n type: \"node\";\n tag: string;\n start: number;\n end: number;\n range?: ResolvedAndFocusedMark;\n children: (TreeNode | TreeLeaf)[];\n};\n\n/**\n * Split a node at a specific index. So that the node is split into two parts, one before the index, and one after the index.\n */\nexport function splitNode(\n node: TreeNode | TreeLeaf,\n at: number,\n): [TreeNode | TreeLeaf | undefined, TreeNode | TreeLeaf | undefined] {\n if (node.type === \"leaf\") {\n return [\n at > node.start\n ? {\n type: \"leaf\",\n start: node.start,\n end: Math.min(at, node.end),\n }\n : undefined,\n at < node.end\n ? {\n type: \"leaf\",\n start: Math.max(at, node.start),\n end: node.end,\n }\n : undefined,\n ];\n } else {\n const children = node.children;\n return [\n at > node.start\n ? {\n type: \"node\",\n tag: node.tag,\n start: node.start,\n end: Math.min(at, node.end),\n children: children\n .map((child) => splitNode(child, at)[0])\n .filter((c): c is Exclude<typeof c, undefined> => !!c),\n }\n : undefined,\n at < node.end\n ? {\n type: \"node\",\n tag: node.tag,\n start: Math.max(at, node.start),\n end: node.end,\n children: children\n .map((child) => splitNode(child, at)[1])\n .filter((c): c is Exclude<typeof c, undefined> => !!c),\n }\n : undefined,\n ];\n }\n}\n\n/**\n * Heading mark for rich text formatting.\n */\nexport class Heading extends Mark {\n tag = co.literal(\"heading\");\n level = co.number;\n}\n\n/**\n * Paragraph mark for rich text formatting.\n */\nexport class Paragraph extends Mark {\n tag = co.literal(\"paragraph\");\n}\n\n/**\n * Link mark for rich text formatting.\n */\nexport class Link extends Mark {\n tag = co.literal(\"link\");\n url = co.string;\n}\n\n/**\n * Strong (bold) mark for rich text formatting.\n */\nexport class Strong extends Mark {\n tag = co.literal(\"strong\");\n}\n\n/**\n * Emphasis (italic) mark for rich text formatting.\n */\nexport class Em extends Mark {\n tag = co.literal(\"em\");\n}\n\n/**\n * Collection of predefined mark types for common text formatting.\n * Includes marks for headings, paragraphs, links, and text styling.\n */\nexport const Marks = {\n Heading,\n Paragraph,\n Link,\n Strong,\n Em,\n};\n","import { co, subscriptionsScopes } from \"../../internal.js\";\nimport { FileStream } from \"../coFeed.js\";\nimport { CoMap } from \"../coMap.js\";\n\n/** @category Media */\nexport class ImageDefinition extends CoMap {\n originalSize = co.json<[number, number]>();\n placeholderDataURL? = co.string;\n\n [co.items] = co.ref(FileStream);\n [res: `${number}x${number}`]: co<FileStream | null>;\n\n highestResAvailable(options?: {\n maxWidth?: number;\n targetWidth?: number;\n }): { res: `${number}x${number}`; stream: FileStream } | undefined {\n if (!subscriptionsScopes.get(this)) {\n console.warn(\n \"highestResAvailable() only makes sense when used within a subscription.\",\n );\n }\n\n const resolutions = Object.keys(this).filter((key) =>\n key.match(/^\\d+x\\d+$/),\n ) as `${number}x${number}`[];\n\n let maxWidth = options?.maxWidth;\n\n if (options?.targetWidth) {\n const targetWidth = options.targetWidth;\n const widths = resolutions.map((res) => Number(res.split(\"x\")[0]));\n\n maxWidth = Math.min(...widths.filter((w) => w >= targetWidth));\n }\n\n const validResolutions = resolutions.filter(\n (key) => maxWidth === undefined || Number(key.split(\"x\")[0]) <= maxWidth,\n ) as `${number}x${number}`[];\n\n // Sort the resolutions by width, smallest to largest\n validResolutions.sort((a, b) => {\n const aWidth = Number(a.split(\"x\")[0]);\n const bWidth = Number(b.split(\"x\")[0]);\n return aWidth - bWidth; // Sort smallest to largest\n });\n\n let highestAvailableResolution: `${number}x${number}` | undefined;\n\n for (const resolution of validResolutions) {\n if (this[resolution] && this[resolution]?.getChunks()) {\n highestAvailableResolution = resolution;\n }\n }\n\n // Return the highest complete resolution if we found one\n return (\n highestAvailableResolution && {\n res: highestAvailableResolution,\n stream: this[highestAvailableResolution]!,\n }\n );\n }\n}\n","import {\n CoValue,\n CoValueBase,\n CoValueClass,\n CoValueFromRaw,\n} from \"../internal.js\";\n\n/**\n * SchemaUnion allows you to create union types of CoValues that can be discriminated at runtime.\n *\n * @categoryDescription Declaration\n * Declare your union types by extending `SchemaUnion.Of(...)` and passing a discriminator function that determines which concrete type to use based on the raw data.\n *\n * ```ts\n * import { SchemaUnion, CoMap } from \"jazz-tools\";\n *\n * class BaseWidget extends CoMap {\n * type = co.string;\n * }\n *\n * class ButtonWidget extends BaseWidget {\n * type = co.literal(\"button\");\n * label = co.string;\n * }\n *\n * class SliderWidget extends BaseWidget {\n * type = co.literal(\"slider\");\n * min = co.number;\n * max = co.number;\n * }\n *\n * const WidgetUnion = SchemaUnion.Of<BaseWidget>((raw) => {\n * switch (raw.get(\"type\")) {\n * case \"button\": return ButtonWidget;\n * case \"slider\": return SliderWidget;\n * default: throw new Error(\"Unknown widget type\");\n * }\n * });\n * ```\n *\n * @category CoValues\n */\nexport abstract class SchemaUnion extends CoValueBase implements CoValue {\n /**\n * Create a new union type from a discriminator function.\n *\n * The discriminator function receives the raw data and should return the appropriate concrete class to use for that data.\n *\n * When loading a SchemaUnion, the correct subclass will be instantiated based on the discriminator.\n *\n * @param discriminator - Function that determines which concrete type to use\n * @returns A new class that can create/load instances of the union type\n *\n * @example\n * ```ts\n * const WidgetUnion = SchemaUnion.Of<BaseWidget>((raw) => {\n * switch (raw.get(\"type\")) {\n * case \"button\": return ButtonWidget;\n * case \"slider\": return SliderWidget;\n * default: throw new Error(\"Unknown widget type\");\n * }\n * });\n *\n * const widget = await loadCoValue(WidgetUnion, id, me, {});\n *\n * // You can narrow the returned instance to a subclass by using `instanceof`\n * if (widget instanceof ButtonWidget) {\n * console.log(widget.label);\n * } else if (widget instanceof SliderWidget) {\n * console.log(widget.min, widget.max);\n * }\n * ```\n *\n * @category Declaration\n **/\n static Of<V extends CoValue>(\n discriminator: (raw: V[\"_raw\"]) => CoValueClass<V> & CoValueFromRaw<V>,\n ): CoValueClass<V> & typeof SchemaUnion {\n return class SchemaUnionClass extends SchemaUnion {\n static override fromRaw<T extends CoValue>(\n this: CoValueClass<T> & CoValueFromRaw<T>,\n raw: T[\"_raw\"],\n ): T {\n const ResolvedClass = discriminator(\n raw as V[\"_raw\"],\n ) as unknown as CoValueClass<T> & CoValueFromRaw<T>;\n return ResolvedClass.fromRaw(raw);\n }\n } as unknown as CoValueClass<V> & typeof SchemaUnion;\n }\n\n /**\n * Create an instance from raw data. This is called internally and should not be used directly.\n * Use {@link SchemaUnion.Of} to create a union type instead.\n *\n * @internal\n */\n // @ts-ignore\n static fromRaw<V extends CoValue>(this: CoValueClass<V>, raw: V[\"_raw\"]): V {\n throw new Error(\"Not implemented\");\n }\n}\n","export interface KvStore {\n get(key: string): Promise<string | null>;\n set(key: string, value: string): Promise<void>;\n delete(key: string): Promise<void>;\n clearAll(): Promise<void>;\n}\n\nexport class KvStoreContext {\n private static instance: KvStoreContext;\n private storageInstance: KvStore | null = null;\n\n private constructor() {}\n\n public static getInstance(): KvStoreContext {\n if (!KvStoreContext.instance) {\n KvStoreContext.instance = new KvStoreContext();\n }\n return KvStoreContext.instance;\n }\n\n public isInitialized(): boolean {\n return this.storageInstance !== null;\n }\n\n public initialize(store: KvStore): void {\n if (!this.storageInstance) {\n this.storageInstance = store;\n }\n }\n\n public getStorage(): KvStore {\n if (!this.storageInstance) {\n throw new Error(\"Storage instance is not initialized.\");\n }\n return this.storageInstance;\n }\n}\n\nexport default KvStoreContext;\n","import { AgentSecret } from \"cojson\";\nimport type { Account } from \"../coValues/account.js\";\nimport type { ID } from \"../internal.js\";\nimport { AuthCredentials } from \"../types.js\";\nimport KvStoreContext from \"./KvStoreContext.js\";\n\nconst STORAGE_KEY = \"jazz-logged-in-secret\";\n\nexport type AuthSetPayload = {\n accountID: ID<Account>;\n secretSeed?: Uint8Array;\n accountSecret: AgentSecret;\n provider: \"anonymous\" | \"clerk\" | \"demo\" | \"passkey\" | \"passphrase\" | string;\n};\n\nexport class AuthSecretStorage {\n private listeners: Set<(isAuthenticated: boolean) => void>;\n public isAuthenticated: boolean;\n\n constructor() {\n this.listeners = new Set();\n this.isAuthenticated = false;\n }\n\n async migrate() {\n const kvStore = KvStoreContext.getInstance().getStorage();\n\n if (!(await kvStore.get(STORAGE_KEY))) {\n const demoAuthSecret = await kvStore.get(\"demo-auth-logged-in-secret\");\n if (demoAuthSecret) {\n const parsed = JSON.parse(demoAuthSecret);\n await kvStore.set(\n STORAGE_KEY,\n JSON.stringify({\n accountID: parsed.accountID,\n accountSecret: parsed.accountSecret,\n provider: \"demo\",\n }),\n );\n await kvStore.delete(\"demo-auth-logged-in-secret\");\n }\n\n const clerkAuthSecret = await kvStore.get(\"jazz-clerk-auth\");\n if (clerkAuthSecret) {\n const parsed = JSON.parse(clerkAuthSecret);\n await kvStore.set(\n STORAGE_KEY,\n JSON.stringify({\n accountID: parsed.accountID,\n accountSecret: parsed.secret,\n provider: \"clerk\",\n }),\n );\n await kvStore.delete(\"jazz-clerk-auth\");\n }\n }\n\n const value = await kvStore.get(STORAGE_KEY);\n\n if (value) {\n const parsed = JSON.parse(value);\n\n if (\"secret\" in parsed) {\n await kvStore.set(\n STORAGE_KEY,\n JSON.stringify({\n accountID: parsed.accountID,\n secretSeed: parsed.secretSeed,\n accountSecret: parsed.secret,\n provider: parsed.provider,\n }),\n );\n }\n }\n }\n\n async get(): Promise<AuthCredentials | null> {\n const kvStore = KvStoreContext.getInstance().getStorage();\n const data = await kvStore.get(STORAGE_KEY);\n\n if (!data) return null;\n\n const parsed = JSON.parse(data);\n\n if (!parsed.accountID || !parsed.accountSecret) {\n throw new Error(\"Invalid auth secret storage data\");\n }\n\n return {\n accountID: parsed.accountID,\n secretSeed: parsed.secretSeed\n ? new Uint8Array(parsed.secretSeed)\n : undefined,\n accountSecret: parsed.accountSecret,\n provider: parsed.provider,\n };\n }\n\n async setWithoutNotify(payload: AuthSetPayload) {\n const kvStore = KvStoreContext.getInstance().getStorage();\n await kvStore.set(\n STORAGE_KEY,\n JSON.stringify({\n accountID: payload.accountID,\n secretSeed: payload.secretSeed\n ? Array.from(payload.secretSeed)\n : undefined,\n accountSecret: payload.accountSecret,\n provider: payload.provider,\n }),\n );\n }\n\n async set(payload: AuthSetPayload) {\n this.setWithoutNotify(payload);\n this.emitUpdate(payload);\n }\n\n getIsAuthenticated(data: AuthCredentials | null): boolean {\n if (!data) return false;\n return data.provider !== \"anonymous\";\n }\n\n onUpdate(handler: (isAuthenticated: boolean) => void) {\n this.listeners.add(handler);\n return () => {\n this.listeners.delete(handler);\n };\n }\n\n emitUpdate(data: AuthCredentials | null) {\n const isAuthenticated = this.getIsAuthenticated(data);\n\n if (this.isAuthenticated === isAuthenticated) return;\n\n this.isAuthenticated = isAuthenticated;\n for (const listener of this.listeners) {\n listener(this.isAuthenticated);\n }\n }\n\n async clearWithoutNotify() {\n const kvStore = KvStoreContext.getInstance().getStorage();\n await kvStore.delete(STORAGE_KEY);\n }\n\n async clear() {\n await this.clearWithoutNotify();\n this.emitUpdate(null);\n }\n}\n","import { KvStore } from \"./KvStoreContext.js\";\n\nexport class InMemoryKVStore implements KvStore {\n private store: Record<string, string> = {};\n\n async get(key: string) {\n const data = this.store[key];\n\n if (!data) return null;\n\n return data;\n }\n\n async set(key: string, value: string) {\n this.store[key] = value;\n }\n\n async delete(key: string) {\n delete this.store[key];\n }\n\n async clearAll() {\n this.store = {};\n }\n}\n","import { AgentSecret, LocalNode, cojsonInternals } from \"cojson\";\nimport { AuthSecretStorage } from \"../auth/AuthSecretStorage.js\";\nimport { InMemoryKVStore } from \"../auth/InMemoryKVStore.js\";\nimport { KvStore, KvStoreContext } from \"../auth/KvStoreContext.js\";\nimport { Account } from \"../coValues/account.js\";\nimport { AuthCredentials } from \"../types.js\";\nimport { JazzContextType } from \"../types.js\";\nimport { AnonymousJazzAgent } from \"./anonymousJazzAgent.js\";\n\nexport type JazzContextManagerAuthProps = {\n credentials?: AuthCredentials;\n newAccountProps?: { secret: AgentSecret; creationProps: { name: string } };\n};\n\nexport type JazzContextManagerBaseProps<Acc extends Account> = {\n onAnonymousAccountDiscarded?: (anonymousAccount: Acc) => Promise<void>;\n onLogOut?: () => void | Promise<unknown>;\n};\n\ntype PlatformSpecificAuthContext<Acc extends Account> = {\n me: Acc;\n node: LocalNode;\n logOut: () => Promise<void>;\n done: () => void;\n};\n\ntype PlatformSpecificGuestContext = {\n guest: AnonymousJazzAgent;\n node: LocalNode;\n logOut: () => Promise<void>;\n done: () => void;\n};\n\ntype PlatformSpecificContext<Acc extends Account> =\n | PlatformSpecificAuthContext<Acc>\n | PlatformSpecificGuestContext;\n\nexport class JazzContextManager<\n Acc extends Account,\n P extends JazzContextManagerBaseProps<Acc>,\n> {\n protected value: JazzContextType<Acc> | undefined;\n protected context: PlatformSpecificContext<Acc> | undefined;\n protected props: P | undefined;\n protected authSecretStorage = new AuthSecretStorage();\n protected keepContextOpen = false;\n protected contextPromise: Promise<void> | undefined;\n\n constructor() {\n KvStoreContext.getInstance().initialize(this.getKvStore());\n }\n\n getKvStore(): KvStore {\n return new InMemoryKVStore();\n }\n\n async createContext(props: P, authProps?: JazzContextManagerAuthProps) {\n // We need to store the props here to block the double effect execution\n // on React. Otherwise when calling propsChanged this.props is undefined.\n this.props = props;\n\n // Avoid race condition between the previous context and the new one\n const { promise, resolve } = createResolvablePromise<void>();\n\n const prevPromise = this.contextPromise;\n this.contextPromise = promise;\n\n await prevPromise;\n\n try {\n const result = await this.getNewContext(props, authProps);\n await this.updateContext(props, result, authProps);\n\n resolve();\n } catch (error) {\n resolve();\n throw error;\n }\n }\n\n async getNewContext(\n props: P,\n authProps?: JazzContextManagerAuthProps,\n ): Promise<PlatformSpecificContext<Acc>> {\n props;\n authProps;\n throw new Error(\"Not implemented\");\n }\n\n async updateContext(\n props: P,\n context: PlatformSpecificContext<Acc>,\n authProps?: JazzContextManagerAuthProps,\n ) {\n // When keepContextOpen we don't want to close the previous context\n // because we might need to handle the onAnonymousAccountDiscarded callback\n if (!this.keepContextOpen) {\n this.context?.done();\n }\n\n this.context = context;\n this.props = props;\n this.value = {\n ...context,\n node: context.node,\n authenticate: this.authenticate,\n register: this.register,\n logOut: this.logOut,\n };\n\n if (authProps?.credentials) {\n this.authSecretStorage.emitUpdate(authProps.credentials);\n } else {\n this.authSecretStorage.emitUpdate(await this.authSecretStorage.get());\n }\n\n this.notify();\n }\n\n propsChanged(props: P) {\n props;\n throw new Error(\"Not implemented\");\n }\n\n getCurrentValue() {\n return this.value;\n }\n\n getAuthSecretStorage() {\n return this.authSecretStorage;\n }\n\n logOut = async () => {\n if (!this.context || !this.props) {\n return;\n }\n\n await this.props.onLogOut?.();\n await this.context.logOut();\n return this.createContext(this.props);\n };\n\n done = () => {\n if (!this.context) {\n return;\n }\n\n this.context.done();\n };\n\n shouldMigrateAnonymousAccount = async () => {\n if (!this.props?.onAnonymousAccountDiscarded) {\n return false;\n }\n\n const prevCredentials = await this.authSecretStorage.get();\n const wasAnonymous =\n this.authSecretStorage.getIsAuthenticated(prevCredentials) === false;\n\n return wasAnonymous;\n };\n\n /**\n * Authenticates the user with the given credentials\n */\n authenticate = async (credentials: AuthCredentials) => {\n if (!this.props) {\n throw new Error(\"Props required\");\n }\n\n const prevContext = this.context;\n const migratingAnonymousAccount =\n await this.shouldMigrateAnonymousAccount();\n\n this.keepContextOpen = migratingAnonymousAccount;\n await this.createContext(this.props, { credentials }).finally(() => {\n this.keepContextOpen = false;\n });\n\n if (migratingAnonymousAccount) {\n await this.handleAnonymousAccountMigration(prevContext);\n }\n };\n\n register = async (\n accountSecret: AgentSecret,\n creationProps: { name: string },\n ) => {\n if (!this.props) {\n throw new Error(\"Props required\");\n }\n\n const prevContext = this.context;\n const migratingAnonymousAccount =\n await this.shouldMigrateAnonymousAccount();\n\n this.keepContextOpen = migratingAnonymousAccount;\n await this.createContext(this.props, {\n newAccountProps: {\n secret: accountSecret,\n creationProps,\n },\n }).finally(() => {\n this.keepContextOpen = false;\n });\n\n if (migratingAnonymousAccount) {\n await this.handleAnonymousAccountMigration(prevContext);\n }\n\n if (this.context && \"me\" in this.context) {\n return this.context.me.id;\n }\n\n throw new Error(\"The registration hasn't created a new account\");\n };\n\n private async handleAnonymousAccountMigration(\n prevContext: PlatformSpecificContext<Acc> | undefined,\n ) {\n if (!this.props) {\n throw new Error(\"Props required\");\n }\n\n const currentContext = this.context;\n\n if (\n prevContext &&\n currentContext &&\n \"me\" in prevContext &&\n \"me\" in currentContext\n ) {\n // Using a direct connection to make coValue transfer almost synchronous\n const [prevAccountAsPeer, currentAccountAsPeer] =\n cojsonInternals.connectedPeers(\n prevContext.me.id,\n currentContext.me.id,\n {\n peer1role: \"client\",\n peer2role: \"server\",\n },\n );\n\n prevContext.node.syncManager.addPeer(currentAccountAsPeer);\n currentContext.node.syncManager.addPeer(prevAccountAsPeer);\n\n try {\n await this.props.onAnonymousAccountDiscarded?.(prevContext.me);\n await prevContext.me.waitForAllCoValuesSync();\n } catch (error) {\n console.error(\"Error onAnonymousAccountDiscarded\", error);\n }\n\n prevAccountAsPeer.outgoing.close();\n currentAccountAsPeer.outgoing.close();\n }\n\n prevContext?.done();\n }\n\n listeners = new Set<() => void>();\n subscribe = (callback: () => void) => {\n this.listeners.add(callback);\n\n return () => {\n this.listeners.delete(callback);\n };\n };\n\n notify() {\n for (const listener of this.listeners) {\n listener();\n }\n }\n}\n\nfunction createResolvablePromise<T>() {\n let resolve!: (value: T) => void;\n\n const promise = new Promise<T>((res) => {\n resolve = res;\n });\n\n return { promise, resolve };\n}\n","import { AgentSecret } from \"cojson\";\nimport { Account } from \"../coValues/account.js\";\nimport { ID } from \"../internal.js\";\nimport { AuthenticateAccountFunction } from \"../types.js\";\nimport { AuthSecretStorage } from \"./AuthSecretStorage.js\";\nimport { KvStore, KvStoreContext } from \"./KvStoreContext.js\";\n\ntype StorageData = {\n accountID: ID<Account>;\n accountSecret: AgentSecret;\n secretSeed?: number[];\n};\n\n/**\n * `DemoAuth` provides a `JazzAuth` object for demo authentication.\n *\n * Demo authentication is useful for quickly testing your app, as it allows you to create new accounts and log in as existing ones.\n *\n * ```\n * import { DemoAuth } from \"jazz-tools\";\n *\n * const auth = new DemoAuth(jazzContext.authenticate, new AuthSecretStorage());\n * ```\n *\n * @category Auth Providers\n */\nexport class DemoAuth {\n constructor(\n private authenticate: AuthenticateAccountFunction,\n private authSecretStorage: AuthSecretStorage,\n ) {}\n\n logIn = async (username: string) => {\n const existingUsers = await this.getExisitingUsersWithData();\n const storageData = existingUsers[username];\n\n if (!storageData?.accountID) {\n throw new Error(\"User not found\");\n }\n\n await this.authenticate({\n accountID: storageData.accountID,\n accountSecret: storageData.accountSecret,\n });\n\n await this.authSecretStorage.set({\n accountID: storageData.accountID,\n accountSecret: storageData.accountSecret,\n secretSeed: storageData.secretSeed\n ? new Uint8Array(storageData.secretSeed)\n : undefined,\n provider: \"demo\",\n });\n };\n\n signUp = async (username: string) => {\n const existingUsers = await this.getExistingUsers();\n if (existingUsers.includes(username)) {\n throw new Error(\"User already registered\");\n }\n\n const credentials = await this.authSecretStorage.get();\n\n if (!credentials) {\n throw new Error(\"No credentials found\");\n }\n\n const currentAccount = await Account.getMe().ensureLoaded({\n resolve: {\n profile: true,\n },\n });\n\n currentAccount.profile.name = username;\n\n await this.authSecretStorage.set({\n accountID: credentials.accountID,\n accountSecret: credentials.accountSecret,\n secretSeed: credentials.secretSeed\n ? new Uint8Array(credentials.secretSeed)\n : undefined,\n provider: \"demo\",\n });\n\n await this.addToExistingUsers(username, {\n accountID: credentials.accountID,\n accountSecret: credentials.accountSecret,\n secretSeed: credentials.secretSeed\n ? Array.from(credentials.secretSeed)\n : undefined,\n });\n };\n\n private async addToExistingUsers(username: string, data: StorageData) {\n const existingUsers = await this.getExisitingUsersWithData();\n\n if (existingUsers[username]) {\n return;\n }\n\n existingUsers[username] = data;\n\n const kvStore = KvStoreContext.getInstance().getStorage();\n await kvStore.set(\"demo-auth-users\", JSON.stringify(existingUsers));\n }\n\n private async getExisitingUsersWithData() {\n const kvStore = KvStoreContext.getInstance().getStorage();\n await migrateExistingUsers(kvStore);\n\n const existingUsers = await kvStore.get(\"demo-auth-users\");\n return existingUsers ? JSON.parse(existingUsers) : {};\n }\n\n getExistingUsers = async () => {\n return Object.keys(await this.getExisitingUsersWithData());\n };\n}\n\nexport function encodeUsername(username: string) {\n return btoa(username)\n .replace(/=/g, \"-\")\n .replace(/\\+/g, \"_\")\n .replace(/\\//g, \".\");\n}\n\nasync function getStorageVersion(kvStore: KvStore) {\n try {\n const version = await kvStore.get(\"demo-auth-storage-version\");\n return version ? parseInt(version) : 1;\n } catch (error) {\n return 1;\n }\n}\n\nasync function setStorageVersion(kvStore: KvStore, version: number) {\n await kvStore.set(\"demo-auth-storage-version\", version.toString());\n}\n\nasync function getExistingUsersList(kvStore: KvStore) {\n const existingUsers = await kvStore.get(\"demo-auth-existing-users\");\n return existingUsers ? existingUsers.split(\",\") : [];\n}\n\n/**\n * Migrates existing users keys to work with any storage.\n */\nasync function migrateExistingUsers(kvStore: KvStore) {\n if ((await getStorageVersion(kvStore)) < 2) {\n const existingUsers = await getExistingUsersList(kvStore);\n\n for (const username of existingUsers) {\n const legacyKey = `demo-auth-existing-users-${username}`;\n const storageData = await kvStore.get(legacyKey);\n if (storageData) {\n await kvStore.set(\n `demo-auth-existing-users-${encodeUsername(username)}`,\n storageData,\n );\n await kvStore.delete(legacyKey);\n }\n }\n\n await setStorageVersion(kvStore, 2);\n }\n\n if ((await getStorageVersion(kvStore)) < 3) {\n const existingUsersList = await getExistingUsersList(kvStore);\n\n const existingUsers: Record<string, StorageData> = {};\n const keysToDelete: string[] = [\"demo-auth-existing-users\"];\n\n for (const username of existingUsersList) {\n const key = `demo-auth-existing-users-${encodeUsername(username)}`;\n const storageData = await kvStore.get(key);\n if (storageData) {\n existingUsers[username] = JSON.parse(storageData);\n keysToDelete.push(key);\n }\n }\n\n await kvStore.set(\"demo-auth-users\", JSON.stringify(existingUsers));\n\n for (const key of keysToDelete) {\n await kvStore.delete(key);\n }\n\n await setStorageVersion(kvStore, 3);\n }\n}\n","import * as bip39 from \"@scure/bip39\";\nimport { entropyToMnemonic } from \"@scure/bip39\";\nimport { CryptoProvider, cojsonInternals } from \"cojson\";\nimport { Account } from \"../coValues/account.js\";\nimport type { ID } from \"../internal.js\";\nimport type {\n AuthenticateAccountFunction,\n RegisterAccountFunction,\n} from \"../types.js\";\nimport { AuthSecretStorage } from \"./AuthSecretStorage.js\";\n\n/**\n * `PassphraseAuth` provides a `JazzAuth` object for passphrase authentication.\n *\n * ```ts\n * import { PassphraseAuth } from \"jazz-tools\";\n *\n * const auth = new PassphraseAuth(crypto, jazzContext.authenticate, new AuthSecretStorage(), wordlist);\n * ```\n *\n * @category Auth Providers\n */\nexport class PassphraseAuth {\n passphrase: string = \"\";\n\n constructor(\n private crypto: CryptoProvider,\n private authenticate: AuthenticateAccountFunction,\n private register: RegisterAccountFunction,\n private authSecretStorage: AuthSecretStorage,\n public wordlist: string[],\n ) {}\n\n logIn = async (passphrase: string) => {\n const { crypto, authenticate } = this;\n\n let secretSeed;\n\n try {\n secretSeed = bip39.mnemonicToEntropy(passphrase, this.wordlist);\n } catch (e) {\n throw new Error(\"Invalid passphrase\");\n }\n\n const accountSecret = crypto.agentSecretFromSecretSeed(secretSeed);\n\n const accountID = cojsonInternals.idforHeader(\n cojsonInternals.accountHeaderForInitialAgentSecret(accountSecret, crypto),\n crypto,\n ) as ID<Account>;\n\n await authenticate({\n accountID,\n accountSecret,\n });\n\n await this.authSecretStorage.set({\n accountID,\n secretSeed,\n accountSecret,\n provider: \"passphrase\",\n });\n\n this.passphrase = passphrase;\n this.notify();\n };\n\n signUp = async (name?: string) => {\n const credentials = await this.authSecretStorage.get();\n\n if (!credentials || !credentials.secretSeed) {\n throw new Error(\"No credentials found\");\n }\n\n const passphrase = entropyToMnemonic(credentials.secretSeed, this.wordlist);\n\n await this.authSecretStorage.set({\n accountID: credentials.accountID,\n secretSeed: credentials.secretSeed,\n accountSecret: credentials.accountSecret,\n provider: \"passphrase\",\n });\n\n if (name?.trim()) {\n const currentAccount = await Account.getMe().ensureLoaded({\n resolve: {\n profile: true,\n },\n });\n\n currentAccount.profile.name = name;\n }\n\n return passphrase;\n };\n\n registerNewAccount = async (passphrase: string, name: string) => {\n const secretSeed = bip39.mnemonicToEntropy(passphrase, this.wordlist);\n const accountSecret = this.crypto.agentSecretFromSecretSeed(secretSeed);\n const accountID = await this.register(accountSecret, { name });\n\n await this.authSecretStorage.set({\n accountID,\n secretSeed,\n accountSecret,\n provider: \"passphrase\",\n });\n\n return accountID;\n };\n\n getCurrentAccountPassphrase = async () => {\n const credentials = await this.authSecretStorage.get();\n\n if (!credentials || !credentials.secretSeed) {\n throw new Error(\"No credentials found\");\n }\n\n return entropyToMnemonic(credentials.secretSeed, this.wordlist);\n };\n\n generateRandomPassphrase = () => {\n return entropyToMnemonic(this.crypto.newRandomSecretSeed(), this.wordlist);\n };\n\n loadCurrentAccountPassphrase = async () => {\n const passphrase = await this.getCurrentAccountPassphrase();\n this.passphrase = passphrase;\n this.notify();\n };\n\n listeners = new Set<() => void>();\n subscribe = (callback: () => void) => {\n this.listeners.add(callback);\n\n return () => {\n this.listeners.delete(callback);\n };\n };\n\n notify() {\n for (const listener of this.listeners) {\n listener();\n }\n }\n}\n","import { type InviteSecret, cojsonInternals } from \"cojson\";\nimport { Account } from \"../coValues/account.js\";\nimport type { CoValue, CoValueClass, ID } from \"../internal.js\";\n\n/** @category Invite Links */\nexport function createInviteLink<C extends CoValue>(\n value: C,\n role: \"reader\" | \"writer\" | \"admin\" | \"writeOnly\",\n baseURL: string,\n valueHint?: string,\n): string {\n const coValueCore = value._raw.core;\n let currentCoValue = coValueCore;\n\n while (currentCoValue.header.ruleset.type === \"ownedByGroup\") {\n currentCoValue = currentCoValue.getGroup().core;\n }\n\n const { ruleset, meta } = currentCoValue.header;\n\n if (ruleset.type !== \"group\" || meta?.type === \"account\") {\n throw new Error(\"Can't create invite link for object without group\");\n }\n\n const group = cojsonInternals.expectGroup(currentCoValue.getCurrentContent());\n const inviteSecret = group.createInvite(role);\n\n return `${baseURL}#/invite/${valueHint ? valueHint + \"/\" : \"\"}${\n value.id\n }/${inviteSecret}`;\n}\n\n/** @category Invite Links */\nexport function parseInviteLink<C extends CoValue>(\n inviteURL: string,\n):\n | {\n valueID: ID<C>;\n valueHint?: string;\n inviteSecret: InviteSecret;\n }\n | undefined {\n const url = new URL(inviteURL);\n const parts = url.hash.split(\"/\");\n\n let valueHint: string | undefined;\n let valueID: ID<C> | undefined;\n let inviteSecret: InviteSecret | undefined;\n\n if (parts[0] === \"#\" && parts[1] === \"invite\") {\n if (parts.length === 5) {\n valueHint = parts[2];\n valueID = parts[3] as ID<C>;\n inviteSecret = parts[4] as InviteSecret;\n } else if (parts.length === 4) {\n valueID = parts[2] as ID<C>;\n inviteSecret = parts[3] as InviteSecret;\n }\n\n if (!valueID || !inviteSecret) {\n return undefined;\n }\n return { valueID, inviteSecret, valueHint };\n }\n}\n\n/** @category Invite Links */\nexport function consumeInviteLink<V extends CoValue>({\n inviteURL,\n as = Account.getMe(),\n forValueHint,\n invitedObjectSchema,\n}: {\n inviteURL: string;\n as?: Account;\n forValueHint?: string;\n invitedObjectSchema: CoValueClass<V>;\n}): Promise<\n | {\n valueID: ID<V>;\n valueHint?: string;\n inviteSecret: InviteSecret;\n }\n | undefined\n> {\n return new Promise((resolve, reject) => {\n const result = parseInviteLink<V>(inviteURL);\n\n if (result && result.valueHint === forValueHint) {\n as.acceptInvite(result.valueID, result.inviteSecret, invitedObjectSchema)\n .then(() => {\n resolve(result);\n })\n .catch(reject);\n } else {\n resolve(undefined);\n }\n });\n}\n"],"mappings":";AAEA,IAAM,uBAAN,MAA2B;AAAA,EAA3B;AACE,SAAQ,gBAAgC;AACxC,SAAQ,YAAqB;AAAA;AAAA,EAE7B,IAAI,SAAyB;AAC3B,SAAK,gBAAgB;AACrB,SAAK,YAAY;AAAA,EACnB;AAAA,EAEA,eAAe;AACb,SAAK,gBAAgB;AACrB,SAAK,YAAY;AAAA,EACnB;AAAA,EAEA,WAAW;AACT,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM;AACJ,QAAI,CAAC,KAAK,eAAe;AACvB,UAAI,KAAK,WAAW;AAClB,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAEA,YAAM,IAAI,MAAM,mBAAmB;AAAA,IACrC;AAEA,WAAO,KAAK;AAAA,EACd;AACF;AAIO,IAAM,uBAAuB,IAAI,qBAAqB;;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M,GAAG;AAEhC,MAAI;AACJ,MAAI;AACJ,MAAI;AAEJ,MAAI,MAAM,CAAC,MAAM,OAAO,MAAM,CAAC,MAAM,UAAU;AAC7C,QAAI,MAAM,WAAW,GAAG;AACtB,kBAAY,MAAM,CAAC;AACnB,gBAAU,MAAM,CAAC;AACjB,qBAAe,MAAM,CAAC;AAAA,IACxB,WAAW,MAAM,WAAW,GAAG;AAC7B,gBAAU,MAAM,CAAC;AACjB,qBAAe,MAAM,CAAC;AAAA,IACxB;AAEA,QAAI,CAAC,WAAW,CAAC,cAAc;AAC7B,aAAO;AAAA,IACT;AACA,WAAO,EAAE,SAAS,cAAc,UAAU;AAAA,EAC5C;AACF;AAGO,SAAS,kBAAqC;AAAA,EACnD;AAAA,EACA,KAAK,QAAQ,MAAM;AAAA,EACnB;AAAA,EACA;AACF,GAYE;AACA,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,SAAS,gBAAmB,SAAS;AAE3C,QAAI,UAAU,OAAO,cAAc,cAAc;AAC/C,SAAG,aAAa,OAAO,SAAS,OAAO,cAAc,mBAAmB,EACrE,KAAK,MAAM;AACV,gBAAQ,MAAM;AAAA,MAChB,CAAC,EACA,MAAM,MAAM;AAAA,IACjB,OAAO;AACL,cAAQ,MAAS;AAAA,IACnB;AAAA,EACF,CAAC;AACH;","names":["RawAccount","key","account","creationProps","RawAccount","loadCoValue","ref","subscription","Group","RawAccount","RawAccount","loadCoValue","message","rawEdit","_a","_b","LocalNode","RawAccount","cojsonInternals","RawAccount","ref","loadCoValue","LocalNode","cojsonInternals","cojsonInternals","_a","_b","rawEntry","cojsonInternals","RawAccount","_a","_b","RawAccount","ref","RawAccount","RawAccount","cojsonInternals","cojsonInternals","cojsonInternals","cojsonInternals","cojsonInternals","cojsonInternals"]}
|