diff --git a/api-reference/classes/Change.html b/api-reference/classes/Change.html index e9b31c3e6..c8577ac74 100644 --- a/api-reference/classes/Change.html +++ b/api-reference/classes/Change.html @@ -1,5 +1,5 @@ Change | yorkie-js-sdk

Class Change<P>

Change represents a unit of modification in the document.

-

Type Parameters

Constructors

Type Parameters

Constructors

Properties

Constructors

  • Type Parameters

    Parameters

    • __namedParameters: {
          id: ChangeID;
          message?: string;
          operations?: Operation[];
          presenceChange?: PresenceChange<P>;
      }
      • id: ChangeID
      • Optional message?: string
      • Optional operations?: Operation[]
      • Optional presenceChange?: PresenceChange<P>

    Returns Change<P>

Properties

id: ChangeID
message?: string
operations: Operation[]
presenceChange?: PresenceChange<P>

Methods

  • execute executes the operations of this change to the given root.

    -

    Parameters

    • root: CRDTRoot
    • presences: Map<string, P>
    • source: OpSource

    Returns {
        opInfos: OperationInfo[];
        reverseOps: HistoryOperation<P>[];
    }

  • getMessage returns the message of this change.

    -

    Returns undefined | string

  • getPresenceChange returns the presence change of this change.

    -

    Returns undefined | PresenceChange<P>

  • hasOperations returns whether this change has operations or not.

    -

    Returns boolean

  • hasPresenceChange returns whether this change has presence change or not.

    -

    Returns boolean

  • toTestString returns a string containing the meta data of this change.

    -

    Returns string

  • create creates a new instance of Change.

    -

    Type Parameters

    Parameters

    • __namedParameters: {
          id: ChangeID;
          message?: string;
          operations?: Operation[];
          presenceChange?: PresenceChange<P>;
      }
      • id: ChangeID
      • Optional message?: string
      • Optional operations?: Operation[]
      • Optional presenceChange?: PresenceChange<P>

    Returns Change<P>

\ No newline at end of file +

Constructors

Properties

id: ChangeID
message?: string
operations: Operation[]
presenceChange?: PresenceChange<P>

Methods

\ No newline at end of file diff --git a/api-reference/classes/Client.html b/api-reference/classes/Client.html index 401484b82..b81bf132e 100644 --- a/api-reference/classes/Client.html +++ b/api-reference/classes/Client.html @@ -1,7 +1,7 @@ Client | yorkie-js-sdk

Client is a normal client that can communicate with the server. It has documents and sends changes of the documents in local to the server to synchronize with other replicas in remote.

-

Constructors

Constructors

Properties

Constructors

Properties

apiKey: string
attachmentMap: Map<string, Attachment<unknown, any>>
conditions: Record<ClientCondition, boolean>
id?: string
key: string
processing: boolean = false
reconnectStreamDelay: number
retrySyncLoopDelay: number
rpcClient: PromiseClient<{
    methods: {
        activateClient: {
            I: typeof ActivateClientRequest;
            O: typeof ActivateClientResponse;
            kind: Unary;
            name: "ActivateClient";
        };
        attachDocument: {
            I: typeof AttachDocumentRequest;
            O: typeof AttachDocumentResponse;
            kind: Unary;
            name: "AttachDocument";
        };
        broadcast: {
            I: typeof BroadcastRequest;
            O: typeof BroadcastResponse;
            kind: Unary;
            name: "Broadcast";
        };
        deactivateClient: {
            I: typeof DeactivateClientRequest;
            O: typeof DeactivateClientResponse;
            kind: Unary;
            name: "DeactivateClient";
        };
        detachDocument: {
            I: typeof DetachDocumentRequest;
            O: typeof DetachDocumentResponse;
            kind: Unary;
            name: "DetachDocument";
        };
        pushPullChanges: {
            I: typeof PushPullChangesRequest;
            O: typeof PushPullChangesResponse;
            kind: Unary;
            name: "PushPullChanges";
        };
        removeDocument: {
            I: typeof RemoveDocumentRequest;
            O: typeof RemoveDocumentResponse;
            kind: Unary;
            name: "RemoveDocument";
        };
        watchDocument: {
            I: typeof WatchDocumentRequest;
            O: typeof WatchDocumentResponse;
            kind: ServerStreaming;
            name: "WatchDocument";
        };
    };
    typeName: "yorkie.v1.YorkieService";
}>

Type declaration

  • Readonly methods: {
        activateClient: {
            I: typeof ActivateClientRequest;
            O: typeof ActivateClientResponse;
            kind: Unary;
            name: "ActivateClient";
        };
        attachDocument: {
            I: typeof AttachDocumentRequest;
            O: typeof AttachDocumentResponse;
            kind: Unary;
            name: "AttachDocument";
        };
        broadcast: {
            I: typeof BroadcastRequest;
            O: typeof BroadcastResponse;
            kind: Unary;
            name: "Broadcast";
        };
        deactivateClient: {
            I: typeof DeactivateClientRequest;
            O: typeof DeactivateClientResponse;
            kind: Unary;
            name: "DeactivateClient";
        };
        detachDocument: {
            I: typeof DetachDocumentRequest;
            O: typeof DetachDocumentResponse;
            kind: Unary;
            name: "DetachDocument";
        };
        pushPullChanges: {
            I: typeof PushPullChangesRequest;
            O: typeof PushPullChangesResponse;
            kind: Unary;
            name: "PushPullChanges";
        };
        removeDocument: {
            I: typeof RemoveDocumentRequest;
            O: typeof RemoveDocumentResponse;
            kind: Unary;
            name: "RemoveDocument";
        };
        watchDocument: {
            I: typeof WatchDocumentRequest;
            O: typeof WatchDocumentResponse;
            kind: ServerStreaming;
            name: "WatchDocument";
        };
    }
    • Readonly activateClient: {
          I: typeof ActivateClientRequest;
          O: typeof ActivateClientResponse;
          kind: Unary;
          name: "ActivateClient";
      }

      Generated

      from rpc yorkie.v1.YorkieService.ActivateClient

      +

Returns Client

Properties

apiKey: string
attachmentMap: Map<string, Attachment<unknown, any>>
conditions: Record<ClientCondition, boolean>
id?: string
key: string
processing: boolean = false
reconnectStreamDelay: number
retrySyncLoopDelay: number
rpcClient: PromiseClient<{
    methods: {
        activateClient: {
            I: typeof ActivateClientRequest;
            O: typeof ActivateClientResponse;
            kind: Unary;
            name: "ActivateClient";
        };
        attachDocument: {
            I: typeof AttachDocumentRequest;
            O: typeof AttachDocumentResponse;
            kind: Unary;
            name: "AttachDocument";
        };
        broadcast: {
            I: typeof BroadcastRequest;
            O: typeof BroadcastResponse;
            kind: Unary;
            name: "Broadcast";
        };
        deactivateClient: {
            I: typeof DeactivateClientRequest;
            O: typeof DeactivateClientResponse;
            kind: Unary;
            name: "DeactivateClient";
        };
        detachDocument: {
            I: typeof DetachDocumentRequest;
            O: typeof DetachDocumentResponse;
            kind: Unary;
            name: "DetachDocument";
        };
        pushPullChanges: {
            I: typeof PushPullChangesRequest;
            O: typeof PushPullChangesResponse;
            kind: Unary;
            name: "PushPullChanges";
        };
        removeDocument: {
            I: typeof RemoveDocumentRequest;
            O: typeof RemoveDocumentResponse;
            kind: Unary;
            name: "RemoveDocument";
        };
        watchDocument: {
            I: typeof WatchDocumentRequest;
            O: typeof WatchDocumentResponse;
            kind: ServerStreaming;
            name: "WatchDocument";
        };
    };
    typeName: "yorkie.v1.YorkieService";
}>

Type declaration

  • Readonly methods: {
        activateClient: {
            I: typeof ActivateClientRequest;
            O: typeof ActivateClientResponse;
            kind: Unary;
            name: "ActivateClient";
        };
        attachDocument: {
            I: typeof AttachDocumentRequest;
            O: typeof AttachDocumentResponse;
            kind: Unary;
            name: "AttachDocument";
        };
        broadcast: {
            I: typeof BroadcastRequest;
            O: typeof BroadcastResponse;
            kind: Unary;
            name: "Broadcast";
        };
        deactivateClient: {
            I: typeof DeactivateClientRequest;
            O: typeof DeactivateClientResponse;
            kind: Unary;
            name: "DeactivateClient";
        };
        detachDocument: {
            I: typeof DetachDocumentRequest;
            O: typeof DetachDocumentResponse;
            kind: Unary;
            name: "DetachDocument";
        };
        pushPullChanges: {
            I: typeof PushPullChangesRequest;
            O: typeof PushPullChangesResponse;
            kind: Unary;
            name: "PushPullChanges";
        };
        removeDocument: {
            I: typeof RemoveDocumentRequest;
            O: typeof RemoveDocumentResponse;
            kind: Unary;
            name: "RemoveDocument";
        };
        watchDocument: {
            I: typeof WatchDocumentRequest;
            O: typeof WatchDocumentResponse;
            kind: ServerStreaming;
            name: "WatchDocument";
        };
    }
    • Readonly activateClient: {
          I: typeof ActivateClientRequest;
          O: typeof ActivateClientResponse;
          kind: Unary;
          name: "ActivateClient";
      }

      Generated

      from rpc yorkie.v1.YorkieService.ActivateClient

      • Readonly I: typeof ActivateClientRequest
      • Readonly O: typeof ActivateClientResponse
      • Readonly kind: Unary
      • Readonly name: "ActivateClient"
    • Readonly attachDocument: {
          I: typeof AttachDocumentRequest;
          O: typeof AttachDocumentResponse;
          kind: Unary;
          name: "AttachDocument";
      }

      Generated

      from rpc yorkie.v1.YorkieService.AttachDocument

      • Readonly I: typeof AttachDocumentRequest
      • Readonly O: typeof AttachDocumentResponse
      • Readonly kind: Unary
      • Readonly name: "AttachDocument"
    • Readonly broadcast: {
          I: typeof BroadcastRequest;
          O: typeof BroadcastResponse;
          kind: Unary;
          name: "Broadcast";
      }

      Generated

      from rpc yorkie.v1.YorkieService.Broadcast

      • Readonly I: typeof BroadcastRequest
      • Readonly O: typeof BroadcastResponse
      • Readonly kind: Unary
      • Readonly name: "Broadcast"
    • Readonly deactivateClient: {
          I: typeof DeactivateClientRequest;
          O: typeof DeactivateClientResponse;
          kind: Unary;
          name: "DeactivateClient";
      }

      Generated

      from rpc yorkie.v1.YorkieService.DeactivateClient

      @@ -46,35 +46,35 @@
      • Readonly I: typeof DetachDocumentRequest
      • Readonly O: typeof DetachDocumentResponse
      • Readonly kind: Unary
      • Readonly name: "DetachDocument"
    • Readonly pushPullChanges: {
          I: typeof PushPullChangesRequest;
          O: typeof PushPullChangesResponse;
          kind: Unary;
          name: "PushPullChanges";
      }

      Generated

      from rpc yorkie.v1.YorkieService.PushPullChanges

      • Readonly I: typeof PushPullChangesRequest
      • Readonly O: typeof PushPullChangesResponse
      • Readonly kind: Unary
      • Readonly name: "PushPullChanges"
    • Readonly removeDocument: {
          I: typeof RemoveDocumentRequest;
          O: typeof RemoveDocumentResponse;
          kind: Unary;
          name: "RemoveDocument";
      }

      Generated

      from rpc yorkie.v1.YorkieService.RemoveDocument

      • Readonly I: typeof RemoveDocumentRequest
      • Readonly O: typeof RemoveDocumentResponse
      • Readonly kind: Unary
      • Readonly name: "RemoveDocument"
    • Readonly watchDocument: {
          I: typeof WatchDocumentRequest;
          O: typeof WatchDocumentResponse;
          kind: ServerStreaming;
          name: "WatchDocument";
      }

      Generated

      from rpc yorkie.v1.YorkieService.WatchDocument

      -
      • Readonly I: typeof WatchDocumentRequest
      • Readonly O: typeof WatchDocumentResponse
      • Readonly kind: ServerStreaming
      • Readonly name: "WatchDocument"
  • Readonly typeName: "yorkie.v1.YorkieService"
status: ClientStatus
syncLoopDuration: number
taskQueue: (() => Promise<any>)[]

Type declaration

    • (): Promise<any>
    • Returns Promise<any>

Methods

  • activate activates this client. That is, it registers itself to the server +

    • Readonly I: typeof WatchDocumentRequest
    • Readonly O: typeof WatchDocumentResponse
    • Readonly kind: ServerStreaming
    • Readonly name: "WatchDocument"
  • Readonly typeName: "yorkie.v1.YorkieService"
  • status: ClientStatus
    syncLoopDuration: number
    taskQueue: (() => Promise<any>)[]

    Type declaration

      • (): Promise<any>
      • Returns Promise<any>

    Methods

    • activate activates this client. That is, it registers itself to the server and receives a unique ID from the server. The given ID is used to distinguish different clients.

      -

      Returns Promise<void>

    • attach attaches the given document to this client. It tells the server that +

      Returns Promise<void>

    • attach attaches the given document to this client. It tells the server that this client will synchronize the given document.

      -

      Type Parameters

      Parameters

      • doc: Document<T, P>
      • options: {
            initialPresence?: P;
            initialRoot?: T;
            syncMode?: SyncMode;
        } = {}
        • Optional initialPresence?: P
        • Optional initialRoot?: T
        • Optional syncMode?: SyncMode

      Returns Promise<Document<T, P>>

    • broadcast broadcasts the given payload to the given topic.

      -

      Parameters

      • docKey: string
      • topic: string
      • payload: Json
      • Optional options: BroadcastOptions

      Returns Promise<void>

    • deactivate deactivates this client.

      -

      Returns Promise<void>

    • detach detaches the given document from this client. It tells the +

      Type Parameters

      Parameters

      • doc: Document<T, P>
      • options: {
            initialPresence?: P;
            initialRoot?: T;
            syncMode?: SyncMode;
        } = {}
        • Optional initialPresence?: P
        • Optional initialRoot?: T
        • Optional syncMode?: SyncMode

      Returns Promise<Document<T, P>>

    • broadcast broadcasts the given payload to the given topic.

      +

      Parameters

      • docKey: string
      • topic: string
      • payload: Json
      • Optional options: BroadcastOptions

      Returns Promise<void>

    • deactivate deactivates this client.

      +

      Returns Promise<void>

    • detach detaches the given document from this client. It tells the server that this client will no longer synchronize the given document.

      To collect garbage things like CRDT tombstones left on the document, all the changes should be applied to other replicas before GC time. For this, if the document is no longer used by this client, it should be detached.

      -

      Type Parameters

      Parameters

      • doc: Document<T, P>
      • options: {
            removeIfNotAttached?: boolean;
        } = {}
        • Optional removeIfNotAttached?: boolean

      Returns Promise<Document<T, P>>

    • enqueueTask enqueues the given task to the task queue.

      -

      Parameters

      • task: (() => Promise<any>)
          • (): Promise<any>
          • Returns Promise<any>

      Returns Promise<any>

    • getID returns a ActorID of client.

      -

      Returns undefined | string

    • handleConnectError handles the given error. If the given error can be +

      Type Parameters

      Parameters

      • doc: Document<T, P>
      • options: {
            removeIfNotAttached?: boolean;
        } = {}
        • Optional removeIfNotAttached?: boolean

      Returns Promise<Document<T, P>>

    • enqueueTask enqueues the given task to the task queue.

      +

      Parameters

      • task: (() => Promise<any>)
          • (): Promise<any>
          • Returns Promise<any>

      Returns Promise<any>

    • getID returns a ActorID of client.

      +

      Returns undefined | string

    • handleConnectError handles the given error. If the given error can be retried after handling, it returns true.

      -

      Parameters

      • err: any

      Returns boolean

    • Type Parameters

      Parameters

      • attachment: Attachment<T, P>
      • resp: WatchDocumentResponse

      Returns void

    • isActive checks if the client is active.

      -

      Returns boolean

    • processNext processes the next task in the task queue. This method is +

      Parameters

      • err: any

      Returns boolean

    • Type Parameters

      Parameters

      • attachment: Attachment<T, P>
      • resp: WatchDocumentResponse

      Returns void

    • isActive checks if the client is active.

      +

      Returns boolean

    • processNext processes the next task in the task queue. This method is part of enqueueTask.

      -

      Returns Promise<void>

    • runSyncLoop runs the sync loop. The sync loop pushes local changes to +

      Returns Promise<void>

    • runSyncLoop runs the sync loop. The sync loop pushes local changes to the server and pulls remote changes from the server.

      -

      Returns void

    • runWatchLoop runs the watch loop for the given document. The watch loop +

      Returns void

    • runWatchLoop runs the watch loop for the given document. The watch loop listens to the events of the given document from the server.

      -

      Parameters

      • docKey: string

      Returns Promise<void>

    • sync pushes local changes of the attached documents to the server and +

      Parameters

      • docKey: string

      Returns Promise<void>

    • sync pushes local changes of the attached documents to the server and receives changes of the remote replica from the server then apply them to local documents.

      -

      Type Parameters

      Parameters

      Returns Promise<Document<T, P>[]>

    \ No newline at end of file +

    Type Parameters

    Parameters

    Returns Promise<Document<T, P>[]>

    \ No newline at end of file diff --git a/api-reference/classes/Counter.html b/api-reference/classes/Counter.html index 46b3bbb4e..477869c5d 100644 --- a/api-reference/classes/Counter.html +++ b/api-reference/classes/Counter.html @@ -1,5 +1,5 @@ Counter | yorkie-js-sdk

    Counter is a custom data type that is used to counter.

    -

    Constructors

    Constructors

    Properties

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    counter?: CRDTCounter
    value: number | Long
    valueType: CounterType

    Methods

    • Internal

      getValue returns the value of this counter;

      -

      Returns number | Long

    • getValueType returns the value type of this counter.

      -

      Returns CounterType

    • Internal

      initialize initialize this text with context and internal text.

      -

      Parameters

      • context: ChangeContext<Indexable>
      • counter: CRDTCounter

      Returns void

    \ No newline at end of file +

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    counter?: CRDTCounter
    value: number | Long
    valueType: CounterType

    Methods

    \ No newline at end of file diff --git a/api-reference/classes/Document.html b/api-reference/classes/Document.html index 8b80840e2..b61a10cf9 100644 --- a/api-reference/classes/Document.html +++ b/api-reference/classes/Document.html @@ -1,6 +1,6 @@ Document | yorkie-js-sdk

    Class Document<T, P>

    Document is a CRDT-based data type. We can represent the model of the application and edit it even while offline.

    -

    Type Parameters

    Constructors

    Type Parameters

    Constructors

    Properties

    Constructors

    Properties

    changeID: ChangeID
    checkpoint: Checkpoint
    clone?: {
        presences: Map<string, P>;
        root: CRDTRoot;
    }

    Type declaration

    • presences: Map<string, P>
    • root: CRDTRoot
    eventStreamObserver: Observer<TransactionEvent<P>>
    history: {
        canRedo: (() => boolean);
        canUndo: (() => boolean);
        redo: (() => void);
        undo: (() => void);
    }

    history is exposed to the user to manage undo/redo operations.

    +

    Constructors

    Properties

    changeID: ChangeID
    checkpoint: Checkpoint
    clone?: {
        presences: Map<string, P>;
        root: CRDTRoot;
    }

    Type declaration

    • presences: Map<string, P>
    • root: CRDTRoot
    eventStreamObserver: Observer<TransactionEvent<P>>
    history: {
        canRedo: (() => boolean);
        canUndo: (() => boolean);
        redo: (() => void);
        undo: (() => void);
    }

    history is exposed to the user to manage undo/redo operations.

    Type declaration

    • canRedo: (() => boolean)
        • (): boolean
        • canRedo returns whether there are any operations to redo.

          Returns boolean

    • canUndo: (() => boolean)
        • (): boolean
        • canUndo returns whether there are any operations to undo.

          Returns boolean

    • redo: (() => void)
        • (): void
        • redo redoes the last operation executed by the current client. It does not impact operations made by other clients.

          Returns void

    • undo: (() => void)
        • (): void
        • undo undoes the last operation executed by the current client. It does not impact operations made by other clients.

          -

          Returns void

    internalHistory: History<P>

    internalHistory is used to manage undo/redo operations internally.

    -
    isUpdating: boolean

    isUpdating is whether the document is updating by updater or not. It is +

    Returns void

    internalHistory: History<P>

    internalHistory is used to manage undo/redo operations internally.

    +
    isUpdating: boolean

    isUpdating is whether the document is updating by updater or not. It is used to prevent the updater from calling undo/redo.

    -
    key: string
    localChanges: Change<P>[]
    onlineClients: Set<string>

    onlineClients is a set of client IDs that are currently online.

    -
    opts: DocumentOptions
    presences: Map<string, P>

    presences is a map of client IDs to their presence information.

    -
    root: CRDTRoot

    Methods

    • Internal

      addOnlineClient adds the given clientID into the online client set.

      -

      Parameters

      • clientID: string

      Returns void

    • Internal

      applyChangePack applies the given change pack into this document.

      +
    key: string
    localChanges: Change<P>[]
    onlineClients: Set<string>

    onlineClients is a set of client IDs that are currently online.

    +
    opts: DocumentOptions
    presences: Map<string, P>

    presences is a map of client IDs to their presence information.

    +
    root: CRDTRoot

    Methods

    • Internal

      addOnlineClient adds the given clientID into the online client set.

      +

      Parameters

      • clientID: string

      Returns void

    • Internal

      applyChangePack applies the given change pack into this document.

      1. Remove local changes applied to server.
      2. Update the checkpoint.
      3. Do Garbage collection.

      Parameters

      • pack: ChangePack<P>

        change pack

        -

      Returns void

    • applySnapshot applies the given snapshot into this document.

      -

      Parameters

      • serverSeq: bigint
      • snapshotVector: VersionVector
      • Optional snapshot: Uint8Array

      Returns void

    • applyWatchStream applies the given watch stream response into this document.

      -

      Parameters

      • resp: WatchDocumentResponse

      Returns void

    • broadcast the payload to the given topic.

      -

      Parameters

      • topic: string
      • payload: Json
      • Optional options: BroadcastOptions

      Returns void

    • canRedo returns whether there are any operations to redo.

      -

      Returns boolean

    • canUndo returns whether there are any operations to undo.

      -

      Returns boolean

    • Internal

      createChangePack create change pack of the local changes to send to the +

    Returns void

    \ No newline at end of file +

    Returns void

    \ No newline at end of file diff --git a/api-reference/classes/Primitive.html b/api-reference/classes/Primitive.html index cc0b79aa6..82d871dea 100644 --- a/api-reference/classes/Primitive.html +++ b/api-reference/classes/Primitive.html @@ -1,6 +1,6 @@ Primitive | yorkie-js-sdk

    Class Primitive

    Primitive represents primitive data type including logical clock. It has a type and a value.

    -

    Hierarchy

    • CRDTElement
      • Primitive

    Constructors

    Hierarchy

    • CRDTElement
      • Primitive

    Constructors

    Properties

    Methods

    deepcopy @@ -25,27 +25,27 @@ isSupport of valueFromBytes -

    Constructors

    Properties

    valueType: PrimitiveType

    Methods

    • getPositionedAt returns the time of this element when it was positioned +

    Constructors

    Properties

    valueType: PrimitiveType

    Methods

    • getPositionedAt returns the time of this element when it was positioned in the document by undo/redo or move operation.

      -

      Returns TimeTicket

    • isRemoved check if this element was removed.

      -

      Returns boolean

    • setMovedAt sets the move time of this element.

      -

      Parameters

      Returns boolean

    • setRemovedAt sets the remove time of this element.

      -

      Parameters

      Returns void

    • toSortedJSON returns the sorted JSON encoding of the value.

      -

      Returns string

    • getPrimitiveType returns the primitive type of the value.

      -

      Parameters

      • value: unknown

      Returns undefined | PrimitiveType

    • isInteger checks if the given number is integer.

      -

      Parameters

      • num: number

      Returns boolean

    • isSupport check if the given value is supported type.

      -

      Parameters

      • value: unknown

      Returns boolean

    \ No newline at end of file +

    Returns TimeTicket

    \ No newline at end of file diff --git a/api-reference/classes/Text.html b/api-reference/classes/Text.html index 1719ee2ef..31edd9f9a 100644 --- a/api-reference/classes/Text.html +++ b/api-reference/classes/Text.html @@ -1,5 +1,5 @@ Text | yorkie-js-sdk

    Class Text<A>

    Text is an extended data type for the contents of a text editor.

    -

    Type Parameters

    Constructors

    Type Parameters

    Constructors

    Properties

    Accessors

    length @@ -19,23 +19,23 @@ toString toTestString values -

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    text?: CRDTText<A>

    Accessors

    Methods

    • createRangeForTest returns pair of RGATreeSplitNodePos of the given indexes +

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    text?: CRDTText<A>

    Accessors

    Methods

    • createRangeForTest returns pair of RGATreeSplitNodePos of the given indexes for testing purpose.

      -

      Parameters

      • fromIdx: number
      • toIdx: number

      Returns RGATreeSplitPosRange

    • delete deletes the text in the given range.

      -

      Parameters

      • fromIdx: number
      • toIdx: number

      Returns undefined | [number, number]

    • edit edits this text with the given content.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • content: string
      • Optional attributes: A

      Returns undefined | [number, number]

    • empty makes the text empty.

      -

      Returns undefined | [number, number]

    • getTreeByID returns IDTree of the text for testing purpose.

      -

      Returns LLRBTree<RGATreeSplitNodeID, RGATreeSplitNode<CRDTTextValue>>

    • getTreeByIndex returns IndexTree of the text for testing purpose.

      -

      Returns SplayTree<CRDTTextValue>

    • Internal

      initialize initialize this text with context and internal text.

      -

      Parameters

      • context: ChangeContext<Indexable>
      • text: CRDTText<A>

      Returns void

    • setStyle styles this text with the given attributes.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • attributes: A

      Returns boolean

    • toString returns the string representation of this text.

      -

      Returns string

    • toTestString returns a String containing the meta data of the node +

      Parameters

      • fromIdx: number
      • toIdx: number

      Returns RGATreeSplitPosRange

    • delete deletes the text in the given range.

      +

      Parameters

      • fromIdx: number
      • toIdx: number

      Returns undefined | [number, number]

    • edit edits this text with the given content.

      +

      Parameters

      • fromIdx: number
      • toIdx: number
      • content: string
      • Optional attributes: A

      Returns undefined | [number, number]

    • empty makes the text empty.

      +

      Returns undefined | [number, number]

    • getTreeByID returns IDTree of the text for testing purpose.

      +

      Returns LLRBTree<RGATreeSplitNodeID, RGATreeSplitNode<CRDTTextValue>>

    • getTreeByIndex returns IndexTree of the text for testing purpose.

      +

      Returns SplayTree<CRDTTextValue>

    • Internal

      initialize initialize this text with context and internal text.

      +

      Parameters

      • context: ChangeContext<Indexable>
      • text: CRDTText<A>

      Returns void

    • setStyle styles this text with the given attributes.

      +

      Parameters

      • fromIdx: number
      • toIdx: number
      • attributes: A

      Returns boolean

    • toString returns the string representation of this text.

      +

      Returns string

    • toTestString returns a String containing the meta data of the node for debugging purpose.

      -

      Returns string

    \ No newline at end of file +

    Returns string

    \ No newline at end of file diff --git a/api-reference/classes/TimeTicket.html b/api-reference/classes/TimeTicket.html index d80607d85..7bb7fb652 100644 --- a/api-reference/classes/TimeTicket.html +++ b/api-reference/classes/TimeTicket.html @@ -1,6 +1,6 @@ TimeTicket | yorkie-js-sdk

    Class TimeTicket

    TimeTicket is a timestamp of the logical clock. Ticket is immutable. It is created by ChangeID.

    -

    Constructors

    Constructors

    Properties

    Constructors

    Properties

    actorID: string
    delimiter: number
    lamport: bigint

    Methods

    • compare returns an integer comparing two Ticket. +

    Constructors

    Properties

    actorID: string
    delimiter: number
    lamport: bigint

    Methods

    • compare returns an integer comparing two Ticket. The result will be 0 if id==other, -1 if id < other, and +1 if id > other. If the receiver or argument is nil, it would panic at runtime.

      -

      Parameters

      Returns number

    • toTestString returns a string containing the meta data of the ticket for debugging purpose.

      -

      Returns string

    \ No newline at end of file +

    Returns string

    \ No newline at end of file diff --git a/api-reference/classes/Tree.html b/api-reference/classes/Tree.html index 6f6352188..b4c6c3ce2 100644 --- a/api-reference/classes/Tree.html +++ b/api-reference/classes/Tree.html @@ -1,6 +1,6 @@ Tree | yorkie-js-sdk

    Tree is a CRDT-based tree structure that is used to represent the document tree of text-based editor such as ProseMirror.

    -

    Constructors

    Constructors

    Properties

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    initialRoot?: ElementNode
    tree?: CRDTTree

    Methods

    • buildRoot builds the root of this tree with the given initial root +

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    initialRoot?: ElementNode
    tree?: CRDTTree

    Methods

    • buildRoot builds the root of this tree with the given initial root which set by the user.

      -

      Parameters

      Returns CRDTTreeNode

    • edit edits this tree with the given nodes.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • Optional content: TreeNode
      • splitLevel: number = 0

      Returns boolean

    • editBulk edits this tree with the given nodes.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • contents: TreeNode[]
      • splitLevel: number = 0

      Returns boolean

    • editBulkByPath edits this tree with the given node and path.

      -

      Parameters

      • fromPath: number[]
      • toPath: number[]
      • contents: TreeNode[]
      • splitLevel: number = 0

      Returns boolean

    • editByPath edits this tree with the given node and path.

      -

      Parameters

      • fromPath: number[]
      • toPath: number[]
      • Optional content: TreeNode
      • splitLevel: number = 0

      Returns boolean

    • Parameters

      • fromPos: CRDTTreePos
      • toPos: CRDTTreePos
      • contents: TreeNode[]
      • splitLevel: number = 0

      Returns boolean

    • getIndexTree returns the index tree of this tree.

      -

      Returns IndexTree<CRDTTreeNode>

    • indexToPath returns the path of the given index.

      -

      Parameters

      • index: number

      Returns number[]

    • Internal

      initialize initialize this tree with context and internal tree.

      -

      Parameters

      • context: ChangeContext<Indexable>
      • tree: CRDTTree

      Returns void

    • pathToIndex returns the index of given path.

      -

      Parameters

      • path: number[]

      Returns number

    • posRangeToPathRange converts the position range into the path range.

      -

      Parameters

      Returns [number[], number[]]

    • removeStyle removes the attributes to the elements of the given range.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • attributesToRemove: string[]

      Returns void

    • style sets the attributes to the elements of the given range.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • attributes: {
            [key: string]: any;
        }
        • [key: string]: any

      Returns void

    • styleByPath sets the attributes to the elements of the given path.

      -

      Parameters

      • path: number[]
      • attributes: {
            [key: string]: any;
        }
        • [key: string]: any

      Returns void

    \ No newline at end of file +

    Parameters

    Returns CRDTTreeNode

    \ No newline at end of file diff --git a/api-reference/classes/VersionVector.html b/api-reference/classes/VersionVector.html index 36f182bcf..a0c7877f3 100644 --- a/api-reference/classes/VersionVector.html +++ b/api-reference/classes/VersionVector.html @@ -2,7 +2,7 @@ between changes whether they are causally related or concurrent. It is similar to vector clocks, but it is synced with lamport timestamp of the change.

    -

    Constructors

    Constructors

    Properties

    Methods

    [iterator] afterOrEqual @@ -13,12 +13,12 @@ maxLamport set size -

    Constructors

    Properties

    vector: Map<string, bigint>

    Methods

    • get gets the lamport timestamp of the given actor.

      -

      Parameters

      • actorID: string

      Returns undefined | bigint

    • set sets the lamport timestamp of the given actor.

      -

      Parameters

      • actorID: string
      • lamport: bigint

      Returns void

    \ No newline at end of file +

    Constructors

    Properties

    vector: Map<string, bigint>

    Methods

    \ No newline at end of file diff --git a/api-reference/enums/ClientCondition.html b/api-reference/enums/ClientCondition.html index 17598cb72..62037431d 100644 --- a/api-reference/enums/ClientCondition.html +++ b/api-reference/enums/ClientCondition.html @@ -1,6 +1,6 @@ ClientCondition | yorkie-js-sdk

    Enumeration ClientCondition

    ClientCondition represents the condition of the client.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    SyncLoop: "SyncLoop"

    SyncLoop is a key of the sync loop condition.

    -
    WatchLoop: "WatchLoop"

    WatchLoop is a key of the watch loop condition.

    -
    \ No newline at end of file +
    WatchLoop: "WatchLoop"

    WatchLoop is a key of the watch loop condition.

    +
    \ No newline at end of file diff --git a/api-reference/enums/ClientStatus.html b/api-reference/enums/ClientStatus.html index f279a8ab3..1ff0f3bd3 100644 --- a/api-reference/enums/ClientStatus.html +++ b/api-reference/enums/ClientStatus.html @@ -1,9 +1,9 @@ ClientStatus | yorkie-js-sdk

    Enumeration ClientStatus

    ClientStatus represents the status of the client.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Activated: "activated"

    Activated means that the client is activated. If the client is activated, all Documents of the client are also ready to be used.

    -
    Deactivated: "deactivated"

    Deactivated means that the client is not activated. It is the initial +

    Deactivated: "deactivated"

    Deactivated means that the client is not activated. It is the initial status of the client. If the client is deactivated, all Documents of the client are also not used.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/enums/DocEventType.html b/api-reference/enums/DocEventType.html index b92d033be..3096f6767 100644 --- a/api-reference/enums/DocEventType.html +++ b/api-reference/enums/DocEventType.html @@ -1,5 +1,5 @@ DocEventType | yorkie-js-sdk

    Enumeration DocEventType

    DocEventType represents the type of the event that occurs in Document.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Broadcast: "broadcast"

    Broadcast means that the broadcast event is received from the remote client.

    -
    ConnectionChanged: "connection-changed"

    ConnectionChanged means that the watch stream connection status has changed.

    -
    Initialized: "initialized"

    Initialized means that online clients have been loaded from the server.

    -
    LocalBroadcast: "local-broadcast"

    LocalBroadcast means that the broadcast event is sent from the local client.

    -
    LocalChange: "local-change"

    local document change event type

    -
    PresenceChanged: "presence-changed"

    PresenceChanged means that the presences of the client has updated.

    -
    RemoteChange: "remote-change"

    remote document change event type

    -
    Snapshot: "snapshot"

    snapshot event type

    -
    StatusChanged: "status-changed"

    status changed event type

    -
    SyncStatusChanged: "sync-status-changed"

    SyncStatusChanged means that the document sync status has changed.

    -
    Unwatched: "unwatched"

    Unwatched means that the connection has been disconnected.

    -
    Watched: "watched"

    Watched means that the client has established a connection with the server, +

    ConnectionChanged: "connection-changed"

    ConnectionChanged means that the watch stream connection status has changed.

    +
    Initialized: "initialized"

    Initialized means that online clients have been loaded from the server.

    +
    LocalBroadcast: "local-broadcast"

    LocalBroadcast means that the broadcast event is sent from the local client.

    +
    LocalChange: "local-change"

    local document change event type

    +
    PresenceChanged: "presence-changed"

    PresenceChanged means that the presences of the client has updated.

    +
    RemoteChange: "remote-change"

    remote document change event type

    +
    Snapshot: "snapshot"

    snapshot event type

    +
    StatusChanged: "status-changed"

    status changed event type

    +
    SyncStatusChanged: "sync-status-changed"

    SyncStatusChanged means that the document sync status has changed.

    +
    Unwatched: "unwatched"

    Unwatched means that the connection has been disconnected.

    +
    Watched: "watched"

    Watched means that the client has established a connection with the server, enabling real-time synchronization.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/enums/DocumentStatus.html b/api-reference/enums/DocumentStatus.html index f25d4cacf..f179e16f1 100644 --- a/api-reference/enums/DocumentStatus.html +++ b/api-reference/enums/DocumentStatus.html @@ -1,11 +1,11 @@ DocumentStatus | yorkie-js-sdk

    Enumeration DocumentStatus

    DocumentStatus represents the status of the document.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Attached: "attached"

    Attached means that this document is attached to the client. The actor of the ticket is created with being assigned by the client.

    -
    Detached: "detached"

    Detached means that the document is not attached to the client. +

    Detached: "detached"

    Detached means that the document is not attached to the client. The actor of the ticket is created without being assigned.

    -
    Removed: "removed"

    Removed means that this document is removed. If the document is removed, +

    Removed: "removed"

    Removed means that this document is removed. If the document is removed, it cannot be edited.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/enums/DocumentSyncStatus.html b/api-reference/enums/DocumentSyncStatus.html index 20179825c..4b4d8fc61 100644 --- a/api-reference/enums/DocumentSyncStatus.html +++ b/api-reference/enums/DocumentSyncStatus.html @@ -1,6 +1,6 @@ DocumentSyncStatus | yorkie-js-sdk

    Enumeration DocumentSyncStatus

    DocumentSyncStatus represents the result of synchronizing the document with the server.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    SyncFailed: "sync-failed"

    SyncFiled means that document synchronization has failed.

    -
    Synced: "synced"

    Synced means that document synced successfully.

    -
    \ No newline at end of file +
    Synced: "synced"

    Synced means that document synced successfully.

    +
    \ No newline at end of file diff --git a/api-reference/enums/LogLevel.html b/api-reference/enums/LogLevel.html index d227ba35c..b0f89490a 100644 --- a/api-reference/enums/LogLevel.html +++ b/api-reference/enums/LogLevel.html @@ -1,7 +1,7 @@ -LogLevel | yorkie-js-sdk

    Enumeration LogLevel

    Enumeration Members

    Debug +LogLevel | yorkie-js-sdk

    Enumeration LogLevel

    Enumeration Members

    Enumeration Members

    Debug: 1
    Error: 4
    Fatal: 5
    Info: 2
    Trivial: 0
    Warn: 3
    \ No newline at end of file +

    Enumeration Members

    Debug: 1
    Error: 4
    Fatal: 5
    Info: 2
    Trivial: 0
    Warn: 3
    \ No newline at end of file diff --git a/api-reference/enums/OpSource.html b/api-reference/enums/OpSource.html index 6cd9a69c2..985217a57 100644 --- a/api-reference/enums/OpSource.html +++ b/api-reference/enums/OpSource.html @@ -1,7 +1,7 @@ OpSource | yorkie-js-sdk

    Enumeration OpSource

    OpSource represents the source of the operation. It is used to handle corner cases in the operations created by undo/redo allow the removed elements when executing them.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Local: "local"
    Remote: "remote"
    UndoRedo: "undoredo"
    \ No newline at end of file +

    Enumeration Members

    Local: "local"
    Remote: "remote"
    UndoRedo: "undoredo"
    \ No newline at end of file diff --git a/api-reference/enums/StreamConnectionStatus.html b/api-reference/enums/StreamConnectionStatus.html index bfaf6fcca..ba0ed0134 100644 --- a/api-reference/enums/StreamConnectionStatus.html +++ b/api-reference/enums/StreamConnectionStatus.html @@ -1,6 +1,6 @@ StreamConnectionStatus | yorkie-js-sdk

    Enumeration StreamConnectionStatus

    StreamConnectionStatus represents whether the stream connection is connected or not.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Connected: "connected"

    Connected means that the stream connection is connected.

    -
    Disconnected: "disconnected"

    Disconnected means that the stream connection is disconnected.

    -
    \ No newline at end of file +
    Disconnected: "disconnected"

    Disconnected means that the stream connection is disconnected.

    +
    \ No newline at end of file diff --git a/api-reference/enums/SyncMode.html b/api-reference/enums/SyncMode.html index d65a25fc9..6507ccb68 100644 --- a/api-reference/enums/SyncMode.html +++ b/api-reference/enums/SyncMode.html @@ -1,11 +1,11 @@ SyncMode | yorkie-js-sdk

    Enumeration SyncMode

    SyncMode defines synchronization modes for the PushPullChanges API.

    -

    Enumeration Members

    Enumeration Members

    Manual: "manual"

    Manual mode indicates that changes are not automatically pushed or pulled.

    -
    Realtime: "realtime"

    Realtime mode indicates that changes are automatically pushed and pulled.

    -
    RealtimePushOnly: "realtime-pushonly"

    RealtimePushOnly mode indicates that only local changes are automatically pushed.

    -
    RealtimeSyncOff: "realtime-syncoff"

    RealtimeSyncOff mode indicates that changes are not automatically pushed or pulled, +

    Realtime: "realtime"

    Realtime mode indicates that changes are automatically pushed and pulled.

    +
    RealtimePushOnly: "realtime-pushonly"

    RealtimePushOnly mode indicates that only local changes are automatically pushed.

    +
    RealtimeSyncOff: "realtime-syncoff"

    RealtimeSyncOff mode indicates that changes are not automatically pushed or pulled, but the watch stream is kept active.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/enums/TreeChangeType.html b/api-reference/enums/TreeChangeType.html index aa0d29046..2a69e8406 100644 --- a/api-reference/enums/TreeChangeType.html +++ b/api-reference/enums/TreeChangeType.html @@ -1,5 +1,5 @@ TreeChangeType | yorkie-js-sdk

    Enumeration TreeChangeType

    TreeChangeType represents the type of change in the tree.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Content: "content"
    RemoveStyle: "removeStyle"
    Style: "style"
    \ No newline at end of file +

    Enumeration Members

    Content: "content"
    RemoveStyle: "removeStyle"
    Style: "style"
    \ No newline at end of file diff --git a/api-reference/interfaces/ChangeInfo.html b/api-reference/interfaces/ChangeInfo.html index ce3fd9176..2043049db 100644 --- a/api-reference/interfaces/ChangeInfo.html +++ b/api-reference/interfaces/ChangeInfo.html @@ -1,8 +1,8 @@ ChangeInfo | yorkie-js-sdk

    Interface ChangeInfo<T>

    ChangeInfo represents the modifications made during a document update and the message passed.

    -
    interface ChangeInfo<T> {
        actor: string;
        clientSeq: number;
        message: string;
        operations: T[];
        serverSeq: string;
    }

    Type Parameters

    Properties

    interface ChangeInfo<T> {
        actor: string;
        clientSeq: number;
        message: string;
        operations: T[];
        serverSeq: string;
    }

    Type Parameters

    Properties

    actor: string
    clientSeq: number
    message: string
    operations: T[]
    serverSeq: string
    \ No newline at end of file +

    Properties

    actor: string
    clientSeq: number
    message: string
    operations: T[]
    serverSeq: string
    \ No newline at end of file diff --git a/api-reference/interfaces/ClientOptions.html b/api-reference/interfaces/ClientOptions.html index a3fb411d2..2daa2ade3 100644 --- a/api-reference/interfaces/ClientOptions.html +++ b/api-reference/interfaces/ClientOptions.html @@ -1,5 +1,5 @@ ClientOptions | yorkie-js-sdk

    Interface ClientOptions

    ClientOptions are user-settable options used when defining clients.

    -
    interface ClientOptions {
        apiKey?: string;
        key?: string;
        reconnectStreamDelay?: number;
        retrySyncLoopDelay?: number;
        syncLoopDuration?: number;
        token?: string;
    }

    Properties

    interface ClientOptions {
        apiKey?: string;
        key?: string;
        reconnectStreamDelay?: number;
        retrySyncLoopDelay?: number;
        syncLoopDuration?: number;
        token?: string;
    }

    Properties

    apiKey?: string

    apiKey is the API key of the project. It is used to identify the project. If not set, API key of the default project is used.

    -
    key?: string

    key is the client key. It is used to identify the client. +

    key?: string

    key is the client key. It is used to identify the client. If not set, a random key is generated.

    -
    reconnectStreamDelay?: number

    reconnectStreamDelay is the delay of the reconnect stream. If the stream +

    reconnectStreamDelay?: number

    reconnectStreamDelay is the delay of the reconnect stream. If the stream is disconnected, the client waits for the delay to reconnect the stream. The default value is 1000(ms).

    -
    retrySyncLoopDelay?: number

    retrySyncLoopDelay is the delay of the retry sync loop. If the sync loop +

    retrySyncLoopDelay?: number

    retrySyncLoopDelay is the delay of the retry sync loop. If the sync loop fails, the client waits for the delay to retry the sync loop. The default value is 1000(ms).

    -
    syncLoopDuration?: number

    syncLoopDuration is the duration of the sync loop. After each sync loop, +

    syncLoopDuration?: number

    syncLoopDuration is the duration of the sync loop. After each sync loop, the client waits for the duration to next sync. The default value is 50(ms).

    -
    token?: string

    token is the authentication token of this client. It is used to identify +

    token?: string

    token is the authentication token of this client. It is used to identify the user of the client.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/interfaces/ConnectionChangedEvent.html b/api-reference/interfaces/ConnectionChangedEvent.html index 33545349c..5ae9e8be0 100644 --- a/api-reference/interfaces/ConnectionChangedEvent.html +++ b/api-reference/interfaces/ConnectionChangedEvent.html @@ -1,5 +1,5 @@ ConnectionChangedEvent | yorkie-js-sdk

    Interface ConnectionChangedEvent

    ConnectionChangedEvent is an event that occurs when the stream connection state changes.

    -
    interface ConnectionChangedEvent {
        type: ConnectionChanged;
        value: StreamConnectionStatus;
    }

    Hierarchy

    • BaseDocEvent
      • ConnectionChangedEvent

    Properties

    interface ConnectionChangedEvent {
        type: ConnectionChanged;
        value: StreamConnectionStatus;
    }

    Hierarchy

    • BaseDocEvent
      • ConnectionChangedEvent

    Properties

    Properties

    enum DocEventType.ConnectionChanged

    -
    \ No newline at end of file +
    value: StreamConnectionStatus
    \ No newline at end of file diff --git a/api-reference/interfaces/InitializedEvent.html b/api-reference/interfaces/InitializedEvent.html index 0cb103ca7..510da9d9e 100644 --- a/api-reference/interfaces/InitializedEvent.html +++ b/api-reference/interfaces/InitializedEvent.html @@ -1,4 +1,4 @@ -InitializedEvent | yorkie-js-sdk

    Interface InitializedEvent<P>

    interface InitializedEvent<P> {
        source: Local;
        type: Initialized;
        value: {
            clientID: string;
            presence: P;
        }[];
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • InitializedEvent

    Properties

    source +InitializedEvent | yorkie-js-sdk

    Interface InitializedEvent<P>

    interface InitializedEvent<P> {
        source: Local;
        type: Initialized;
        value: {
            clientID: string;
            presence: P;
        }[];
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • InitializedEvent

    Properties

    Properties

    source: Local
    value: {
        clientID: string;
        presence: P;
    }[]

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file +

    Properties

    source: Local
    value: {
        clientID: string;
        presence: P;
    }[]

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file diff --git a/api-reference/interfaces/LocalChangeEvent.html b/api-reference/interfaces/LocalChangeEvent.html index 78355774f..e691cc87a 100644 --- a/api-reference/interfaces/LocalChangeEvent.html +++ b/api-reference/interfaces/LocalChangeEvent.html @@ -1,8 +1,8 @@ LocalChangeEvent | yorkie-js-sdk

    Interface LocalChangeEvent<T, P>

    LocalChangeEvent is an event that occurs when the document is changed by local changes.

    -
    interface LocalChangeEvent<T, P> {
        rawChange?: ChangeStruct<P>;
        source: Local | UndoRedo;
        type: LocalChange;
        value: ChangeInfo<T>;
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • LocalChangeEvent

    Properties

    interface LocalChangeEvent<T, P> {
        rawChange?: ChangeStruct<P>;
        source: Local | UndoRedo;
        type: LocalChange;
        value: ChangeInfo<T>;
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • LocalChangeEvent

    Properties

    rawChange?: ChangeStruct<P>
    source: Local | UndoRedo

    enum DocEventType.LocalChange

    -
    value: ChangeInfo<T>
    \ No newline at end of file +

    Properties

    rawChange?: ChangeStruct<P>
    source: Local | UndoRedo

    enum DocEventType.LocalChange

    +
    value: ChangeInfo<T>
    \ No newline at end of file diff --git a/api-reference/interfaces/Observable.html b/api-reference/interfaces/Observable.html index 644c32994..81b12e4b5 100644 --- a/api-reference/interfaces/Observable.html +++ b/api-reference/interfaces/Observable.html @@ -1,3 +1,3 @@ -Observable | yorkie-js-sdk

    Interface Observable<T>

    interface Observable<T> {
        getProxy?: (() => ObserverProxy<T>);
        subscribe: SubscribeFn<T>;
    }

    Type Parameters

    • T

    Properties

    getProxy? +Observable | yorkie-js-sdk

    Interface Observable<T>

    interface Observable<T> {
        getProxy?: (() => ObserverProxy<T>);
        subscribe: SubscribeFn<T>;
    }

    Type Parameters

    • T

    Properties

    Properties

    getProxy?: (() => ObserverProxy<T>)

    Type declaration

      • (): ObserverProxy<T>
      • Returns ObserverProxy<T>

    subscribe: SubscribeFn<T>
    \ No newline at end of file +

    Properties

    getProxy?: (() => ObserverProxy<T>)

    Type declaration

      • (): ObserverProxy<T>
      • Returns ObserverProxy<T>

    subscribe: SubscribeFn<T>
    \ No newline at end of file diff --git a/api-reference/interfaces/Observer.html b/api-reference/interfaces/Observer.html index 5a5f2e5cf..5cbbe0c21 100644 --- a/api-reference/interfaces/Observer.html +++ b/api-reference/interfaces/Observer.html @@ -1,4 +1,4 @@ -Observer | yorkie-js-sdk

    Interface Observer<T>

    interface Observer<T> {
        complete?: CompleteFn;
        error?: ErrorFn;
        next: NextFn<T>;
    }

    Type Parameters

    • T

    Properties

    complete? +Observer | yorkie-js-sdk

    Interface Observer<T>

    interface Observer<T> {
        complete?: CompleteFn;
        error?: ErrorFn;
        next: NextFn<T>;
    }

    Type Parameters

    • T

    Properties

    Properties

    complete?: CompleteFn
    error?: ErrorFn
    next: NextFn<T>
    \ No newline at end of file +

    Properties

    complete?: CompleteFn
    error?: ErrorFn
    next: NextFn<T>
    \ No newline at end of file diff --git a/api-reference/interfaces/PresenceChangedEvent.html b/api-reference/interfaces/PresenceChangedEvent.html index ae4279d3c..d130c9c83 100644 --- a/api-reference/interfaces/PresenceChangedEvent.html +++ b/api-reference/interfaces/PresenceChangedEvent.html @@ -1,4 +1,4 @@ -PresenceChangedEvent | yorkie-js-sdk

    Interface PresenceChangedEvent<P>

    interface PresenceChangedEvent<P> {
        source: OpSource;
        type: PresenceChanged;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • PresenceChangedEvent

    Properties

    source +PresenceChangedEvent | yorkie-js-sdk

    Interface PresenceChangedEvent<P>

    interface PresenceChangedEvent<P> {
        source: OpSource;
        type: PresenceChanged;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • PresenceChangedEvent

    Properties

    Properties

    source: OpSource
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file +

    Properties

    source: OpSource
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file diff --git a/api-reference/interfaces/RemoteChangeEvent.html b/api-reference/interfaces/RemoteChangeEvent.html index f3db9f874..2c56ec64f 100644 --- a/api-reference/interfaces/RemoteChangeEvent.html +++ b/api-reference/interfaces/RemoteChangeEvent.html @@ -1,8 +1,8 @@ RemoteChangeEvent | yorkie-js-sdk

    Interface RemoteChangeEvent<T, P>

    RemoteChangeEvent is an event that occurs when the document is changed by remote changes.

    -
    interface RemoteChangeEvent<T, P> {
        rawChange?: ChangeStruct<P>;
        source: Remote;
        type: RemoteChange;
        value: ChangeInfo<T>;
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • RemoteChangeEvent

    Properties

    interface RemoteChangeEvent<T, P> {
        rawChange?: ChangeStruct<P>;
        source: Remote;
        type: RemoteChange;
        value: ChangeInfo<T>;
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • RemoteChangeEvent

    Properties

    rawChange?: ChangeStruct<P>
    source: Remote

    enum DocEventType.RemoteChange

    -
    value: ChangeInfo<T>
    \ No newline at end of file +

    Properties

    rawChange?: ChangeStruct<P>
    source: Remote

    enum DocEventType.RemoteChange

    +
    value: ChangeInfo<T>
    \ No newline at end of file diff --git a/api-reference/interfaces/SnapshotEvent.html b/api-reference/interfaces/SnapshotEvent.html index c793368c3..9d8ea7b54 100644 --- a/api-reference/interfaces/SnapshotEvent.html +++ b/api-reference/interfaces/SnapshotEvent.html @@ -1,7 +1,7 @@ SnapshotEvent | yorkie-js-sdk

    Interface SnapshotEvent

    SnapshotEvent is an event that occurs when a snapshot is received from the server.

    -
    interface SnapshotEvent {
        source: Remote;
        type: Snapshot;
        value: {
            serverSeq: string;
            snapshot: undefined | string;
            snapshotVector: string;
        };
    }

    Hierarchy

    • BaseDocEvent
      • SnapshotEvent

    Properties

    interface SnapshotEvent {
        source: Remote;
        type: Snapshot;
        value: {
            serverSeq: string;
            snapshot: undefined | string;
            snapshotVector: string;
        };
    }

    Hierarchy

    • BaseDocEvent
      • SnapshotEvent

    Properties

    Properties

    source: Remote
    type: Snapshot

    enum DocEventType.Snapshot

    -
    value: {
        serverSeq: string;
        snapshot: undefined | string;
        snapshotVector: string;
    }

    Type declaration

    • serverSeq: string
    • snapshot: undefined | string
    • snapshotVector: string
    \ No newline at end of file +

    Properties

    source: Remote
    type: Snapshot

    enum DocEventType.Snapshot

    +
    value: {
        serverSeq: string;
        snapshot: undefined | string;
        snapshotVector: string;
    }

    Type declaration

    • serverSeq: string
    • snapshot: undefined | string
    • snapshotVector: string
    \ No newline at end of file diff --git a/api-reference/interfaces/SyncStatusChangedEvent.html b/api-reference/interfaces/SyncStatusChangedEvent.html index 5c3e5e17a..7c8a6fefe 100644 --- a/api-reference/interfaces/SyncStatusChangedEvent.html +++ b/api-reference/interfaces/SyncStatusChangedEvent.html @@ -1,5 +1,5 @@ SyncStatusChangedEvent | yorkie-js-sdk

    Interface SyncStatusChangedEvent

    SyncStatusChangedEvent is an event that occurs when document is synced with the server.

    -
    interface SyncStatusChangedEvent {
        type: SyncStatusChanged;
        value: DocumentSyncStatus;
    }

    Hierarchy

    • BaseDocEvent
      • SyncStatusChangedEvent

    Properties

    interface SyncStatusChangedEvent {
        type: SyncStatusChanged;
        value: DocumentSyncStatus;
    }

    Hierarchy

    • BaseDocEvent
      • SyncStatusChangedEvent

    Properties

    Properties

    enum DocEventType.SyncStatusChanged

    -
    \ No newline at end of file +
    value: DocumentSyncStatus
    \ No newline at end of file diff --git a/api-reference/interfaces/UnwatchedEvent.html b/api-reference/interfaces/UnwatchedEvent.html index e581aa95e..50242c9d4 100644 --- a/api-reference/interfaces/UnwatchedEvent.html +++ b/api-reference/interfaces/UnwatchedEvent.html @@ -1,4 +1,4 @@ -UnwatchedEvent | yorkie-js-sdk

    Interface UnwatchedEvent<P>

    interface UnwatchedEvent<P> {
        source: Remote;
        type: Unwatched;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • UnwatchedEvent

    Properties

    source +UnwatchedEvent | yorkie-js-sdk

    Interface UnwatchedEvent<P>

    interface UnwatchedEvent<P> {
        source: Remote;
        type: Unwatched;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • UnwatchedEvent

    Properties

    Properties

    source: Remote
    type: Unwatched
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file +

    Properties

    source: Remote
    type: Unwatched
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file diff --git a/api-reference/interfaces/WatchedEvent.html b/api-reference/interfaces/WatchedEvent.html index d9ecd7c67..8880e0174 100644 --- a/api-reference/interfaces/WatchedEvent.html +++ b/api-reference/interfaces/WatchedEvent.html @@ -1,4 +1,4 @@ -WatchedEvent | yorkie-js-sdk

    Interface WatchedEvent<P>

    interface WatchedEvent<P> {
        source: Remote;
        type: Watched;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • WatchedEvent

    Properties

    source +WatchedEvent | yorkie-js-sdk

    Interface WatchedEvent<P>

    interface WatchedEvent<P> {
        source: Remote;
        type: Watched;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • WatchedEvent

    Properties

    Properties

    source: Remote
    type: Watched
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file +

    Properties

    source: Remote
    type: Watched
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file diff --git a/api-reference/modules/Devtools.html b/api-reference/modules/Devtools.html index 258158083..a008115aa 100644 --- a/api-reference/modules/Devtools.html +++ b/api-reference/modules/Devtools.html @@ -1,4 +1,4 @@ -Devtools | yorkie-js-sdk

    Namespace Devtools

    Index

    Type Aliases

    Client +Devtools | yorkie-js-sdk

    Namespace Devtools

    Index

    Type Aliases

    Client ContainerValue JSONElement TreeNodeInfo diff --git a/api-reference/types/ActorID.html b/api-reference/types/ActorID.html index 3f7b910e9..39f239f7f 100644 --- a/api-reference/types/ActorID.html +++ b/api-reference/types/ActorID.html @@ -1,3 +1,3 @@ ActorID | yorkie-js-sdk

    Type alias ActorID

    ActorID: string

    ActorID is used to identify who is making changes to the document. It is a hexadecimal string and should be generated by a unique value.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/AddOpInfo.html b/api-reference/types/AddOpInfo.html index d401ccf55..5dfa16db8 100644 --- a/api-reference/types/AddOpInfo.html +++ b/api-reference/types/AddOpInfo.html @@ -1,2 +1,2 @@ AddOpInfo | yorkie-js-sdk

    Type alias AddOpInfo

    AddOpInfo: {
        index: number;
        path: string;
        type: "add";
    }

    AddOpInfo represents the information of the add operation.

    -

    Type declaration

    • index: number
    • path: string
    • type: "add"
    \ No newline at end of file +

    Type declaration

    • index: number
    • path: string
    • type: "add"
    \ No newline at end of file diff --git a/api-reference/types/ArrayOperationInfo.html b/api-reference/types/ArrayOperationInfo.html index bf20476f7..9f8d282d3 100644 --- a/api-reference/types/ArrayOperationInfo.html +++ b/api-reference/types/ArrayOperationInfo.html @@ -1,2 +1,2 @@ ArrayOperationInfo | yorkie-js-sdk

    Type alias ArrayOperationInfo

    ArrayOperationInfo: AddOpInfo | RemoveOpInfo | MoveOpInfo

    ArrayOperationInfo represents the OperationInfo for the JSONArray.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/CRDTTreeNodeIDStruct.html b/api-reference/types/CRDTTreeNodeIDStruct.html index 52147cf34..6bef35a31 100644 --- a/api-reference/types/CRDTTreeNodeIDStruct.html +++ b/api-reference/types/CRDTTreeNodeIDStruct.html @@ -1,3 +1,3 @@ CRDTTreeNodeIDStruct | yorkie-js-sdk

    Type alias CRDTTreeNodeIDStruct

    CRDTTreeNodeIDStruct: {
        createdAt: TimeTicketStruct;
        offset: number;
    }

    CRDTTreeNodeIDStruct represents the structure of CRDTTreeNodeID. It is used to serialize and deserialize the CRDTTreeNodeID.

    -

    Type declaration

    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/CompleteFn.html b/api-reference/types/CompleteFn.html index cdbe68fda..09a497d9f 100644 --- a/api-reference/types/CompleteFn.html +++ b/api-reference/types/CompleteFn.html @@ -1 +1 @@ -CompleteFn | yorkie-js-sdk

    Type alias CompleteFn

    CompleteFn: (() => void)

    Type declaration

      • (): void
      • Returns void

    \ No newline at end of file +CompleteFn | yorkie-js-sdk

    Type alias CompleteFn

    CompleteFn: (() => void)

    Type declaration

      • (): void
      • Returns void

    \ No newline at end of file diff --git a/api-reference/types/CounterOperationInfo.html b/api-reference/types/CounterOperationInfo.html index e9da20c40..1db1676e6 100644 --- a/api-reference/types/CounterOperationInfo.html +++ b/api-reference/types/CounterOperationInfo.html @@ -1,2 +1,2 @@ CounterOperationInfo | yorkie-js-sdk

    Type alias CounterOperationInfo

    CounterOperationInfo: IncreaseOpInfo

    CounterOperationInfo represents the OperationInfo for the yorkie.Counter.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/CounterValue.html b/api-reference/types/CounterValue.html index 7d8265047..e6327f0fe 100644 --- a/api-reference/types/CounterValue.html +++ b/api-reference/types/CounterValue.html @@ -1 +1 @@ -CounterValue | yorkie-js-sdk

    Type alias CounterValue

    CounterValue: number | Long
    \ No newline at end of file +CounterValue | yorkie-js-sdk

    Type alias CounterValue

    CounterValue: number | Long
    \ No newline at end of file diff --git a/api-reference/types/Devtools.Client.html b/api-reference/types/Devtools.Client.html index 9e2c29e14..a362db7d5 100644 --- a/api-reference/types/Devtools.Client.html +++ b/api-reference/types/Devtools.Client.html @@ -1,2 +1,2 @@ Client | yorkie-js-sdk
    Client: {
        clientID: string;
        presence: Json;
    }

    Client represents a client value in devtools.

    -

    Type declaration

    • clientID: string
    • presence: Json
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Devtools.ContainerValue.html b/api-reference/types/Devtools.ContainerValue.html index 32f831a87..2a50b256f 100644 --- a/api-reference/types/Devtools.ContainerValue.html +++ b/api-reference/types/Devtools.ContainerValue.html @@ -1,3 +1,3 @@ ContainerValue | yorkie-js-sdk

    Type alias ContainerValue

    ContainerValue: {
        [key: string]: Devtools.JSONElement;
    }

    ContainerValue represents the result of Array.toJSForTest() and Object.toJSForTest().

    -

    Type declaration

    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Devtools.JSONElement.html b/api-reference/types/Devtools.JSONElement.html index 56f9b592c..95c6dcb55 100644 --- a/api-reference/types/Devtools.JSONElement.html +++ b/api-reference/types/Devtools.JSONElement.html @@ -1,2 +1,2 @@ JSONElement | yorkie-js-sdk

    Type alias JSONElement

    JSONElement: {
        createdAt: string;
        key?: string;
        type: JSONElementType;
        value: JSONElementValue;
    }

    JSONElement represents the result of Element.toJSForTest().

    -

    Type declaration

    • createdAt: string
    • Optional key?: string
    • type: JSONElementType
    • value: JSONElementValue
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Devtools.TreeNodeInfo.html b/api-reference/types/Devtools.TreeNodeInfo.html index bc083e971..b9cb1ec13 100644 --- a/api-reference/types/Devtools.TreeNodeInfo.html +++ b/api-reference/types/Devtools.TreeNodeInfo.html @@ -1,2 +1,2 @@ TreeNodeInfo | yorkie-js-sdk

    Type alias TreeNodeInfo

    TreeNodeInfo: {
        attributes?: object;
        children: TreeNodeInfo[];
        depth: number;
        id: string;
        index?: number;
        insNext?: string;
        insPrev?: string;
        isRemoved: boolean;
        parent?: string;
        path?: number[];
        pos?: CRDTTreePosStruct;
        removedAt?: string;
        size: number;
        type: string;
        value?: string;
    }

    TreeNodeInfo represents the crdt tree node information in devtools.

    -

    Type declaration

    • Optional attributes?: object
    • children: TreeNodeInfo[]
    • depth: number
    • id: string
    • Optional index?: number
    • Optional insNext?: string
    • Optional insPrev?: string
    • isRemoved: boolean
    • Optional parent?: string
    • Optional path?: number[]
    • Optional pos?: CRDTTreePosStruct
    • Optional removedAt?: string
    • size: number
    • type: string
    • Optional value?: string
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/DocEvent.html b/api-reference/types/DocEvent.html index 665ff2424..a1d6d66cf 100644 --- a/api-reference/types/DocEvent.html +++ b/api-reference/types/DocEvent.html @@ -1,3 +1,3 @@ DocEvent | yorkie-js-sdk

    Type alias DocEvent<P, T>

    DocEvent<P, T>: StatusChangedEvent | ConnectionChangedEvent | SyncStatusChangedEvent | SnapshotEvent | LocalChangeEvent<T, P> | RemoteChangeEvent<T, P> | InitializedEvent<P> | WatchedEvent<P> | UnwatchedEvent<P> | PresenceChangedEvent<P> | BroadcastEvent | LocalBroadcastEvent

    DocEvent is an event that occurs in Document. It can be delivered using Document.subscribe().

    -

    Type Parameters

    \ No newline at end of file +

    Type Parameters

    \ No newline at end of file diff --git a/api-reference/types/EditOpInfo.html b/api-reference/types/EditOpInfo.html index b3565a6b7..c84f8f05a 100644 --- a/api-reference/types/EditOpInfo.html +++ b/api-reference/types/EditOpInfo.html @@ -1,2 +1,2 @@ EditOpInfo | yorkie-js-sdk

    Type alias EditOpInfo

    EditOpInfo: {
        from: number;
        path: string;
        to: number;
        type: "edit";
        value: {
            attributes: Indexable;
            content: string;
        };
    }

    EditOpInfo represents the information of the edit operation.

    -

    Type declaration

    • from: number
    • path: string
    • to: number
    • type: "edit"
    • value: {
          attributes: Indexable;
          content: string;
      }
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/ElementNode.html b/api-reference/types/ElementNode.html index 3ed4b52a0..aa1f44c72 100644 --- a/api-reference/types/ElementNode.html +++ b/api-reference/types/ElementNode.html @@ -1,2 +1,2 @@ ElementNode | yorkie-js-sdk

    Type alias ElementNode<A>

    ElementNode<A>: {
        attributes?: A;
        children: TreeNode[];
        type: TreeNodeType;
    }

    ElementNode represents an element node. It has an attributes and children.

    -

    Type Parameters

    Type declaration

    • Optional attributes?: A
    • children: TreeNode[]
    • type: TreeNodeType
    \ No newline at end of file +

    Type Parameters

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/ErrorFn.html b/api-reference/types/ErrorFn.html index c590ea9d3..737955c4a 100644 --- a/api-reference/types/ErrorFn.html +++ b/api-reference/types/ErrorFn.html @@ -1 +1 @@ -ErrorFn | yorkie-js-sdk

    Type alias ErrorFn

    ErrorFn: ((error) => void)

    Type declaration

      • (error): void
      • Parameters

        • error: Error

        Returns void

    \ No newline at end of file +ErrorFn | yorkie-js-sdk

    Type alias ErrorFn

    ErrorFn: ((error) => void)

    Type declaration

      • (error): void
      • Parameters

        • error: Error

        Returns void

    \ No newline at end of file diff --git a/api-reference/types/FullPanelToSDKMessage.html b/api-reference/types/FullPanelToSDKMessage.html index 5bcb17593..bbe5c49af 100644 --- a/api-reference/types/FullPanelToSDKMessage.html +++ b/api-reference/types/FullPanelToSDKMessage.html @@ -1 +1 @@ -FullPanelToSDKMessage | yorkie-js-sdk

    Type alias FullPanelToSDKMessage

    FullPanelToSDKMessage: PanelToSDKMessage & {
        source: "yorkie-devtools-panel";
    }

    Type declaration

    • source: "yorkie-devtools-panel"
    \ No newline at end of file +FullPanelToSDKMessage | yorkie-js-sdk

    Type alias FullPanelToSDKMessage

    FullPanelToSDKMessage: PanelToSDKMessage & {
        source: "yorkie-devtools-panel";
    }

    Type declaration

    • source: "yorkie-devtools-panel"
    \ No newline at end of file diff --git a/api-reference/types/FullSDKToPanelMessage.html b/api-reference/types/FullSDKToPanelMessage.html index cd438b0d8..a7ee2cc12 100644 --- a/api-reference/types/FullSDKToPanelMessage.html +++ b/api-reference/types/FullSDKToPanelMessage.html @@ -1 +1 @@ -FullSDKToPanelMessage | yorkie-js-sdk

    Type alias FullSDKToPanelMessage

    FullSDKToPanelMessage: SDKToPanelMessage & {
        source: "yorkie-devtools-sdk";
    }

    Type declaration

    • source: "yorkie-devtools-sdk"
    \ No newline at end of file +FullSDKToPanelMessage | yorkie-js-sdk

    Type alias FullSDKToPanelMessage

    FullSDKToPanelMessage: SDKToPanelMessage & {
        source: "yorkie-devtools-sdk";
    }

    Type declaration

    • source: "yorkie-devtools-sdk"
    \ No newline at end of file diff --git a/api-reference/types/IncreaseOpInfo.html b/api-reference/types/IncreaseOpInfo.html index c5b2c02e8..f760fbfb9 100644 --- a/api-reference/types/IncreaseOpInfo.html +++ b/api-reference/types/IncreaseOpInfo.html @@ -1,2 +1,2 @@ IncreaseOpInfo | yorkie-js-sdk

    Type alias IncreaseOpInfo

    IncreaseOpInfo: {
        path: string;
        type: "increase";
        value: number;
    }

    IncreaseOpInfo represents the information of the increase operation.

    -

    Type declaration

    • path: string
    • type: "increase"
    • value: number
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Indexable.html b/api-reference/types/Indexable.html index 3a06e364c..2d3d27968 100644 --- a/api-reference/types/Indexable.html +++ b/api-reference/types/Indexable.html @@ -1,3 +1,3 @@ Indexable | yorkie-js-sdk

    Type alias Indexable

    Indexable: Record<string, Json>

    Indexable represents the type of the indexable object. It is used to represent the presence information of the client.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/JSONArray.html b/api-reference/types/JSONArray.html index 6570f9fe0..0dedebac4 100644 --- a/api-reference/types/JSONArray.html +++ b/api-reference/types/JSONArray.html @@ -1,17 +1,17 @@ JSONArray | yorkie-js-sdk

    Type alias JSONArray<T>

    JSONArray<T>: {
        deleteByID?(createdAt): WrappedElement<T>;
        getElementByID?(createdAt): WrappedElement<T>;
        getElementByIndex?(index): WrappedElement<T>;
        getID?(): TimeTicket;
        getLast?(): WrappedElement<T>;
        insertAfter?(prevID, value): WrappedElement<T>;
        insertBefore?(nextID, value): WrappedElement<T>;
        moveAfter?(prevID, id): void;
        moveBefore?(nextID, id): void;
        moveFront?(id): void;
        moveLast?(id): void;
        toJSForTest?(): Devtools.JSONElement;
        toTestString?(): string;
    } & T[]

    JSONArray represents JSON array, but unlike regular JSON, it has time tickets created by a logical clock to resolve conflicts.

    Type Parameters

    • T

    Type declaration

    \ No newline at end of file +

    Returns string

    \ No newline at end of file diff --git a/api-reference/types/JSONElement.html b/api-reference/types/JSONElement.html index 749cbb17f..a4049c62f 100644 --- a/api-reference/types/JSONElement.html +++ b/api-reference/types/JSONElement.html @@ -1,3 +1,3 @@ JSONElement | yorkie-js-sdk

    Type alias JSONElement<T, A>

    JSONElement<T, A>: PrimitiveValue | JSONObject<T> | JSONArray<T> | Text<A> | Counter | Tree

    JSONElement is a wrapper for CRDTElement that provides users with an easy-to-use interface for manipulating Documents.

    -

    Type Parameters

    \ No newline at end of file +

    Type Parameters

    \ No newline at end of file diff --git a/api-reference/types/JSONObject.html b/api-reference/types/JSONObject.html index 1df293254..bb0d9d397 100644 --- a/api-reference/types/JSONObject.html +++ b/api-reference/types/JSONObject.html @@ -1,7 +1,7 @@ JSONObject | yorkie-js-sdk

    Type alias JSONObject<T>

    JSONObject<T>: {
        getID?(): TimeTicket;
        toJS?(): T;
        toJSForTest?(): Devtools.JSONElement;
        toJSON?(): string;
    } & T

    JSONObject represents a JSON object, but unlike regular JSON, it has time tickets created by a logical clock to resolve conflicts.

    Type Parameters

    • T

    Type declaration

    \ No newline at end of file +

    Returns TimeTicket

  • toJS?:function
  • toJSForTest?:function
  • toJSON?:function
  • \ No newline at end of file diff --git a/api-reference/types/MoveOpInfo.html b/api-reference/types/MoveOpInfo.html index 9f625e123..13826b898 100644 --- a/api-reference/types/MoveOpInfo.html +++ b/api-reference/types/MoveOpInfo.html @@ -1,2 +1,2 @@ MoveOpInfo | yorkie-js-sdk

    Type alias MoveOpInfo

    MoveOpInfo: {
        index: number;
        path: string;
        previousIndex: number;
        type: "move";
    }

    MoveOpInfo represents the information of the move operation.

    -

    Type declaration

    • index: number
    • path: string
    • previousIndex: number
    • type: "move"
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/NextFn.html b/api-reference/types/NextFn.html index e867b9c2a..f763ca5be 100644 --- a/api-reference/types/NextFn.html +++ b/api-reference/types/NextFn.html @@ -1 +1 @@ -NextFn | yorkie-js-sdk

    Type alias NextFn<T>

    NextFn<T>: ((value) => void)

    Type Parameters

    • T

    Type declaration

      • (value): void
      • Parameters

        • value: T

        Returns void

    \ No newline at end of file +NextFn | yorkie-js-sdk

    Type alias NextFn<T>

    NextFn<T>: ((value) => void)

    Type Parameters

    • T

    Type declaration

      • (value): void
      • Parameters

        • value: T

        Returns void

    \ No newline at end of file diff --git a/api-reference/types/ObjectOperationInfo.html b/api-reference/types/ObjectOperationInfo.html index f1191ead2..cba824ef2 100644 --- a/api-reference/types/ObjectOperationInfo.html +++ b/api-reference/types/ObjectOperationInfo.html @@ -1,2 +1,2 @@ ObjectOperationInfo | yorkie-js-sdk

    Type alias ObjectOperationInfo

    ObjectOperationInfo: SetOpInfo | RemoveOpInfo

    ObjectOperationInfo represents the OperationInfo for the JSONObject.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/OperationInfo.html b/api-reference/types/OperationInfo.html index 9458f34ec..3694867bc 100644 --- a/api-reference/types/OperationInfo.html +++ b/api-reference/types/OperationInfo.html @@ -1,3 +1,3 @@ OperationInfo | yorkie-js-sdk

    Type alias OperationInfo

    OperationInfo represents the information of an operation. It is used to inform to the user what kind of operation was executed.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/PanelToSDKMessage.html b/api-reference/types/PanelToSDKMessage.html index a2d560906..3cdf8ffbd 100644 --- a/api-reference/types/PanelToSDKMessage.html +++ b/api-reference/types/PanelToSDKMessage.html @@ -1,2 +1,2 @@ PanelToSDKMessage | yorkie-js-sdk

    Type alias PanelToSDKMessage

    PanelToSDKMessage: {
        msg: "devtools::connect";
    } | {
        msg: "devtools::disconnect";
    } | {
        docKey: string;
        msg: "devtools::subscribe";
    }

    PanelToSDKMessage is a message sent from the Devtools panel to the SDK.

    -

    Type declaration

    • msg: "devtools::connect"

    Type declaration

    • msg: "devtools::disconnect"

    Type declaration

    • docKey: string
    • msg: "devtools::subscribe"
    \ No newline at end of file +

    Type declaration

    Type declaration

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/PrimitiveValue.html b/api-reference/types/PrimitiveValue.html index 18f2271c2..f0f29515f 100644 --- a/api-reference/types/PrimitiveValue.html +++ b/api-reference/types/PrimitiveValue.html @@ -1,3 +1,3 @@ PrimitiveValue | yorkie-js-sdk

    Type alias PrimitiveValue

    PrimitiveValue: null | boolean | number | Long | string | Uint8Array | Date

    PrimitiveValue represents a value of primitive type. Only values of type included in PrimitiveValue can be set to the document.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/RemoveOpInfo.html b/api-reference/types/RemoveOpInfo.html index a4b6a4ee2..a3aa7e428 100644 --- a/api-reference/types/RemoveOpInfo.html +++ b/api-reference/types/RemoveOpInfo.html @@ -1,2 +1,2 @@ RemoveOpInfo | yorkie-js-sdk

    Type alias RemoveOpInfo

    RemoveOpInfo: {
        index?: number;
        key?: string;
        path: string;
        type: "remove";
    }

    RemoveOpInfo represents the information of the remove operation.

    -

    Type declaration

    • Optional index?: number
    • Optional key?: string
    • path: string
    • type: "remove"
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/SDKToPanelMessage.html b/api-reference/types/SDKToPanelMessage.html index 6c541e730..9f1ac3019 100644 --- a/api-reference/types/SDKToPanelMessage.html +++ b/api-reference/types/SDKToPanelMessage.html @@ -1,2 +1,2 @@ SDKToPanelMessage | yorkie-js-sdk

    Type alias SDKToPanelMessage

    SDKToPanelMessage: {
        msg: "refresh-devtools";
    } | {
        docKey: string;
        msg: "doc::available";
    } | {
        docKey: string;
        events: TransactionEvent[];
        msg: "doc::sync::full";
    } | {
        docKey: string;
        event: TransactionEvent;
        msg: "doc::sync::partial";
    }

    Definition of all messages the SDK can send to the Devtools panel.

    -

    Type declaration

    • msg: "refresh-devtools"

    Type declaration

    • docKey: string
    • msg: "doc::available"

    Type declaration

    Type declaration

    \ No newline at end of file +

    Type declaration

    Type declaration

    Type declaration

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/SetOpInfo.html b/api-reference/types/SetOpInfo.html index ab1165bf3..2d2d5a4ae 100644 --- a/api-reference/types/SetOpInfo.html +++ b/api-reference/types/SetOpInfo.html @@ -1,2 +1,2 @@ SetOpInfo | yorkie-js-sdk

    Type alias SetOpInfo

    SetOpInfo: {
        key: string;
        path: string;
        type: "set";
    }

    SetOpInfo represents the information of the set operation.

    -

    Type declaration

    • key: string
    • path: string
    • type: "set"
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/StyleOpInfo.html b/api-reference/types/StyleOpInfo.html index e38783c6a..a196f542c 100644 --- a/api-reference/types/StyleOpInfo.html +++ b/api-reference/types/StyleOpInfo.html @@ -1,2 +1,2 @@ StyleOpInfo | yorkie-js-sdk

    Type alias StyleOpInfo

    StyleOpInfo: {
        from: number;
        path: string;
        to: number;
        type: "style";
        value: {
            attributes: Indexable;
        };
    }

    StyleOpInfo represents the information of the style operation.

    -

    Type declaration

    • from: number
    • path: string
    • to: number
    • type: "style"
    • value: {
          attributes: Indexable;
      }
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TextNode.html b/api-reference/types/TextNode.html index 777dd5735..971d36e3b 100644 --- a/api-reference/types/TextNode.html +++ b/api-reference/types/TextNode.html @@ -1,2 +1,2 @@ TextNode | yorkie-js-sdk

    Type alias TextNode

    TextNode: {
        type: typeof DefaultTextType;
        value: string;
    }

    TextNode represents a text node. It has a string value.

    -

    Type declaration

    • type: typeof DefaultTextType
    • value: string
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TextOperationInfo.html b/api-reference/types/TextOperationInfo.html index 9934c18e6..0fd7c27fb 100644 --- a/api-reference/types/TextOperationInfo.html +++ b/api-reference/types/TextOperationInfo.html @@ -1,2 +1,2 @@ TextOperationInfo | yorkie-js-sdk

    Type alias TextOperationInfo

    TextOperationInfo: EditOpInfo | StyleOpInfo

    TextOperationInfo represents the OperationInfo for the yorkie.Text.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TextPosStruct.html b/api-reference/types/TextPosStruct.html index 1d36dc294..46c7c768a 100644 --- a/api-reference/types/TextPosStruct.html +++ b/api-reference/types/TextPosStruct.html @@ -1,3 +1,3 @@ TextPosStruct | yorkie-js-sdk

    Type alias TextPosStruct

    TextPosStruct: {
        id: {
            createdAt: TimeTicketStruct;
            offset: number;
        };
        relativeOffset: number;
    }

    TextPosStruct represents the structure of RGATreeSplitPos. It is used to serialize and deserialize the RGATreeSplitPos.

    -

    Type declaration

    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TextPosStructRange.html b/api-reference/types/TextPosStructRange.html index e05aa1fcc..b750efe30 100644 --- a/api-reference/types/TextPosStructRange.html +++ b/api-reference/types/TextPosStructRange.html @@ -1,3 +1,3 @@ TextPosStructRange | yorkie-js-sdk

    Type alias TextPosStructRange

    TextPosStructRange: [TextPosStruct, TextPosStruct]

    TextPosStructRange represents the structure of RGATreeSplitPosRange. It is used to serialize and deserialize the RGATreeSplitPosRange.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TimeTicketStruct.html b/api-reference/types/TimeTicketStruct.html index d7f704198..d76ebb62b 100644 --- a/api-reference/types/TimeTicketStruct.html +++ b/api-reference/types/TimeTicketStruct.html @@ -1,3 +1,3 @@ TimeTicketStruct | yorkie-js-sdk

    Type alias TimeTicketStruct

    TimeTicketStruct: {
        actorID: ActorID;
        delimiter: number;
        lamport: string;
    }

    TimeTicketStruct is a structure represents the meta data of the ticket. It is used to serialize and deserialize the ticket.

    -

    Type declaration

    • actorID: ActorID
    • delimiter: number
    • lamport: string
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TransactionEvent.html b/api-reference/types/TransactionEvent.html index f5d53306d..62b795584 100644 --- a/api-reference/types/TransactionEvent.html +++ b/api-reference/types/TransactionEvent.html @@ -1,3 +1,3 @@ TransactionEvent | yorkie-js-sdk

    Type alias TransactionEvent<P>

    TransactionEvent<P>: DocEvent<P>[]

    TransactionEvent represents document events that occur within a single transaction (e.g., doc.update).

    -

    Type Parameters

    \ No newline at end of file +

    Type Parameters

    \ No newline at end of file diff --git a/api-reference/types/TreeChange.html b/api-reference/types/TreeChange.html index 62c420e11..29468a9ae 100644 --- a/api-reference/types/TreeChange.html +++ b/api-reference/types/TreeChange.html @@ -1,2 +1,2 @@ TreeChange | yorkie-js-sdk

    Type alias TreeChange

    TreeChange: {
        actor: ActorID;
        from: number;
        fromPath: number[];
        splitLevel?: number;
        to: number;
        toPath: number[];
        type: Content;
        value?: TreeNode[];
    } | {
        actor: ActorID;
        from: number;
        fromPath: number[];
        splitLevel?: number;
        to: number;
        toPath: number[];
        type: Style;
        value: {
            [key: string]: string;
        };
    } | {
        actor: ActorID;
        from: number;
        fromPath: number[];
        splitLevel?: number;
        to: number;
        toPath: number[];
        type: RemoveStyle;
        value?: string[];
    }

    TreeChange represents the change in the tree.

    -

    Type declaration

    • actor: ActorID
    • from: number
    • fromPath: number[]
    • Optional splitLevel?: number
    • to: number
    • toPath: number[]
    • type: Content
    • Optional value?: TreeNode[]

    Type declaration

    • actor: ActorID
    • from: number
    • fromPath: number[]
    • Optional splitLevel?: number
    • to: number
    • toPath: number[]
    • type: Style
    • value: {
          [key: string]: string;
      }
      • [key: string]: string

    Type declaration

    • actor: ActorID
    • from: number
    • fromPath: number[]
    • Optional splitLevel?: number
    • to: number
    • toPath: number[]
    • type: RemoveStyle
    • Optional value?: string[]
    \ No newline at end of file +

    Type declaration

    Type declaration

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TreeEditOpInfo.html b/api-reference/types/TreeEditOpInfo.html index 6188f3046..c4e31c83a 100644 --- a/api-reference/types/TreeEditOpInfo.html +++ b/api-reference/types/TreeEditOpInfo.html @@ -1,2 +1,2 @@ TreeEditOpInfo | yorkie-js-sdk

    Type alias TreeEditOpInfo

    TreeEditOpInfo: {
        from: number;
        fromPath: number[];
        path: string;
        splitLevel?: number;
        to: number;
        toPath: number[];
        type: "tree-edit";
        value?: TreeNode[];
    }

    TreeEditOpInfo represents the information of the tree edit operation.

    -

    Type declaration

    • from: number
    • fromPath: number[]
    • path: string
    • Optional splitLevel?: number
    • to: number
    • toPath: number[]
    • type: "tree-edit"
    • Optional value?: TreeNode[]
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TreeNode.html b/api-reference/types/TreeNode.html index 42edd4863..4af60079a 100644 --- a/api-reference/types/TreeNode.html +++ b/api-reference/types/TreeNode.html @@ -1,2 +1,2 @@ TreeNode | yorkie-js-sdk

    Type alias TreeNode

    TreeNode: TextNode | ElementNode

    TreeNode represents a node in the tree.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TreeOperationInfo.html b/api-reference/types/TreeOperationInfo.html index c9c1ed92a..c60a492ad 100644 --- a/api-reference/types/TreeOperationInfo.html +++ b/api-reference/types/TreeOperationInfo.html @@ -1,2 +1,2 @@ TreeOperationInfo | yorkie-js-sdk

    Type alias TreeOperationInfo

    TreeOperationInfo: TreeEditOpInfo | TreeStyleOpInfo

    TreeOperationInfo represents the OperationInfo for the yorkie.Tree.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TreePosStructRange.html b/api-reference/types/TreePosStructRange.html index d70674bc7..8a81b8f0a 100644 --- a/api-reference/types/TreePosStructRange.html +++ b/api-reference/types/TreePosStructRange.html @@ -1,3 +1,3 @@ TreePosStructRange | yorkie-js-sdk

    Type alias TreePosStructRange

    TreePosStructRange: [CRDTTreePosStruct, CRDTTreePosStruct]

    TreePosStructRange represents the structure of TreeRange. It is used to serialize and deserialize the TreeRange.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TreeStyleOpInfo.html b/api-reference/types/TreeStyleOpInfo.html index 6af41d433..b8c778ddc 100644 --- a/api-reference/types/TreeStyleOpInfo.html +++ b/api-reference/types/TreeStyleOpInfo.html @@ -1,2 +1,2 @@ TreeStyleOpInfo | yorkie-js-sdk

    Type alias TreeStyleOpInfo

    TreeStyleOpInfo: {
        from: number;
        fromPath: number[];
        path: string;
        to: number;
        toPath: number[];
        type: "tree-style";
        value: {
            attributes?: Indexable;
            attributesToRemove?: string[];
        };
    }

    TreeStyleOpInfo represents the information of the tree style operation.

    -

    Type declaration

    • from: number
    • fromPath: number[]
    • path: string
    • to: number
    • toPath: number[]
    • type: "tree-style"
    • value: {
          attributes?: Indexable;
          attributesToRemove?: string[];
      }
      • Optional attributes?: Indexable
      • Optional attributesToRemove?: string[]
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Unsubscribe.html b/api-reference/types/Unsubscribe.html index ee9945fc6..25f1fe5a7 100644 --- a/api-reference/types/Unsubscribe.html +++ b/api-reference/types/Unsubscribe.html @@ -1 +1 @@ -Unsubscribe | yorkie-js-sdk

    Type alias Unsubscribe

    Unsubscribe: (() => void)

    Type declaration

      • (): void
      • Returns void

    \ No newline at end of file +Unsubscribe | yorkie-js-sdk

    Type alias Unsubscribe

    Unsubscribe: (() => void)

    Type declaration

      • (): void
      • Returns void

    \ No newline at end of file diff --git a/api-reference/types/WrappedElement.html b/api-reference/types/WrappedElement.html index a975947c5..14e3576ae 100644 --- a/api-reference/types/WrappedElement.html +++ b/api-reference/types/WrappedElement.html @@ -1,2 +1,2 @@ WrappedElement | yorkie-js-sdk

    Type alias WrappedElement<T, A>

    WrappedElement<T, A>: Primitive | JSONObject<T> | JSONArray<T> | Text<A> | Counter | Tree

    WrappedElement is a wrapper of JSONElement that provides getID().

    -

    Type Parameters

    \ No newline at end of file +

    Type Parameters

    \ No newline at end of file diff --git a/api-reference/variables/EventSourceDevPanel.html b/api-reference/variables/EventSourceDevPanel.html index bd5f41d48..9fdbbf074 100644 --- a/api-reference/variables/EventSourceDevPanel.html +++ b/api-reference/variables/EventSourceDevPanel.html @@ -1,3 +1,3 @@ EventSourceDevPanel | yorkie-js-sdk

    Variable EventSourceDevPanelConst

    EventSourceDevPanel: "yorkie-devtools-panel" = 'yorkie-devtools-panel'

    EventSourceDevPanel is the name of the source representing messages from the Devtools panel.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/variables/EventSourceSDK.html b/api-reference/variables/EventSourceSDK.html index 07afc76fe..d0ed2159e 100644 --- a/api-reference/variables/EventSourceSDK.html +++ b/api-reference/variables/EventSourceSDK.html @@ -1,3 +1,3 @@ EventSourceSDK | yorkie-js-sdk

    Variable EventSourceSDKConst

    EventSourceSDK: "yorkie-devtools-sdk" = 'yorkie-devtools-sdk'

    EventSourceSDK is the name of the source representing messages from the SDK.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/variables/converter.html b/api-reference/variables/converter.html index b5be91beb..007823f49 100644 --- a/api-reference/variables/converter.html +++ b/api-reference/variables/converter.html @@ -19,4 +19,4 @@

    Parameters

    Returns PbOperation

  • toTreeNodes: ((node) => PbTreeNode[])
  • toUint8Array: ((hex) => Uint8Array)
  • versionVectorToHex: ((vector) => string)
  • \ No newline at end of file +

    Parameters

    Returns string

    \ No newline at end of file diff --git a/api-reference/variables/default.html b/api-reference/variables/default.html index 2827ffd06..7d7070f53 100644 --- a/api-reference/variables/default.html +++ b/api-reference/variables/default.html @@ -3,4 +3,4 @@ assigned to the yorkie global.

    e.g) new yorkie.Client(...);

    Type declaration

    \ No newline at end of file +

    Parameters

    Returns void

    \ No newline at end of file diff --git a/examples/nextjs-scheduler/404.html b/examples/nextjs-scheduler/404.html index e44fd5c25..ecffac18d 100644 --- a/examples/nextjs-scheduler/404.html +++ b/examples/nextjs-scheduler/404.html @@ -1 +1 @@ -Next.js react-calendar example

    404 not found

    \ No newline at end of file +Next.js react-calendar example

    404 not found

    \ No newline at end of file diff --git a/examples/nextjs-scheduler/_next/static/bkgGMaTsh79HkOzLjOPfM/_buildManifest.js b/examples/nextjs-scheduler/_next/static/6_IyhgbJWQCmw1jrIomT-/_buildManifest.js similarity index 100% rename from examples/nextjs-scheduler/_next/static/bkgGMaTsh79HkOzLjOPfM/_buildManifest.js rename to examples/nextjs-scheduler/_next/static/6_IyhgbJWQCmw1jrIomT-/_buildManifest.js diff --git a/examples/nextjs-scheduler/_next/static/bkgGMaTsh79HkOzLjOPfM/_ssgManifest.js b/examples/nextjs-scheduler/_next/static/6_IyhgbJWQCmw1jrIomT-/_ssgManifest.js similarity index 100% rename from examples/nextjs-scheduler/_next/static/bkgGMaTsh79HkOzLjOPfM/_ssgManifest.js rename to examples/nextjs-scheduler/_next/static/6_IyhgbJWQCmw1jrIomT-/_ssgManifest.js diff --git a/examples/nextjs-scheduler/_next/static/chunks/app/page-344366f5b41338b3.js b/examples/nextjs-scheduler/_next/static/chunks/app/page-a4871ed0264d2385.js similarity index 88% rename from examples/nextjs-scheduler/_next/static/chunks/app/page-344366f5b41338b3.js rename to examples/nextjs-scheduler/_next/static/chunks/app/page-a4871ed0264d2385.js index 1b6ca50c9..0958cb12a 100644 --- a/examples/nextjs-scheduler/_next/static/chunks/app/page-344366f5b41338b3.js +++ b/examples/nextjs-scheduler/_next/static/chunks/app/page-a4871ed0264d2385.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{4629:function(e,t,r){Promise.resolve().then(r.bind(r,1802))},1802:function(e,t,r){"use strict";r.r(t),r.d(t,{default:function(){return nv}});var n,i,s,o,a,c,l,h,d,u,g,f,m,p,y,v,w,A,T,S,I,C,x,P,E,b,k,D,R,N,O,B,J,L,_,M,q,z,K=r(3165),F=r(7397),V=r.n(F),U=r(6189);let j=["Alice","Bob","Carol","Chuck","Dave","Erin","Frank","Grace","Ivan","Justin","Matilda","Oscar","Steve","Victor","Zoe"];function W(e){let[t,r,n]=e.toLocaleDateString("en").split("/");return t=Number(t)>9?t:"0"+t,r=Number(r)>9?r:"0"+r,n=n.slice(2),"".concat(r,"-").concat(t,"-").concat(n)}var G=r(8358),H=r(6390),Y=r(4715),Z=r(1582),X=r(8728),Q=r(601),$=r(1089),ee=r(6731),et=r(9782);(n=S||(S={}))[n.NULL=0]="NULL",n[n.BOOLEAN=1]="BOOLEAN",n[n.INTEGER=2]="INTEGER",n[n.LONG=3]="LONG",n[n.DOUBLE=4]="DOUBLE",n[n.STRING=5]="STRING",n[n.BYTES=6]="BYTES",n[n.DATE=7]="DATE",n[n.JSON_OBJECT=8]="JSON_OBJECT",n[n.JSON_ARRAY=9]="JSON_ARRAY",n[n.TEXT=10]="TEXT",n[n.INTEGER_CNT=11]="INTEGER_CNT",n[n.LONG_CNT=12]="LONG_CNT",n[n.TREE=13]="TREE",Q.w.util.setEnumType(S,"yorkie.v1.ValueType",[{no:0,name:"VALUE_TYPE_NULL"},{no:1,name:"VALUE_TYPE_BOOLEAN"},{no:2,name:"VALUE_TYPE_INTEGER"},{no:3,name:"VALUE_TYPE_LONG"},{no:4,name:"VALUE_TYPE_DOUBLE"},{no:5,name:"VALUE_TYPE_STRING"},{no:6,name:"VALUE_TYPE_BYTES"},{no:7,name:"VALUE_TYPE_DATE"},{no:8,name:"VALUE_TYPE_JSON_OBJECT"},{no:9,name:"VALUE_TYPE_JSON_ARRAY"},{no:10,name:"VALUE_TYPE_TEXT"},{no:11,name:"VALUE_TYPE_INTEGER_CNT"},{no:12,name:"VALUE_TYPE_LONG_CNT"},{no:13,name:"VALUE_TYPE_TREE"}]),(i=I||(I={}))[i.DOCUMENT_CHANGED=0]="DOCUMENT_CHANGED",i[i.DOCUMENT_WATCHED=1]="DOCUMENT_WATCHED",i[i.DOCUMENT_UNWATCHED=2]="DOCUMENT_UNWATCHED",i[i.DOCUMENT_BROADCAST=3]="DOCUMENT_BROADCAST",Q.w.util.setEnumType(I,"yorkie.v1.DocEventType",[{no:0,name:"DOC_EVENT_TYPE_DOCUMENT_CHANGED"},{no:1,name:"DOC_EVENT_TYPE_DOCUMENT_WATCHED"},{no:2,name:"DOC_EVENT_TYPE_DOCUMENT_UNWATCHED"},{no:3,name:"DOC_EVENT_TYPE_DOCUMENT_BROADCAST"}]);class er extends X.v{static fromBinary(e,t){return new er().fromBinary(e,t)}static fromJson(e,t){return new er().fromJson(e,t)}static fromJsonString(e,t){return new er().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(er,e,t)}constructor(e){super(),this.presences={},Q.w.util.initPartial(e,this)}}er.runtime=Q.w,er.typeName="yorkie.v1.Snapshot",er.fields=Q.w.util.newFieldList(()=>[{no:1,name:"root",kind:"message",T:eA},{no:2,name:"presences",kind:"map",K:9,V:{kind:"message",T:eF}}]);class en extends X.v{static fromBinary(e,t){return new en().fromBinary(e,t)}static fromJson(e,t){return new en().fromJson(e,t)}static fromJsonString(e,t){return new en().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(en,e,t)}constructor(e){super(),this.documentKey="",this.snapshot=new Uint8Array(0),this.changes=[],this.isRemoved=!1,Q.w.util.initPartial(e,this)}}en.runtime=Q.w,en.typeName="yorkie.v1.ChangePack",en.fields=Q.w.util.newFieldList(()=>[{no:1,name:"document_key",kind:"scalar",T:9},{no:2,name:"checkpoint",kind:"message",T:eV},{no:3,name:"snapshot",kind:"scalar",T:12},{no:4,name:"changes",kind:"message",T:ei,repeated:!0},{no:5,name:"min_synced_ticket",kind:"message",T:ej},{no:6,name:"is_removed",kind:"scalar",T:8},{no:7,name:"version_vector",kind:"message",T:eo}]);class ei extends X.v{static fromBinary(e,t){return new ei().fromBinary(e,t)}static fromJson(e,t){return new ei().fromJson(e,t)}static fromJsonString(e,t){return new ei().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ei,e,t)}constructor(e){super(),this.message="",this.operations=[],Q.w.util.initPartial(e,this)}}ei.runtime=Q.w,ei.typeName="yorkie.v1.Change",ei.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:es},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"operations",kind:"message",T:ea,repeated:!0},{no:4,name:"presence_change",kind:"message",T:eK}]);class es extends X.v{static fromBinary(e,t){return new es().fromBinary(e,t)}static fromJson(e,t){return new es().fromJson(e,t)}static fromJsonString(e,t){return new es().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(es,e,t)}constructor(e){super(),this.clientSeq=0,this.serverSeq=$.q.zero,this.lamport=$.q.zero,this.actorId=new Uint8Array(0),Q.w.util.initPartial(e,this)}}es.runtime=Q.w,es.typeName="yorkie.v1.ChangeID",es.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_seq",kind:"scalar",T:13},{no:2,name:"server_seq",kind:"scalar",T:3},{no:3,name:"lamport",kind:"scalar",T:3},{no:4,name:"actor_id",kind:"scalar",T:12},{no:5,name:"version_vector",kind:"message",T:eo}]);class eo extends X.v{static fromBinary(e,t){return new eo().fromBinary(e,t)}static fromJson(e,t){return new eo().fromJson(e,t)}static fromJsonString(e,t){return new eo().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eo,e,t)}constructor(e){super(),this.vector={},Q.w.util.initPartial(e,this)}}eo.runtime=Q.w,eo.typeName="yorkie.v1.VersionVector",eo.fields=Q.w.util.newFieldList(()=>[{no:1,name:"vector",kind:"map",K:9,V:{kind:"scalar",T:3}}]);class ea extends X.v{static fromBinary(e,t){return new ea().fromBinary(e,t)}static fromJson(e,t){return new ea().fromJson(e,t)}static fromJsonString(e,t){return new ea().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ea,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}ea.runtime=Q.w,ea.typeName="yorkie.v1.Operation",ea.fields=Q.w.util.newFieldList(()=>[{no:1,name:"set",kind:"message",T:ec,oneof:"body"},{no:2,name:"add",kind:"message",T:el,oneof:"body"},{no:3,name:"move",kind:"message",T:eh,oneof:"body"},{no:4,name:"remove",kind:"message",T:ed,oneof:"body"},{no:5,name:"edit",kind:"message",T:eu,oneof:"body"},{no:6,name:"select",kind:"message",T:eg,oneof:"body"},{no:7,name:"style",kind:"message",T:ef,oneof:"body"},{no:8,name:"increase",kind:"message",T:em,oneof:"body"},{no:9,name:"tree_edit",kind:"message",T:ep,oneof:"body"},{no:10,name:"tree_style",kind:"message",T:ey,oneof:"body"},{no:11,name:"array_set",kind:"message",T:ev,oneof:"body"}]);class ec extends X.v{static fromBinary(e,t){return new ec().fromBinary(e,t)}static fromJson(e,t){return new ec().fromJson(e,t)}static fromJsonString(e,t){return new ec().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ec,e,t)}constructor(e){super(),this.key="",Q.w.util.initPartial(e,this)}}ec.runtime=Q.w,ec.typeName="yorkie.v1.Operation.Set",ec.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class el extends X.v{static fromBinary(e,t){return new el().fromBinary(e,t)}static fromJson(e,t){return new el().fromJson(e,t)}static fromJsonString(e,t){return new el().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(el,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}el.runtime=Q.w,el.typeName="yorkie.v1.Operation.Add",el.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"prev_created_at",kind:"message",T:ej},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class eh extends X.v{static fromBinary(e,t){return new eh().fromBinary(e,t)}static fromJson(e,t){return new eh().fromJson(e,t)}static fromJsonString(e,t){return new eh().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eh,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eh.runtime=Q.w,eh.typeName="yorkie.v1.Operation.Move",eh.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"prev_created_at",kind:"message",T:ej},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"executed_at",kind:"message",T:ej}]);class ed extends X.v{static fromBinary(e,t){return new ed().fromBinary(e,t)}static fromJson(e,t){return new ed().fromJson(e,t)}static fromJsonString(e,t){return new ed().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ed,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}ed.runtime=Q.w,ed.typeName="yorkie.v1.Operation.Remove",ed.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"executed_at",kind:"message",T:ej}]);class eu extends X.v{static fromBinary(e,t){return new eu().fromBinary(e,t)}static fromJson(e,t){return new eu().fromJson(e,t)}static fromJsonString(e,t){return new eu().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eu,e,t)}constructor(e){super(),this.createdAtMapByActor={},this.content="",this.attributes={},Q.w.util.initPartial(e,this)}}eu.runtime=Q.w,eu.typeName="yorkie.v1.Operation.Edit",eu.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}},{no:5,name:"content",kind:"scalar",T:9},{no:6,name:"executed_at",kind:"message",T:ej},{no:7,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]);class eg extends X.v{static fromBinary(e,t){return new eg().fromBinary(e,t)}static fromJson(e,t){return new eg().fromJson(e,t)}static fromJsonString(e,t){return new eg().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eg,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eg.runtime=Q.w,eg.typeName="yorkie.v1.Operation.Select",eg.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"executed_at",kind:"message",T:ej}]);class ef extends X.v{static fromBinary(e,t){return new ef().fromBinary(e,t)}static fromJson(e,t){return new ef().fromJson(e,t)}static fromJsonString(e,t){return new ef().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ef,e,t)}constructor(e){super(),this.attributes={},this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}ef.runtime=Q.w,ef.typeName="yorkie.v1.Operation.Style",ef.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:ej},{no:6,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}}]);class em extends X.v{static fromBinary(e,t){return new em().fromBinary(e,t)}static fromJson(e,t){return new em().fromJson(e,t)}static fromJsonString(e,t){return new em().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(em,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}em.runtime=Q.w,em.typeName="yorkie.v1.Operation.Increase",em.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"value",kind:"message",T:ew},{no:3,name:"executed_at",kind:"message",T:ej}]);class ep extends X.v{static fromBinary(e,t){return new ep().fromBinary(e,t)}static fromJson(e,t){return new ep().fromJson(e,t)}static fromJsonString(e,t){return new ep().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ep,e,t)}constructor(e){super(),this.createdAtMapByActor={},this.contents=[],this.splitLevel=0,Q.w.util.initPartial(e,this)}}ep.runtime=Q.w,ep.typeName="yorkie.v1.Operation.TreeEdit",ep.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eJ},{no:3,name:"to",kind:"message",T:eJ},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}},{no:5,name:"contents",kind:"message",T:eO,repeated:!0},{no:7,name:"split_level",kind:"scalar",T:5},{no:6,name:"executed_at",kind:"message",T:ej}]);class ey extends X.v{static fromBinary(e,t){return new ey().fromBinary(e,t)}static fromJson(e,t){return new ey().fromJson(e,t)}static fromJsonString(e,t){return new ey().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ey,e,t)}constructor(e){super(),this.attributes={},this.attributesToRemove=[],this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}ey.runtime=Q.w,ey.typeName="yorkie.v1.Operation.TreeStyle",ey.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eJ},{no:3,name:"to",kind:"message",T:eJ},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:ej},{no:6,name:"attributes_to_remove",kind:"scalar",T:9,repeated:!0},{no:7,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}}]);class ev extends X.v{static fromBinary(e,t){return new ev().fromBinary(e,t)}static fromJson(e,t){return new ev().fromJson(e,t)}static fromJsonString(e,t){return new ev().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ev,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}ev.runtime=Q.w,ev.typeName="yorkie.v1.Operation.ArraySet",ev.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class ew extends X.v{static fromBinary(e,t){return new ew().fromBinary(e,t)}static fromJson(e,t){return new ew().fromJson(e,t)}static fromJsonString(e,t){return new ew().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ew,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ew.runtime=Q.w,ew.typeName="yorkie.v1.JSONElementSimple",ew.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"moved_at",kind:"message",T:ej},{no:3,name:"removed_at",kind:"message",T:ej},{no:4,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:5,name:"value",kind:"scalar",T:12}]);class eA extends X.v{static fromBinary(e,t){return new eA().fromBinary(e,t)}static fromJson(e,t){return new eA().fromJson(e,t)}static fromJsonString(e,t){return new eA().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eA,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}eA.runtime=Q.w,eA.typeName="yorkie.v1.JSONElement",eA.fields=Q.w.util.newFieldList(()=>[{no:1,name:"json_object",kind:"message",T:eT,oneof:"body"},{no:2,name:"json_array",kind:"message",T:eS,oneof:"body"},{no:3,name:"primitive",kind:"message",T:eI,oneof:"body"},{no:5,name:"text",kind:"message",T:eC,oneof:"body"},{no:6,name:"counter",kind:"message",T:ex,oneof:"body"},{no:7,name:"tree",kind:"message",T:eP,oneof:"body"}]);class eT extends X.v{static fromBinary(e,t){return new eT().fromBinary(e,t)}static fromJson(e,t){return new eT().fromJson(e,t)}static fromJsonString(e,t){return new eT().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eT,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eT.runtime=Q.w,eT.typeName="yorkie.v1.JSONElement.JSONObject",eT.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eE,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eS extends X.v{static fromBinary(e,t){return new eS().fromBinary(e,t)}static fromJson(e,t){return new eS().fromJson(e,t)}static fromJsonString(e,t){return new eS().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eS,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eS.runtime=Q.w,eS.typeName="yorkie.v1.JSONElement.JSONArray",eS.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eb,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eI extends X.v{static fromBinary(e,t){return new eI().fromBinary(e,t)}static fromJson(e,t){return new eI().fromJson(e,t)}static fromJsonString(e,t){return new eI().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eI,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eI.runtime=Q.w,eI.typeName="yorkie.v1.JSONElement.Primitive",eI.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"moved_at",kind:"message",T:ej},{no:5,name:"removed_at",kind:"message",T:ej}]);class eC extends X.v{static fromBinary(e,t){return new eC().fromBinary(e,t)}static fromJson(e,t){return new eC().fromJson(e,t)}static fromJsonString(e,t){return new eC().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eC,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eC.runtime=Q.w,eC.typeName="yorkie.v1.JSONElement.Text",eC.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eD,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class ex extends X.v{static fromBinary(e,t){return new ex().fromBinary(e,t)}static fromJson(e,t){return new ex().fromJson(e,t)}static fromJsonString(e,t){return new ex().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ex,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ex.runtime=Q.w,ex.typeName="yorkie.v1.JSONElement.Counter",ex.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"moved_at",kind:"message",T:ej},{no:5,name:"removed_at",kind:"message",T:ej}]);class eP extends X.v{static fromBinary(e,t){return new eP().fromBinary(e,t)}static fromJson(e,t){return new eP().fromJson(e,t)}static fromJsonString(e,t){return new eP().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eP,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eP.runtime=Q.w,eP.typeName="yorkie.v1.JSONElement.Tree",eP.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eN,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eE extends X.v{static fromBinary(e,t){return new eE().fromBinary(e,t)}static fromJson(e,t){return new eE().fromJson(e,t)}static fromJsonString(e,t){return new eE().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eE,e,t)}constructor(e){super(),this.key="",Q.w.util.initPartial(e,this)}}eE.runtime=Q.w,eE.typeName="yorkie.v1.RHTNode",eE.fields=Q.w.util.newFieldList(()=>[{no:1,name:"key",kind:"scalar",T:9},{no:2,name:"element",kind:"message",T:eA}]);class eb extends X.v{static fromBinary(e,t){return new eb().fromBinary(e,t)}static fromJson(e,t){return new eb().fromJson(e,t)}static fromJsonString(e,t){return new eb().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eb,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eb.runtime=Q.w,eb.typeName="yorkie.v1.RGANode",eb.fields=Q.w.util.newFieldList(()=>[{no:1,name:"next",kind:"message",T:eb},{no:2,name:"element",kind:"message",T:eA}]);class ek extends X.v{static fromBinary(e,t){return new ek().fromBinary(e,t)}static fromJson(e,t){return new ek().fromJson(e,t)}static fromJsonString(e,t){return new ek().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ek,e,t)}constructor(e){super(),this.value="",this.isRemoved=!1,Q.w.util.initPartial(e,this)}}ek.runtime=Q.w,ek.typeName="yorkie.v1.NodeAttr",ek.fields=Q.w.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:9},{no:2,name:"updated_at",kind:"message",T:ej},{no:3,name:"is_removed",kind:"scalar",T:8}]);class eD extends X.v{static fromBinary(e,t){return new eD().fromBinary(e,t)}static fromJson(e,t){return new eD().fromJson(e,t)}static fromJsonString(e,t){return new eD().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eD,e,t)}constructor(e){super(),this.value="",this.attributes={},Q.w.util.initPartial(e,this)}}eD.runtime=Q.w,eD.typeName="yorkie.v1.TextNode",eD.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:eR},{no:2,name:"value",kind:"scalar",T:9},{no:3,name:"removed_at",kind:"message",T:ej},{no:4,name:"ins_prev_id",kind:"message",T:eR},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"message",T:ek}}]);class eR extends X.v{static fromBinary(e,t){return new eR().fromBinary(e,t)}static fromJson(e,t){return new eR().fromJson(e,t)}static fromJsonString(e,t){return new eR().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eR,e,t)}constructor(e){super(),this.offset=0,Q.w.util.initPartial(e,this)}}eR.runtime=Q.w,eR.typeName="yorkie.v1.TextNodeID",eR.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5}]);class eN extends X.v{static fromBinary(e,t){return new eN().fromBinary(e,t)}static fromJson(e,t){return new eN().fromJson(e,t)}static fromJsonString(e,t){return new eN().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eN,e,t)}constructor(e){super(),this.type="",this.value="",this.depth=0,this.attributes={},Q.w.util.initPartial(e,this)}}eN.runtime=Q.w,eN.typeName="yorkie.v1.TreeNode",eN.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:eB},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"value",kind:"scalar",T:9},{no:4,name:"removed_at",kind:"message",T:ej},{no:5,name:"ins_prev_id",kind:"message",T:eB},{no:6,name:"ins_next_id",kind:"message",T:eB},{no:7,name:"depth",kind:"scalar",T:5},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"message",T:ek}}]);class eO extends X.v{static fromBinary(e,t){return new eO().fromBinary(e,t)}static fromJson(e,t){return new eO().fromJson(e,t)}static fromJsonString(e,t){return new eO().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eO,e,t)}constructor(e){super(),this.content=[],Q.w.util.initPartial(e,this)}}eO.runtime=Q.w,eO.typeName="yorkie.v1.TreeNodes",eO.fields=Q.w.util.newFieldList(()=>[{no:1,name:"content",kind:"message",T:eN,repeated:!0}]);class eB extends X.v{static fromBinary(e,t){return new eB().fromBinary(e,t)}static fromJson(e,t){return new eB().fromJson(e,t)}static fromJsonString(e,t){return new eB().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eB,e,t)}constructor(e){super(),this.offset=0,Q.w.util.initPartial(e,this)}}eB.runtime=Q.w,eB.typeName="yorkie.v1.TreeNodeID",eB.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5}]);class eJ extends X.v{static fromBinary(e,t){return new eJ().fromBinary(e,t)}static fromJson(e,t){return new eJ().fromJson(e,t)}static fromJsonString(e,t){return new eJ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eJ,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eJ.runtime=Q.w,eJ.typeName="yorkie.v1.TreePos",eJ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_id",kind:"message",T:eB},{no:2,name:"left_sibling_id",kind:"message",T:eB}]);class eL extends X.v{static fromBinary(e,t){return new eL().fromBinary(e,t)}static fromJson(e,t){return new eL().fromJson(e,t)}static fromJsonString(e,t){return new eL().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eL,e,t)}constructor(e){super(),this.id="",this.username="",Q.w.util.initPartial(e,this)}}eL.runtime=Q.w,eL.typeName="yorkie.v1.User",eL.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"created_at",kind:"message",T:ee.E}]);class e_ extends X.v{static fromBinary(e,t){return new e_().fromBinary(e,t)}static fromJson(e,t){return new e_().fromJson(e,t)}static fromJsonString(e,t){return new e_().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e_,e,t)}constructor(e){super(),this.id="",this.name="",this.publicKey="",this.secretKey="",this.authWebhookUrl="",this.authWebhookMethods=[],this.clientDeactivateThreshold="",Q.w.util.initPartial(e,this)}}e_.runtime=Q.w,e_.typeName="yorkie.v1.Project",e_.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"public_key",kind:"scalar",T:9},{no:4,name:"secret_key",kind:"scalar",T:9},{no:5,name:"auth_webhook_url",kind:"scalar",T:9},{no:6,name:"auth_webhook_methods",kind:"scalar",T:9,repeated:!0},{no:7,name:"client_deactivate_threshold",kind:"scalar",T:9},{no:8,name:"created_at",kind:"message",T:ee.E},{no:9,name:"updated_at",kind:"message",T:ee.E}]);class eM extends X.v{static fromBinary(e,t){return new eM().fromBinary(e,t)}static fromJson(e,t){return new eM().fromJson(e,t)}static fromJsonString(e,t){return new eM().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eM,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eM.runtime=Q.w,eM.typeName="yorkie.v1.UpdatableProjectFields",eM.fields=Q.w.util.newFieldList(()=>[{no:1,name:"name",kind:"message",T:et.Gm},{no:2,name:"auth_webhook_url",kind:"message",T:et.Gm},{no:3,name:"auth_webhook_methods",kind:"message",T:eq},{no:4,name:"client_deactivate_threshold",kind:"message",T:et.Gm}]);class eq extends X.v{static fromBinary(e,t){return new eq().fromBinary(e,t)}static fromJson(e,t){return new eq().fromJson(e,t)}static fromJsonString(e,t){return new eq().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eq,e,t)}constructor(e){super(),this.methods=[],Q.w.util.initPartial(e,this)}}eq.runtime=Q.w,eq.typeName="yorkie.v1.UpdatableProjectFields.AuthWebhookMethods",eq.fields=Q.w.util.newFieldList(()=>[{no:1,name:"methods",kind:"scalar",T:9,repeated:!0}]);class ez extends X.v{static fromBinary(e,t){return new ez().fromBinary(e,t)}static fromJson(e,t){return new ez().fromJson(e,t)}static fromJsonString(e,t){return new ez().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ez,e,t)}constructor(e){super(),this.id="",this.key="",this.snapshot="",Q.w.util.initPartial(e,this)}}ez.runtime=Q.w,ez.typeName="yorkie.v1.DocumentSummary",ez.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"snapshot",kind:"scalar",T:9},{no:4,name:"created_at",kind:"message",T:ee.E},{no:5,name:"accessed_at",kind:"message",T:ee.E},{no:6,name:"updated_at",kind:"message",T:ee.E}]);class eK extends X.v{static fromBinary(e,t){return new eK().fromBinary(e,t)}static fromJson(e,t){return new eK().fromJson(e,t)}static fromJsonString(e,t){return new eK().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eK,e,t)}constructor(e){super(),this.type=0,Q.w.util.initPartial(e,this)}}eK.runtime=Q.w,eK.typeName="yorkie.v1.PresenceChange",eK.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(C)},{no:2,name:"presence",kind:"message",T:eF}]),(s=C||(C={}))[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.PUT=1]="PUT",s[s.DELETE=2]="DELETE",s[s.CLEAR=3]="CLEAR",Q.w.util.setEnumType(C,"yorkie.v1.PresenceChange.ChangeType",[{no:0,name:"CHANGE_TYPE_UNSPECIFIED"},{no:1,name:"CHANGE_TYPE_PUT"},{no:2,name:"CHANGE_TYPE_DELETE"},{no:3,name:"CHANGE_TYPE_CLEAR"}]);class eF extends X.v{static fromBinary(e,t){return new eF().fromBinary(e,t)}static fromJson(e,t){return new eF().fromJson(e,t)}static fromJsonString(e,t){return new eF().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eF,e,t)}constructor(e){super(),this.data={},Q.w.util.initPartial(e,this)}}eF.runtime=Q.w,eF.typeName="yorkie.v1.Presence",eF.fields=Q.w.util.newFieldList(()=>[{no:1,name:"data",kind:"map",K:9,V:{kind:"scalar",T:9}}]);class eV extends X.v{static fromBinary(e,t){return new eV().fromBinary(e,t)}static fromJson(e,t){return new eV().fromJson(e,t)}static fromJsonString(e,t){return new eV().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eV,e,t)}constructor(e){super(),this.serverSeq=$.q.zero,this.clientSeq=0,Q.w.util.initPartial(e,this)}}eV.runtime=Q.w,eV.typeName="yorkie.v1.Checkpoint",eV.fields=Q.w.util.newFieldList(()=>[{no:1,name:"server_seq",kind:"scalar",T:3},{no:2,name:"client_seq",kind:"scalar",T:13}]);class eU extends X.v{static fromBinary(e,t){return new eU().fromBinary(e,t)}static fromJson(e,t){return new eU().fromJson(e,t)}static fromJsonString(e,t){return new eU().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eU,e,t)}constructor(e){super(),this.offset=0,this.relativeOffset=0,Q.w.util.initPartial(e,this)}}eU.runtime=Q.w,eU.typeName="yorkie.v1.TextNodePos",eU.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5},{no:3,name:"relative_offset",kind:"scalar",T:5}]);class ej extends X.v{static fromBinary(e,t){return new ej().fromBinary(e,t)}static fromJson(e,t){return new ej().fromJson(e,t)}static fromJsonString(e,t){return new ej().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ej,e,t)}constructor(e){super(),this.lamport=$.q.zero,this.delimiter=0,this.actorId=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ej.runtime=Q.w,ej.typeName="yorkie.v1.TimeTicket",ej.fields=Q.w.util.newFieldList(()=>[{no:1,name:"lamport",kind:"scalar",T:3},{no:2,name:"delimiter",kind:"scalar",T:13},{no:3,name:"actor_id",kind:"scalar",T:12}]);class eW extends X.v{static fromBinary(e,t){return new eW().fromBinary(e,t)}static fromJson(e,t){return new eW().fromJson(e,t)}static fromJsonString(e,t){return new eW().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eW,e,t)}constructor(e){super(),this.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eW.runtime=Q.w,eW.typeName="yorkie.v1.DocEventBody",eW.fields=Q.w.util.newFieldList(()=>[{no:1,name:"topic",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12}]);class eG extends X.v{static fromBinary(e,t){return new eG().fromBinary(e,t)}static fromJson(e,t){return new eG().fromJson(e,t)}static fromJsonString(e,t){return new eG().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eG,e,t)}constructor(e){super(),this.type=0,this.publisher="",Q.w.util.initPartial(e,this)}}eG.runtime=Q.w,eG.typeName="yorkie.v1.DocEvent",eG.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(I)},{no:2,name:"publisher",kind:"scalar",T:9},{no:3,name:"body",kind:"message",T:eW}]);class eH extends X.v{static fromBinary(e,t){return new eH().fromBinary(e,t)}static fromJson(e,t){return new eH().fromJson(e,t)}static fromJsonString(e,t){return new eH().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eH,e,t)}constructor(e){super(),this.clientKey="",Q.w.util.initPartial(e,this)}}eH.runtime=Q.w,eH.typeName="yorkie.v1.ActivateClientRequest",eH.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_key",kind:"scalar",T:9}]);class eY extends X.v{static fromBinary(e,t){return new eY().fromBinary(e,t)}static fromJson(e,t){return new eY().fromJson(e,t)}static fromJsonString(e,t){return new eY().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eY,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eY.runtime=Q.w,eY.typeName="yorkie.v1.ActivateClientResponse",eY.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]);class eZ extends X.v{static fromBinary(e,t){return new eZ().fromBinary(e,t)}static fromJson(e,t){return new eZ().fromJson(e,t)}static fromJsonString(e,t){return new eZ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eZ,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eZ.runtime=Q.w,eZ.typeName="yorkie.v1.DeactivateClientRequest",eZ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]);class eX extends X.v{static fromBinary(e,t){return new eX().fromBinary(e,t)}static fromJson(e,t){return new eX().fromJson(e,t)}static fromJsonString(e,t){return new eX().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eX,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eX.runtime=Q.w,eX.typeName="yorkie.v1.DeactivateClientResponse",eX.fields=Q.w.util.newFieldList(()=>[]);class eQ extends X.v{static fromBinary(e,t){return new eQ().fromBinary(e,t)}static fromJson(e,t){return new eQ().fromJson(e,t)}static fromJsonString(e,t){return new eQ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eQ,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eQ.runtime=Q.w,eQ.typeName="yorkie.v1.AttachDocumentRequest",eQ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:en}]);class e$ extends X.v{static fromBinary(e,t){return new e$().fromBinary(e,t)}static fromJson(e,t){return new e$().fromJson(e,t)}static fromJsonString(e,t){return new e$().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e$,e,t)}constructor(e){super(),this.documentId="",Q.w.util.initPartial(e,this)}}e$.runtime=Q.w,e$.typeName="yorkie.v1.AttachDocumentResponse",e$.fields=Q.w.util.newFieldList(()=>[{no:1,name:"document_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:en}]);class e0 extends X.v{static fromBinary(e,t){return new e0().fromBinary(e,t)}static fromJson(e,t){return new e0().fromJson(e,t)}static fromJsonString(e,t){return new e0().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e0,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.removeIfNotAttached=!1,Q.w.util.initPartial(e,this)}}e0.runtime=Q.w,e0.typeName="yorkie.v1.DetachDocumentRequest",e0.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:en},{no:4,name:"remove_if_not_attached",kind:"scalar",T:8}]);class e1 extends X.v{static fromBinary(e,t){return new e1().fromBinary(e,t)}static fromJson(e,t){return new e1().fromJson(e,t)}static fromJsonString(e,t){return new e1().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e1,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e1.runtime=Q.w,e1.typeName="yorkie.v1.DetachDocumentResponse",e1.fields=Q.w.util.newFieldList(()=>[{no:2,name:"change_pack",kind:"message",T:en}]);class e2 extends X.v{static fromBinary(e,t){return new e2().fromBinary(e,t)}static fromJson(e,t){return new e2().fromJson(e,t)}static fromJsonString(e,t){return new e2().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e2,e,t)}constructor(e){super(),this.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e2.runtime=Q.w,e2.typeName="yorkie.v1.WatchDocumentRequest",e2.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9}]);class e3 extends X.v{static fromBinary(e,t){return new e3().fromBinary(e,t)}static fromJson(e,t){return new e3().fromJson(e,t)}static fromJsonString(e,t){return new e3().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e3,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}e3.runtime=Q.w,e3.typeName="yorkie.v1.WatchDocumentResponse",e3.fields=Q.w.util.newFieldList(()=>[{no:1,name:"initialization",kind:"message",T:e9,oneof:"body"},{no:2,name:"event",kind:"message",T:eG,oneof:"body"}]);class e9 extends X.v{static fromBinary(e,t){return new e9().fromBinary(e,t)}static fromJson(e,t){return new e9().fromJson(e,t)}static fromJsonString(e,t){return new e9().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e9,e,t)}constructor(e){super(),this.clientIds=[],Q.w.util.initPartial(e,this)}}e9.runtime=Q.w,e9.typeName="yorkie.v1.WatchDocumentResponse.Initialization",e9.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_ids",kind:"scalar",T:9,repeated:!0}]);class e4 extends X.v{static fromBinary(e,t){return new e4().fromBinary(e,t)}static fromJson(e,t){return new e4().fromJson(e,t)}static fromJsonString(e,t){return new e4().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e4,e,t)}constructor(e){super(),this.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e4.runtime=Q.w,e4.typeName="yorkie.v1.RemoveDocumentRequest",e4.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:en}]);class e8 extends X.v{static fromBinary(e,t){return new e8().fromBinary(e,t)}static fromJson(e,t){return new e8().fromJson(e,t)}static fromJsonString(e,t){return new e8().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e8,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e8.runtime=Q.w,e8.typeName="yorkie.v1.RemoveDocumentResponse",e8.fields=Q.w.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:en}]);class e5 extends X.v{static fromBinary(e,t){return new e5().fromBinary(e,t)}static fromJson(e,t){return new e5().fromJson(e,t)}static fromJsonString(e,t){return new e5().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e5,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.pushOnly=!1,Q.w.util.initPartial(e,this)}}e5.runtime=Q.w,e5.typeName="yorkie.v1.PushPullChangesRequest",e5.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:en},{no:4,name:"push_only",kind:"scalar",T:8}]);class e6 extends X.v{static fromBinary(e,t){return new e6().fromBinary(e,t)}static fromJson(e,t){return new e6().fromJson(e,t)}static fromJsonString(e,t){return new e6().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e6,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e6.runtime=Q.w,e6.typeName="yorkie.v1.PushPullChangesResponse",e6.fields=Q.w.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:en}]);class e7 extends X.v{static fromBinary(e,t){return new e7().fromBinary(e,t)}static fromJson(e,t){return new e7().fromJson(e,t)}static fromJsonString(e,t){return new e7().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e7,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}e7.runtime=Q.w,e7.typeName="yorkie.v1.BroadcastRequest",e7.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}]);class te extends X.v{static fromBinary(e,t){return new te().fromBinary(e,t)}static fromJson(e,t){return new te().fromJson(e,t)}static fromJsonString(e,t){return new te().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(te,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}te.runtime=Q.w,te.typeName="yorkie.v1.BroadcastResponse",te.fields=Q.w.util.newFieldList(()=>[]);var tt=r(6438);let tr={typeName:"yorkie.v1.YorkieService",methods:{activateClient:{name:"ActivateClient",I:eH,O:eY,kind:tt.t.Unary},deactivateClient:{name:"DeactivateClient",I:eZ,O:eX,kind:tt.t.Unary},attachDocument:{name:"AttachDocument",I:eQ,O:e$,kind:tt.t.Unary},detachDocument:{name:"DetachDocument",I:e0,O:e1,kind:tt.t.Unary},removeDocument:{name:"RemoveDocument",I:e4,O:e8,kind:tt.t.Unary},pushPullChanges:{name:"PushPullChanges",I:e5,O:e6,kind:tt.t.Unary},watchDocument:{name:"WatchDocument",I:e2,O:e3,kind:tt.t.ServerStreaming},broadcast:{name:"Broadcast",I:e7,O:te,kind:tt.t.Unary}}};var tn=r(624);(o=x||(x={})).Ok="ok",o.ErrClientNotActivated="ErrClientNotActivated",o.ErrClientNotFound="ErrClientNotFound",o.ErrUnimplemented="ErrUnimplemented",o.ErrInvalidType="ErrInvalidType",o.ErrDummy="ErrDummy",o.ErrDocumentNotAttached="ErrDocumentNotAttached",o.ErrDocumentNotDetached="ErrDocumentNotDetached",o.ErrDocumentRemoved="ErrDocumentRemoved",o.ErrInvalidObjectKey="ErrInvalidObjectKey",o.ErrInvalidArgument="ErrInvalidArgument",o.ErrNotInitialized="ErrNotInitialized",o.ErrNotReady="ErrNotReady",o.ErrRefused="ErrRefused",o.ErrContextNotProvided="ErrContextNotProvided";class ti extends Error{constructor(e,t){super(t),this.code=e,this.message=t,this.name="YorkieError",this.toString=()=>"[code=".concat(this.code,"]: ").concat(this.message)}}function ts(e){if(e instanceof Map){let t=Array.from(e);return new Map(JSON.parse(JSON.stringify(t)))}return JSON.parse(JSON.stringify(e))}let to=e=>!e||0===Object.entries(e).length,ta=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.stringify(n);return t},tc=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.parse(n);return t};(a=P||(P={})).Put="put",a.Clear="clear";class tl{set(e,t){for(let t of Object.keys(e))this.presence[t]=e[t];this.context.setPresenceChange({type:"put",presence:ts(this.presence)}),this.context.setReversePresence(e,t)}get(e){return this.presence[e]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}constructor(e,t){this.context=e,this.presence=t}}let th="000000000000000000000000";class td{static of(e,t,r){return new td(e,t,r)}static fromStruct(e){return td.of(BigInt(e.lamport),e.delimiter,e.actorID)}toIDString(){return"".concat(this.lamport.toString(),":").concat(this.actorID,":").concat(this.delimiter)}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actorID.slice(-2),":").concat(this.delimiter)}setActor(e){return new td(this.lamport,this.delimiter,e)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(e){return this.compare(e)>0}equals(e){return 0===this.compare(e)}compare(e){if(this.lamport>e.lamport)return 1;if(e.lamport>this.lamport)return -1;let t=this.actorID.localeCompare(e.actorID);return 0!==t?t:this.delimiter>e.delimiter?1:e.delimiter>this.delimiter?-1:0}constructor(e,t,r){this.lamport=e,this.delimiter=t,this.actorID=r}}let tu=new td(0n,0,th),tg=new td(0x7fffffffffffffffn,4294967295,"FFFFFFFFFFFFFFFFFFFFFFFF");function tf(e){return e.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(e){switch(e){case'"':case"\\":return"\\"+e;case"\n":return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class tm{getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!!(!this.movedAt||e&&e.after(this.movedAt))&&(this.movedAt=e,!0)}setRemovedAt(e){this.removedAt=e}remove(e){return!!(e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt)))&&(this.removedAt=e,!0)}isRemoved(){return!!this.removedAt}constructor(e){this.createdAt=e}}class tp extends tm{constructor(e){super(e)}}class ty{static of(e,t){return new ty(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}constructor(e,t){this.strKey=e,this.value=t}}class tv{static create(){return new tv}set(e,t,r){let n;let i=this.nodeMapByKey.get(e);null!=i&&!i.isRemoved()&&i.remove(r)&&(n=i.getValue());let s=ty.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),s),(null==i||r.after(i.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,s),t.setMovedAt(r)),n}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new ti(x.ErrInvalidArgument,"fail to find ".concat(e.toIDString()));let r=this.nodeMapByCreatedAt.get(e.toIDString());return r.remove(t),r.getValue()}subPathOf(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){let t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(e.getCreatedAt().toIDString()));let r=this.nodeMapByKey.get(t.getStrKey());t===r&&this.nodeMapByKey.delete(r.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){let r=this.nodeMapByKey.get(e);if(null!=r&&r.remove(t))return r.getValue()}has(e){let t=this.nodeMapByKey.get(e);return null!=t&&!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){let t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(let[,e]of this.nodeMapByKey)yield e}constructor(){this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}}class tw extends tp{static create(e,t){if(!t)return new tw(e,tv.create());let r=tv.create();for(let[e,n]of Object.entries(t))r.set(e,n.deepcopy(),n.getCreatedAt());return new tw(e,r)}subPathOf(e){return this.memberNodes.subPathOf(e)}purge(e){this.memberNodes.purge(e)}set(e,t,r){return this.memberNodes.set(e,t,r)}delete(e,t){return this.memberNodes.delete(e,t)}deleteByKey(e,t){return this.memberNodes.deleteByKey(e,t)}get(e){let t=this.memberNodes.get(e);return null==t?void 0:t.getValue()}getByID(e){let t=this.memberNodes.getByID(e);return null==t?void 0:t.getValue()}has(e){return this.memberNodes.has(e)}toJSON(){let e=[];for(let[t,r]of this)e.push('"'.concat(tf(t),'":').concat(r.toJSON()));return"{".concat(e.join(","),"}")}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){let e={};for(let[t,r]of this){let{createdAt:n,value:i,type:s}=r.toJSForTest();e[t]={key:t,createdAt:n,value:i,type:s}}return{createdAt:this.getCreatedAt().toTestString(),value:e,type:"YORKIE_OBJECT"}}getKeys(){let e=[];for(let[t]of this)e.push(t);return e}toSortedJSON(){let e=[];for(let[t]of this)e.push(t);let t=[];for(let n of e.sort()){var r;let e=null===(r=this.memberNodes.get(n))||void 0===r?void 0:r.getValue();t.push('"'.concat(tf(n),'":').concat(e.toSortedJSON()))}return"{".concat(t.join(","),"}")}getRHT(){return this.memberNodes}deepcopy(){let e=tw.create(this.getCreatedAt());for(let t of this.memberNodes)e.memberNodes.set(t.getStrKey(),t.getValue().deepcopy(),this.getPositionedAt());return e.remove(this.getRemovedAt()),e}getDescendants(e){for(let t of this.memberNodes){let r=t.getValue();if(e(r,this))return;r instanceof tp&&r.getDescendants(e)}}*[Symbol.iterator](){let e=new Set;for(let t of this.memberNodes)e.has(t.getStrKey())||(e.add(t.getStrKey()),t.isRemoved()||(yield[t.getStrKey(),t.getValue()]))}constructor(e,t){super(e),this.memberNodes=t}}(c=E||(E={})).Local="local",c.Remote="remote",c.UndoRedo="undoredo";class tA{getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new ti(x.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}constructor(e,t){this.parentCreatedAt=e,this.executedAt=t}}class tT{getNodeString(){return"".concat(this.weight).concat(this.value)}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}constructor(e){this.value=e,this.initWeight()}}class tS{get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new ti(x.ErrInvalidArgument,"out of index range: pos: ".concat(e," > node.length: ").concat(t.getLength()));return this.splayNode(t),[t,e]}indexOf(e){return e&&(e===this.root||e.hasLinks())?(this.splayNode(e),this.root.getLeftWeight()):-1}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t)):this.root=t,t}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);let t=new tS(e.getLeft());t.root&&t.root.setParent();let r=new tS(e.getRight());if(r.root&&r.root.setParent(),t.root){let e=t.getRightmost();t.splayNode(e),t.root.setRight(r.root),r.root&&r.root.setParent(t.root),this.root=t.root}else this.root=r.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){let t=[];for(let r of(this.traversePostorder(e.getRight(),t),t))r.initWeight();this.updateTreeWeight(e)}toTestString(){let e=[];return this.traverseInorder(this.root,e),e.map(e=>"[".concat(e.getWeight(),",").concat(e.getLength(),"]").concat(e.getValue()||"")).join("")}checkWeight(){let e=[];for(let t of(this.traverseInorder(this.root,e),e))if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){let t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){let t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return!!(e&&e.hasParent())&&e.getParent().getLeft()===e}isRightChild(e){return!!(e&&e.hasParent())&&e.getParent().getRight()===e}constructor(e){this.root=e}}var tI=r(7319);(l=b||(b={}))[l.Null=0]="Null",l[l.Boolean=1]="Boolean",l[l.Integer=2]="Integer",l[l.Long=3]="Long",l[l.Double=4]="Double",l[l.String=5]="String",l[l.Bytes=6]="Bytes",l[l.Date=7]="Date";class tC extends tm{static of(e,t){return new tC(e,t)}static valueFromBytes(e,t){switch(e){case 0:return null;case 1:return!!t[0];case 2:return t[0]|t[1]<<8|t[2]<<16|t[3]<<24;case 4:{let e=new DataView(t.buffer);return t.forEach(function(t,r){e.setUint8(r,t)}),e.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(t);case 3:return tI.Z.fromBytesLE(Array.from(t));case 6:return t;case 7:return new Date(tI.Z.fromBytesLE(Array.from(t),!0).toNumber());default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}toJSON(){return 5===this.valueType?'"'.concat(tf(this.value),'"'):"".concat(this.value)}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){let e=tC.of(this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e.setRemovedAt(this.getRemovedAt()),e}getType(){return this.valueType}static getPrimitiveType(e){switch(typeof e){case"undefined":return 0;case"boolean":return 1;case"number":if(this.isInteger(e))return 2;return 4;case"string":return 5;case"object":if(null===e)return 0;if(e instanceof tI.Z)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return void 0!==tC.getPrimitiveType(e)}static isInteger(e){return e%1==0}isNumericType(){let e=this.valueType;return 2===e||3===e||4===e}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:{let e=this.value;return new Uint8Array(e?[1]:[0])}case 2:{let e=this.value;return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}case 4:{let e=this.value,t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),t}case 5:return new TextEncoder().encode(this.value);case 3:{let e=this.value.toBytesLE();return Uint8Array.from(e)}case 6:return this.value;case 7:{let e=this.value,t=tI.Z.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(t)}default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(this.valueType))}}constructor(e,t){super(t),this.valueType=tC.getPrimitiveType(e),this.value=void 0===e?null:e}}class tx extends tT{static createAfter(e,t){let r=new tx(t),n=e.next;return e.next=r,r.prev=e,r.next=n,n&&(n.prev=r),r}remove(e){return this.value.remove(e)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}constructor(e){super(e),this.value=e}}class tP{static create(){return new tP}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new ti(x.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));for(;r.getNext()&&r.getNext().getPositionedAt().after(t);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.getCreatedAt(),n=this.findNextBeforeExecutedAt(e,r),i=tx.createAfter(n,t);n===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(n,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(e,t,r){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new ti(x.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));let i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new ti(x.ErrInvalidArgument,"cant find the given node: ".concat(t.toIDString()));n!==i&&(!i.getValue().getMovedAt()||r.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(n.getCreatedAt(),i.getValue(),r),i.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){let t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find the given createdAt: ".concat(e.getCreatedAt().toIDString()));this.release(t)}getByIndex(e){if(e>=this.length)return;let[t,r]=this.nodeMapByIndex.find(e),n=t;if(0===e&&t===this.dummyHead||r>0)do n&&(n=n.getNext());while(n&&n.isRemoved());return n}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString()),n=r.isRemoved();return r.remove(t)&&!n&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,t){let r=this.getByIndex(e);if(r)return r.remove(t)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){let e=[];for(let t of this){let r="".concat(t.getCreatedAt().toIDString(),":").concat(t.getValue().toJSON());t.isRemoved()?e.push("{".concat(r,"}")):e.push("[".concat(r,"]"))}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}constructor(){let e=tC.of(0,tu);e.setRemovedAt(tu),this.dummyHead=new tx(e),this.last=this.dummyHead,this.nodeMapByIndex=new tS,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}}class tE extends tp{static create(e,t){if(!t)return new tE(e,tP.create());let r=tP.create();for(let e of t)r.insertAfter(r.getLastCreatedAt(),e.deepcopy());return new tE(e,r)}subPathOf(e){return this.elements.subPathOf(e)}purge(e){this.elements.purge(e)}insertAfter(e,t){this.elements.insertAfter(e,t)}moveAfter(e,t,r){this.elements.moveAfter(e,t,r)}get(e){let t=this.elements.getByIndex(e);return null==t?void 0:t.getValue()}getByID(e){let t=this.elements.getByID(e);return null==t?void 0:t.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(e){return this.elements.getPrevCreatedAt(e)}delete(e,t){return this.elements.delete(e,t)}deleteByIndex(e,t){return this.elements.deleteByIndex(e,t)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(let e of this.elements)e.isRemoved()||(yield e.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(e){for(let t of this.elements){let r=t.getValue();if(e(r,this))return;r instanceof tp&&r.getDescendants(e)}}toJSON(){let e=[];for(let t of this)e.push(t.toJSON());return"[".concat(e.join(","),"]")}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){let e={};for(let t=0;t({...e,value:e.value?{attributes:tc(e.value.getAttributes()),content:e.value.getContent()}:{attributes:void 0,content:""},type:"content"})),c,[o,o]]}setStyle(e,t,r,n){let[,i]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,s]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),o=[],a=this.rgaTreeSplit.findBetween(s,i),c=new Map,l=[];for(let e of a){let t=e.getCreatedAt().getActorID(),i=(null==n?void 0:n.size)?n.has(t)?n.get(t):tu:tg;if(e.canStyle(r,i)){let r=c.get(t),n=e.getCreatedAt();(!r||n.after(r))&&c.set(t,n),l.push(e)}}let h=[];for(let e of l){if(e.isRemoved())continue;let[n,i]=this.rgaTreeSplit.findIndexesFromRange(e.createPosRange());for(let[s,a]of(o.push({type:"style",actor:r.getActorID(),from:n,to:i,value:{attributes:tc(t)}}),Object.entries(t))){let[t]=e.getValue().setAttr(s,a,r);void 0!==t&&h.push({parent:e.getValue(),child:t})}}return[c,h,o]}indexRangeToPosRange(e,t){let r=this.rgaTreeSplit.indexToPos(e);return e===t?[r,r]:[r,this.rgaTreeSplit.indexToPos(t)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){let e=[];for(let t of this.rgaTreeSplit)t.isRemoved()||e.push(t.getValue().toJSON());return"[".concat(e.join(","),"]")}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){let e=[];for(let t of this.rgaTreeSplit)if(!t.isRemoved()){let r=t.getValue();e.push({attributes:tc(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){let e=new tJ(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return e.remove(this.getRemovedAt()),e}findIndexesFromRange(e){return this.rgaTreeSplit.findIndexesFromRange(e)}getGCPairs(){let e=[];for(let t of this.rgaTreeSplit)for(let r of(t.getRemovedAt()&&e.push({parent:this.rgaTreeSplit,child:t}),t.getValue().getGCPairs()))e.push(r);return e}constructor(e,t){super(t),this.rgaTreeSplit=e}}class tL extends tA{static create(e,t,r,n,i,s,o){return new tL(e,t,r,n,i,s,o)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tJ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(let t of n)e.registerGCPair(t);return{opInfos:r.map(t=>{let{from:r,to:n,value:i}=t;return{type:"edit",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.content;return"".concat(e,".EDIT(").concat(t,",").concat(r,",").concat(n,")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,o){super(e,o),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.content=i,this.attributes=s}}class t_ extends tA{static create(e,t,r,n,i,s){return new t_(e,t,r,n,i,s)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tJ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(let t of r)e.registerGCPair(t);return{opInfos:n.map(t=>{let{from:r,to:n,value:i}=t;return{type:"style",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.attributes;return"".concat(e,".STYL(").concat(t,",").concat(r,",").concat(JSON.stringify(n),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s){super(e,s),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i}}let tM="text";function tq(e,t){let r=0,n=e.children;for(let e=0;e!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(){for(var e=arguments.length,t=Array(e),r=0;re+t.paddedSize,0),r.size=r._children.reduce((e,t)=>e+t.paddedSize,0),r._children))e.parent=r;return r}insertAfterInternal(e,t){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");let r=this._children.indexOf(t);if(-1===r)throw new ti(x.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");if(e.isRemoved){let t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(e=>!e.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");let t=e;for(;t;){let e=this._children.indexOf(t);if(-1!==e)return e;t=t.parent}return -1}constructor(e,t=[]){if(this.type=e,this.size=0,this._children=t,this.isText&&this._children.length>0)throw new ti(x.ErrRefused,"Text node cannot have children")}}function tK(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let n of e._children)tK(n,t,r+1);t(e,r)}(d=D||(D={})).Start="Start",d.End="End",d.Text="Text";class tF{tokensBetween(e,t,r){!function e(t,r,n,i){if(r>n)throw new ti(x.ErrInvalidArgument,"from is greater than to: ".concat(r," > ").concat(n));if(r>t.size)throw new ti(x.ErrInvalidArgument,"from is out of range: ".concat(r," > ").concat(t.size));if(n>t.size)throw new ti(x.ErrInvalidArgument,"to is out of range: ".concat(n," > ").concat(t.size));if(r===n)return;let s=0;for(let o of t.children){if(r-o.paddedSizeo.size;(o.isText||c)&&i([o,o.isText?"Text":"Start"],l),e(o,Math.max(0,t),Math.min(a,o.size),i),l&&i([o,"End"],l)}s+=o.paddedSize}}(this.root,e,t,r)}traverse(e){!function e(t,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let i of t.children)e(i,r,n+1);r(t,n)}(this.root,e,0)}traverseAll(e){tK(this.root,e,0)}findTreePos(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function e(t,r){let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];if(r>t.size)throw new ti(x.ErrInvalidArgument,"index is out of range: ".concat(r," > ").concat(t.size));if(t.isText)return{node:t,offset:r};let i=0,s=0;for(let o of t.children){if(n&&o.isText&&o.size>=r-s)return e(o,r-s,n);if(r===s)break;if(!n&&o.paddedSize===r-s)return{node:t,offset:i+1};if(o.paddedSize>r-s)return e(o,r-s-1,n);s+=o.paddedSize,i+=1}return{node:t,offset:i}}(this.root,e,t)}treePosToPath(e){let t=[],r=e.node;if(r.isText){let n=r.parent.findOffset(r);if(-1===n)throw new ti(x.ErrInvalidArgument,"invalid treePos");let i=tq(r.parent,n);t.push(i+e.offset),r=r.parent}else if(r.hasTextChild()){let n=tq(r,e.offset);t.push(n)}else t.push(e.offset);for(;r.parent;){let e=r.parent.findOffset(r);if(-1===e)throw new ti(x.ErrInvalidArgument,"invalid treePos");t.push(e),r=r.parent}return t.reverse()}pathToIndex(e){let t=this.pathToTreePos(e);return this.indexOf(t)}pathToTreePos(e){if(!e.length)throw new ti(x.ErrInvalidArgument,"unacceptable path");let t=this.root;for(let r=0;re===t?0:e0){if(!t.right)return t;t.right.parent=t,t=t.right}else if(!(r<0))return t;else if(t.left)t.left.parent=t,t=t.left;else{let e=t.parent,r=t;for(;e&&r===e.left;)r=e,e=e.parent;return e}}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return 0===this.counter}getInternal(e,t){for(;t;){let r=this.comparator(e,t.key);if(0===r)return t;r<0?t=t.left:r>0&&(t=t.right)}}putInternal(e,t,r){if(!r)return this.counter+=1,new tU(e,t,!0);let n=this.comparator(e,r.key);return n<0?r.left=this.putInternal(e,t,r.left):n>0?r.right=this.putInternal(e,t,r.right):r.value=t,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,t){if(0>this.comparator(t,e.key))this.isRed(e.left)||this.isRed(e.left.left)||(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),0===this.comparator(t,e.key)&&!e.right){this.counter-=1;return}if(this.isRed(e.right)||this.isRed(e.right.left)||(e=this.moveRedRight(e)),0===this.comparator(t,e.key)){this.counter-=1;let t=this.min(e.right);e.value=t.value,e.key=t.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return this.isRed(e.left)||this.isRed(e.left.left)||(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){let t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){let t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}constructor(e){this.comparator=void 0!==e?e:tV,this.counter=0}}(u=R||(R={})).Content="content",u.Style="style",u.RemoveStyle="removeStyle";class tG{static of(e,t){return new tG(e,t)}static fromTreePos(e){let t;let{offset:r}=e,{node:n}=e;return n.isText?(t=n.parent.children[0]===n&&0===r?n.parent:n,n=n.parent):t=0===r?n:n.children[r-1],tG.of(n.id,tH.of(t.getCreatedAt(),t.getOffset()+r))}getParentID(){return this.parentID}static fromStruct(e){return tG.of(tH.of(td.fromStruct(e.parentID.createdAt),e.parentID.offset),tH.of(td.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){let t=this.getParentID(),r=this.getLeftSiblingID(),n=e.findFloorNode(t),i=e.findFloorNode(r);if(!n||!i)throw new ti(x.ErrRefused,"cannot find node of CRDTTreePos(".concat(t.toTestString(),", ").concat(r.toTestString(),")"));return!r.equals(t)&&r.getOffset()>0&&r.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=e.findFloorNode(i.insPrevID)),[n,i]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}constructor(e,t){this.parentID=e,this.leftSiblingID=t}}class tH{static of(e,t){return new tH(e,t)}static fromStruct(e){return tH.of(td.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{let r=e.getCreatedAt().compare(t.getCreatedAt());return 0!==r?r:e.getOffset()>t.getOffset()?1:e.getOffset(){let r=e.deepcopy();return r.parent=t,r}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new ti(x.ErrInvalidType,"cannot get value of element node: ".concat(this.type));return this._value}set value(e){if(!this.isText)throw new ti(x.ErrInvalidType,"cannot set value of element node: ".concat(this.type));this._value=e,this.size=e.length}get isRemoved(){return!!this.removedAt}remove(e){let t=!this.removedAt;(!this.removedAt||this.removedAt.compare(e)>0)&&(this.removedAt=e),t&&this.updateAncestorsSize()}cloneText(e){return new tY(tH.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new tY(tH.of(e(),0),this.type,void 0,void 0,this.removedAt)}split(e,t,r){let n=this.isText?this.splitText(t,this.id.getOffset()):this.splitElement(t,r);return n&&(n.insPrevID=this.id,this.insNextID&&(e.findFloorNode(this.insNextID).insPrevID=n.id,n.insNextID=this.insNextID),this.insNextID=n.id,e.registerNode(n)),n}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(e,t){return!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,t){return!this.isText&&!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,t){this.attrs||(this.attrs=new tO);let r=[];for(let[n,i]of Object.entries(e))r.push(this.attrs.set(n,i,t));return r}purge(e){this.attrs&&this.attrs.purge(e)}getGCPairs(){let e=[];if(!this.attrs)return e;for(let t of this.attrs)t.getRemovedAt()&&e.push({parent:this,child:t});return e}constructor(e,t,r,n,i){super(t),this._value="",this.id=e,this.removedAt=i,n&&(this.attrs=n),"string"==typeof r?this.value=r:Array.isArray(r)&&(this._children=r)}}function tZ(e){if(e.isText)return{type:e.type,value:e.value};let t={type:e.type,children:e.children.map(tZ)};if(e.attrs){var r;t.attributes=tc(null===(r=e.attrs)||void 0===r?void 0:r.toObject())}return t}function tX(e){if(e.isText)return e.value;let t="";return e.attrs&&e.attrs.size()&&(t=" "+Array.from(e.attrs).filter(e=>!e.isRemoved()).sort((e,t)=>e.getKey().localeCompare(t.getKey())).map(e=>{let t=JSON.parse(e.getValue());return"string"==typeof t?"".concat(e.getKey(),'="').concat(t,'"'):"".concat(e.getKey(),'="').concat(tf(e.getValue()),'"')}).join(" ")),"<".concat(e.type).concat(t,">").concat(e.children.map(e=>tX(e)).join(""),"")}class tQ extends tm{static create(e,t){return new tQ(e,t)}findFloorNode(e){let t=this.nodeMapByID.floorEntry(e);if(t&&t.key.getCreatedAt().equals(e.getCreatedAt()))return t.value}registerNode(e){this.nodeMapByID.put(e.id,e)}findNodesAndSplitText(e,t){let[r,n]=e.toTreeNodePair(this),i=n,s=r===i,o=i.parent&&!s?i.parent:r;if(i.isText&&i.split(this,e.getLeftSiblingID().getOffset()-i.id.getOffset()),t){let e=o.allChildren,r=s?0:e.indexOf(i)+1;for(let n=r;n{let[i]=e,s=i.getCreatedAt().getActorID(),o=n?n.has(s)?n.get(s):tu:tg;if(i.canStyle(r,o)&&t){let e=h.get(s),n=i.getCreatedAt();(!e||n.after(e))&&h.set(s,n);let o=i.setAttrs(t,r),a=o.reduce((e,t)=>{let[,r]=t;return r&&(e[r.getKey()]=l[r.getKey()]),e},{}),u=i.parent,g=i.prevSibling||i.parent;for(let[e]of(Object.keys(a).length>0&&c.push({type:"style",from:this.toIndex(u,g),to:this.toIndex(i,i),fromPath:this.toPath(u,g),toPath:this.toPath(i,i),actor:r.getActorID(),value:a}),o))e&&d.push({parent:i,child:e})}}),[h,d,c]}removeStyle(e,t,r,n){let[i,s]=this.findNodesAndSplitText(e[0],r),[o,a]=this.findNodesAndSplitText(e[1],r),c=[],l=new Map,h=[];return this.traverseInPosRange(i,s,o,a,e=>{let[i]=e,s=i.getCreatedAt().getActorID(),o=n?n.has(s)?n.get(s):tu:tg;if(i.canStyle(r,o)&&t){let e=l.get(s),n=i.getCreatedAt();for(let o of((!e||n.after(e))&&l.set(s,n),i.attrs||(i.attrs=new tO),t))for(let e of i.attrs.remove(o,r))h.push({parent:i,child:e});let o=i.parent,a=i.prevSibling||i.parent;c.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(o,a),to:this.toIndex(i,i),fromPath:this.toPath(o,a),toPath:this.toPath(i,i),value:t})}}),[l,h,c]}edit(e,t,r,n,i,s){let[o,a]=this.findNodesAndSplitText(e[0],n),[c,l]=this.findNodesAndSplitText(e[1],n),h=this.toIndex(o,a),d=this.toPath(o,a),u=[],g=[],f=[],m=new Map;this.traverseInPosRange(o,a,c,l,(e,t)=>{let[r,i]=e;if(i===D.Start&&!t)for(let e of r.children)f.push(e);let o=r.getCreatedAt().getActorID(),a=s?s.has(o)?s.get(o):tu:tg;if(r.canDelete(n,a)||u.includes(r.parent)){let e=m.get(o),t=r.getCreatedAt();(!e||t.after(e))&&m.set(o,t),(i===D.Text||i===D.Start)&&u.push(r),g.push([r,i])}});let p=this.makeDeletionChanges(g,n),y=[];for(let e of u)e.remove(n),e.isRemoved&&y.push({parent:this,child:e});for(let e of f)e.removedAt||o.append(e);if(r>0){let e=0,t=o,s=a;for(;e{o.isRemoved&&(e.remove(n),y.push({parent:this,child:e})),this.nodeMapByID.put(e.id,e)}),i.isRemoved||e.push(i);if(e.length){let t=e.map(e=>tZ(e));p.length&&p[p.length-1].from===h?p[p.length-1].value=t:p.push({type:"content",from:h,to:h,fromPath:d,toPath:d,actor:n.getActorID(),value:t})}}return[p,y,m]}editT(e,t,r,n,i){let s=this.findPos(e[0]),o=this.findPos(e[1]);this.edit([s,o],t,r,n,i)}move(e,t,r){throw new ti(x.ErrUnimplemented,"not implemented: ".concat(e,", ").concat(t,", ").concat(r))}purge(e){var t;null===(t=e.parent)||void 0===t||t.removeChild(e),this.nodeMapByID.remove(e.id);let r=e.insPrevID,n=e.insNextID;r&&(this.findFloorNode(r).insNextID=n),n&&(this.findFloorNode(n).insPrevID=r),e.insPrevID=void 0,e.insNextID=void 0}getGCPairs(){let e=[];return this.indexTree.traverse(t=>{for(let r of(t.getRemovedAt()&&e.push({parent:this,child:t}),t.getGCPairs()))e.push(r)}),e}findPos(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1],r=this.indexTree.findTreePos(e,t);return tG.fromTreePos(r)}pathToPosRange(e){let t=this.pathToIndex(e);return[this.findPos(t),this.findPos(t+1)]}pathToPos(e){let t=this.indexTree.pathToIndex(e);return this.findPos(t)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return tX(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){var e=this;let t=this.indexTree.getRoot(),r=function(t){var n,i,s,o;let a,c,l,h=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,g=t.isText?{node:t,offset:0}:h&&d?e.toTreePos(h,d):null;g&&(a=e.indexTree.indexOf(g),c=e.indexTree.treePosToPath(g),l=tG.fromTreePos(g).toStruct());let f={type:t.type,parent:null==h?void 0:h.id.toTestString(),size:t.size,id:t.id.toTestString(),removedAt:null===(n=t.removedAt)||void 0===n?void 0:n.toTestString(),insPrev:null===(i=t.insPrevID)||void 0===i?void 0:i.toTestString(),insNext:null===(s=t.insNextID)||void 0===s?void 0:s.toTestString(),value:t.isText?t.value:void 0,isRemoved:t.isRemoved,children:[],depth:u,attributes:t.attrs?tc(null===(o=t.attrs)||void 0===o?void 0:o.toObject()):void 0,index:a,path:c,pos:l};for(let e=0;e0&&d===r[r.length-1].to?(r[r.length-1].to=u,r[r.length-1].toPath=this.toPath(h,a)):r.push({type:"content",from:d,to:u,fromPath:this.toPath(l,s),toPath:this.toPath(h,a),actor:t.getActorID()}))}return r.reverse()}findRightToken(e){let[t,r]=e;if(r===D.Start){let e=t.allChildren;return e.length>0?[e[0],e[0].isText?D.Text:D.Start]:[t,D.End]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&s===i.length-1)return[n,D.End];let o=i[s+1];return[o,o.isText?D.Text:D.Start]}findLeftToken(e){let[t,r]=e;if(r===D.End){let e=t.allChildren;if(e.length>0){let t=e[e.length-1];return[t,t.isText?D.Text:D.End]}return[t,D.Start]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&0===s)return[n,D.Start];let o=i[s-1];return[o,o.isText?D.Text:D.End]}constructor(e,t){super(t),this.indexTree=new tF(e),this.nodeMapByID=new tW(tH.createComparator()),this.indexTree.traverseAll(e=>{this.nodeMapByID.put(e.id,e)})}}class t$ extends tA{static create(e,t,r,n,i,s,o){return new t$(e,t,r,n,i,s,o)}execute(e){var t;let r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(r instanceof tQ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Tree can execute edit");let n=this.getExecutedAt(),[i,s]=r.edit([this.fromPos,this.toPos],null===(t=this.contents)||void 0===t?void 0:t.map(e=>e.deepcopy()),this.splitLevel,n,(()=>{let e=n.getDelimiter();return void 0!==this.contents&&(e+=this.contents.length),()=>td.of(n.getLamport(),++e,n.getActorID())})(),this.maxCreatedAtMapByActor);for(let t of s)e.registerGCPair(t);return{opInfos:i.map(t=>{let{from:r,to:n,value:i,splitLevel:s,fromPath:o,toPath:a}=t;return{type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:r,to:n,value:i,splitLevel:s,fromPath:o,toPath:a}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t="".concat(this.fromPos.getLeftSiblingID().getCreatedAt().toTestString(),"/").concat(this.fromPos.getLeftSiblingID().getOffset()),r="".concat(this.toPos.getLeftSiblingID().getCreatedAt().toTestString(),"/").concat(this.toPos.getLeftSiblingID().getOffset()),n=this.contents||[];return"".concat(e,".EDIT(").concat(t,",").concat(r,",").concat(n.map(e=>tX(e)).join(""),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,o){super(e,o),this.fromPos=t,this.toPos=r,this.contents=n,this.splitLevel=i,this.maxCreatedAtMapByActor=s}}class t0{set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(let[,t]of this)t>e&&(e=t);return e}max(e){let t=new Map;for(let[r,n]of e){let e=this.vector.get(r),i=e&&e>n?e:n;t.set(r,i)}for(let[r,n]of this){let i=e.get(r),s=i&&i>n?i:n;t.set(r,s)}return new t0(t)}afterOrEqual(e){let t=this.vector.get(e.getActorID());return void 0!==t&&t>=e.getLamport()}deepcopy(){let e=new Map;for(let[t,r]of this.vector)e.set(t,r);return new t0(e)}filter(e){let t=new Map;for(let[r]of e){let e=this.vector.get(r);void 0!==e&&t.set(r,e)}return new t0(t)}size(){return this.vector.size}*[Symbol.iterator](){for(let[e,t]of this.vector)yield[e,t]}constructor(e){this.vector=e||new Map}}let t1=new t0(new Map);class t2{static of(e,t,r,n,i){return new t2(e,t,r,n,i)}next(){let e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new t2(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){let t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,r=this.versionVector.max(e.versionVector),n=new t2(this.clientSeq,t,this.actor,r);return n.versionVector.set(this.actor,t),n}setClocks(e,t){let r=e>this.lamport?e:this.lamport+1n,n=this.versionVector.max(t);return n.set(this.actor,r),t2.of(this.clientSeq,r,this.actor,n)}createTimeTicket(e){return td.of(this.lamport,e,this.actor)}setActor(e){return new t2(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new t2(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actor.slice(-2),":").concat(this.clientSeq)}constructor(e,t,r,n,i){this.clientSeq=e,this.serverSeq=i,this.lamport=t,this.versionVector=n,this.actor=r}}let t3=new t2(0,0n,th,t1);class t9{static create(e){let{id:t,operations:r,presenceChange:n,message:i}=e;return new t9({id:t,operations:r,presenceChange:n,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(let t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return void 0!==this.presenceChange}getPresenceChange(){return this.presenceChange}execute(e,t,r){let n=[],i=[];for(let t of this.operations){let s=t.execute(e,r);if(!s)continue;let{opInfos:o,reverseOp:a}=s;n.push(...o),a&&i.unshift(a)}return this.presenceChange&&(this.presenceChange.type===P.Put?t.set(this.id.getActorID(),ts(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:n,reverseOps:i}}toTestString(){return"".concat(this.operations.map(e=>e.toTestString()).join(","))}toStruct(){return{changeID:rU.bytesToHex(rU.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>rU.bytesToHex(rU.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){let{changeID:t,operations:r,presenceChange:n,message:i}=e;return t9.create({id:rU.bytesToChangeID(rU.hexToBytes(t)),operations:null==r?void 0:r.map(e=>rU.bytesToOperation(rU.hexToBytes(e))),presenceChange:n,message:i})}constructor({id:e,operations:t,presenceChange:r,message:n}){this.id=e,this.operations=t||[],this.presenceChange=r,this.message=n}}class t4{static create(e,t,r,n,i,s,o){return new t4(e,t,r,n,i,s,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}constructor(e,t,r,n,i,s,o){this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=n,this.snapshot=s,this.minSyncedTicket=o,this.versionVector=i}}class t8{static of(e,t){return new t8(e,t)}increaseClientSeq(e){return 0===e?this:new t8(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;let t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return t8.of(t,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return"serverSeq=".concat(this.serverSeq,", clientSeq=").concat(this.clientSeq)}constructor(e,t){this.serverSeq=e,this.clientSeq=t}}let t5=new t8(0n,0);class t6{static of(e,t){return new t6(e,t)}static fromStruct(e){return t6.of(td.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return 0===this.createdAt.compare(e.createdAt)&&this.offset===e.offset}hasSameCreatedAt(e){return 0===this.createdAt.compare(e.createdAt)}split(e){return new t6(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return"".concat(this.createdAt.toTestString(),":").concat(this.offset)}toIDString(){return"".concat(this.createdAt.toIDString(),":").concat(this.offset)}constructor(e,t){this.createdAt=e,this.offset=t}}let t7=t6.of(tu,0);class re{static of(e,t){return new re(e,t)}static fromStruct(e){let t=t6.fromStruct(e.id);return re.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return t6.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return"".concat(this.id.toTestString(),":").concat(this.relativeOffset)}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return!!this.id.equals(e.id)&&this.relativeOffset===e.relativeOffset}constructor(e,t){this.id=e,this.relativeOffset=t}}class rt extends tT{static create(e,t){return new rt(e,t)}static createComparator(){return(e,t)=>{let r=e.getCreatedAt().compare(t.getCreatedAt());return 0!==r?r:e.getOffset()>t.getOffset()?1:e.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){let t=this.treeByID.floorEntry(e);if(t&&(t.key.equals(e)||t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){let r=[],n=e;for(;n&&n!==t;)r.push(n),n=n.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new ti(x.ErrInvalidArgument,"offset should be less than or equal to length");if(0===t)return e;if(t===e.getContentLength())return e.getNext();let r=e.split(t);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);let n=e.getInsNext();return n&&n.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r){if(!e.length)return[[],new Map,new Map];let[n,i]=this.filterNodes(e,t,r),s=new Map,o=new Map,a=this.makeChanges(i,t);for(let e of n){let r=e.getCreatedAt().getActorID();(!s.has(r)||e.getID().getCreatedAt().after(s.get(r)))&&s.set(r,e.getID().getCreatedAt()),o.set(e.getID().toIDString(),e),e.remove(t)}return this.deleteIndexNodes(i),[a,s,o]}filterNodes(e,t,r){let n=!!r,i=[],s=[],[o,a]=this.findEdgesOfCandidates(e);for(let a of(s.push(o),e)){let e=a.getCreatedAt().getActorID(),o=n?r.has(e)?r.get(e):tu:tg;a.canDelete(t,o)?i.push(a):s.push(a)}return s.push(a),[i,s]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){let r,n;let i=[];for(let s=0;se<0?Math.ceil(e):Math.floor(e);(g=N||(N={}))[g.IntegerCnt=0]="IntegerCnt",g[g.LongCnt=1]="LongCnt";class ri extends tm{static create(e,t,r){return new ri(e,t,r)}static valueFromBytes(e,t){switch(e){case 0:return t[0]|t[1]<<8|t[2]<<16|t[3]<<24;case 1:return tI.Z.fromBytesLE(Array.from(t));default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}toJSON(){return"".concat(this.value)}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){let e=ri.create(this.valueType,this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e}getType(){return this.valueType}static getCounterType(e){switch(typeof e){case"object":if(e instanceof tI.Z)return 1;return;case"number":if(e>2147483647||e<-2147483648)return 1;return 0;default:return}}static isSupport(e){return!!ri.getCounterType(e)}static isInteger(e){return e%1==0}isNumericType(){let e=this.valueType;return 0===e||1===e}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{let e=this.value;return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}case 1:{let e=this.value.toBytesLE();return Uint8Array.from(e)}default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(this.valueType))}}increase(e){function t(e){if(!e.isNumericType())throw TypeError("Unsupported type of value: ".concat(typeof e.getValue()))}return t(this),t(e),1===this.valueType?this.value=this.value.add(e.getValue()):e.getType()===b.Long?this.value=this.value+e.getValue().toInt():this.value=tI.Z.fromNumber(this.value+rn(e.getValue())).toInt(),this}constructor(e,t,r){switch(super(r),this.valueType=e,e){case 0:"number"==typeof t?t>2147483647||t<-2147483648?this.value=tI.Z.fromNumber(t).toInt():this.value=rn(t):this.value=t.toInt();break;case 1:"number"==typeof t?this.value=tI.Z.fromNumber(t):this.value=t;break;default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}}class rs extends tA{static create(e,t,r){return new rs(e,t,r)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof ri))throw new ti(x.ErrInvalidArgument,"fail to execute, only Counter can execute increase");let r=this.value.deepcopy();return t.increase(r),{opInfos:[{type:"increase",path:e.createPath(this.getParentCreatedAt()),value:r.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){let e=this.value.deepcopy(),t=e.getType()===b.Long?e.getValue().multiply(-1):-1*e.getValue();return rs.create(this.getParentCreatedAt(),tC.of(t,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return"".concat(this.getParentCreatedAt().toTestString(),".INCREASE.").concat(this.value.toJSON())}getValue(){return this.value}constructor(e,t,r){super(e,r),this.value=t}}class ro extends tA{static create(e,t,r,n,i,s){return new ro(e,t,r,n,i,[],s)}static createTreeRemoveStyleOperation(e,t,r,n,i,s){return new ro(e,t,r,n,new Map,i,s)}execute(e){let t,r;let n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(n instanceof tQ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Tree can execute edit");if(this.attributes.size){let e={};[...this.attributes].forEach(t=>{let[r,n]=t;return e[r]=n}),[,r,t]=n.style([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{let e=this.attributesToRemove;[,r,t]=n.removeStyle([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(let t of r)e.registerGCPair(t);return{opInfos:t.map(t=>{let{from:r,to:n,value:i,fromPath:s,toPath:o}=t;return{type:"tree-style",from:r,to:n,value:this.attributes.size?{attributes:i}:{attributesToRemove:i},fromPath:s,toPath:o,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t="".concat(this.fromPos.getLeftSiblingID().getCreatedAt().toTestString(),":").concat(this.fromPos.getLeftSiblingID().getOffset()),r="".concat(this.toPos.getLeftSiblingID().getCreatedAt().toTestString(),":").concat(this.toPos.getLeftSiblingID().getOffset());return"".concat(e,".STYLE(").concat(t,",").concat(r,",").concat(Object.entries(this.attributes||{}).map(e=>{let[t,r]=e;return"".concat(t,':"').concat(r,'"')}).join(" "),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,o){super(e,o),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i,this.attributesToRemove=s}}function ra(e){return new es({clientSeq:e.getClientSeq(),lamport:e.getLamport(),actorId:rV(e.getActorID()),versionVector:rl(e.getVersionVector())})}function rc(e){if(e)return new ej({lamport:e.getLamport(),delimiter:e.getDelimiter(),actorId:rV(e.getActorID())})}function rl(e){if(!e)return;let t=new eo;for(let[r,n]of e)t.vector[r]=BigInt(n.toString());return t}function rh(e){switch(e){case b.Null:return S.NULL;case b.Boolean:return S.BOOLEAN;case b.Integer:return S.INTEGER;case b.Long:return S.LONG;case b.Double:return S.DOUBLE;case b.String:return S.STRING;case b.Bytes:return S.BYTES;case b.Date:return S.DATE;default:throw new ti(x.ErrInvalidType,"unsupported type: ".concat(e))}}function rd(e){switch(e){case N.IntegerCnt:return S.INTEGER_CNT;case N.LongCnt:return S.LONG_CNT;default:throw new ti(x.ErrInvalidType,"unsupported type: ".concat(e))}}function ru(e){if(e instanceof tw)return new ew({type:S.JSON_OBJECT,createdAt:rc(e.getCreatedAt()),value:rK(e)});if(e instanceof tE)return new ew({type:S.JSON_ARRAY,createdAt:rc(e.getCreatedAt()),value:rv(e).toBinary()});if(e instanceof tJ)return new ew({type:S.TEXT,createdAt:rc(e.getCreatedAt())});if(e instanceof tC)return new ew({type:rh(e.getType()),createdAt:rc(e.getCreatedAt()),value:e.toBytes()});if(e instanceof ri)return new ew({type:rd(e.getType()),createdAt:rc(e.getCreatedAt()),value:e.toBytes()});if(e instanceof tQ)return new ew({type:S.TREE,createdAt:rc(e.getCreatedAt()),value:rw(e).toBinary()});throw new ti(x.ErrUnimplemented,"unimplemented element")}function rg(e){return new eU({createdAt:rc(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function rf(e){return new eJ({parentId:rm(e.getParentID()),leftSiblingId:rm(e.getLeftSiblingID())})}function rm(e){return new eB({createdAt:rc(e.getCreatedAt()),offset:e.getOffset()})}function rp(e){let t=new ea;if(e instanceof tk){let r=new ec;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.key=e.getKey(),r.value=ru(e.getValue()),r.executedAt=rc(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof tD){let r=new el;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.prevCreatedAt=rc(e.getPrevCreatedAt()),r.value=ru(e.getValue()),r.executedAt=rc(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof tR){let r=new eh;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.prevCreatedAt=rc(e.getPrevCreatedAt()),r.createdAt=rc(e.getCreatedAt()),r.executedAt=rc(e.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof tb){let r=new ed;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.createdAt=rc(e.getCreatedAt()),r.executedAt=rc(e.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof tL){let r=new eu;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rg(e.getFromPos()),r.to=rg(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);r.content=e.getContent();let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=rc(e.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof t_){let r=new ef;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rg(e.getFromPos()),r.to=rg(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=rc(e.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof rs){let r=new em;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.value=ru(e.getValue()),r.executedAt=rc(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof t$){let r=new ep,n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rf(e.getFromPos()),r.to=rf(e.getToPos()),r.contents=function(e){let t=[];if(!e||!e.length)return t;for(let r of e)t.push(new eO({content:ry(r)}));return t}(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=rc(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof ro){let r=new ey;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rf(e.getFromPos()),r.to=rf(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);let i=e.getAttributesToRemove();if(i.length>0)r.attributesToRemove=i;else{let t=r.attributes;for(let[r,n]of e.getAttributes())t[r]=n}r.executedAt=rc(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new ti(x.ErrUnimplemented,"unimplemented operation");return t}function ry(e){if(!e)return[];let t=[];return tK(e,(e,r)=>{let n=new eN({id:rm(e.id),type:e.type,removedAt:rc(e.removedAt),depth:r});e.isText&&(n.value=e.value),e.insPrevID&&(n.insPrevId=rm(e.insPrevID)),e.insNextID&&(n.insNextId=rm(e.insNextID)),e.attrs&&(n.attributes=function(e){let t={};for(let r of e)t[r.getKey()]=new ek({value:r.getValue(),updatedAt:rc(r.getUpdatedAt()),isRemoved:r.isRemoved()});return t}(e.attrs)),t.push(n)}),t}function rv(e){let t=new eA;return t.body.case="jsonArray",t.body.value=new eS({nodes:function(e){let t=[];for(let r of e)t.push(new eb({element:rA(r.getValue())}));return t}(e.getElements()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}function rw(e){let t=new eA;return t.body.case="tree",t.body.value=new eP({nodes:ry(e.getRoot()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}function rA(e){if(e instanceof tw)return function(e){let t=new eA;return t.body.case="jsonObject",t.body.value=new eT({nodes:function(e){let t=[];for(let r of e)t.push(new eE({key:r.getStrKey(),element:rA(r.getValue())}));return t}(e.getRHT()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof tE)return rv(e);if(e instanceof tC)return function(e){let t=new eA;return t.body.case="primitive",t.body.value=new eI({type:rh(e.getType()),value:e.toBytes(),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof tJ)return function(e){let t=new eA;return t.body.case="text",t.body.value=new eC({nodes:function(e){let t=[];for(let n of e){var r;let e=new eD;e.id=new eR({createdAt:rc((r=n.getID()).getCreatedAt()),offset:r.getOffset()}),e.value=n.getValue().getContent(),e.removedAt=rc(n.getRemovedAt());let i=e.attributes;for(let e of n.getValue().getAttrs()){let t=new ek;t.value=e.getValue(),t.updatedAt=rc(e.getUpdatedAt()),i[e.getKey()]=t}t.push(e)}return t}(e.getRGATreeSplit()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof ri)return function(e){let t=new eA;return t.body.case="counter",t.body.value=new ex({type:rd(e.getType()),value:e.toBytes(),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof tQ)return rw(e);throw new ti(x.ErrUnimplemented,"unimplemented element")}function rT(e){for(let t of e.findDetails(tn.Qf))if(t.metadata.code)return t.metadata.code;return""}function rS(e){return t2.of(e.clientSeq,BigInt(e.lamport),rF(e.actorId),rI(e.versionVector),BigInt(e.serverSeq))}function rI(e){if(!e)return;let t=new t0;return Object.entries(e.vector).forEach(e=>{let[r,n]=e;t.set(r,BigInt(n.toString()))}),t}function rC(e){if(e)return td.of(BigInt(e.lamport),e.delimiter,rF(e.actorId))}function rx(e){let t={};return Object.entries(e.data).forEach(e=>{let[r,n]=e;t[r]=JSON.parse(n)}),t}function rP(e){switch(e){case S.NULL:return b.Null;case S.BOOLEAN:return b.Boolean;case S.INTEGER:return b.Integer;case S.LONG:return b.Long;case S.DOUBLE:return b.Double;case S.STRING:return b.String;case S.BYTES:return b.Bytes;case S.DATE:return b.Date}throw new ti(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rE(e){switch(e){case S.INTEGER_CNT:return N.IntegerCnt;case S.LONG_CNT:return N.LongCnt}throw new ti(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rb(e){switch(e.type){case S.JSON_OBJECT:if(!e.value)return tw.create(rC(e.createdAt));return rz(e.value);case S.JSON_ARRAY:if(!e.value)return tE.create(rC(e.createdAt));return function(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return r_(eA.fromBinary(e).body.value)}(e.value);case S.TEXT:return tJ.create(rr.create(),rC(e.createdAt));case S.TREE:return function(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return rM(eA.fromBinary(e).body.value)}(e.value);case S.NULL:case S.BOOLEAN:case S.INTEGER:case S.LONG:case S.DOUBLE:case S.STRING:case S.BYTES:case S.DATE:return tC.of(tC.valueFromBytes(rP(e.type),e.value),rC(e.createdAt));case S.INTEGER_CNT:case S.LONG_CNT:return ri.create(rE(e.type),ri.valueFromBytes(rE(e.type),e.value),rC(e.createdAt))}}function rk(e){return re.of(t6.of(rC(e.createdAt),e.offset),e.relativeOffset)}function rD(e){return t6.of(rC(e.createdAt),e.offset)}function rR(e){return tG.of(rN(e.parentId),rN(e.leftSiblingId))}function rN(e){return tH.of(rC(e.createdAt),e.offset)}function rO(e){if(0===e.length)return;let t=[];for(let r of e)t.push(function(e){let t=rN(e.id),r=tY.create(t,e.type),n=Object.entries(e.attributes);return r.isText?r.value=e.value:n.length&&(r.attrs=function(e){let t=tO.create();for(let[r,n]of Object.entries(e))t.setInternal(r,n.value,rC(n.updatedAt),n.isRemoved);return t}(e.attributes)),e.insPrevId&&(r.insPrevID=rN(e.insPrevId)),e.insNextId&&(r.insNextID=rN(e.insNextId)),r.removedAt=rC(e.removedAt),r}(r));let r=t[t.length-1],n=new Map;n.set(e[t.length-1].depth,t[t.length-1]);for(let r=t.length-2;r>=0;r--)n.get(e[r].depth-1).prepend(t[r]),n.set(e[r].depth,t[r]);return r.updateDescendantsSize(),tQ.create(r,tu).getRoot()}function rB(e){if("set"===e.body.case){let t=e.body.value;return tk.create(t.key,rb(t.value),rC(t.parentCreatedAt),rC(t.executedAt))}if("add"===e.body.case){let t=e.body.value;return tD.create(rC(t.parentCreatedAt),rC(t.prevCreatedAt),rb(t.value),rC(t.executedAt))}if("move"===e.body.case){let t=e.body.value;return tR.create(rC(t.parentCreatedAt),rC(t.prevCreatedAt),rC(t.createdAt),rC(t.executedAt))}if("remove"===e.body.case){let t=e.body.value;return tb.create(rC(t.parentCreatedAt),rC(t.createdAt),rC(t.executedAt))}if("edit"===e.body.case){let t=e.body.value,r=new Map;Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rC(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tL.create(rC(t.parentCreatedAt),rk(t.from),rk(t.to),r,t.content,n,rC(t.executedAt))}if("style"===e.body.case){let t=e.body.value,r=new Map;Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rC(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),t_.create(rC(t.parentCreatedAt),rk(t.from),rk(t.to),r,n,rC(t.executedAt))}if("select"===e.body.case)return;else if("increase"===e.body.case){let t=e.body.value;return rs.create(rC(t.parentCreatedAt),rb(t.value),rC(t.executedAt))}else if("treeEdit"===e.body.case){let t=e.body.value,r=new Map;return Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rC(n))}),t$.create(rC(t.parentCreatedAt),rR(t.from),rR(t.to),function(e){if(!e.length)return;let t=[];return e.forEach(e=>{let r=rO(e.content);t.push(r)}),t}(t.contents),t.splitLevel,r,rC(t.executedAt))}else if("treeStyle"===e.body.case){let t=e.body.value,r=new Map,n=t.attributesToRemove,i=new Map;return((null==t?void 0:t.createdAtMapByActor)&&Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,r]=e;i.set(t,rC(r))}),(null==n?void 0:n.length)>0)?ro.createTreeRemoveStyleOperation(rC(t.parentCreatedAt),rR(t.from),rR(t.to),i,n,rC(t.executedAt)):(Object.entries(t.attributes).forEach(e=>{let[t,n]=e;r.set(t,n)}),ro.create(rC(t.parentCreatedAt),rR(t.from),rR(t.to),i,r,rC(t.executedAt)))}else throw new ti(x.ErrUnimplemented,"unimplemented operation")}function rJ(e){let t=[];for(let r of e)t.push(t9.create({id:rS(r.id),operations:function(e){let t=[];for(let r of e){let e=rB(r);e&&t.push(e)}return t}(r.operations),presenceChange:r.presenceChange?function(e){let t=e.type;if(t===C.PUT){let t=rx(e.presence);return{type:P.Put,presence:t}}if(t===C.CLEAR)return{type:P.Clear};throw new ti(x.ErrInvalidType,"unsupported type: ".concat(t))}(r.presenceChange):void 0,message:r.message}));return t}function rL(e){let t=new tv;for(let r of e.nodes){let e=rq(r.element);t.set(r.key,e,e.getPositionedAt())}let r=new tw(rC(e.createdAt),t);return r.setMovedAt(rC(e.movedAt)),r.setRemovedAt(rC(e.removedAt)),r}function r_(e){let t=new tP;for(let r of e.nodes)t.insert(rq(r.element));let r=new tE(rC(e.createdAt),t);return r.setMovedAt(rC(e.movedAt)),r.setRemovedAt(rC(e.removedAt)),r}function rM(e){let t=rO(e.nodes);return tQ.create(t,rC(e.createdAt))}function rq(e){if("jsonObject"===e.body.case)return rL(e.body.value);if("jsonArray"===e.body.case)return r_(e.body.value);if("primitive"===e.body.case)return function(e){let t=tC.of(tC.valueFromBytes(rP(e.type),e.value),rC(e.createdAt));return t.setMovedAt(rC(e.movedAt)),t.setRemovedAt(rC(e.removedAt)),t}(e.body.value);if("text"===e.body.case)return function(e){let t=new rr,r=t.getHead();for(let n of e.nodes){let e=t.insertAfter(r,function(e){let t=tB.create(e.value);Object.entries(e.attributes).forEach(e=>{let[r,n]=e;t.setAttr(r,n.value,rC(n.updatedAt))});let r=rt.create(rD(e.id),t);return r.remove(rC(e.removedAt)),r}(n));n.insPrevId&&e.setInsPrev(t.findNode(rD(n.insPrevId))),r=e}let n=new tJ(t,rC(e.createdAt));return n.setMovedAt(rC(e.movedAt)),n.setRemovedAt(rC(e.removedAt)),n}(e.body.value);if("counter"===e.body.case)return function(e){let t=ri.create(rE(e.type),ri.valueFromBytes(rE(e.type),e.value),rC(e.createdAt));return t.setMovedAt(rC(e.movedAt)),t.setRemovedAt(rC(e.removedAt)),t}(e.body.value);if("tree"===e.body.case)return rM(e.body.value);throw new ti(x.ErrUnimplemented,"unimplemented element")}function rz(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return rL(eA.fromBinary(e).body.value)}function rK(e){return rA(e).toBinary()}function rF(e){return e?Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function rV(e){return new Uint8Array(e.match(/.{1,2}/g).map(e=>parseInt(e,16)))}let rU={fromPresence:rx,toChangePack:function(e){var t;return new en({documentKey:e.getDocumentKey(),checkpoint:new eV({serverSeq:(t=e.getCheckpoint()).getServerSeq(),clientSeq:t.getClientSeq()}),isRemoved:e.getIsRemoved(),changes:function(e){let t=[];for(let r of e)t.push(function(e){let t=new ei({id:ra(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=function(e){let t=[];for(let r of e)t.push(rp(r));return t}(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=function(e){if(e.type===P.Put)return new eK({type:C.PUT,presence:function(e){let t=new eF,r=t.data;for(let[t,n]of Object.entries(e))r[t]=JSON.stringify(n);return t}(e.presence)});if(e.type===P.Clear)return new eK({type:C.CLEAR});throw new ti(x.ErrUnimplemented,"unimplemented type")}(e.getPresenceChange())),t}(r));return t}(e.getChanges()),snapshot:e.getSnapshot(),versionVector:rl(e.getVersionVector()),minSyncedTicket:rc(e.getMinSyncedTicket())})},fromChangePack:function(e){var t;return t4.create(e.documentKey,(t=e.checkpoint,t8.of(BigInt(t.serverSeq),t.clientSeq)),e.isRemoved,rJ(e.changes),rI(e.versionVector),e.snapshot,rC(e.minSyncedTicket))},fromChanges:rJ,toTreeNodes:ry,fromTreeNodes:rO,objectToBytes:rK,bytesToObject:rz,bytesToSnapshot:function(e){if(!e)return{root:tw.create(tu),presences:new Map};let t=er.fromBinary(e);return{root:rq(t.root),presences:function(e){let t=new Map;return Object.entries(e).forEach(e=>{let[r,n]=e;t.set(r,rx(n))}),t}(t.presences)}},bytesToHex:rF,hexToBytes:rV,toHexString:function(e){return rF(e)},toUint8Array:function(e){return rV(e)},toOperation:rp,toChangeID:ra,PbChangeID:es,bytesToChangeID:function(e){return rS(es.fromBinary(e))},bytesToOperation:function(e){return rB(ea.fromBinary(e))},versionVectorToHex:function(e){return rF(rl(e).toBinary())},hexToVersionVector:function(e){let t=rV(e);return rI(eo.fromBinary(t))}};(f=O||(O={}))[f.Trivial=0]="Trivial",f[f.Debug=1]="Debug",f[f.Info=2]="Info",f[f.Warn=3]="Warn",f[f.Error=4]="Error",f[f.Fatal=5]="Fatal";let rj=3;function rW(e){rj=e}let rG={trivial:function(){for(var e=arguments.length,t=Array(e),r=0;r0||"undefined"==typeof console||console.log("YORKIE T:",...t)},debug:function(){for(var e=arguments.length,t=Array(e),r=0;r1||"undefined"==typeof console||console.log("YORKIE D:",...t)},info:function(){for(var e=arguments.length,t=Array(e),r=0;r2||"undefined"==typeof console||console.log("YORKIE I:",...t)},warn:function(){for(var e=arguments.length,t=Array(e),r=0;r3||"undefined"==typeof console||(void 0!==console.warn?console.warn("YORKIE W:",...t):console.log("YORKIE W:",...t))},error:function(){for(var e=arguments.length,t=Array(e),r=0;r4||"undefined"==typeof console||(void 0!==console.error?console.error("YORKIE E:",...t):console.log("YORKIE E:",...t))},fatal:function(){for(var e=arguments.length,t=Array(e),r=0;rrj<=e};function rH(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}class rY{changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode!==M.RealtimeSyncOff&&(this.syncMode===M.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==M.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived))}async runWatchLoop(e){let t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch(e){}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}constructor(e,t,r,n,i){this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=n,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}}let rZ=()=>{};class rX{next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let n;if(!e)throw new ti(x.ErrInvalidArgument,"missing observer");if(this.finalized)throw new ti(x.ErrRefused,"observable is finalized due to previous error");void 0===(n="object"==typeof e?e:{next:e,error:t,complete:r}).next&&(n.next=rZ),void 0===n.error&&(n.error=rZ),void 0===n.complete&&(n.complete=rZ);let i=rH(),s=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:n}),this.finalized)try{this.finalError?n.error(this.finalError):n.complete()}catch(e){rG.warn(e)}return s}unsubscribeOne(e){var t;this.observers=null===(t=this.observers)||void 0===t?void 0:t.filter(t=>t.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;t0||void 0!==this.presenceChange}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(let r of Object.keys(e))(null==t?void 0:t.addToHistory)?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(0===this.reversePresenceKeys.size)return;let e={};for(let t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}constructor(e,t,r,n){this.id=e,this.delimiter=0,this.root=t,this.operations=[],this.previousPresence=ts(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=n}}class r${static create(){return new r$(tw.create(tu))}findByCreatedAt(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];let r=[];for(;t.parent;){let e=t.element.getCreatedAt(),n=t.parent.subPathOf(e);if(void 0===n)throw new ti(x.ErrInvalidArgument,"cant find the given element: ".concat(e.toIDString()));r.unshift(n),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof tp&&e.getDescendants((e,t)=>(this.registerElement(e,t),!1))}deregisterElement(e){let t=0,r=e=>{let r=e.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(r),this.gcElementSetByCreatedAt.delete(r),t++};return r(e),e instanceof tp&&e.getDescendants(e=>(r(e),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){let e=new Set;for(let t of this.gcElementSetByCreatedAt){e.add(t);let r=this.elementPairMapByCreatedAt.get(t);r.element instanceof tp&&r.element.getDescendants(t=>(e.add(t.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new r$(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(let r of this.gcElementSetByCreatedAt){let n=this.elementPairMapByCreatedAt.get(r),i=n.element.getRemovedAt();i&&(null==e?void 0:e.afterOrEqual(i))&&(n.parent.purge(n.element),t+=this.deregisterElement(n.element))}for(let[,r]of this.gcPairMap){let n=r.child.getRemovedAt();n&&(null==e?void 0:e.afterOrEqual(n))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}constructor(e){this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof tJ||e instanceof tQ)for(let t of e.getGCPairs())this.registerGCPair(t);return!1})}}function r0(e,t){let r=new r1(e);return new Proxy(t,r.getHandlers())}class r1{static setInternal(e,t,r,n){if(r.includes("."))throw new ti(x.ErrInvalidObjectKey,"key must not contain the '.'.");let i=e.issueTimeTicket(),s=nt(e,n,i),o=t.set(r,s,i);e.registerElement(s,t),o&&e.registerRemovedElement(o),e.push(tk.create(r,s.deepcopy(),t.getCreatedAt(),i))}static buildObjectMembers(e,t){let r={};for(let[n,i]of Object.entries(t)){if(n.includes("."))throw new ti(x.ErrInvalidObjectKey,"key must not contain the '.'.");let t=e.issueTimeTicket(),s=nt(e,i,t);r[n]=s}return r}static deleteInternal(e,t,r){let n=e.issueTimeTicket(),i=t.deleteByKey(r,n);i&&(e.push(tb.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}constructor(e){this.context=e,this.handlers={set:(t,r,n)=>(rG.isEnabled(O.Trivial)&&rG.trivial("obj[".concat(r,"]=").concat(JSON.stringify(n))),r1.setInternal(e,t,r,n),!0),get:(t,r)=>(rG.isEnabled(O.Trivial)&&rG.trivial("obj[".concat(r,"]")),"getID"===r)?()=>t.getCreatedAt():"toJSON"===r||"toString"===r?()=>t.toJSON():"toJS"===r?()=>t.toJS():"toJSForTest"===r?()=>t.toJSForTest():ne(e,t.get(r)),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(rG.isEnabled(O.Trivial)&&rG.trivial("obj[".concat(r,"]")),r1.deleteInternal(e,t,r),!0)}}}class r2{static*iteratorInternal(e,t){for(let r of t)yield r7(e,r)}static buildArrayElements(e,t){let r=[];for(let n of t){let t=e.issueTimeTicket(),i=nt(e,n,t);r.push(i)}return r}static pushInternal(e,t,r){return r2.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,n){let i=e.issueTimeTicket(),s=t.getPrevCreatedAt(r);t.moveAfter(s,n,i),e.push(tR.create(t.getCreatedAt(),s,n,i))}static moveAfterInternal(e,t,r,n){let i=e.issueTimeTicket();t.moveAfter(r,n,i),e.push(tR.create(t.getCreatedAt(),r,n,i))}static moveFrontInternal(e,t,r){let n=e.issueTimeTicket(),i=t.getHead();t.moveAfter(i.getCreatedAt(),r,n),e.push(tR.create(t.getCreatedAt(),i.getCreatedAt(),r,n))}static moveLastInternal(e,t,r){let n=e.issueTimeTicket(),i=t.getLastCreatedAt();t.moveAfter(i,r,n),e.push(tR.create(t.getCreatedAt(),i,r,n))}static insertAfterInternal(e,t,r,n){let i=e.issueTimeTicket(),s=nt(e,n,i);return t.insertAfter(r,s),e.registerElement(s,t),e.push(tD.create(t.getCreatedAt(),r,s.deepcopy(),i)),s}static insertBeforeInternal(e,t,r,n){return r2.insertAfterInternal(e,t,t.getPrevCreatedAt(r),n)}static deleteInternalByIndex(e,t,r){let n=e.issueTimeTicket(),i=t.deleteByIndex(r,n);if(i)return e.push(tb.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i),i}static deleteInternalByID(e,t,r){let n=e.issueTimeTicket(),i=t.delete(r,n);return e.push(tb.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i),i}static splice(e,t,r,n){for(var i=arguments.length,s=Array(i>4?i-4:0),o=4;o=0?Math.min(r,a):Math.max(a+r,0),l=void 0===n?a:n<0?c:Math.min(c+n,a),h=[];for(let r=c;r=i)return!1;if(tC.isSupport(r))return Array.from(t).map(t=>ne(e,t)).includes(r,s);for(let e=s;e=i)return -1;if(tC.isSupport(r))return Array.from(t).map(t=>ne(e,t)).indexOf(r,s);for(let e=s;e=i?i-1:n<0?n+i:n;if(s<0)return -1;if(tC.isSupport(r))return Array.from(t).map(t=>ne(e,t)).lastIndexOf(r,s);for(let e=s;e>0;e--){var o;if((null===(o=t.get(e))||void 0===o?void 0:o.getID())===r.getID())return e}return -1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}constructor(e,t){this.context=e,this.array=t,this.handlers={get:(t,r,n)=>"getID"===r?()=>t.getCreatedAt():"getElementByID"===r?r=>{let n=t.getByID(r);if(!(!n||n.isRemoved()))return r7(e,n)}:"getElementByIndex"===r?r=>r7(e,t.get(r)):"getLast"===r?()=>r7(e,t.getLast()):"deleteByID"===r?r=>{let n=r2.deleteInternalByID(e,t,r);return r7(e,n)}:"insertAfter"===r?(r,n)=>{let i=r2.insertAfterInternal(e,t,r,n);return r7(e,i)}:"insertBefore"===r?(r,n)=>{let i=r2.insertBeforeInternal(e,t,r,n);return r7(e,i)}:"moveBefore"===r?(r,n)=>{r2.moveBeforeInternal(e,t,r,n)}:"moveAfter"===r?(r,n)=>{r2.moveAfterInternal(e,t,r,n)}:"moveFront"===r?r=>{r2.moveFrontInternal(e,t,r)}:"moveLast"===r?r=>{r2.moveLastInternal(e,t,r)}:("string"==typeof r||r instanceof String)&&!isNaN(r)?ne(e,t.get(Number(r))):"push"===r?r=>r2.pushInternal(e,t,r):"splice"===r?function(r,n){for(var i=arguments.length,s=Array(i>2?i-2:0),o=2;or2.includes(e,t,r,n):"indexOf"===r?(r,n)=>r2.indexOf(e,t,r,n):"lastIndexOf"===r?(r,n)=>r2.lastIndexOf(e,t,r,n):"toJSForTest"===r?()=>t.toJSForTest():"toTestString"===r?()=>r2.toTestString(t):"string"==typeof r&&["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(r)?function(){for(var n=arguments.length,i=Array(n),s=0;sne(e,t));return Array.prototype[r].apply(o,i)}:Reflect.get(t,r,n),deleteProperty:(t,r)=>(rG.isEnabled(O.Trivial)&&rG.trivial("array[".concat(r,"]")),r2.deleteInternalByIndex(e,t,Number.parseInt(r)),!0)}}}class r3{initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,n){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.text.indexRangeToPosRange(e,t);rG.isEnabled(O.Debug)&&rG.debug("EDIT: f:".concat(e,"->").concat(i[0].toTestString(),", t:").concat(t,"->").concat(i[1].toTestString()," c:").concat(r));let s=n?ta(n):void 0,o=this.context.issueTimeTicket(),[a,,c,l]=this.text.edit(i,r,o,s);for(let e of c)this.context.registerGCPair(e);return this.context.push(new tL(this.text.getCreatedAt(),i[0],i[1],a,r,s?new Map(Object.entries(s)):new Map,o)),this.text.findIndexesFromRange(l)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,r){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.text.indexRangeToPosRange(e,t);rG.isEnabled(O.Debug)&&rG.debug("STYL: f:".concat(e,"->").concat(n[0].toTestString(),", t:").concat(t,"->").concat(n[1].toTestString()," a:").concat(JSON.stringify(r)));let i=ta(r),s=this.context.issueTimeTicket(),[o,a]=this.text.setStyle(n,i,s);for(let e of a)this.context.registerGCPair(e);return this.context.push(new t_(this.text.getCreatedAt(),n[0],n[1],o,new Map(Object.entries(i)),s)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");let t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");let t=this.text.findIndexesFromRange([re.fromStruct(e[0]),re.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}constructor(e,t){this.context=e,this.text=t}}class r9{initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new ti(x.ErrNotInitialized,"Counter is not initialized yet");let t=this.context.issueTimeTicket(),r=tC.of(e,t);if(!r.isNumericType())throw TypeError("Unsupported type of value: ".concat(typeof r.getValue()));return this.counter.increase(r),this.context.push(rs.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new ti(x.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}constructor(e,t){this.valueType=e,this.value=t}}function r4(e,t,r){let{type:n}=e,i=r.issueTimeTicket();if(n===tM){r8(e);let{value:r}=e,s=tY.create(tH.of(i,0),n,r);t.append(s)}else{let s;let{children:o=[]}=e,{attributes:a}=e;if("object"==typeof a&&!to(a)){let e=ta(a);for(let[t,r]of(s=new tO,Object.entries(e)))s.set(t,r,i)}let c=tY.create(tH.of(i,0),n,void 0,s);for(let e of(t.append(c),o))r4(e,c,r)}}function r8(e){if(!e.value.length)throw new ti(x.ErrInvalidArgument,"text node cannot have empty value");return!0}function r5(e){if(!e.length)return!0;if(e[0].type===tM)for(let t of e){let{type:e}=t;if(e!==tM)throw new ti(x.ErrInvalidArgument,"element node and text node cannot be passed together");r8(t)}else for(let t of e){let{type:e}=t;if(e===tM)throw new ti(x.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class r6{initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return tY.create(tH.of(e.issueTimeTicket(),0),"root");let t=tY.create(tH.of(e.issueTimeTicket(),0),this.initialRoot.type);for(let r of this.initialRoot.children)r4(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new ti(x.ErrInvalidArgument,"path should not be empty");let[r,n]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),s=t?ta(t):void 0,[o]=this.tree.style([r,n],s,i);this.context.push(ro.create(this.tree.getCreatedAt(),r,n,o,s?new Map(Object.entries(s)):new Map,i))}style(e,t,r){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.tree.findPos(e),i=this.tree.findPos(t),s=this.context.issueTimeTicket(),o=r?ta(r):void 0,[a,c]=this.tree.style([n,i],o,s);for(let e of c)this.context.registerGCPair(e);this.context.push(ro.create(this.tree.getCreatedAt(),n,i,a,o?new Map(Object.entries(o)):new Map,s))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.tree.findPos(e),i=this.tree.findPos(t),s=this.context.issueTimeTicket(),[o,a]=this.tree.removeStyle([n,i],r,s);for(let e of a)this.context.registerGCPair(e);this.context.push(ro.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),n,i,o,r,s))}editInternal(e,t,r){var n;let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(0!==r.length&&r[0]&&(r5(r),r[0].type!==tM))for(let e of r){let{children:t=[]}=e;r5(t)}let s=this.context.getLastTimeTicket(),o=[];if((null===(n=r[0])||void 0===n?void 0:n.type)===tM){let e="";for(let t of r){let{value:r}=t;e+=r}o.push(tY.create(tH.of(this.context.issueTimeTicket(),0),tM,e))}else o=r.map(e=>e&&function(e,t){let r;let{type:n}=t,i=e.issueTimeTicket();if(t.type===tM){let{value:e}=t;r=tY.create(tH.of(i,0),n,e)}else if(t){let s;let{children:o=[]}=t,{attributes:a}=t;if("object"==typeof a&&!to(a)){let e=ta(a);for(let[t,r]of(s=new tO,Object.entries(e)))s.set(t,r,i)}for(let t of(r=tY.create(tH.of(e.issueTimeTicket(),0),n,void 0,s),o))r4(t,r,e)}return r}(this.context,e)).filter(e=>e);let[,a,c]=this.tree.edit([e,t],o.length?o.map(e=>null==e?void 0:e.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(let e of a)this.context.registerGCPair(e);return this.context.push(t$.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,i,c,s)),!0}editByPath(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ti(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ti(x.ErrInvalidArgument,"path should not be empty");let i=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(i,s,r?[r]:[],n)}editBulkByPath(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ti(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ti(x.ErrInvalidArgument,"path should not be empty");let i=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(i,s,r,n)}edit(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(i,s,r?[r]:[],n)}editBulk(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(i,s,r,n)}toXML(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(t);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[tG.fromStruct(e[0]),tG.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[tG.fromStruct(e[0]),tG.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}constructor(e){this.initialRoot=e}}function r7(e,t){if(t){if(t instanceof tC)return t;if(t instanceof tw)return r0(e,t);if(t instanceof tE)return function(e,t){let r=new r2(e,t);return new Proxy(t,r.getHandlers())}(e,t);if(t instanceof tJ)return new r3(e,t);else if(t instanceof ri){let r=new r9(N.IntegerCnt,0);return r.initialize(e,t),r}else if(t instanceof tQ){let r=new r6;return r.initialize(e,t),r}throw TypeError("Unsupported type of element: ".concat(typeof t))}}function ne(e,t){let r=r7(e,t);return r instanceof tC?r.getValue():r}function nt(e,t,r){let n;if(tC.isSupport(t))n=tC.of(t,r);else if(Array.isArray(t))n=tE.create(r,r2.buildArrayElements(e,t));else if("object"==typeof t)t instanceof r3?(n=tJ.create(rr.create(),r),t.initialize(e,n)):t instanceof r9?(n=ri.create(t.getValueType(),t.getValue(),r),t.initialize(e,n)):t instanceof r6?(n=tQ.create(t.buildRoot(e),r),t.initialize(e,n)):n=tw.create(r,r1.buildObjectMembers(e,t));else throw TypeError("Unsupported type of value: ".concat(typeof t));return n}class nr{hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=50&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=50&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}constructor(){this.undoStack=[],this.redoStack=[]}}let nn="disconnected",ni=new Map,ns=new Map;function no(e,t){((null==t?void 0:t.force)||"disconnected"!==nn)&&window.postMessage({source:"yorkie-devtools-sdk",...e},"*")}window.transactionEventsByDocKey=ns,(m=B||(B={})).Detached="detached",m.Attached="attached",m.Removed="removed",(p=J||(J={})).StatusChanged="status-changed",p.ConnectionChanged="connection-changed",p.SyncStatusChanged="sync-status-changed",p.Snapshot="snapshot",p.LocalChange="local-change",p.RemoteChange="remote-change",p.Initialized="initialized",p.Watched="watched",p.Unwatched="unwatched",p.PresenceChanged="presence-changed",p.Broadcast="broadcast",p.LocalBroadcast="local-broadcast",(y=L||(L={})).Connected="connected",y.Disconnected="disconnected",(v=_||(_={})).Synced="synced",v.SyncFailed="sync-failed";class na{update(e,t){if("removed"===this.getStatus())throw new ti(x.ErrDocumentRemoved,"".concat(this.key," is removed"));this.ensureClone();let r=this.changeID.getActorID(),n=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{var i;let t=(i=this.clone.root.getObject(),r0(n,i));this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(t,new tl(n,this.clone.presences.get(r)))}catch(e){throw this.clone=void 0,e}finally{this.isUpdating=!1}if(n.hasChange()){rG.isEnabled(O.Trivial)&&rG.trivial("trying to update a local change: ".concat(this.toJSON()));let e=n.getChange(),{opInfos:t,reverseOps:i}=e.execute(this.root,this.presences,E.Local),s=n.getReversePresence();s&&i.push({type:"presence",value:s}),this.localChanges.push(e),i.length>0&&this.internalHistory.pushUndo(i),t.length>0&&this.internalHistory.clearRedo(),this.changeID=e.getID();let o=[];t.length>0&&o.push({type:"local-change",source:E.Local,value:{message:e.getMessage()||"",operations:t,actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq()},rawChange:this.isEnableDevtools()?e.toStruct():void 0}),e.hasPresenceChange()&&o.push({type:"presence-changed",source:E.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(o),rG.isEnabled(O.Trivial)&&rG.trivial("after update a local change: ".concat(this.toJSON()))}}subscribe(e,t,r,n){if("string"==typeof e){if("function"!=typeof t)throw new ti(x.ErrInvalidArgument,"Second argument must be a callback function");return"presence"===e?this.eventStream.subscribe(e=>{for(let r of e)("initialized"===r.type||"watched"===r.type||"unwatched"===r.type||"presence-changed"===r.type)&&t(r)},r,n):"my-presence"===e?this.eventStream.subscribe(e=>{for(let r of e)("initialized"===r.type||"presence-changed"===r.type)&&("presence-changed"!==r.type||r.value.clientID===this.changeID.getActorID())&&t(r)},r,n):"others"===e?this.eventStream.subscribe(e=>{for(let r of e)("watched"===r.type||"unwatched"===r.type||"presence-changed"===r.type)&&r.value.clientID!==this.changeID.getActorID()&&t(r)},r,n):"connection"===e?this.eventStream.subscribe(e=>{for(let r of e)"connection-changed"===r.type&&t(r)},r,n):"status"===e?this.eventStream.subscribe(e=>{for(let r of e)"status-changed"===r.type&&t(r)},r,n):"sync"===e?this.eventStream.subscribe(e=>{for(let r of e)"sync-status-changed"===r.type&&t(r)},r,n):"local-broadcast"===e?this.eventStream.subscribe(e=>{for(let r of e)"local-broadcast"===r.type&&t(r)},r):"broadcast"===e?this.eventStream.subscribe(e=>{for(let r of e)"broadcast"===r.type&&t(r)},r):"all"===e?this.eventStream.subscribe(t,r,n):this.eventStream.subscribe(r=>{for(let n of r){if("local-change"!==n.type&&"remote-change"!==n.type)continue;let r=[];for(let t of n.value.operations)this.isSameElementOrChildOf(t.path,e)&&r.push(t);r.length&&t({...n,value:{...n.value,operations:r}})}},r,n)}if("function"==typeof e)return this.eventStream.subscribe(t=>{for(let r of t)("snapshot"===r.type||"local-change"===r.type||"remote-change"===r.type)&&e(r)},t,r);throw new ti(x.ErrInvalidArgument,'"'.concat(e,'" is not a valid'))}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;let r=e.split(".");return t.split(".").every((e,t)=>e===r[t])}applyChangePack(e){let t=e.hasSnapshot();for(t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),E.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();t&&this.applyChanges(this.localChanges,E.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),rG.isEnabled(O.Trivial)&&rG.trivial("".concat(this.root.toJSON()))}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:ts(this.presences)})}createChangePack(){let e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return t4.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(let t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){return this.ensureClone(),r0(rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{}),this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r){let{root:n,presences:i}=rU.bytesToSnapshot(r);this.root=new r$(n),this.presences=i,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.publish([{type:"snapshot",source:E.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?rU.bytesToHex(r):void 0,snapshotVector:rU.versionVectorToHex(t)}}])}applyChanges(e,t){for(let r of(rG.isEnabled(O.Debug)&&rG.debug("trying to apply ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+"removeds:".concat(this.root.getGarbageElementSetSize())),rG.isEnabled(O.Trivial)&&rG.trivial(e.map(e=>"".concat(e.getID().toTestString()," ").concat(e.toTestString())).join("\n")),e))this.applyChange(r,t);rG.isEnabled(O.Debug)&&rG.debug("after appling ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+" removeds:".concat(this.root.getGarbageElementSetSize()))}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);let r=[],n=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(n)){let i=e.getPresenceChange();switch(i.type){case P.Put:r.push(this.presences.has(n)?{type:"presence-changed",source:t,value:{clientID:n,presence:i.presence}}:{type:"watched",source:E.Remote,value:{clientID:n,presence:i.presence}});break;case P.Clear:r.push({type:"unwatched",source:E.Remote,value:{clientID:n,presence:this.getPresence(n)}}),this.removeOnlineClient(n)}}let{opInfos:i}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),i.length>0){let s=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===E.Remote?{type:"remote-change",source:t,value:{actor:n,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:s}:{type:"local-change",source:t,value:{actor:n,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:s})}r.length>0&&this.publish(r)}applyWatchStream(e){if("initialization"===e.body.case){let t=e.body.value.clientIds,r=new Set;for(let e of t)e!==this.changeID.getActorID()&&r.add(e);this.setOnlineClients(r),this.publish([{type:"initialized",source:E.Local,value:this.getPresences()}]);return}if("event"===e.body.case){let{type:t,publisher:r}=e.body.value,n=[];if(t===I.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&n.push({type:"watched",source:E.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(t===I.DOCUMENT_UNWATCHED){let e=this.getPresence(r);this.removeOnlineClient(r),e&&n.push({type:"unwatched",source:E.Remote,value:{clientID:r,presence:e}})}else if(t===I.DOCUMENT_BROADCAST&&e.body.value.body){let{topic:t,payload:i}=e.body.value.body,s=new TextDecoder;n.push({type:"broadcast",value:{clientID:r,topic:t,payload:JSON.parse(s.decode(i))}})}n.length>0&&this.publish(n)}}applyStatus(e){this.status=e,"detached"===e&&this.setActor(th),this.publish([{source:"removed"===e?E.Remote:E.Local,type:"status-changed",value:"attached"===e?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if("status-changed"===e.type){this.applyStatus(e.value.status),"attached"===e.value.status&&this.setActor(e.value.actorID);return}if("snapshot"===e.type){let{snapshot:t,serverSeq:r,snapshotVector:n}=e.value;if(!t)return;this.applySnapshot(BigInt(r),rU.hexToVersionVector(n),rU.hexToBytes(t));return}if("local-change"===e.type||"remote-change"===e.type){if(!e.rawChange)return;let t=t9.fromStruct(e.rawChange);this.applyChange(t,e.source)}if("initialized"===e.type){let t=new Set;for(let{clientID:r,presence:n}of e.value)t.add(r),this.presences.set(r,n);this.setOnlineClients(t);return}if("watched"===e.type){let{clientID:t,presence:r}=e.value;this.addOnlineClient(t),this.presences.set(t,r);return}if("unwatched"===e.type){let{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if("presence-changed"===e.type){let{clientID:t,presence:r}=e.value;this.presences.set(t,r)}}applyTransactionEvent(e){for(let t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new ti(x.ErrInvalidArgument,'path must start with "$"');let t=e.split(".");t.shift();let r=this.getRoot();for(let e of t)if(void 0===(r=r[e]))return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if("attached"!==this.status)return{};let e=this.presences.get(this.changeID.getActorID());return e?ts(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;let t=this.presences.get(e);return t?ts(t):void 0}getPresenceForTest(e){let t=this.presences.get(e);return t?ts(t):void 0}getPresences(){let e=[];for(let t of(e.push({clientID:this.changeID.getActorID(),presence:ts(this.getMyPresence())}),this.onlineClients))this.presences.has(t)&&e.push({clientID:t,presence:ts(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){let e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((e,t)=>e.clientID>t.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){let t=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(t)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new ti(x.ErrRefused,"Undo is not allowed during an update");let e=this.internalHistory.popUndo();if(void 0===e)throw new ti(x.ErrRefused,"There is no operation to be undone");this.ensureClone();let t=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tA)){new tl(t,ts(this.clone.presences.get(this.changeID.getActorID()))).set(r.value,{addToHistory:!0});continue}let e=t.issueTimeTicket();r.setExecutedAt(e),t.push(r)}let r=t.getChange();r.execute(this.clone.root,this.clone.presences,E.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,E.UndoRedo),s=t.getReversePresence();if(s&&i.push({type:"presence",value:s}),i.length>0&&this.internalHistory.pushRedo(i),!r.hasPresenceChange()&&0===n.length)return;this.localChanges.push(r),this.changeID=r.getID();let o=this.changeID.getActorID(),a=[];n.length>0&&a.push({type:"local-change",source:E.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:o,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&a.push({type:"presence-changed",source:E.UndoRedo,value:{clientID:o,presence:this.getPresence(o)}}),this.publish(a)}redo(){if(this.isUpdating)throw new ti(x.ErrRefused,"Redo is not allowed during an update");let e=this.internalHistory.popRedo();if(void 0===e)throw new ti(x.ErrRefused,"There is no operation to be redone");this.ensureClone();let t=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tA)){new tl(t,ts(this.clone.presences.get(this.changeID.getActorID()))).set(r.value,{addToHistory:!0});continue}let e=t.issueTimeTicket();r.setExecutedAt(e),t.push(r)}let r=t.getChange();r.execute(this.clone.root,this.clone.presences,E.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,E.UndoRedo),s=t.getReversePresence();if(s&&i.push({type:"presence",value:s}),i.length>0&&this.internalHistory.pushUndo(i),!r.hasPresenceChange()&&0===n.length)return;this.localChanges.push(r),this.changeID=r.getID();let o=this.changeID.getActorID(),a=[];n.length>0&&a.push({type:"local-change",source:E.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:o,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&a.push({type:"presence-changed",source:E.UndoRedo,value:{clientID:o,presence:this.getPresence(o)}}),this.publish(a)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){this.publish([{type:"local-broadcast",value:{topic:e,payload:t},options:r}])}getVersionVector(){return this.changeID.getVersionVector()}constructor(e,t){this.opts=t||{},this.key=e,this.status="detached",this.root=r$.create(),this.changeID=t3,this.checkpoint=t5,this.localChanges=[],this.eventStream=function(e){let t=new rX(e);return{subscribe:t.subscribe.bind(t),getProxy:()=>t}}(e=>{this.eventStreamObserver=e}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new nr,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},function(e){if(!e.isEnableDevtools()||ni.has(e.getKey()))return;ns.set(e.getKey(),[]);let t=e.subscribe("all",t=>{t.some(e=>e.type!==J.StatusChanged&&e.type!==J.Snapshot&&e.type!==J.LocalChange&&e.type!==J.RemoteChange&&e.type!==J.Initialized&&e.type!==J.Watched&&e.type!==J.Unwatched&&e.type!==J.PresenceChanged)||(ns.get(e.getKey()).push(t),"synced"===nn&&no({msg:"doc::sync::partial",docKey:e.getKey(),event:t}))});ni.set(e.getKey(),[t]),no({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if((null===(r=t.data)||void 0===r?void 0:r.source)==="yorkie-devtools-panel")switch(t.data.msg){case"devtools::connect":if("disconnected"!==nn)break;nn="connected",no({msg:"doc::available",docKey:e.getKey()}),rG.info("[YD] Devtools connected. Doc: ".concat(e.getKey()));break;case"devtools::disconnect":nn="disconnected",rG.info("[YD] Devtools disconnected. Doc: ".concat(e.getKey()));break;case"devtools::subscribe":nn="synced",no({msg:"doc::sync::full",docKey:e.getKey(),events:ns.get(e.getKey())}),rG.info("[YD] Devtools subscribed. Doc: ".concat(e.getKey()))}})}(this)}}var nc=JSON.parse('{"u2":"yorkie-js-sdk","i8":"0.5.4"}');let nl=e=>{try{let t=JSON.stringify(e);if(void 0===t)return!1}catch(e){return!1}return!0};(w=M||(M={})).Manual="manual",w.Realtime="realtime",w.RealtimePushOnly="realtime-pushonly",w.RealtimeSyncOff="realtime-syncoff",(A=q||(q={})).Deactivated="deactivated",A.Activated="activated",(T=z||(z={})).SyncLoop="SyncLoop",T.WatchLoop="WatchLoop";let nh={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},nd={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class nu{activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),rG.info('[AC] c:"'.concat(this.getKey(),'" activated, id:"').concat(this.id,'"'))}).catch(e=>{throw rG.error('[AC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}deactivate(){return"deactivated"===this.status?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),rG.info('[DC] c"'.concat(this.getKey(),'" deactivated'))}).catch(e=>{throw rG.error('[DC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}attach(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e.getStatus()!==B.Detached)throw new ti(x.ErrDocumentNotDetached,"".concat(e.getKey()," is not detached"));e.setActor(this.id),e.update((e,t)=>t.set(r.initialPresence||{}));let n=e.subscribe("local-broadcast",async t=>{var r;let{topic:n,payload:i}=t.value,s=null===(r=t.options)||void 0===r?void 0:r.error,o=t.options;try{await this.broadcast(e.getKey(),n,i,o)}catch(e){e instanceof Error&&(null==s||s(e))}}),i=null!==(t=r.syncMode)&&void 0!==t?t:"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:rU.toChangePack(e.createChangePack())},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(async t=>{let s=rU.fromChangePack(t.changePack);if(e.applyChangePack(s),e.getStatus()===B.Removed)return e;e.applyStatus(B.Attached),this.attachmentMap.set(e.getKey(),new rY(this.reconnectStreamDelay,e,t.documentId,i,n)),"manual"!==i&&await this.runWatchLoop(e.getKey()),rG.info('[AD] c:"'.concat(this.getKey(),'" attaches d:"').concat(e.getKey(),'"'));let o=e.getRootObject();if(r.initialRoot){let t=r.initialRoot;e.update(e=>{for(let[r,n]of Object.entries(t))o.has(r)||(e[r]=n)})}return e}).catch(e=>{throw rG.error('[AD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}detach(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return e.update((e,t)=>t.clear()),this.enqueueTask(async()=>{var n;return this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:rU.toChangePack(e.createChangePack()),removeIfNotAttached:null!==(n=t.removeIfNotAttached)&&void 0!==n&&n},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(t=>{let r=rU.fromChangePack(t.changePack);return e.applyChangePack(r),e.getStatus()!==B.Removed&&e.applyStatus(B.Detached),this.detachInternal(e.getKey()),rG.info('[DD] c:"'.concat(this.getKey(),'" detaches d:"').concat(e.getKey(),'"')),e}).catch(e=>{throw rG.error('[DD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}async changeSyncMode(e,t){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));let n=r.syncMode;return n===t||((r.changeSyncMode(t),"manual"===t)?r.cancelWatchStream():("realtime"===t&&(r.remoteChangeEventReceived=!0),"manual"===n&&await this.runWatchLoop(e.getKey()))),e}sync(e){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e){let t=this.attachmentMap.get(e.getKey());if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(e=>{throw rG.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}return this.enqueueTask(async()=>{let e=[];for(let[,t]of this.attachmentMap)e.push(this.syncInternal(t,t.syncMode));return Promise.all(e).catch(e=>{throw rG.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}remove(e){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let t=this.attachmentMap.get(e.getKey());if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));e.setActor(this.id);let r=rU.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:r},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(t=>{let r=rU.fromChangePack(t.changePack);e.applyChangePack(r),this.detachInternal(e.getKey()),rG.info('[RD] c:"'.concat(this.getKey(),'" removes d:"').concat(e.getKey(),'"'))}).catch(e=>{throw rG.error('[RD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}getID(){return this.id}getKey(){return this.key}isActive(){return"activated"===this.status}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,n){var i;if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let s=this.attachmentMap.get(e);if(!s)throw new ti(x.ErrDocumentNotAttached,"".concat(e," is not attached"));if(!nl(r))throw new ti(x.ErrInvalidArgument,"payload is not serializable");let o=null!==(i=null==n?void 0:n.maxRetries)&&void 0!==i?i:nd.maxRetries,a=nd.maxBackoff,c=0,l=e=>Math.min(nd.initialRetryInterval*2**e,a),h=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e)}}).then(()=>{rG.info('[BC] c:"'.concat(this.getKey(),'" broadcasts d:"').concat(e,'" t:"').concat(t,'"'))}).catch(e=>{if(rG.error('[BC] c:"'.concat(this.getKey(),'" err:'),e),this.handleConnectError(e)){if(ch(),l(++c-1)),rG.info('[BC] c:"'.concat(this.getKey(),'" retry attempt ').concat(c,"/").concat(o));else throw rG.error('[BC] c:"'.concat(this.getKey(),'" exceeded maximum retry attempts')),e}else throw e}));return h()}runSyncLoop(){let e=()=>{if(!this.isActive()){rG.debug('[SL] c:"'.concat(this.getKey(),'" exit sync loop')),this.conditions.SyncLoop=!1;return}let t=[];for(let[,e]of this.attachmentMap)e.needRealtimeSync()&&(e.remoteChangeEventReceived=!1,t.push(this.syncInternal(e,e.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(t=>{rG.error('[SL] c:"'.concat(this.getKey(),'" sync failed:'),t),this.handleConnectError(t)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};rG.debug('[SL] c:"'.concat(this.getKey(),'" run sync loop')),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){let t=this.attachmentMap.get(e);if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e," is not attached"));return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new ti(x.ErrClientNotActivated,"".concat(this.key," is not active")));let n=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e)},signal:n.signal});return t.doc.publish([{type:J.ConnectionChanged,value:L.Connected}]),rG.info('[WD] c:"'.concat(this.getKey(),'" watches d:"').concat(e,'"')),new Promise((e,s)=>{(async()=>{try{for await(let r of i)this.handleWatchDocumentsResponse(t,r),"initialization"===r.body.case&&e([i,n])}catch(e){t.doc.resetOnlineClients(),t.doc.publish([{type:J.Initialized,source:E.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:J.ConnectionChanged,value:L.Disconnected}]),rG.debug('[WD] c:"'.concat(this.getKey(),'" unwatches')),this.handleConnectError(e)?r():this.conditions.WatchLoop=!1,s(e)}})()})})}handleWatchDocumentsResponse(e,t){if("event"===t.body.case&&t.body.value.type===I.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){for(let[e,t]of(this.status="deactivated",this.attachmentMap))this.detachInternal(e),t.doc.applyStatus(B.Detached)}detachInternal(e){let t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){let{doc:r,docID:n}=e,i=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:n,changePack:rU.toChangePack(i),pushOnly:"realtime-pushonly"===t},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(r.getKey())}}).then(t=>{let n=rU.fromChangePack(t.changePack);if(n.hasChanges()&&("realtime-pushonly"===e.syncMode||"realtime-syncoff"===e.syncMode))return r;r.applyChangePack(n),e.doc.publish([{type:J.SyncStatusChanged,value:_.Synced}]),r.getStatus()===B.Removed&&this.detachInternal(r.getKey());let s=r.getKey(),o=n.getChangeSize();return rG.info('[PP] c:"'.concat(this.getKey(),'" sync d:"').concat(s,'", push:').concat(i.getChangeSize()," pull:").concat(o," cp:").concat(n.getCheckpoint().toTestString())),r}).catch(e=>{throw r.publish([{type:J.SyncStatusChanged,value:_.SyncFailed}]),rG.error('[PP] c:"'.concat(this.getKey(),'" err :'),e),e})}handleConnectError(e){return e instanceof G.K&&(e.code===H.E.Canceled||e.code===H.E.Unknown||e.code===H.E.ResourceExhausted||e.code===H.E.Unavailable||((rT(e)===x.ErrClientNotActivated||rT(e)===x.ErrClientNotFound)&&this.deactivateInternal(),!1))}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(0===this.taskQueue.length){this.processing=!1;return}try{this.processing=!0;let e=this.taskQueue.shift();await e()}catch(e){rG.error('[TQ] c:"'.concat(this.getKey(),'" process failed, id:"').concat(this.id,'"'))}this.processNext()}constructor(e,t){var r,n;this.processing=!1,t=t||nh,this.key=t.key?t.key:rH(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||nh.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||nh.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||nh.retrySyncLoopDelay,this.rpcClient=(0,Y.Hb)(tr,(0,Z.u)({baseUrl:e,interceptors:[(r=t.apiKey,n=t.token,e=>async t=>(r&&t.header.set("x-api-key",r),n&&t.header.set("authorization",n),await e(t))),e=>async t=>(t.header.set("x-yorkie-user-agent",nc.u2+"/"+nc.i8),await e(t))]})),this.taskQueue=[]}}var ng={Client:nu,Document:na,Primitive:tC,Text:r3,Counter:r9,Tree:r6,LogLevel:O,setLogLevel:rW,IntType:N.IntegerCnt,LongType:N.LongCnt};"undefined"!=typeof globalThis&&(globalThis.yorkie={Client:nu,Document:na,Primitive:tC,Text:r3,Counter:r9,Tree:r6,LogLevel:O,setLogLevel:rW,IntType:N.IntegerCnt,LongType:N.LongCnt}),r(109);var nf=r(6182);function nm(e){let{content:t,actions:r}=e,[n,i]=(0,U.useState)(new Date),[s,o]=(0,U.useState)("Enter text here!"),a=n?W(new Date(n.toString())):"",c=e=>{let n=!1;switch(e){case"PUSH":n=!1,t.forEach(e=>{if(e.date===a)return n=!n,0}),n?r.updateContent(a,s):r.addContent(a,s),o("Enter text here!");break;case"DELETE":r.deleteContent(a)}};return(0,K.jsx)("article",{children:(0,K.jsxs)("div",{children:[(0,K.jsx)(nf.ZP,{onChange:i,value:n,locale:"en-EN",showNeighboringMonth:!1,formatDay:(e,t)=>t.toLocaleString("en",{day:"numeric"}),tileClassName:e=>{let{date:r}=e;return t.find(e=>e.date===W(r))?"highlight":""}}),(0,K.jsxs)("p",{children:["selected day : ",a]}),(0,K.jsx)("div",{className:V().memo,children:t.map((e,t)=>{if(e.date===a)return(0,K.jsx)("p",{children:e.text},t)})}),(0,K.jsxs)("div",{className:V().inputForm_editor,children:[(0,K.jsx)("h3",{children:"input form"}),(0,K.jsx)("textarea",{className:V().textArea,value:s,onChange:e=>o(e.target.value)})]}),(0,K.jsx)("button",{className:"button",onClick:()=>c("PUSH"),children:"push"}),(0,K.jsx)("button",{className:"button",onClick:()=>c("DELETE"),children:"pop"})]})})}let np=[{date:W(new Date).replace(/^\d{2}/,"01"),text:"payday"},{date:W(new Date).replace(/^\d{2}/,"17"),text:"Garry's birthday"}],ny="next.js-Scheduler-".concat(W(new Date));function nv(){let[e,t]=(0,U.useState)([]),[r,n]=(0,U.useState)(np),[i]=(0,U.useState)(()=>new ng.Document(ny));return(0,U.useEffect)(()=>{let e=new ng.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});i.subscribe("presence",e=>{e.type!==J.PresenceChanged&&t(function(e){let t=[];for(let{presence:r}of e)t.push(r.userName);return t}(i.getPresences()))}),async function(t,r){await e.activate(),await e.attach(t,{initialPresence:{userName:function(){let e=Math.floor(Math.random()*j.length);return j[e]}()}}),t.update(e=>{e.content||(e.content=np)},"create default content if not exists"),t.subscribe(()=>{r(t.getRoot().content)}),r(t.getRoot().content)}(i,e=>n(e))},[]),(0,K.jsxs)("main",{className:V().main,children:[(0,K.jsxs)("p",{children:["peers : [",e.map((e,t)=>(0,K.jsxs)("span",{children:[" ",e,", "]},t))," ","]"]}),(0,K.jsx)(nm,{content:r,actions:{addContent(e,t){i.update(r=>{r.content.push({date:e,text:t})})},deleteContent(e){i.update(t=>{let r;for(let n of t.content)if(n.date===e){r=n;break}r&&t.content.deleteByID(r.getID())})},updateContent(e,t){i.update(r=>{let n;for(let t of r.content)if(t.date===e){n=t;break}n&&(n.text=t)})}}})]})}},109:function(){},7397:function(e){e.exports={main:"page_main__s_E_L",textArea:"page_textArea__sVKfA",memo:"page_memo__V0Ipn",inputForm_editor:"page_inputForm_editor__Tk7dD"}}},function(e){e.O(0,[662,828,852,744],function(){return e(e.s=4629)}),_N_E=e.O()}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{4629:function(e,t,r){Promise.resolve().then(r.bind(r,1802))},1802:function(e,t,r){"use strict";r.r(t),r.d(t,{default:function(){return nv}});var n,i,s,o,a,c,l,h,d,u,g,f,m,p,y,v,w,A,T,S,I,C,x,P,E,b,k,D,R,N,O,B,J,L,_,M,q,z,K=r(3165),F=r(7397),V=r.n(F),U=r(6189);let j=["Alice","Bob","Carol","Chuck","Dave","Erin","Frank","Grace","Ivan","Justin","Matilda","Oscar","Steve","Victor","Zoe"];function W(e){let[t,r,n]=e.toLocaleDateString("en").split("/");return t=Number(t)>9?t:"0"+t,r=Number(r)>9?r:"0"+r,n=n.slice(2),"".concat(r,"-").concat(t,"-").concat(n)}var G=r(8358),H=r(6390),Y=r(4715),Z=r(1582),X=r(8728),Q=r(601),$=r(1089),ee=r(6731),et=r(9782);(n=S||(S={}))[n.NULL=0]="NULL",n[n.BOOLEAN=1]="BOOLEAN",n[n.INTEGER=2]="INTEGER",n[n.LONG=3]="LONG",n[n.DOUBLE=4]="DOUBLE",n[n.STRING=5]="STRING",n[n.BYTES=6]="BYTES",n[n.DATE=7]="DATE",n[n.JSON_OBJECT=8]="JSON_OBJECT",n[n.JSON_ARRAY=9]="JSON_ARRAY",n[n.TEXT=10]="TEXT",n[n.INTEGER_CNT=11]="INTEGER_CNT",n[n.LONG_CNT=12]="LONG_CNT",n[n.TREE=13]="TREE",Q.w.util.setEnumType(S,"yorkie.v1.ValueType",[{no:0,name:"VALUE_TYPE_NULL"},{no:1,name:"VALUE_TYPE_BOOLEAN"},{no:2,name:"VALUE_TYPE_INTEGER"},{no:3,name:"VALUE_TYPE_LONG"},{no:4,name:"VALUE_TYPE_DOUBLE"},{no:5,name:"VALUE_TYPE_STRING"},{no:6,name:"VALUE_TYPE_BYTES"},{no:7,name:"VALUE_TYPE_DATE"},{no:8,name:"VALUE_TYPE_JSON_OBJECT"},{no:9,name:"VALUE_TYPE_JSON_ARRAY"},{no:10,name:"VALUE_TYPE_TEXT"},{no:11,name:"VALUE_TYPE_INTEGER_CNT"},{no:12,name:"VALUE_TYPE_LONG_CNT"},{no:13,name:"VALUE_TYPE_TREE"}]),(i=I||(I={}))[i.DOCUMENT_CHANGED=0]="DOCUMENT_CHANGED",i[i.DOCUMENT_WATCHED=1]="DOCUMENT_WATCHED",i[i.DOCUMENT_UNWATCHED=2]="DOCUMENT_UNWATCHED",i[i.DOCUMENT_BROADCAST=3]="DOCUMENT_BROADCAST",Q.w.util.setEnumType(I,"yorkie.v1.DocEventType",[{no:0,name:"DOC_EVENT_TYPE_DOCUMENT_CHANGED"},{no:1,name:"DOC_EVENT_TYPE_DOCUMENT_WATCHED"},{no:2,name:"DOC_EVENT_TYPE_DOCUMENT_UNWATCHED"},{no:3,name:"DOC_EVENT_TYPE_DOCUMENT_BROADCAST"}]);class er extends X.v{static fromBinary(e,t){return new er().fromBinary(e,t)}static fromJson(e,t){return new er().fromJson(e,t)}static fromJsonString(e,t){return new er().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(er,e,t)}constructor(e){super(),this.presences={},Q.w.util.initPartial(e,this)}}er.runtime=Q.w,er.typeName="yorkie.v1.Snapshot",er.fields=Q.w.util.newFieldList(()=>[{no:1,name:"root",kind:"message",T:eA},{no:2,name:"presences",kind:"map",K:9,V:{kind:"message",T:eF}}]);class en extends X.v{static fromBinary(e,t){return new en().fromBinary(e,t)}static fromJson(e,t){return new en().fromJson(e,t)}static fromJsonString(e,t){return new en().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(en,e,t)}constructor(e){super(),this.documentKey="",this.snapshot=new Uint8Array(0),this.changes=[],this.isRemoved=!1,Q.w.util.initPartial(e,this)}}en.runtime=Q.w,en.typeName="yorkie.v1.ChangePack",en.fields=Q.w.util.newFieldList(()=>[{no:1,name:"document_key",kind:"scalar",T:9},{no:2,name:"checkpoint",kind:"message",T:eV},{no:3,name:"snapshot",kind:"scalar",T:12},{no:4,name:"changes",kind:"message",T:ei,repeated:!0},{no:5,name:"min_synced_ticket",kind:"message",T:ej},{no:6,name:"is_removed",kind:"scalar",T:8},{no:7,name:"version_vector",kind:"message",T:eo}]);class ei extends X.v{static fromBinary(e,t){return new ei().fromBinary(e,t)}static fromJson(e,t){return new ei().fromJson(e,t)}static fromJsonString(e,t){return new ei().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ei,e,t)}constructor(e){super(),this.message="",this.operations=[],Q.w.util.initPartial(e,this)}}ei.runtime=Q.w,ei.typeName="yorkie.v1.Change",ei.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:es},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"operations",kind:"message",T:ea,repeated:!0},{no:4,name:"presence_change",kind:"message",T:eK}]);class es extends X.v{static fromBinary(e,t){return new es().fromBinary(e,t)}static fromJson(e,t){return new es().fromJson(e,t)}static fromJsonString(e,t){return new es().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(es,e,t)}constructor(e){super(),this.clientSeq=0,this.serverSeq=$.q.zero,this.lamport=$.q.zero,this.actorId=new Uint8Array(0),Q.w.util.initPartial(e,this)}}es.runtime=Q.w,es.typeName="yorkie.v1.ChangeID",es.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_seq",kind:"scalar",T:13},{no:2,name:"server_seq",kind:"scalar",T:3},{no:3,name:"lamport",kind:"scalar",T:3},{no:4,name:"actor_id",kind:"scalar",T:12},{no:5,name:"version_vector",kind:"message",T:eo}]);class eo extends X.v{static fromBinary(e,t){return new eo().fromBinary(e,t)}static fromJson(e,t){return new eo().fromJson(e,t)}static fromJsonString(e,t){return new eo().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eo,e,t)}constructor(e){super(),this.vector={},Q.w.util.initPartial(e,this)}}eo.runtime=Q.w,eo.typeName="yorkie.v1.VersionVector",eo.fields=Q.w.util.newFieldList(()=>[{no:1,name:"vector",kind:"map",K:9,V:{kind:"scalar",T:3}}]);class ea extends X.v{static fromBinary(e,t){return new ea().fromBinary(e,t)}static fromJson(e,t){return new ea().fromJson(e,t)}static fromJsonString(e,t){return new ea().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ea,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}ea.runtime=Q.w,ea.typeName="yorkie.v1.Operation",ea.fields=Q.w.util.newFieldList(()=>[{no:1,name:"set",kind:"message",T:ec,oneof:"body"},{no:2,name:"add",kind:"message",T:el,oneof:"body"},{no:3,name:"move",kind:"message",T:eh,oneof:"body"},{no:4,name:"remove",kind:"message",T:ed,oneof:"body"},{no:5,name:"edit",kind:"message",T:eu,oneof:"body"},{no:6,name:"select",kind:"message",T:eg,oneof:"body"},{no:7,name:"style",kind:"message",T:ef,oneof:"body"},{no:8,name:"increase",kind:"message",T:em,oneof:"body"},{no:9,name:"tree_edit",kind:"message",T:ep,oneof:"body"},{no:10,name:"tree_style",kind:"message",T:ey,oneof:"body"},{no:11,name:"array_set",kind:"message",T:ev,oneof:"body"}]);class ec extends X.v{static fromBinary(e,t){return new ec().fromBinary(e,t)}static fromJson(e,t){return new ec().fromJson(e,t)}static fromJsonString(e,t){return new ec().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ec,e,t)}constructor(e){super(),this.key="",Q.w.util.initPartial(e,this)}}ec.runtime=Q.w,ec.typeName="yorkie.v1.Operation.Set",ec.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class el extends X.v{static fromBinary(e,t){return new el().fromBinary(e,t)}static fromJson(e,t){return new el().fromJson(e,t)}static fromJsonString(e,t){return new el().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(el,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}el.runtime=Q.w,el.typeName="yorkie.v1.Operation.Add",el.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"prev_created_at",kind:"message",T:ej},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class eh extends X.v{static fromBinary(e,t){return new eh().fromBinary(e,t)}static fromJson(e,t){return new eh().fromJson(e,t)}static fromJsonString(e,t){return new eh().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eh,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eh.runtime=Q.w,eh.typeName="yorkie.v1.Operation.Move",eh.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"prev_created_at",kind:"message",T:ej},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"executed_at",kind:"message",T:ej}]);class ed extends X.v{static fromBinary(e,t){return new ed().fromBinary(e,t)}static fromJson(e,t){return new ed().fromJson(e,t)}static fromJsonString(e,t){return new ed().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ed,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}ed.runtime=Q.w,ed.typeName="yorkie.v1.Operation.Remove",ed.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"executed_at",kind:"message",T:ej}]);class eu extends X.v{static fromBinary(e,t){return new eu().fromBinary(e,t)}static fromJson(e,t){return new eu().fromJson(e,t)}static fromJsonString(e,t){return new eu().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eu,e,t)}constructor(e){super(),this.createdAtMapByActor={},this.content="",this.attributes={},Q.w.util.initPartial(e,this)}}eu.runtime=Q.w,eu.typeName="yorkie.v1.Operation.Edit",eu.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}},{no:5,name:"content",kind:"scalar",T:9},{no:6,name:"executed_at",kind:"message",T:ej},{no:7,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]);class eg extends X.v{static fromBinary(e,t){return new eg().fromBinary(e,t)}static fromJson(e,t){return new eg().fromJson(e,t)}static fromJsonString(e,t){return new eg().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eg,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eg.runtime=Q.w,eg.typeName="yorkie.v1.Operation.Select",eg.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"executed_at",kind:"message",T:ej}]);class ef extends X.v{static fromBinary(e,t){return new ef().fromBinary(e,t)}static fromJson(e,t){return new ef().fromJson(e,t)}static fromJsonString(e,t){return new ef().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ef,e,t)}constructor(e){super(),this.attributes={},this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}ef.runtime=Q.w,ef.typeName="yorkie.v1.Operation.Style",ef.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:ej},{no:6,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}}]);class em extends X.v{static fromBinary(e,t){return new em().fromBinary(e,t)}static fromJson(e,t){return new em().fromJson(e,t)}static fromJsonString(e,t){return new em().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(em,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}em.runtime=Q.w,em.typeName="yorkie.v1.Operation.Increase",em.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"value",kind:"message",T:ew},{no:3,name:"executed_at",kind:"message",T:ej}]);class ep extends X.v{static fromBinary(e,t){return new ep().fromBinary(e,t)}static fromJson(e,t){return new ep().fromJson(e,t)}static fromJsonString(e,t){return new ep().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ep,e,t)}constructor(e){super(),this.createdAtMapByActor={},this.contents=[],this.splitLevel=0,Q.w.util.initPartial(e,this)}}ep.runtime=Q.w,ep.typeName="yorkie.v1.Operation.TreeEdit",ep.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eJ},{no:3,name:"to",kind:"message",T:eJ},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}},{no:5,name:"contents",kind:"message",T:eO,repeated:!0},{no:7,name:"split_level",kind:"scalar",T:5},{no:6,name:"executed_at",kind:"message",T:ej}]);class ey extends X.v{static fromBinary(e,t){return new ey().fromBinary(e,t)}static fromJson(e,t){return new ey().fromJson(e,t)}static fromJsonString(e,t){return new ey().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ey,e,t)}constructor(e){super(),this.attributes={},this.attributesToRemove=[],this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}ey.runtime=Q.w,ey.typeName="yorkie.v1.Operation.TreeStyle",ey.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eJ},{no:3,name:"to",kind:"message",T:eJ},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:ej},{no:6,name:"attributes_to_remove",kind:"scalar",T:9,repeated:!0},{no:7,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}}]);class ev extends X.v{static fromBinary(e,t){return new ev().fromBinary(e,t)}static fromJson(e,t){return new ev().fromJson(e,t)}static fromJsonString(e,t){return new ev().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ev,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}ev.runtime=Q.w,ev.typeName="yorkie.v1.Operation.ArraySet",ev.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class ew extends X.v{static fromBinary(e,t){return new ew().fromBinary(e,t)}static fromJson(e,t){return new ew().fromJson(e,t)}static fromJsonString(e,t){return new ew().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ew,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ew.runtime=Q.w,ew.typeName="yorkie.v1.JSONElementSimple",ew.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"moved_at",kind:"message",T:ej},{no:3,name:"removed_at",kind:"message",T:ej},{no:4,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:5,name:"value",kind:"scalar",T:12}]);class eA extends X.v{static fromBinary(e,t){return new eA().fromBinary(e,t)}static fromJson(e,t){return new eA().fromJson(e,t)}static fromJsonString(e,t){return new eA().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eA,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}eA.runtime=Q.w,eA.typeName="yorkie.v1.JSONElement",eA.fields=Q.w.util.newFieldList(()=>[{no:1,name:"json_object",kind:"message",T:eT,oneof:"body"},{no:2,name:"json_array",kind:"message",T:eS,oneof:"body"},{no:3,name:"primitive",kind:"message",T:eI,oneof:"body"},{no:5,name:"text",kind:"message",T:eC,oneof:"body"},{no:6,name:"counter",kind:"message",T:ex,oneof:"body"},{no:7,name:"tree",kind:"message",T:eP,oneof:"body"}]);class eT extends X.v{static fromBinary(e,t){return new eT().fromBinary(e,t)}static fromJson(e,t){return new eT().fromJson(e,t)}static fromJsonString(e,t){return new eT().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eT,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eT.runtime=Q.w,eT.typeName="yorkie.v1.JSONElement.JSONObject",eT.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eE,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eS extends X.v{static fromBinary(e,t){return new eS().fromBinary(e,t)}static fromJson(e,t){return new eS().fromJson(e,t)}static fromJsonString(e,t){return new eS().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eS,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eS.runtime=Q.w,eS.typeName="yorkie.v1.JSONElement.JSONArray",eS.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eb,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eI extends X.v{static fromBinary(e,t){return new eI().fromBinary(e,t)}static fromJson(e,t){return new eI().fromJson(e,t)}static fromJsonString(e,t){return new eI().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eI,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eI.runtime=Q.w,eI.typeName="yorkie.v1.JSONElement.Primitive",eI.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"moved_at",kind:"message",T:ej},{no:5,name:"removed_at",kind:"message",T:ej}]);class eC extends X.v{static fromBinary(e,t){return new eC().fromBinary(e,t)}static fromJson(e,t){return new eC().fromJson(e,t)}static fromJsonString(e,t){return new eC().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eC,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eC.runtime=Q.w,eC.typeName="yorkie.v1.JSONElement.Text",eC.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eD,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class ex extends X.v{static fromBinary(e,t){return new ex().fromBinary(e,t)}static fromJson(e,t){return new ex().fromJson(e,t)}static fromJsonString(e,t){return new ex().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ex,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ex.runtime=Q.w,ex.typeName="yorkie.v1.JSONElement.Counter",ex.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"moved_at",kind:"message",T:ej},{no:5,name:"removed_at",kind:"message",T:ej}]);class eP extends X.v{static fromBinary(e,t){return new eP().fromBinary(e,t)}static fromJson(e,t){return new eP().fromJson(e,t)}static fromJsonString(e,t){return new eP().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eP,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eP.runtime=Q.w,eP.typeName="yorkie.v1.JSONElement.Tree",eP.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eN,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eE extends X.v{static fromBinary(e,t){return new eE().fromBinary(e,t)}static fromJson(e,t){return new eE().fromJson(e,t)}static fromJsonString(e,t){return new eE().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eE,e,t)}constructor(e){super(),this.key="",Q.w.util.initPartial(e,this)}}eE.runtime=Q.w,eE.typeName="yorkie.v1.RHTNode",eE.fields=Q.w.util.newFieldList(()=>[{no:1,name:"key",kind:"scalar",T:9},{no:2,name:"element",kind:"message",T:eA}]);class eb extends X.v{static fromBinary(e,t){return new eb().fromBinary(e,t)}static fromJson(e,t){return new eb().fromJson(e,t)}static fromJsonString(e,t){return new eb().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eb,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eb.runtime=Q.w,eb.typeName="yorkie.v1.RGANode",eb.fields=Q.w.util.newFieldList(()=>[{no:1,name:"next",kind:"message",T:eb},{no:2,name:"element",kind:"message",T:eA}]);class ek extends X.v{static fromBinary(e,t){return new ek().fromBinary(e,t)}static fromJson(e,t){return new ek().fromJson(e,t)}static fromJsonString(e,t){return new ek().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ek,e,t)}constructor(e){super(),this.value="",this.isRemoved=!1,Q.w.util.initPartial(e,this)}}ek.runtime=Q.w,ek.typeName="yorkie.v1.NodeAttr",ek.fields=Q.w.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:9},{no:2,name:"updated_at",kind:"message",T:ej},{no:3,name:"is_removed",kind:"scalar",T:8}]);class eD extends X.v{static fromBinary(e,t){return new eD().fromBinary(e,t)}static fromJson(e,t){return new eD().fromJson(e,t)}static fromJsonString(e,t){return new eD().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eD,e,t)}constructor(e){super(),this.value="",this.attributes={},Q.w.util.initPartial(e,this)}}eD.runtime=Q.w,eD.typeName="yorkie.v1.TextNode",eD.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:eR},{no:2,name:"value",kind:"scalar",T:9},{no:3,name:"removed_at",kind:"message",T:ej},{no:4,name:"ins_prev_id",kind:"message",T:eR},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"message",T:ek}}]);class eR extends X.v{static fromBinary(e,t){return new eR().fromBinary(e,t)}static fromJson(e,t){return new eR().fromJson(e,t)}static fromJsonString(e,t){return new eR().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eR,e,t)}constructor(e){super(),this.offset=0,Q.w.util.initPartial(e,this)}}eR.runtime=Q.w,eR.typeName="yorkie.v1.TextNodeID",eR.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5}]);class eN extends X.v{static fromBinary(e,t){return new eN().fromBinary(e,t)}static fromJson(e,t){return new eN().fromJson(e,t)}static fromJsonString(e,t){return new eN().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eN,e,t)}constructor(e){super(),this.type="",this.value="",this.depth=0,this.attributes={},Q.w.util.initPartial(e,this)}}eN.runtime=Q.w,eN.typeName="yorkie.v1.TreeNode",eN.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:eB},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"value",kind:"scalar",T:9},{no:4,name:"removed_at",kind:"message",T:ej},{no:5,name:"ins_prev_id",kind:"message",T:eB},{no:6,name:"ins_next_id",kind:"message",T:eB},{no:7,name:"depth",kind:"scalar",T:5},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"message",T:ek}}]);class eO extends X.v{static fromBinary(e,t){return new eO().fromBinary(e,t)}static fromJson(e,t){return new eO().fromJson(e,t)}static fromJsonString(e,t){return new eO().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eO,e,t)}constructor(e){super(),this.content=[],Q.w.util.initPartial(e,this)}}eO.runtime=Q.w,eO.typeName="yorkie.v1.TreeNodes",eO.fields=Q.w.util.newFieldList(()=>[{no:1,name:"content",kind:"message",T:eN,repeated:!0}]);class eB extends X.v{static fromBinary(e,t){return new eB().fromBinary(e,t)}static fromJson(e,t){return new eB().fromJson(e,t)}static fromJsonString(e,t){return new eB().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eB,e,t)}constructor(e){super(),this.offset=0,Q.w.util.initPartial(e,this)}}eB.runtime=Q.w,eB.typeName="yorkie.v1.TreeNodeID",eB.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5}]);class eJ extends X.v{static fromBinary(e,t){return new eJ().fromBinary(e,t)}static fromJson(e,t){return new eJ().fromJson(e,t)}static fromJsonString(e,t){return new eJ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eJ,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eJ.runtime=Q.w,eJ.typeName="yorkie.v1.TreePos",eJ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_id",kind:"message",T:eB},{no:2,name:"left_sibling_id",kind:"message",T:eB}]);class eL extends X.v{static fromBinary(e,t){return new eL().fromBinary(e,t)}static fromJson(e,t){return new eL().fromJson(e,t)}static fromJsonString(e,t){return new eL().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eL,e,t)}constructor(e){super(),this.id="",this.username="",Q.w.util.initPartial(e,this)}}eL.runtime=Q.w,eL.typeName="yorkie.v1.User",eL.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"created_at",kind:"message",T:ee.E}]);class e_ extends X.v{static fromBinary(e,t){return new e_().fromBinary(e,t)}static fromJson(e,t){return new e_().fromJson(e,t)}static fromJsonString(e,t){return new e_().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e_,e,t)}constructor(e){super(),this.id="",this.name="",this.publicKey="",this.secretKey="",this.authWebhookUrl="",this.authWebhookMethods=[],this.clientDeactivateThreshold="",Q.w.util.initPartial(e,this)}}e_.runtime=Q.w,e_.typeName="yorkie.v1.Project",e_.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"public_key",kind:"scalar",T:9},{no:4,name:"secret_key",kind:"scalar",T:9},{no:5,name:"auth_webhook_url",kind:"scalar",T:9},{no:6,name:"auth_webhook_methods",kind:"scalar",T:9,repeated:!0},{no:7,name:"client_deactivate_threshold",kind:"scalar",T:9},{no:8,name:"created_at",kind:"message",T:ee.E},{no:9,name:"updated_at",kind:"message",T:ee.E}]);class eM extends X.v{static fromBinary(e,t){return new eM().fromBinary(e,t)}static fromJson(e,t){return new eM().fromJson(e,t)}static fromJsonString(e,t){return new eM().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eM,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eM.runtime=Q.w,eM.typeName="yorkie.v1.UpdatableProjectFields",eM.fields=Q.w.util.newFieldList(()=>[{no:1,name:"name",kind:"message",T:et.Gm},{no:2,name:"auth_webhook_url",kind:"message",T:et.Gm},{no:3,name:"auth_webhook_methods",kind:"message",T:eq},{no:4,name:"client_deactivate_threshold",kind:"message",T:et.Gm}]);class eq extends X.v{static fromBinary(e,t){return new eq().fromBinary(e,t)}static fromJson(e,t){return new eq().fromJson(e,t)}static fromJsonString(e,t){return new eq().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eq,e,t)}constructor(e){super(),this.methods=[],Q.w.util.initPartial(e,this)}}eq.runtime=Q.w,eq.typeName="yorkie.v1.UpdatableProjectFields.AuthWebhookMethods",eq.fields=Q.w.util.newFieldList(()=>[{no:1,name:"methods",kind:"scalar",T:9,repeated:!0}]);class ez extends X.v{static fromBinary(e,t){return new ez().fromBinary(e,t)}static fromJson(e,t){return new ez().fromJson(e,t)}static fromJsonString(e,t){return new ez().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ez,e,t)}constructor(e){super(),this.id="",this.key="",this.snapshot="",Q.w.util.initPartial(e,this)}}ez.runtime=Q.w,ez.typeName="yorkie.v1.DocumentSummary",ez.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"snapshot",kind:"scalar",T:9},{no:4,name:"created_at",kind:"message",T:ee.E},{no:5,name:"accessed_at",kind:"message",T:ee.E},{no:6,name:"updated_at",kind:"message",T:ee.E}]);class eK extends X.v{static fromBinary(e,t){return new eK().fromBinary(e,t)}static fromJson(e,t){return new eK().fromJson(e,t)}static fromJsonString(e,t){return new eK().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eK,e,t)}constructor(e){super(),this.type=0,Q.w.util.initPartial(e,this)}}eK.runtime=Q.w,eK.typeName="yorkie.v1.PresenceChange",eK.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(C)},{no:2,name:"presence",kind:"message",T:eF}]),(s=C||(C={}))[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.PUT=1]="PUT",s[s.DELETE=2]="DELETE",s[s.CLEAR=3]="CLEAR",Q.w.util.setEnumType(C,"yorkie.v1.PresenceChange.ChangeType",[{no:0,name:"CHANGE_TYPE_UNSPECIFIED"},{no:1,name:"CHANGE_TYPE_PUT"},{no:2,name:"CHANGE_TYPE_DELETE"},{no:3,name:"CHANGE_TYPE_CLEAR"}]);class eF extends X.v{static fromBinary(e,t){return new eF().fromBinary(e,t)}static fromJson(e,t){return new eF().fromJson(e,t)}static fromJsonString(e,t){return new eF().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eF,e,t)}constructor(e){super(),this.data={},Q.w.util.initPartial(e,this)}}eF.runtime=Q.w,eF.typeName="yorkie.v1.Presence",eF.fields=Q.w.util.newFieldList(()=>[{no:1,name:"data",kind:"map",K:9,V:{kind:"scalar",T:9}}]);class eV extends X.v{static fromBinary(e,t){return new eV().fromBinary(e,t)}static fromJson(e,t){return new eV().fromJson(e,t)}static fromJsonString(e,t){return new eV().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eV,e,t)}constructor(e){super(),this.serverSeq=$.q.zero,this.clientSeq=0,Q.w.util.initPartial(e,this)}}eV.runtime=Q.w,eV.typeName="yorkie.v1.Checkpoint",eV.fields=Q.w.util.newFieldList(()=>[{no:1,name:"server_seq",kind:"scalar",T:3},{no:2,name:"client_seq",kind:"scalar",T:13}]);class eU extends X.v{static fromBinary(e,t){return new eU().fromBinary(e,t)}static fromJson(e,t){return new eU().fromJson(e,t)}static fromJsonString(e,t){return new eU().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eU,e,t)}constructor(e){super(),this.offset=0,this.relativeOffset=0,Q.w.util.initPartial(e,this)}}eU.runtime=Q.w,eU.typeName="yorkie.v1.TextNodePos",eU.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5},{no:3,name:"relative_offset",kind:"scalar",T:5}]);class ej extends X.v{static fromBinary(e,t){return new ej().fromBinary(e,t)}static fromJson(e,t){return new ej().fromJson(e,t)}static fromJsonString(e,t){return new ej().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ej,e,t)}constructor(e){super(),this.lamport=$.q.zero,this.delimiter=0,this.actorId=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ej.runtime=Q.w,ej.typeName="yorkie.v1.TimeTicket",ej.fields=Q.w.util.newFieldList(()=>[{no:1,name:"lamport",kind:"scalar",T:3},{no:2,name:"delimiter",kind:"scalar",T:13},{no:3,name:"actor_id",kind:"scalar",T:12}]);class eW extends X.v{static fromBinary(e,t){return new eW().fromBinary(e,t)}static fromJson(e,t){return new eW().fromJson(e,t)}static fromJsonString(e,t){return new eW().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eW,e,t)}constructor(e){super(),this.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eW.runtime=Q.w,eW.typeName="yorkie.v1.DocEventBody",eW.fields=Q.w.util.newFieldList(()=>[{no:1,name:"topic",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12}]);class eG extends X.v{static fromBinary(e,t){return new eG().fromBinary(e,t)}static fromJson(e,t){return new eG().fromJson(e,t)}static fromJsonString(e,t){return new eG().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eG,e,t)}constructor(e){super(),this.type=0,this.publisher="",Q.w.util.initPartial(e,this)}}eG.runtime=Q.w,eG.typeName="yorkie.v1.DocEvent",eG.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(I)},{no:2,name:"publisher",kind:"scalar",T:9},{no:3,name:"body",kind:"message",T:eW}]);class eH extends X.v{static fromBinary(e,t){return new eH().fromBinary(e,t)}static fromJson(e,t){return new eH().fromJson(e,t)}static fromJsonString(e,t){return new eH().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eH,e,t)}constructor(e){super(),this.clientKey="",Q.w.util.initPartial(e,this)}}eH.runtime=Q.w,eH.typeName="yorkie.v1.ActivateClientRequest",eH.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_key",kind:"scalar",T:9}]);class eY extends X.v{static fromBinary(e,t){return new eY().fromBinary(e,t)}static fromJson(e,t){return new eY().fromJson(e,t)}static fromJsonString(e,t){return new eY().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eY,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eY.runtime=Q.w,eY.typeName="yorkie.v1.ActivateClientResponse",eY.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]);class eZ extends X.v{static fromBinary(e,t){return new eZ().fromBinary(e,t)}static fromJson(e,t){return new eZ().fromJson(e,t)}static fromJsonString(e,t){return new eZ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eZ,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eZ.runtime=Q.w,eZ.typeName="yorkie.v1.DeactivateClientRequest",eZ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]);class eX extends X.v{static fromBinary(e,t){return new eX().fromBinary(e,t)}static fromJson(e,t){return new eX().fromJson(e,t)}static fromJsonString(e,t){return new eX().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eX,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eX.runtime=Q.w,eX.typeName="yorkie.v1.DeactivateClientResponse",eX.fields=Q.w.util.newFieldList(()=>[]);class eQ extends X.v{static fromBinary(e,t){return new eQ().fromBinary(e,t)}static fromJson(e,t){return new eQ().fromJson(e,t)}static fromJsonString(e,t){return new eQ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eQ,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eQ.runtime=Q.w,eQ.typeName="yorkie.v1.AttachDocumentRequest",eQ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:en}]);class e$ extends X.v{static fromBinary(e,t){return new e$().fromBinary(e,t)}static fromJson(e,t){return new e$().fromJson(e,t)}static fromJsonString(e,t){return new e$().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e$,e,t)}constructor(e){super(),this.documentId="",Q.w.util.initPartial(e,this)}}e$.runtime=Q.w,e$.typeName="yorkie.v1.AttachDocumentResponse",e$.fields=Q.w.util.newFieldList(()=>[{no:1,name:"document_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:en}]);class e0 extends X.v{static fromBinary(e,t){return new e0().fromBinary(e,t)}static fromJson(e,t){return new e0().fromJson(e,t)}static fromJsonString(e,t){return new e0().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e0,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.removeIfNotAttached=!1,Q.w.util.initPartial(e,this)}}e0.runtime=Q.w,e0.typeName="yorkie.v1.DetachDocumentRequest",e0.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:en},{no:4,name:"remove_if_not_attached",kind:"scalar",T:8}]);class e1 extends X.v{static fromBinary(e,t){return new e1().fromBinary(e,t)}static fromJson(e,t){return new e1().fromJson(e,t)}static fromJsonString(e,t){return new e1().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e1,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e1.runtime=Q.w,e1.typeName="yorkie.v1.DetachDocumentResponse",e1.fields=Q.w.util.newFieldList(()=>[{no:2,name:"change_pack",kind:"message",T:en}]);class e2 extends X.v{static fromBinary(e,t){return new e2().fromBinary(e,t)}static fromJson(e,t){return new e2().fromJson(e,t)}static fromJsonString(e,t){return new e2().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e2,e,t)}constructor(e){super(),this.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e2.runtime=Q.w,e2.typeName="yorkie.v1.WatchDocumentRequest",e2.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9}]);class e3 extends X.v{static fromBinary(e,t){return new e3().fromBinary(e,t)}static fromJson(e,t){return new e3().fromJson(e,t)}static fromJsonString(e,t){return new e3().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e3,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}e3.runtime=Q.w,e3.typeName="yorkie.v1.WatchDocumentResponse",e3.fields=Q.w.util.newFieldList(()=>[{no:1,name:"initialization",kind:"message",T:e9,oneof:"body"},{no:2,name:"event",kind:"message",T:eG,oneof:"body"}]);class e9 extends X.v{static fromBinary(e,t){return new e9().fromBinary(e,t)}static fromJson(e,t){return new e9().fromJson(e,t)}static fromJsonString(e,t){return new e9().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e9,e,t)}constructor(e){super(),this.clientIds=[],Q.w.util.initPartial(e,this)}}e9.runtime=Q.w,e9.typeName="yorkie.v1.WatchDocumentResponse.Initialization",e9.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_ids",kind:"scalar",T:9,repeated:!0}]);class e4 extends X.v{static fromBinary(e,t){return new e4().fromBinary(e,t)}static fromJson(e,t){return new e4().fromJson(e,t)}static fromJsonString(e,t){return new e4().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e4,e,t)}constructor(e){super(),this.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e4.runtime=Q.w,e4.typeName="yorkie.v1.RemoveDocumentRequest",e4.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:en}]);class e8 extends X.v{static fromBinary(e,t){return new e8().fromBinary(e,t)}static fromJson(e,t){return new e8().fromJson(e,t)}static fromJsonString(e,t){return new e8().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e8,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e8.runtime=Q.w,e8.typeName="yorkie.v1.RemoveDocumentResponse",e8.fields=Q.w.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:en}]);class e5 extends X.v{static fromBinary(e,t){return new e5().fromBinary(e,t)}static fromJson(e,t){return new e5().fromJson(e,t)}static fromJsonString(e,t){return new e5().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e5,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.pushOnly=!1,Q.w.util.initPartial(e,this)}}e5.runtime=Q.w,e5.typeName="yorkie.v1.PushPullChangesRequest",e5.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:en},{no:4,name:"push_only",kind:"scalar",T:8}]);class e6 extends X.v{static fromBinary(e,t){return new e6().fromBinary(e,t)}static fromJson(e,t){return new e6().fromJson(e,t)}static fromJsonString(e,t){return new e6().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e6,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e6.runtime=Q.w,e6.typeName="yorkie.v1.PushPullChangesResponse",e6.fields=Q.w.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:en}]);class e7 extends X.v{static fromBinary(e,t){return new e7().fromBinary(e,t)}static fromJson(e,t){return new e7().fromJson(e,t)}static fromJsonString(e,t){return new e7().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e7,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}e7.runtime=Q.w,e7.typeName="yorkie.v1.BroadcastRequest",e7.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}]);class te extends X.v{static fromBinary(e,t){return new te().fromBinary(e,t)}static fromJson(e,t){return new te().fromJson(e,t)}static fromJsonString(e,t){return new te().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(te,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}te.runtime=Q.w,te.typeName="yorkie.v1.BroadcastResponse",te.fields=Q.w.util.newFieldList(()=>[]);var tt=r(6438);let tr={typeName:"yorkie.v1.YorkieService",methods:{activateClient:{name:"ActivateClient",I:eH,O:eY,kind:tt.t.Unary},deactivateClient:{name:"DeactivateClient",I:eZ,O:eX,kind:tt.t.Unary},attachDocument:{name:"AttachDocument",I:eQ,O:e$,kind:tt.t.Unary},detachDocument:{name:"DetachDocument",I:e0,O:e1,kind:tt.t.Unary},removeDocument:{name:"RemoveDocument",I:e4,O:e8,kind:tt.t.Unary},pushPullChanges:{name:"PushPullChanges",I:e5,O:e6,kind:tt.t.Unary},watchDocument:{name:"WatchDocument",I:e2,O:e3,kind:tt.t.ServerStreaming},broadcast:{name:"Broadcast",I:e7,O:te,kind:tt.t.Unary}}};var tn=r(624);(o=x||(x={})).Ok="ok",o.ErrClientNotActivated="ErrClientNotActivated",o.ErrClientNotFound="ErrClientNotFound",o.ErrUnimplemented="ErrUnimplemented",o.ErrInvalidType="ErrInvalidType",o.ErrDummy="ErrDummy",o.ErrDocumentNotAttached="ErrDocumentNotAttached",o.ErrDocumentNotDetached="ErrDocumentNotDetached",o.ErrDocumentRemoved="ErrDocumentRemoved",o.ErrInvalidObjectKey="ErrInvalidObjectKey",o.ErrInvalidArgument="ErrInvalidArgument",o.ErrNotInitialized="ErrNotInitialized",o.ErrNotReady="ErrNotReady",o.ErrRefused="ErrRefused",o.ErrContextNotProvided="ErrContextNotProvided";class ti extends Error{constructor(e,t){super(t),this.code=e,this.message=t,this.name="YorkieError",this.toString=()=>"[code=".concat(this.code,"]: ").concat(this.message)}}function ts(e){if(e instanceof Map){let t=Array.from(e);return new Map(JSON.parse(JSON.stringify(t)))}return JSON.parse(JSON.stringify(e))}let to=e=>!e||0===Object.entries(e).length,ta=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.stringify(n);return t},tc=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.parse(n);return t};(a=P||(P={})).Put="put",a.Clear="clear";class tl{set(e,t){for(let t of Object.keys(e))this.presence[t]=e[t];this.context.setPresenceChange({type:"put",presence:ts(this.presence)}),this.context.setReversePresence(e,t)}get(e){return this.presence[e]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}constructor(e,t){this.context=e,this.presence=t}}let th="000000000000000000000000";class td{static of(e,t,r){return new td(e,t,r)}static fromStruct(e){return td.of(BigInt(e.lamport),e.delimiter,e.actorID)}toIDString(){return"".concat(this.lamport.toString(),":").concat(this.actorID,":").concat(this.delimiter)}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actorID.slice(-2),":").concat(this.delimiter)}setActor(e){return new td(this.lamport,this.delimiter,e)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(e){return this.compare(e)>0}equals(e){return 0===this.compare(e)}compare(e){if(this.lamport>e.lamport)return 1;if(e.lamport>this.lamport)return -1;let t=this.actorID.localeCompare(e.actorID);return 0!==t?t:this.delimiter>e.delimiter?1:e.delimiter>this.delimiter?-1:0}constructor(e,t,r){this.lamport=e,this.delimiter=t,this.actorID=r}}let tu=new td(0n,0,th),tg=new td(0x7fffffffffffffffn,4294967295,"FFFFFFFFFFFFFFFFFFFFFFFF");function tf(e){return e.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(e){switch(e){case'"':case"\\":return"\\"+e;case"\n":return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class tm{getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!!(!this.movedAt||e&&e.after(this.movedAt))&&(this.movedAt=e,!0)}setRemovedAt(e){this.removedAt=e}remove(e){return!!(e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt)))&&(this.removedAt=e,!0)}isRemoved(){return!!this.removedAt}constructor(e){this.createdAt=e}}class tp extends tm{constructor(e){super(e)}}class ty{static of(e,t){return new ty(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}constructor(e,t){this.strKey=e,this.value=t}}class tv{static create(){return new tv}set(e,t,r){let n;let i=this.nodeMapByKey.get(e);null!=i&&!i.isRemoved()&&i.remove(r)&&(n=i.getValue());let s=ty.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),s),(null==i||r.after(i.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,s),t.setMovedAt(r)),n}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new ti(x.ErrInvalidArgument,"fail to find ".concat(e.toIDString()));let r=this.nodeMapByCreatedAt.get(e.toIDString());return r.remove(t),r.getValue()}subPathOf(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){let t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(e.getCreatedAt().toIDString()));let r=this.nodeMapByKey.get(t.getStrKey());t===r&&this.nodeMapByKey.delete(r.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){let r=this.nodeMapByKey.get(e);if(null!=r&&r.remove(t))return r.getValue()}has(e){let t=this.nodeMapByKey.get(e);return null!=t&&!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){let t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(let[,e]of this.nodeMapByKey)yield e}constructor(){this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}}class tw extends tp{static create(e,t){if(!t)return new tw(e,tv.create());let r=tv.create();for(let[e,n]of Object.entries(t))r.set(e,n.deepcopy(),n.getCreatedAt());return new tw(e,r)}subPathOf(e){return this.memberNodes.subPathOf(e)}purge(e){this.memberNodes.purge(e)}set(e,t,r){return this.memberNodes.set(e,t,r)}delete(e,t){return this.memberNodes.delete(e,t)}deleteByKey(e,t){return this.memberNodes.deleteByKey(e,t)}get(e){let t=this.memberNodes.get(e);return null==t?void 0:t.getValue()}getByID(e){let t=this.memberNodes.getByID(e);return null==t?void 0:t.getValue()}has(e){return this.memberNodes.has(e)}toJSON(){let e=[];for(let[t,r]of this)e.push('"'.concat(tf(t),'":').concat(r.toJSON()));return"{".concat(e.join(","),"}")}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){let e={};for(let[t,r]of this){let{createdAt:n,value:i,type:s}=r.toJSForTest();e[t]={key:t,createdAt:n,value:i,type:s}}return{createdAt:this.getCreatedAt().toTestString(),value:e,type:"YORKIE_OBJECT"}}getKeys(){let e=[];for(let[t]of this)e.push(t);return e}toSortedJSON(){let e=[];for(let[t]of this)e.push(t);let t=[];for(let n of e.sort()){var r;let e=null===(r=this.memberNodes.get(n))||void 0===r?void 0:r.getValue();t.push('"'.concat(tf(n),'":').concat(e.toSortedJSON()))}return"{".concat(t.join(","),"}")}getRHT(){return this.memberNodes}deepcopy(){let e=tw.create(this.getCreatedAt());for(let t of this.memberNodes)e.memberNodes.set(t.getStrKey(),t.getValue().deepcopy(),this.getPositionedAt());return e.remove(this.getRemovedAt()),e}getDescendants(e){for(let t of this.memberNodes){let r=t.getValue();if(e(r,this))return;r instanceof tp&&r.getDescendants(e)}}*[Symbol.iterator](){let e=new Set;for(let t of this.memberNodes)e.has(t.getStrKey())||(e.add(t.getStrKey()),t.isRemoved()||(yield[t.getStrKey(),t.getValue()]))}constructor(e,t){super(e),this.memberNodes=t}}(c=E||(E={})).Local="local",c.Remote="remote",c.UndoRedo="undoredo";class tA{getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new ti(x.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}constructor(e,t){this.parentCreatedAt=e,this.executedAt=t}}class tT{getNodeString(){return"".concat(this.weight).concat(this.value)}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}constructor(e){this.value=e,this.initWeight()}}class tS{get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new ti(x.ErrInvalidArgument,"out of index range: pos: ".concat(e," > node.length: ").concat(t.getLength()));return this.splayNode(t),[t,e]}indexOf(e){return e&&(e===this.root||e.hasLinks())?(this.splayNode(e),this.root.getLeftWeight()):-1}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t)):this.root=t,t}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);let t=new tS(e.getLeft());t.root&&t.root.setParent();let r=new tS(e.getRight());if(r.root&&r.root.setParent(),t.root){let e=t.getRightmost();t.splayNode(e),t.root.setRight(r.root),r.root&&r.root.setParent(t.root),this.root=t.root}else this.root=r.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){let t=[];for(let r of(this.traversePostorder(e.getRight(),t),t))r.initWeight();this.updateTreeWeight(e)}toTestString(){let e=[];return this.traverseInorder(this.root,e),e.map(e=>"[".concat(e.getWeight(),",").concat(e.getLength(),"]").concat(e.getValue()||"")).join("")}checkWeight(){let e=[];for(let t of(this.traverseInorder(this.root,e),e))if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){let t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){let t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return!!(e&&e.hasParent())&&e.getParent().getLeft()===e}isRightChild(e){return!!(e&&e.hasParent())&&e.getParent().getRight()===e}constructor(e){this.root=e}}var tI=r(7319);(l=b||(b={}))[l.Null=0]="Null",l[l.Boolean=1]="Boolean",l[l.Integer=2]="Integer",l[l.Long=3]="Long",l[l.Double=4]="Double",l[l.String=5]="String",l[l.Bytes=6]="Bytes",l[l.Date=7]="Date";class tC extends tm{static of(e,t){return new tC(e,t)}static valueFromBytes(e,t){switch(e){case 0:return null;case 1:return!!t[0];case 2:return t[0]|t[1]<<8|t[2]<<16|t[3]<<24;case 4:{let e=new DataView(t.buffer);return t.forEach(function(t,r){e.setUint8(r,t)}),e.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(t);case 3:return tI.Z.fromBytesLE(Array.from(t));case 6:return t;case 7:return new Date(tI.Z.fromBytesLE(Array.from(t),!0).toNumber());default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}toJSON(){return 5===this.valueType?'"'.concat(tf(this.value),'"'):"".concat(this.value)}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){let e=tC.of(this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e.setRemovedAt(this.getRemovedAt()),e}getType(){return this.valueType}static getPrimitiveType(e){switch(typeof e){case"undefined":return 0;case"boolean":return 1;case"number":if(this.isInteger(e))return 2;return 4;case"string":return 5;case"object":if(null===e)return 0;if(e instanceof tI.Z)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return void 0!==tC.getPrimitiveType(e)}static isInteger(e){return e%1==0}isNumericType(){let e=this.valueType;return 2===e||3===e||4===e}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:{let e=this.value;return new Uint8Array(e?[1]:[0])}case 2:{let e=this.value;return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}case 4:{let e=this.value,t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),t}case 5:return new TextEncoder().encode(this.value);case 3:{let e=this.value.toBytesLE();return Uint8Array.from(e)}case 6:return this.value;case 7:{let e=this.value,t=tI.Z.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(t)}default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(this.valueType))}}constructor(e,t){super(t),this.valueType=tC.getPrimitiveType(e),this.value=void 0===e?null:e}}class tx extends tT{static createAfter(e,t){let r=new tx(t),n=e.next;return e.next=r,r.prev=e,r.next=n,n&&(n.prev=r),r}remove(e){return this.value.remove(e)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}constructor(e){super(e),this.value=e}}class tP{static create(){return new tP}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new ti(x.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));for(;r.getNext()&&r.getNext().getPositionedAt().after(t);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.getCreatedAt(),n=this.findNextBeforeExecutedAt(e,r),i=tx.createAfter(n,t);n===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(n,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(e,t,r){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new ti(x.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));let i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new ti(x.ErrInvalidArgument,"cant find the given node: ".concat(t.toIDString()));n!==i&&(!i.getValue().getMovedAt()||r.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(n.getCreatedAt(),i.getValue(),r),i.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){let t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find the given createdAt: ".concat(e.getCreatedAt().toIDString()));this.release(t)}getByIndex(e){if(e>=this.length)return;let[t,r]=this.nodeMapByIndex.find(e),n=t;if(0===e&&t===this.dummyHead||r>0)do n&&(n=n.getNext());while(n&&n.isRemoved());return n}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString()),n=r.isRemoved();return r.remove(t)&&!n&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,t){let r=this.getByIndex(e);if(r)return r.remove(t)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){let e=[];for(let t of this){let r="".concat(t.getCreatedAt().toIDString(),":").concat(t.getValue().toJSON());t.isRemoved()?e.push("{".concat(r,"}")):e.push("[".concat(r,"]"))}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}constructor(){let e=tC.of(0,tu);e.setRemovedAt(tu),this.dummyHead=new tx(e),this.last=this.dummyHead,this.nodeMapByIndex=new tS,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}}class tE extends tp{static create(e,t){if(!t)return new tE(e,tP.create());let r=tP.create();for(let e of t)r.insertAfter(r.getLastCreatedAt(),e.deepcopy());return new tE(e,r)}subPathOf(e){return this.elements.subPathOf(e)}purge(e){this.elements.purge(e)}insertAfter(e,t){this.elements.insertAfter(e,t)}moveAfter(e,t,r){this.elements.moveAfter(e,t,r)}get(e){let t=this.elements.getByIndex(e);return null==t?void 0:t.getValue()}getByID(e){let t=this.elements.getByID(e);return null==t?void 0:t.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(e){return this.elements.getPrevCreatedAt(e)}delete(e,t){return this.elements.delete(e,t)}deleteByIndex(e,t){return this.elements.deleteByIndex(e,t)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(let e of this.elements)e.isRemoved()||(yield e.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(e){for(let t of this.elements){let r=t.getValue();if(e(r,this))return;r instanceof tp&&r.getDescendants(e)}}toJSON(){let e=[];for(let t of this)e.push(t.toJSON());return"[".concat(e.join(","),"]")}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){let e={};for(let t=0;t({...e,value:e.value?{attributes:tc(e.value.getAttributes()),content:e.value.getContent()}:{attributes:void 0,content:""},type:"content"})),c,[o,o]]}setStyle(e,t,r,n){let[,i]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,s]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),o=[],a=this.rgaTreeSplit.findBetween(s,i),c=new Map,l=[];for(let e of a){let t=e.getCreatedAt().getActorID(),i=(null==n?void 0:n.size)?n.has(t)?n.get(t):tu:tg;if(e.canStyle(r,i)){let r=c.get(t),n=e.getCreatedAt();(!r||n.after(r))&&c.set(t,n),l.push(e)}}let h=[];for(let e of l){if(e.isRemoved())continue;let[n,i]=this.rgaTreeSplit.findIndexesFromRange(e.createPosRange());for(let[s,a]of(o.push({type:"style",actor:r.getActorID(),from:n,to:i,value:{attributes:tc(t)}}),Object.entries(t))){let[t]=e.getValue().setAttr(s,a,r);void 0!==t&&h.push({parent:e.getValue(),child:t})}}return[c,h,o]}indexRangeToPosRange(e,t){let r=this.rgaTreeSplit.indexToPos(e);return e===t?[r,r]:[r,this.rgaTreeSplit.indexToPos(t)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){let e=[];for(let t of this.rgaTreeSplit)t.isRemoved()||e.push(t.getValue().toJSON());return"[".concat(e.join(","),"]")}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){let e=[];for(let t of this.rgaTreeSplit)if(!t.isRemoved()){let r=t.getValue();e.push({attributes:tc(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){let e=new tJ(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return e.remove(this.getRemovedAt()),e}findIndexesFromRange(e){return this.rgaTreeSplit.findIndexesFromRange(e)}getGCPairs(){let e=[];for(let t of this.rgaTreeSplit)for(let r of(t.getRemovedAt()&&e.push({parent:this.rgaTreeSplit,child:t}),t.getValue().getGCPairs()))e.push(r);return e}constructor(e,t){super(t),this.rgaTreeSplit=e}}class tL extends tA{static create(e,t,r,n,i,s,o){return new tL(e,t,r,n,i,s,o)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tJ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(let t of n)e.registerGCPair(t);return{opInfos:r.map(t=>{let{from:r,to:n,value:i}=t;return{type:"edit",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.content;return"".concat(e,".EDIT(").concat(t,",").concat(r,",").concat(n,")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,o){super(e,o),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.content=i,this.attributes=s}}class t_ extends tA{static create(e,t,r,n,i,s){return new t_(e,t,r,n,i,s)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tJ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(let t of r)e.registerGCPair(t);return{opInfos:n.map(t=>{let{from:r,to:n,value:i}=t;return{type:"style",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.attributes;return"".concat(e,".STYL(").concat(t,",").concat(r,",").concat(JSON.stringify(n),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s){super(e,s),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i}}let tM="text";function tq(e,t){let r=0,n=e.children;for(let e=0;e!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(){for(var e=arguments.length,t=Array(e),r=0;re+t.paddedSize,0),r.size=r._children.reduce((e,t)=>e+t.paddedSize,0),r._children))e.parent=r;return r}insertAfterInternal(e,t){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");let r=this._children.indexOf(t);if(-1===r)throw new ti(x.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");if(e.isRemoved){let t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(e=>!e.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");let t=e;for(;t;){let e=this._children.indexOf(t);if(-1!==e)return e;t=t.parent}return -1}constructor(e,t=[]){if(this.type=e,this.size=0,this._children=t,this.isText&&this._children.length>0)throw new ti(x.ErrRefused,"Text node cannot have children")}}function tK(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let n of e._children)tK(n,t,r+1);t(e,r)}(d=D||(D={})).Start="Start",d.End="End",d.Text="Text";class tF{tokensBetween(e,t,r){!function e(t,r,n,i){if(r>n)throw new ti(x.ErrInvalidArgument,"from is greater than to: ".concat(r," > ").concat(n));if(r>t.size)throw new ti(x.ErrInvalidArgument,"from is out of range: ".concat(r," > ").concat(t.size));if(n>t.size)throw new ti(x.ErrInvalidArgument,"to is out of range: ".concat(n," > ").concat(t.size));if(r===n)return;let s=0;for(let o of t.children){if(r-o.paddedSizeo.size;(o.isText||c)&&i([o,o.isText?"Text":"Start"],l),e(o,Math.max(0,t),Math.min(a,o.size),i),l&&i([o,"End"],l)}s+=o.paddedSize}}(this.root,e,t,r)}traverse(e){!function e(t,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let i of t.children)e(i,r,n+1);r(t,n)}(this.root,e,0)}traverseAll(e){tK(this.root,e,0)}findTreePos(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function e(t,r){let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];if(r>t.size)throw new ti(x.ErrInvalidArgument,"index is out of range: ".concat(r," > ").concat(t.size));if(t.isText)return{node:t,offset:r};let i=0,s=0;for(let o of t.children){if(n&&o.isText&&o.size>=r-s)return e(o,r-s,n);if(r===s)break;if(!n&&o.paddedSize===r-s)return{node:t,offset:i+1};if(o.paddedSize>r-s)return e(o,r-s-1,n);s+=o.paddedSize,i+=1}return{node:t,offset:i}}(this.root,e,t)}treePosToPath(e){let t=[],r=e.node;if(r.isText){let n=r.parent.findOffset(r);if(-1===n)throw new ti(x.ErrInvalidArgument,"invalid treePos");let i=tq(r.parent,n);t.push(i+e.offset),r=r.parent}else if(r.hasTextChild()){let n=tq(r,e.offset);t.push(n)}else t.push(e.offset);for(;r.parent;){let e=r.parent.findOffset(r);if(-1===e)throw new ti(x.ErrInvalidArgument,"invalid treePos");t.push(e),r=r.parent}return t.reverse()}pathToIndex(e){let t=this.pathToTreePos(e);return this.indexOf(t)}pathToTreePos(e){if(!e.length)throw new ti(x.ErrInvalidArgument,"unacceptable path");let t=this.root;for(let r=0;re===t?0:e0){if(!t.right)return t;t.right.parent=t,t=t.right}else if(!(r<0))return t;else if(t.left)t.left.parent=t,t=t.left;else{let e=t.parent,r=t;for(;e&&r===e.left;)r=e,e=e.parent;return e}}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return 0===this.counter}getInternal(e,t){for(;t;){let r=this.comparator(e,t.key);if(0===r)return t;r<0?t=t.left:r>0&&(t=t.right)}}putInternal(e,t,r){if(!r)return this.counter+=1,new tU(e,t,!0);let n=this.comparator(e,r.key);return n<0?r.left=this.putInternal(e,t,r.left):n>0?r.right=this.putInternal(e,t,r.right):r.value=t,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,t){if(0>this.comparator(t,e.key))this.isRed(e.left)||this.isRed(e.left.left)||(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),0===this.comparator(t,e.key)&&!e.right){this.counter-=1;return}if(this.isRed(e.right)||this.isRed(e.right.left)||(e=this.moveRedRight(e)),0===this.comparator(t,e.key)){this.counter-=1;let t=this.min(e.right);e.value=t.value,e.key=t.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return this.isRed(e.left)||this.isRed(e.left.left)||(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){let t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){let t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}constructor(e){this.comparator=void 0!==e?e:tV,this.counter=0}}(u=R||(R={})).Content="content",u.Style="style",u.RemoveStyle="removeStyle";class tG{static of(e,t){return new tG(e,t)}static fromTreePos(e){let t;let{offset:r}=e,{node:n}=e;return n.isText?(t=n.parent.children[0]===n&&0===r?n.parent:n,n=n.parent):t=0===r?n:n.children[r-1],tG.of(n.id,tH.of(t.getCreatedAt(),t.getOffset()+r))}getParentID(){return this.parentID}static fromStruct(e){return tG.of(tH.of(td.fromStruct(e.parentID.createdAt),e.parentID.offset),tH.of(td.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){let t=this.getParentID(),r=this.getLeftSiblingID(),n=e.findFloorNode(t),i=e.findFloorNode(r);if(!n||!i)throw new ti(x.ErrRefused,"cannot find node of CRDTTreePos(".concat(t.toTestString(),", ").concat(r.toTestString(),")"));return!r.equals(t)&&r.getOffset()>0&&r.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=e.findFloorNode(i.insPrevID)),[n,i]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}constructor(e,t){this.parentID=e,this.leftSiblingID=t}}class tH{static of(e,t){return new tH(e,t)}static fromStruct(e){return tH.of(td.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{let r=e.getCreatedAt().compare(t.getCreatedAt());return 0!==r?r:e.getOffset()>t.getOffset()?1:e.getOffset(){let r=e.deepcopy();return r.parent=t,r}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new ti(x.ErrInvalidType,"cannot get value of element node: ".concat(this.type));return this._value}set value(e){if(!this.isText)throw new ti(x.ErrInvalidType,"cannot set value of element node: ".concat(this.type));this._value=e,this.size=e.length}get isRemoved(){return!!this.removedAt}remove(e){let t=!this.removedAt;(!this.removedAt||this.removedAt.compare(e)>0)&&(this.removedAt=e),t&&this.updateAncestorsSize()}cloneText(e){return new tY(tH.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new tY(tH.of(e(),0),this.type,void 0,void 0,this.removedAt)}split(e,t,r){let n=this.isText?this.splitText(t,this.id.getOffset()):this.splitElement(t,r);return n&&(n.insPrevID=this.id,this.insNextID&&(e.findFloorNode(this.insNextID).insPrevID=n.id,n.insNextID=this.insNextID),this.insNextID=n.id,e.registerNode(n)),n}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(e,t){return!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,t){return!this.isText&&!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,t){this.attrs||(this.attrs=new tO);let r=[];for(let[n,i]of Object.entries(e))r.push(this.attrs.set(n,i,t));return r}purge(e){this.attrs&&this.attrs.purge(e)}getGCPairs(){let e=[];if(!this.attrs)return e;for(let t of this.attrs)t.getRemovedAt()&&e.push({parent:this,child:t});return e}constructor(e,t,r,n,i){super(t),this._value="",this.id=e,this.removedAt=i,n&&(this.attrs=n),"string"==typeof r?this.value=r:Array.isArray(r)&&(this._children=r)}}function tZ(e){if(e.isText)return{type:e.type,value:e.value};let t={type:e.type,children:e.children.map(tZ)};if(e.attrs){var r;t.attributes=tc(null===(r=e.attrs)||void 0===r?void 0:r.toObject())}return t}function tX(e){if(e.isText)return e.value;let t="";return e.attrs&&e.attrs.size()&&(t=" "+Array.from(e.attrs).filter(e=>!e.isRemoved()).sort((e,t)=>e.getKey().localeCompare(t.getKey())).map(e=>{let t=JSON.parse(e.getValue());return"string"==typeof t?"".concat(e.getKey(),'="').concat(t,'"'):"".concat(e.getKey(),'="').concat(tf(e.getValue()),'"')}).join(" ")),"<".concat(e.type).concat(t,">").concat(e.children.map(e=>tX(e)).join(""),"")}class tQ extends tm{static create(e,t){return new tQ(e,t)}findFloorNode(e){let t=this.nodeMapByID.floorEntry(e);if(t&&t.key.getCreatedAt().equals(e.getCreatedAt()))return t.value}registerNode(e){this.nodeMapByID.put(e.id,e)}findNodesAndSplitText(e,t){let[r,n]=e.toTreeNodePair(this),i=n,s=r===i,o=i.parent&&!s?i.parent:r;if(i.isText&&i.split(this,e.getLeftSiblingID().getOffset()-i.id.getOffset()),t){let e=o.allChildren,r=s?0:e.indexOf(i)+1;for(let n=r;n{let[i]=e,s=i.getCreatedAt().getActorID(),o=n?n.has(s)?n.get(s):tu:tg;if(i.canStyle(r,o)&&t){let e=h.get(s),n=i.getCreatedAt();(!e||n.after(e))&&h.set(s,n);let o=i.setAttrs(t,r),a=o.reduce((e,t)=>{let[,r]=t;return r&&(e[r.getKey()]=l[r.getKey()]),e},{}),u=i.parent,g=i.prevSibling||i.parent;for(let[e]of(Object.keys(a).length>0&&c.push({type:"style",from:this.toIndex(u,g),to:this.toIndex(i,i),fromPath:this.toPath(u,g),toPath:this.toPath(i,i),actor:r.getActorID(),value:a}),o))e&&d.push({parent:i,child:e})}}),[h,d,c]}removeStyle(e,t,r,n){let[i,s]=this.findNodesAndSplitText(e[0],r),[o,a]=this.findNodesAndSplitText(e[1],r),c=[],l=new Map,h=[];return this.traverseInPosRange(i,s,o,a,e=>{let[i]=e,s=i.getCreatedAt().getActorID(),o=n?n.has(s)?n.get(s):tu:tg;if(i.canStyle(r,o)&&t){let e=l.get(s),n=i.getCreatedAt();for(let o of((!e||n.after(e))&&l.set(s,n),i.attrs||(i.attrs=new tO),t))for(let e of i.attrs.remove(o,r))h.push({parent:i,child:e});let o=i.parent,a=i.prevSibling||i.parent;c.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(o,a),to:this.toIndex(i,i),fromPath:this.toPath(o,a),toPath:this.toPath(i,i),value:t})}}),[l,h,c]}edit(e,t,r,n,i,s){let[o,a]=this.findNodesAndSplitText(e[0],n),[c,l]=this.findNodesAndSplitText(e[1],n),h=this.toIndex(o,a),d=this.toPath(o,a),u=[],g=[],f=[],m=new Map;this.traverseInPosRange(o,a,c,l,(e,t)=>{let[r,i]=e;if(i===D.Start&&!t)for(let e of r.children)f.push(e);let o=r.getCreatedAt().getActorID(),a=s?s.has(o)?s.get(o):tu:tg;if(r.canDelete(n,a)||u.includes(r.parent)){let e=m.get(o),t=r.getCreatedAt();(!e||t.after(e))&&m.set(o,t),(i===D.Text||i===D.Start)&&u.push(r),g.push([r,i])}});let p=this.makeDeletionChanges(g,n),y=[];for(let e of u)e.remove(n),e.isRemoved&&y.push({parent:this,child:e});for(let e of f)e.removedAt||o.append(e);if(r>0){let e=0,t=o,s=a;for(;e{o.isRemoved&&(e.remove(n),y.push({parent:this,child:e})),this.nodeMapByID.put(e.id,e)}),i.isRemoved||e.push(i);if(e.length){let t=e.map(e=>tZ(e));p.length&&p[p.length-1].from===h?p[p.length-1].value=t:p.push({type:"content",from:h,to:h,fromPath:d,toPath:d,actor:n.getActorID(),value:t})}}return[p,y,m]}editT(e,t,r,n,i){let s=this.findPos(e[0]),o=this.findPos(e[1]);this.edit([s,o],t,r,n,i)}move(e,t,r){throw new ti(x.ErrUnimplemented,"not implemented: ".concat(e,", ").concat(t,", ").concat(r))}purge(e){var t;null===(t=e.parent)||void 0===t||t.removeChild(e),this.nodeMapByID.remove(e.id);let r=e.insPrevID,n=e.insNextID;r&&(this.findFloorNode(r).insNextID=n),n&&(this.findFloorNode(n).insPrevID=r),e.insPrevID=void 0,e.insNextID=void 0}getGCPairs(){let e=[];return this.indexTree.traverse(t=>{for(let r of(t.getRemovedAt()&&e.push({parent:this,child:t}),t.getGCPairs()))e.push(r)}),e}findPos(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1],r=this.indexTree.findTreePos(e,t);return tG.fromTreePos(r)}pathToPosRange(e){let t=this.pathToIndex(e);return[this.findPos(t),this.findPos(t+1)]}pathToPos(e){let t=this.indexTree.pathToIndex(e);return this.findPos(t)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return tX(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){var e=this;let t=this.indexTree.getRoot(),r=function(t){var n,i,s,o;let a,c,l,h=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,g=t.isText?{node:t,offset:0}:h&&d?e.toTreePos(h,d):null;g&&(a=e.indexTree.indexOf(g),c=e.indexTree.treePosToPath(g),l=tG.fromTreePos(g).toStruct());let f={type:t.type,parent:null==h?void 0:h.id.toTestString(),size:t.size,id:t.id.toTestString(),removedAt:null===(n=t.removedAt)||void 0===n?void 0:n.toTestString(),insPrev:null===(i=t.insPrevID)||void 0===i?void 0:i.toTestString(),insNext:null===(s=t.insNextID)||void 0===s?void 0:s.toTestString(),value:t.isText?t.value:void 0,isRemoved:t.isRemoved,children:[],depth:u,attributes:t.attrs?tc(null===(o=t.attrs)||void 0===o?void 0:o.toObject()):void 0,index:a,path:c,pos:l};for(let e=0;e0&&d===r[r.length-1].to?(r[r.length-1].to=u,r[r.length-1].toPath=this.toPath(h,a)):r.push({type:"content",from:d,to:u,fromPath:this.toPath(l,s),toPath:this.toPath(h,a),actor:t.getActorID()}))}return r.reverse()}findRightToken(e){let[t,r]=e;if(r===D.Start){let e=t.allChildren;return e.length>0?[e[0],e[0].isText?D.Text:D.Start]:[t,D.End]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&s===i.length-1)return[n,D.End];let o=i[s+1];return[o,o.isText?D.Text:D.Start]}findLeftToken(e){let[t,r]=e;if(r===D.End){let e=t.allChildren;if(e.length>0){let t=e[e.length-1];return[t,t.isText?D.Text:D.End]}return[t,D.Start]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&0===s)return[n,D.Start];let o=i[s-1];return[o,o.isText?D.Text:D.End]}constructor(e,t){super(t),this.indexTree=new tF(e),this.nodeMapByID=new tW(tH.createComparator()),this.indexTree.traverseAll(e=>{this.nodeMapByID.put(e.id,e)})}}class t$ extends tA{static create(e,t,r,n,i,s,o){return new t$(e,t,r,n,i,s,o)}execute(e){var t;let r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(r instanceof tQ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Tree can execute edit");let n=this.getExecutedAt(),[i,s]=r.edit([this.fromPos,this.toPos],null===(t=this.contents)||void 0===t?void 0:t.map(e=>e.deepcopy()),this.splitLevel,n,(()=>{let e=n.getDelimiter();return void 0!==this.contents&&(e+=this.contents.length),()=>td.of(n.getLamport(),++e,n.getActorID())})(),this.maxCreatedAtMapByActor);for(let t of s)e.registerGCPair(t);return{opInfos:i.map(t=>{let{from:r,to:n,value:i,splitLevel:s,fromPath:o,toPath:a}=t;return{type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:r,to:n,value:i,splitLevel:s,fromPath:o,toPath:a}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t="".concat(this.fromPos.getLeftSiblingID().getCreatedAt().toTestString(),"/").concat(this.fromPos.getLeftSiblingID().getOffset()),r="".concat(this.toPos.getLeftSiblingID().getCreatedAt().toTestString(),"/").concat(this.toPos.getLeftSiblingID().getOffset()),n=this.contents||[];return"".concat(e,".EDIT(").concat(t,",").concat(r,",").concat(n.map(e=>tX(e)).join(""),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,o){super(e,o),this.fromPos=t,this.toPos=r,this.contents=n,this.splitLevel=i,this.maxCreatedAtMapByActor=s}}class t0{set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(let[,t]of this)t>e&&(e=t);return e}max(e){let t=new Map;for(let[r,n]of e){let e=this.vector.get(r),i=e&&e>n?e:n;t.set(r,i)}for(let[r,n]of this){let i=e.get(r),s=i&&i>n?i:n;t.set(r,s)}return new t0(t)}afterOrEqual(e){let t=this.vector.get(e.getActorID());return void 0!==t&&t>=e.getLamport()}deepcopy(){let e=new Map;for(let[t,r]of this.vector)e.set(t,r);return new t0(e)}filter(e){let t=new Map;for(let[r]of e){let e=this.vector.get(r);void 0!==e&&t.set(r,e)}return new t0(t)}size(){return this.vector.size}*[Symbol.iterator](){for(let[e,t]of this.vector)yield[e,t]}constructor(e){this.vector=e||new Map}}let t1=new t0(new Map);class t2{static of(e,t,r,n,i){return new t2(e,t,r,n,i)}next(){let e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new t2(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){let t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,r=this.versionVector.max(e.versionVector),n=new t2(this.clientSeq,t,this.actor,r);return n.versionVector.set(this.actor,t),n}setClocks(e,t){let r=e>this.lamport?e:this.lamport+1n,n=this.versionVector.max(t);return n.set(this.actor,r),t2.of(this.clientSeq,r,this.actor,n)}createTimeTicket(e){return td.of(this.lamport,e,this.actor)}setActor(e){return new t2(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new t2(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actor.slice(-2),":").concat(this.clientSeq)}constructor(e,t,r,n,i){this.clientSeq=e,this.serverSeq=i,this.lamport=t,this.versionVector=n,this.actor=r}}let t3=new t2(0,0n,th,t1);class t9{static create(e){let{id:t,operations:r,presenceChange:n,message:i}=e;return new t9({id:t,operations:r,presenceChange:n,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(let t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return void 0!==this.presenceChange}getPresenceChange(){return this.presenceChange}execute(e,t,r){let n=[],i=[];for(let t of this.operations){let s=t.execute(e,r);if(!s)continue;let{opInfos:o,reverseOp:a}=s;n.push(...o),a&&i.unshift(a)}return this.presenceChange&&(this.presenceChange.type===P.Put?t.set(this.id.getActorID(),ts(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:n,reverseOps:i}}toTestString(){return"".concat(this.operations.map(e=>e.toTestString()).join(","))}toStruct(){return{changeID:rU.bytesToHex(rU.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>rU.bytesToHex(rU.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){let{changeID:t,operations:r,presenceChange:n,message:i}=e;return t9.create({id:rU.bytesToChangeID(rU.hexToBytes(t)),operations:null==r?void 0:r.map(e=>rU.bytesToOperation(rU.hexToBytes(e))),presenceChange:n,message:i})}constructor({id:e,operations:t,presenceChange:r,message:n}){this.id=e,this.operations=t||[],this.presenceChange=r,this.message=n}}class t4{static create(e,t,r,n,i,s,o){return new t4(e,t,r,n,i,s,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}constructor(e,t,r,n,i,s,o){this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=n,this.snapshot=s,this.minSyncedTicket=o,this.versionVector=i}}class t8{static of(e,t){return new t8(e,t)}increaseClientSeq(e){return 0===e?this:new t8(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;let t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return t8.of(t,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return"serverSeq=".concat(this.serverSeq,", clientSeq=").concat(this.clientSeq)}constructor(e,t){this.serverSeq=e,this.clientSeq=t}}let t5=new t8(0n,0);class t6{static of(e,t){return new t6(e,t)}static fromStruct(e){return t6.of(td.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return 0===this.createdAt.compare(e.createdAt)&&this.offset===e.offset}hasSameCreatedAt(e){return 0===this.createdAt.compare(e.createdAt)}split(e){return new t6(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return"".concat(this.createdAt.toTestString(),":").concat(this.offset)}toIDString(){return"".concat(this.createdAt.toIDString(),":").concat(this.offset)}constructor(e,t){this.createdAt=e,this.offset=t}}let t7=t6.of(tu,0);class re{static of(e,t){return new re(e,t)}static fromStruct(e){let t=t6.fromStruct(e.id);return re.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return t6.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return"".concat(this.id.toTestString(),":").concat(this.relativeOffset)}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return!!this.id.equals(e.id)&&this.relativeOffset===e.relativeOffset}constructor(e,t){this.id=e,this.relativeOffset=t}}class rt extends tT{static create(e,t){return new rt(e,t)}static createComparator(){return(e,t)=>{let r=e.getCreatedAt().compare(t.getCreatedAt());return 0!==r?r:e.getOffset()>t.getOffset()?1:e.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){let t=this.treeByID.floorEntry(e);if(t&&(t.key.equals(e)||t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){let r=[],n=e;for(;n&&n!==t;)r.push(n),n=n.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new ti(x.ErrInvalidArgument,"offset should be less than or equal to length");if(0===t)return e;if(t===e.getContentLength())return e.getNext();let r=e.split(t);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);let n=e.getInsNext();return n&&n.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r){if(!e.length)return[[],new Map,new Map];let[n,i]=this.filterNodes(e,t,r),s=new Map,o=new Map,a=this.makeChanges(i,t);for(let e of n){let r=e.getCreatedAt().getActorID();(!s.has(r)||e.getID().getCreatedAt().after(s.get(r)))&&s.set(r,e.getID().getCreatedAt()),o.set(e.getID().toIDString(),e),e.remove(t)}return this.deleteIndexNodes(i),[a,s,o]}filterNodes(e,t,r){let n=!!r,i=[],s=[],[o,a]=this.findEdgesOfCandidates(e);for(let a of(s.push(o),e)){let e=a.getCreatedAt().getActorID(),o=n?r.has(e)?r.get(e):tu:tg;a.canDelete(t,o)?i.push(a):s.push(a)}return s.push(a),[i,s]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){let r,n;let i=[];for(let s=0;se<0?Math.ceil(e):Math.floor(e);(g=N||(N={}))[g.IntegerCnt=0]="IntegerCnt",g[g.LongCnt=1]="LongCnt";class ri extends tm{static create(e,t,r){return new ri(e,t,r)}static valueFromBytes(e,t){switch(e){case 0:return t[0]|t[1]<<8|t[2]<<16|t[3]<<24;case 1:return tI.Z.fromBytesLE(Array.from(t));default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}toJSON(){return"".concat(this.value)}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){let e=ri.create(this.valueType,this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e}getType(){return this.valueType}static getCounterType(e){switch(typeof e){case"object":if(e instanceof tI.Z)return 1;return;case"number":if(e>2147483647||e<-2147483648)return 1;return 0;default:return}}static isSupport(e){return!!ri.getCounterType(e)}static isInteger(e){return e%1==0}isNumericType(){let e=this.valueType;return 0===e||1===e}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{let e=this.value;return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}case 1:{let e=this.value.toBytesLE();return Uint8Array.from(e)}default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(this.valueType))}}increase(e){function t(e){if(!e.isNumericType())throw TypeError("Unsupported type of value: ".concat(typeof e.getValue()))}return t(this),t(e),1===this.valueType?this.value=this.value.add(e.getValue()):e.getType()===b.Long?this.value=this.value+e.getValue().toInt():this.value=tI.Z.fromNumber(this.value+rn(e.getValue())).toInt(),this}constructor(e,t,r){switch(super(r),this.valueType=e,e){case 0:"number"==typeof t?t>2147483647||t<-2147483648?this.value=tI.Z.fromNumber(t).toInt():this.value=rn(t):this.value=t.toInt();break;case 1:"number"==typeof t?this.value=tI.Z.fromNumber(t):this.value=t;break;default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}}class rs extends tA{static create(e,t,r){return new rs(e,t,r)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof ri))throw new ti(x.ErrInvalidArgument,"fail to execute, only Counter can execute increase");let r=this.value.deepcopy();return t.increase(r),{opInfos:[{type:"increase",path:e.createPath(this.getParentCreatedAt()),value:r.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){let e=this.value.deepcopy(),t=e.getType()===b.Long?e.getValue().multiply(-1):-1*e.getValue();return rs.create(this.getParentCreatedAt(),tC.of(t,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return"".concat(this.getParentCreatedAt().toTestString(),".INCREASE.").concat(this.value.toJSON())}getValue(){return this.value}constructor(e,t,r){super(e,r),this.value=t}}class ro extends tA{static create(e,t,r,n,i,s){return new ro(e,t,r,n,i,[],s)}static createTreeRemoveStyleOperation(e,t,r,n,i,s){return new ro(e,t,r,n,new Map,i,s)}execute(e){let t,r;let n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(n instanceof tQ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Tree can execute edit");if(this.attributes.size){let e={};[...this.attributes].forEach(t=>{let[r,n]=t;return e[r]=n}),[,r,t]=n.style([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{let e=this.attributesToRemove;[,r,t]=n.removeStyle([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(let t of r)e.registerGCPair(t);return{opInfos:t.map(t=>{let{from:r,to:n,value:i,fromPath:s,toPath:o}=t;return{type:"tree-style",from:r,to:n,value:this.attributes.size?{attributes:i}:{attributesToRemove:i},fromPath:s,toPath:o,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t="".concat(this.fromPos.getLeftSiblingID().getCreatedAt().toTestString(),":").concat(this.fromPos.getLeftSiblingID().getOffset()),r="".concat(this.toPos.getLeftSiblingID().getCreatedAt().toTestString(),":").concat(this.toPos.getLeftSiblingID().getOffset());return"".concat(e,".STYLE(").concat(t,",").concat(r,",").concat(Object.entries(this.attributes||{}).map(e=>{let[t,r]=e;return"".concat(t,':"').concat(r,'"')}).join(" "),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,o){super(e,o),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i,this.attributesToRemove=s}}function ra(e){return new es({clientSeq:e.getClientSeq(),lamport:e.getLamport(),actorId:rV(e.getActorID()),versionVector:rl(e.getVersionVector())})}function rc(e){if(e)return new ej({lamport:e.getLamport(),delimiter:e.getDelimiter(),actorId:rV(e.getActorID())})}function rl(e){if(!e)return;let t=new eo;for(let[r,n]of e)t.vector[r]=BigInt(n.toString());return t}function rh(e){switch(e){case b.Null:return S.NULL;case b.Boolean:return S.BOOLEAN;case b.Integer:return S.INTEGER;case b.Long:return S.LONG;case b.Double:return S.DOUBLE;case b.String:return S.STRING;case b.Bytes:return S.BYTES;case b.Date:return S.DATE;default:throw new ti(x.ErrInvalidType,"unsupported type: ".concat(e))}}function rd(e){switch(e){case N.IntegerCnt:return S.INTEGER_CNT;case N.LongCnt:return S.LONG_CNT;default:throw new ti(x.ErrInvalidType,"unsupported type: ".concat(e))}}function ru(e){if(e instanceof tw)return new ew({type:S.JSON_OBJECT,createdAt:rc(e.getCreatedAt()),value:rK(e)});if(e instanceof tE)return new ew({type:S.JSON_ARRAY,createdAt:rc(e.getCreatedAt()),value:rv(e).toBinary()});if(e instanceof tJ)return new ew({type:S.TEXT,createdAt:rc(e.getCreatedAt())});if(e instanceof tC)return new ew({type:rh(e.getType()),createdAt:rc(e.getCreatedAt()),value:e.toBytes()});if(e instanceof ri)return new ew({type:rd(e.getType()),createdAt:rc(e.getCreatedAt()),value:e.toBytes()});if(e instanceof tQ)return new ew({type:S.TREE,createdAt:rc(e.getCreatedAt()),value:rw(e).toBinary()});throw new ti(x.ErrUnimplemented,"unimplemented element")}function rg(e){return new eU({createdAt:rc(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function rf(e){return new eJ({parentId:rm(e.getParentID()),leftSiblingId:rm(e.getLeftSiblingID())})}function rm(e){return new eB({createdAt:rc(e.getCreatedAt()),offset:e.getOffset()})}function rp(e){let t=new ea;if(e instanceof tk){let r=new ec;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.key=e.getKey(),r.value=ru(e.getValue()),r.executedAt=rc(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof tD){let r=new el;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.prevCreatedAt=rc(e.getPrevCreatedAt()),r.value=ru(e.getValue()),r.executedAt=rc(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof tR){let r=new eh;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.prevCreatedAt=rc(e.getPrevCreatedAt()),r.createdAt=rc(e.getCreatedAt()),r.executedAt=rc(e.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof tb){let r=new ed;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.createdAt=rc(e.getCreatedAt()),r.executedAt=rc(e.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof tL){let r=new eu;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rg(e.getFromPos()),r.to=rg(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);r.content=e.getContent();let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=rc(e.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof t_){let r=new ef;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rg(e.getFromPos()),r.to=rg(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=rc(e.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof rs){let r=new em;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.value=ru(e.getValue()),r.executedAt=rc(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof t$){let r=new ep,n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rf(e.getFromPos()),r.to=rf(e.getToPos()),r.contents=function(e){let t=[];if(!e||!e.length)return t;for(let r of e)t.push(new eO({content:ry(r)}));return t}(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=rc(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof ro){let r=new ey;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rf(e.getFromPos()),r.to=rf(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);let i=e.getAttributesToRemove();if(i.length>0)r.attributesToRemove=i;else{let t=r.attributes;for(let[r,n]of e.getAttributes())t[r]=n}r.executedAt=rc(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new ti(x.ErrUnimplemented,"unimplemented operation");return t}function ry(e){if(!e)return[];let t=[];return tK(e,(e,r)=>{let n=new eN({id:rm(e.id),type:e.type,removedAt:rc(e.removedAt),depth:r});e.isText&&(n.value=e.value),e.insPrevID&&(n.insPrevId=rm(e.insPrevID)),e.insNextID&&(n.insNextId=rm(e.insNextID)),e.attrs&&(n.attributes=function(e){let t={};for(let r of e)t[r.getKey()]=new ek({value:r.getValue(),updatedAt:rc(r.getUpdatedAt()),isRemoved:r.isRemoved()});return t}(e.attrs)),t.push(n)}),t}function rv(e){let t=new eA;return t.body.case="jsonArray",t.body.value=new eS({nodes:function(e){let t=[];for(let r of e)t.push(new eb({element:rA(r.getValue())}));return t}(e.getElements()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}function rw(e){let t=new eA;return t.body.case="tree",t.body.value=new eP({nodes:ry(e.getRoot()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}function rA(e){if(e instanceof tw)return function(e){let t=new eA;return t.body.case="jsonObject",t.body.value=new eT({nodes:function(e){let t=[];for(let r of e)t.push(new eE({key:r.getStrKey(),element:rA(r.getValue())}));return t}(e.getRHT()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof tE)return rv(e);if(e instanceof tC)return function(e){let t=new eA;return t.body.case="primitive",t.body.value=new eI({type:rh(e.getType()),value:e.toBytes(),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof tJ)return function(e){let t=new eA;return t.body.case="text",t.body.value=new eC({nodes:function(e){let t=[];for(let n of e){var r;let e=new eD;e.id=new eR({createdAt:rc((r=n.getID()).getCreatedAt()),offset:r.getOffset()}),e.value=n.getValue().getContent(),e.removedAt=rc(n.getRemovedAt());let i=e.attributes;for(let e of n.getValue().getAttrs()){let t=new ek;t.value=e.getValue(),t.updatedAt=rc(e.getUpdatedAt()),i[e.getKey()]=t}t.push(e)}return t}(e.getRGATreeSplit()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof ri)return function(e){let t=new eA;return t.body.case="counter",t.body.value=new ex({type:rd(e.getType()),value:e.toBytes(),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof tQ)return rw(e);throw new ti(x.ErrUnimplemented,"unimplemented element")}function rT(e){for(let t of e.findDetails(tn.Qf))if(t.metadata.code)return t.metadata.code;return""}function rS(e){return t2.of(e.clientSeq,BigInt(e.lamport),rF(e.actorId),rI(e.versionVector),BigInt(e.serverSeq))}function rI(e){if(!e)return;let t=new t0;return Object.entries(e.vector).forEach(e=>{let[r,n]=e;t.set(r,BigInt(n.toString()))}),t}function rC(e){if(e)return td.of(BigInt(e.lamport),e.delimiter,rF(e.actorId))}function rx(e){let t={};return Object.entries(e.data).forEach(e=>{let[r,n]=e;t[r]=JSON.parse(n)}),t}function rP(e){switch(e){case S.NULL:return b.Null;case S.BOOLEAN:return b.Boolean;case S.INTEGER:return b.Integer;case S.LONG:return b.Long;case S.DOUBLE:return b.Double;case S.STRING:return b.String;case S.BYTES:return b.Bytes;case S.DATE:return b.Date}throw new ti(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rE(e){switch(e){case S.INTEGER_CNT:return N.IntegerCnt;case S.LONG_CNT:return N.LongCnt}throw new ti(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rb(e){switch(e.type){case S.JSON_OBJECT:if(!e.value)return tw.create(rC(e.createdAt));return rz(e.value);case S.JSON_ARRAY:if(!e.value)return tE.create(rC(e.createdAt));return function(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return r_(eA.fromBinary(e).body.value)}(e.value);case S.TEXT:return tJ.create(rr.create(),rC(e.createdAt));case S.TREE:return function(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return rM(eA.fromBinary(e).body.value)}(e.value);case S.NULL:case S.BOOLEAN:case S.INTEGER:case S.LONG:case S.DOUBLE:case S.STRING:case S.BYTES:case S.DATE:return tC.of(tC.valueFromBytes(rP(e.type),e.value),rC(e.createdAt));case S.INTEGER_CNT:case S.LONG_CNT:return ri.create(rE(e.type),ri.valueFromBytes(rE(e.type),e.value),rC(e.createdAt))}}function rk(e){return re.of(t6.of(rC(e.createdAt),e.offset),e.relativeOffset)}function rD(e){return t6.of(rC(e.createdAt),e.offset)}function rR(e){return tG.of(rN(e.parentId),rN(e.leftSiblingId))}function rN(e){return tH.of(rC(e.createdAt),e.offset)}function rO(e){if(0===e.length)return;let t=[];for(let r of e)t.push(function(e){let t=rN(e.id),r=tY.create(t,e.type),n=Object.entries(e.attributes);return r.isText?r.value=e.value:n.length&&(r.attrs=function(e){let t=tO.create();for(let[r,n]of Object.entries(e))t.setInternal(r,n.value,rC(n.updatedAt),n.isRemoved);return t}(e.attributes)),e.insPrevId&&(r.insPrevID=rN(e.insPrevId)),e.insNextId&&(r.insNextID=rN(e.insNextId)),r.removedAt=rC(e.removedAt),r}(r));let r=t[t.length-1],n=new Map;n.set(e[t.length-1].depth,t[t.length-1]);for(let r=t.length-2;r>=0;r--)n.get(e[r].depth-1).prepend(t[r]),n.set(e[r].depth,t[r]);return r.updateDescendantsSize(),tQ.create(r,tu).getRoot()}function rB(e){if("set"===e.body.case){let t=e.body.value;return tk.create(t.key,rb(t.value),rC(t.parentCreatedAt),rC(t.executedAt))}if("add"===e.body.case){let t=e.body.value;return tD.create(rC(t.parentCreatedAt),rC(t.prevCreatedAt),rb(t.value),rC(t.executedAt))}if("move"===e.body.case){let t=e.body.value;return tR.create(rC(t.parentCreatedAt),rC(t.prevCreatedAt),rC(t.createdAt),rC(t.executedAt))}if("remove"===e.body.case){let t=e.body.value;return tb.create(rC(t.parentCreatedAt),rC(t.createdAt),rC(t.executedAt))}if("edit"===e.body.case){let t=e.body.value,r=new Map;Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rC(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tL.create(rC(t.parentCreatedAt),rk(t.from),rk(t.to),r,t.content,n,rC(t.executedAt))}if("style"===e.body.case){let t=e.body.value,r=new Map;Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rC(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),t_.create(rC(t.parentCreatedAt),rk(t.from),rk(t.to),r,n,rC(t.executedAt))}if("select"===e.body.case)return;else if("increase"===e.body.case){let t=e.body.value;return rs.create(rC(t.parentCreatedAt),rb(t.value),rC(t.executedAt))}else if("treeEdit"===e.body.case){let t=e.body.value,r=new Map;return Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rC(n))}),t$.create(rC(t.parentCreatedAt),rR(t.from),rR(t.to),function(e){if(!e.length)return;let t=[];return e.forEach(e=>{let r=rO(e.content);t.push(r)}),t}(t.contents),t.splitLevel,r,rC(t.executedAt))}else if("treeStyle"===e.body.case){let t=e.body.value,r=new Map,n=t.attributesToRemove,i=new Map;return((null==t?void 0:t.createdAtMapByActor)&&Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,r]=e;i.set(t,rC(r))}),(null==n?void 0:n.length)>0)?ro.createTreeRemoveStyleOperation(rC(t.parentCreatedAt),rR(t.from),rR(t.to),i,n,rC(t.executedAt)):(Object.entries(t.attributes).forEach(e=>{let[t,n]=e;r.set(t,n)}),ro.create(rC(t.parentCreatedAt),rR(t.from),rR(t.to),i,r,rC(t.executedAt)))}else throw new ti(x.ErrUnimplemented,"unimplemented operation")}function rJ(e){let t=[];for(let r of e)t.push(t9.create({id:rS(r.id),operations:function(e){let t=[];for(let r of e){let e=rB(r);e&&t.push(e)}return t}(r.operations),presenceChange:r.presenceChange?function(e){let t=e.type;if(t===C.PUT){let t=rx(e.presence);return{type:P.Put,presence:t}}if(t===C.CLEAR)return{type:P.Clear};throw new ti(x.ErrInvalidType,"unsupported type: ".concat(t))}(r.presenceChange):void 0,message:r.message}));return t}function rL(e){let t=new tv;for(let r of e.nodes){let e=rq(r.element);t.set(r.key,e,e.getPositionedAt())}let r=new tw(rC(e.createdAt),t);return r.setMovedAt(rC(e.movedAt)),r.setRemovedAt(rC(e.removedAt)),r}function r_(e){let t=new tP;for(let r of e.nodes)t.insert(rq(r.element));let r=new tE(rC(e.createdAt),t);return r.setMovedAt(rC(e.movedAt)),r.setRemovedAt(rC(e.removedAt)),r}function rM(e){let t=rO(e.nodes);return tQ.create(t,rC(e.createdAt))}function rq(e){if("jsonObject"===e.body.case)return rL(e.body.value);if("jsonArray"===e.body.case)return r_(e.body.value);if("primitive"===e.body.case)return function(e){let t=tC.of(tC.valueFromBytes(rP(e.type),e.value),rC(e.createdAt));return t.setMovedAt(rC(e.movedAt)),t.setRemovedAt(rC(e.removedAt)),t}(e.body.value);if("text"===e.body.case)return function(e){let t=new rr,r=t.getHead();for(let n of e.nodes){let e=t.insertAfter(r,function(e){let t=tB.create(e.value);Object.entries(e.attributes).forEach(e=>{let[r,n]=e;t.setAttr(r,n.value,rC(n.updatedAt))});let r=rt.create(rD(e.id),t);return r.remove(rC(e.removedAt)),r}(n));n.insPrevId&&e.setInsPrev(t.findNode(rD(n.insPrevId))),r=e}let n=new tJ(t,rC(e.createdAt));return n.setMovedAt(rC(e.movedAt)),n.setRemovedAt(rC(e.removedAt)),n}(e.body.value);if("counter"===e.body.case)return function(e){let t=ri.create(rE(e.type),ri.valueFromBytes(rE(e.type),e.value),rC(e.createdAt));return t.setMovedAt(rC(e.movedAt)),t.setRemovedAt(rC(e.removedAt)),t}(e.body.value);if("tree"===e.body.case)return rM(e.body.value);throw new ti(x.ErrUnimplemented,"unimplemented element")}function rz(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return rL(eA.fromBinary(e).body.value)}function rK(e){return rA(e).toBinary()}function rF(e){return e?Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function rV(e){return new Uint8Array(e.match(/.{1,2}/g).map(e=>parseInt(e,16)))}let rU={fromPresence:rx,toChangePack:function(e){var t;return new en({documentKey:e.getDocumentKey(),checkpoint:new eV({serverSeq:(t=e.getCheckpoint()).getServerSeq(),clientSeq:t.getClientSeq()}),isRemoved:e.getIsRemoved(),changes:function(e){let t=[];for(let r of e)t.push(function(e){let t=new ei({id:ra(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=function(e){let t=[];for(let r of e)t.push(rp(r));return t}(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=function(e){if(e.type===P.Put)return new eK({type:C.PUT,presence:function(e){let t=new eF,r=t.data;for(let[t,n]of Object.entries(e))r[t]=JSON.stringify(n);return t}(e.presence)});if(e.type===P.Clear)return new eK({type:C.CLEAR});throw new ti(x.ErrUnimplemented,"unimplemented type")}(e.getPresenceChange())),t}(r));return t}(e.getChanges()),snapshot:e.getSnapshot(),versionVector:rl(e.getVersionVector()),minSyncedTicket:rc(e.getMinSyncedTicket())})},fromChangePack:function(e){var t;return t4.create(e.documentKey,(t=e.checkpoint,t8.of(BigInt(t.serverSeq),t.clientSeq)),e.isRemoved,rJ(e.changes),rI(e.versionVector),e.snapshot,rC(e.minSyncedTicket))},fromChanges:rJ,toTreeNodes:ry,fromTreeNodes:rO,objectToBytes:rK,bytesToObject:rz,bytesToSnapshot:function(e){if(!e)return{root:tw.create(tu),presences:new Map};let t=er.fromBinary(e);return{root:rq(t.root),presences:function(e){let t=new Map;return Object.entries(e).forEach(e=>{let[r,n]=e;t.set(r,rx(n))}),t}(t.presences)}},bytesToHex:rF,hexToBytes:rV,toHexString:function(e){return rF(e)},toUint8Array:function(e){return rV(e)},toOperation:rp,toChangeID:ra,PbChangeID:es,bytesToChangeID:function(e){return rS(es.fromBinary(e))},bytesToOperation:function(e){return rB(ea.fromBinary(e))},versionVectorToHex:function(e){return rF(rl(e).toBinary())},hexToVersionVector:function(e){let t=rV(e);return rI(eo.fromBinary(t))}};(f=O||(O={}))[f.Trivial=0]="Trivial",f[f.Debug=1]="Debug",f[f.Info=2]="Info",f[f.Warn=3]="Warn",f[f.Error=4]="Error",f[f.Fatal=5]="Fatal";let rj=3;function rW(e){rj=e}let rG={trivial:function(){for(var e=arguments.length,t=Array(e),r=0;r0||"undefined"==typeof console||console.log("YORKIE T:",...t)},debug:function(){for(var e=arguments.length,t=Array(e),r=0;r1||"undefined"==typeof console||console.log("YORKIE D:",...t)},info:function(){for(var e=arguments.length,t=Array(e),r=0;r2||"undefined"==typeof console||console.log("YORKIE I:",...t)},warn:function(){for(var e=arguments.length,t=Array(e),r=0;r3||"undefined"==typeof console||(void 0!==console.warn?console.warn("YORKIE W:",...t):console.log("YORKIE W:",...t))},error:function(){for(var e=arguments.length,t=Array(e),r=0;r4||"undefined"==typeof console||(void 0!==console.error?console.error("YORKIE E:",...t):console.log("YORKIE E:",...t))},fatal:function(){for(var e=arguments.length,t=Array(e),r=0;rrj<=e};function rH(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}class rY{changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode!==M.RealtimeSyncOff&&(this.syncMode===M.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==M.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived))}async runWatchLoop(e){let t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch(e){}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}constructor(e,t,r,n,i){this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=n,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}}let rZ=()=>{};class rX{next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let n;if(!e)throw new ti(x.ErrInvalidArgument,"missing observer");if(this.finalized)throw new ti(x.ErrRefused,"observable is finalized due to previous error");void 0===(n="object"==typeof e?e:{next:e,error:t,complete:r}).next&&(n.next=rZ),void 0===n.error&&(n.error=rZ),void 0===n.complete&&(n.complete=rZ);let i=rH(),s=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:n}),this.finalized)try{this.finalError?n.error(this.finalError):n.complete()}catch(e){rG.warn(e)}return s}unsubscribeOne(e){var t;this.observers=null===(t=this.observers)||void 0===t?void 0:t.filter(t=>t.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;t0||void 0!==this.presenceChange}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(let r of Object.keys(e))(null==t?void 0:t.addToHistory)?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(0===this.reversePresenceKeys.size)return;let e={};for(let t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}constructor(e,t,r,n){this.id=e,this.delimiter=0,this.root=t,this.operations=[],this.previousPresence=ts(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=n}}class r${static create(){return new r$(tw.create(tu))}findByCreatedAt(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];let r=[];for(;t.parent;){let e=t.element.getCreatedAt(),n=t.parent.subPathOf(e);if(void 0===n)throw new ti(x.ErrInvalidArgument,"cant find the given element: ".concat(e.toIDString()));r.unshift(n),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof tp&&e.getDescendants((e,t)=>(this.registerElement(e,t),!1))}deregisterElement(e){let t=0,r=e=>{let r=e.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(r),this.gcElementSetByCreatedAt.delete(r),t++};return r(e),e instanceof tp&&e.getDescendants(e=>(r(e),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){let e=new Set;for(let t of this.gcElementSetByCreatedAt){e.add(t);let r=this.elementPairMapByCreatedAt.get(t);r.element instanceof tp&&r.element.getDescendants(t=>(e.add(t.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new r$(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(let r of this.gcElementSetByCreatedAt){let n=this.elementPairMapByCreatedAt.get(r),i=n.element.getRemovedAt();i&&(null==e?void 0:e.afterOrEqual(i))&&(n.parent.purge(n.element),t+=this.deregisterElement(n.element))}for(let[,r]of this.gcPairMap){let n=r.child.getRemovedAt();n&&(null==e?void 0:e.afterOrEqual(n))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}constructor(e){this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof tJ||e instanceof tQ)for(let t of e.getGCPairs())this.registerGCPair(t);return!1})}}function r0(e,t){let r=new r1(e);return new Proxy(t,r.getHandlers())}class r1{static setInternal(e,t,r,n){if(r.includes("."))throw new ti(x.ErrInvalidObjectKey,"key must not contain the '.'.");let i=e.issueTimeTicket(),s=nt(e,n,i),o=t.set(r,s,i);e.registerElement(s,t),o&&e.registerRemovedElement(o),e.push(tk.create(r,s.deepcopy(),t.getCreatedAt(),i))}static buildObjectMembers(e,t){let r={};for(let[n,i]of Object.entries(t)){if(n.includes("."))throw new ti(x.ErrInvalidObjectKey,"key must not contain the '.'.");let t=e.issueTimeTicket(),s=nt(e,i,t);r[n]=s}return r}static deleteInternal(e,t,r){let n=e.issueTimeTicket(),i=t.deleteByKey(r,n);i&&(e.push(tb.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}constructor(e){this.context=e,this.handlers={set:(t,r,n)=>(rG.isEnabled(O.Trivial)&&rG.trivial("obj[".concat(r,"]=").concat(JSON.stringify(n))),r1.setInternal(e,t,r,n),!0),get:(t,r)=>(rG.isEnabled(O.Trivial)&&rG.trivial("obj[".concat(r,"]")),"getID"===r)?()=>t.getCreatedAt():"toJSON"===r||"toString"===r?()=>t.toJSON():"toJS"===r?()=>t.toJS():"toJSForTest"===r?()=>t.toJSForTest():ne(e,t.get(r)),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(rG.isEnabled(O.Trivial)&&rG.trivial("obj[".concat(r,"]")),r1.deleteInternal(e,t,r),!0)}}}class r2{static*iteratorInternal(e,t){for(let r of t)yield r7(e,r)}static buildArrayElements(e,t){let r=[];for(let n of t){let t=e.issueTimeTicket(),i=nt(e,n,t);r.push(i)}return r}static pushInternal(e,t,r){return r2.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,n){let i=e.issueTimeTicket(),s=t.getPrevCreatedAt(r);t.moveAfter(s,n,i),e.push(tR.create(t.getCreatedAt(),s,n,i))}static moveAfterInternal(e,t,r,n){let i=e.issueTimeTicket();t.moveAfter(r,n,i),e.push(tR.create(t.getCreatedAt(),r,n,i))}static moveFrontInternal(e,t,r){let n=e.issueTimeTicket(),i=t.getHead();t.moveAfter(i.getCreatedAt(),r,n),e.push(tR.create(t.getCreatedAt(),i.getCreatedAt(),r,n))}static moveLastInternal(e,t,r){let n=e.issueTimeTicket(),i=t.getLastCreatedAt();t.moveAfter(i,r,n),e.push(tR.create(t.getCreatedAt(),i,r,n))}static insertAfterInternal(e,t,r,n){let i=e.issueTimeTicket(),s=nt(e,n,i);return t.insertAfter(r,s),e.registerElement(s,t),e.push(tD.create(t.getCreatedAt(),r,s.deepcopy(),i)),s}static insertBeforeInternal(e,t,r,n){return r2.insertAfterInternal(e,t,t.getPrevCreatedAt(r),n)}static deleteInternalByIndex(e,t,r){let n=e.issueTimeTicket(),i=t.deleteByIndex(r,n);if(i)return e.push(tb.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i),i}static deleteInternalByID(e,t,r){let n=e.issueTimeTicket(),i=t.delete(r,n);return e.push(tb.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i),i}static splice(e,t,r,n){for(var i=arguments.length,s=Array(i>4?i-4:0),o=4;o=0?Math.min(r,a):Math.max(a+r,0),l=void 0===n?a:n<0?c:Math.min(c+n,a),h=[];for(let r=c;r=i)return!1;if(tC.isSupport(r))return Array.from(t).map(t=>ne(e,t)).includes(r,s);for(let e=s;e=i)return -1;if(tC.isSupport(r))return Array.from(t).map(t=>ne(e,t)).indexOf(r,s);for(let e=s;e=i?i-1:n<0?n+i:n;if(s<0)return -1;if(tC.isSupport(r))return Array.from(t).map(t=>ne(e,t)).lastIndexOf(r,s);for(let e=s;e>0;e--){var o;if((null===(o=t.get(e))||void 0===o?void 0:o.getID())===r.getID())return e}return -1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}constructor(e,t){this.context=e,this.array=t,this.handlers={get:(t,r,n)=>"getID"===r?()=>t.getCreatedAt():"getElementByID"===r?r=>{let n=t.getByID(r);if(!(!n||n.isRemoved()))return r7(e,n)}:"getElementByIndex"===r?r=>r7(e,t.get(r)):"getLast"===r?()=>r7(e,t.getLast()):"deleteByID"===r?r=>{let n=r2.deleteInternalByID(e,t,r);return r7(e,n)}:"insertAfter"===r?(r,n)=>{let i=r2.insertAfterInternal(e,t,r,n);return r7(e,i)}:"insertBefore"===r?(r,n)=>{let i=r2.insertBeforeInternal(e,t,r,n);return r7(e,i)}:"moveBefore"===r?(r,n)=>{r2.moveBeforeInternal(e,t,r,n)}:"moveAfter"===r?(r,n)=>{r2.moveAfterInternal(e,t,r,n)}:"moveFront"===r?r=>{r2.moveFrontInternal(e,t,r)}:"moveLast"===r?r=>{r2.moveLastInternal(e,t,r)}:("string"==typeof r||r instanceof String)&&!isNaN(r)?ne(e,t.get(Number(r))):"push"===r?r=>r2.pushInternal(e,t,r):"splice"===r?function(r,n){for(var i=arguments.length,s=Array(i>2?i-2:0),o=2;or2.includes(e,t,r,n):"indexOf"===r?(r,n)=>r2.indexOf(e,t,r,n):"lastIndexOf"===r?(r,n)=>r2.lastIndexOf(e,t,r,n):"toJSForTest"===r?()=>t.toJSForTest():"toTestString"===r?()=>r2.toTestString(t):"string"==typeof r&&["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(r)?function(){for(var n=arguments.length,i=Array(n),s=0;sne(e,t));return Array.prototype[r].apply(o,i)}:Reflect.get(t,r,n),deleteProperty:(t,r)=>(rG.isEnabled(O.Trivial)&&rG.trivial("array[".concat(r,"]")),r2.deleteInternalByIndex(e,t,Number.parseInt(r)),!0)}}}class r3{initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,n){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.text.indexRangeToPosRange(e,t);rG.isEnabled(O.Debug)&&rG.debug("EDIT: f:".concat(e,"->").concat(i[0].toTestString(),", t:").concat(t,"->").concat(i[1].toTestString()," c:").concat(r));let s=n?ta(n):void 0,o=this.context.issueTimeTicket(),[a,,c,l]=this.text.edit(i,r,o,s);for(let e of c)this.context.registerGCPair(e);return this.context.push(new tL(this.text.getCreatedAt(),i[0],i[1],a,r,s?new Map(Object.entries(s)):new Map,o)),this.text.findIndexesFromRange(l)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,r){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.text.indexRangeToPosRange(e,t);rG.isEnabled(O.Debug)&&rG.debug("STYL: f:".concat(e,"->").concat(n[0].toTestString(),", t:").concat(t,"->").concat(n[1].toTestString()," a:").concat(JSON.stringify(r)));let i=ta(r),s=this.context.issueTimeTicket(),[o,a]=this.text.setStyle(n,i,s);for(let e of a)this.context.registerGCPair(e);return this.context.push(new t_(this.text.getCreatedAt(),n[0],n[1],o,new Map(Object.entries(i)),s)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");let t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");let t=this.text.findIndexesFromRange([re.fromStruct(e[0]),re.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}constructor(e,t){this.context=e,this.text=t}}class r9{initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new ti(x.ErrNotInitialized,"Counter is not initialized yet");let t=this.context.issueTimeTicket(),r=tC.of(e,t);if(!r.isNumericType())throw TypeError("Unsupported type of value: ".concat(typeof r.getValue()));return this.counter.increase(r),this.context.push(rs.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new ti(x.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}constructor(e,t){this.valueType=e,this.value=t}}function r4(e,t,r){let{type:n}=e,i=r.issueTimeTicket();if(n===tM){r8(e);let{value:r}=e,s=tY.create(tH.of(i,0),n,r);t.append(s)}else{let s;let{children:o=[]}=e,{attributes:a}=e;if("object"==typeof a&&!to(a)){let e=ta(a);for(let[t,r]of(s=new tO,Object.entries(e)))s.set(t,r,i)}let c=tY.create(tH.of(i,0),n,void 0,s);for(let e of(t.append(c),o))r4(e,c,r)}}function r8(e){if(!e.value.length)throw new ti(x.ErrInvalidArgument,"text node cannot have empty value");return!0}function r5(e){if(!e.length)return!0;if(e[0].type===tM)for(let t of e){let{type:e}=t;if(e!==tM)throw new ti(x.ErrInvalidArgument,"element node and text node cannot be passed together");r8(t)}else for(let t of e){let{type:e}=t;if(e===tM)throw new ti(x.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class r6{initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return tY.create(tH.of(e.issueTimeTicket(),0),"root");let t=tY.create(tH.of(e.issueTimeTicket(),0),this.initialRoot.type);for(let r of this.initialRoot.children)r4(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new ti(x.ErrInvalidArgument,"path should not be empty");let[r,n]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),s=t?ta(t):void 0,[o]=this.tree.style([r,n],s,i);this.context.push(ro.create(this.tree.getCreatedAt(),r,n,o,s?new Map(Object.entries(s)):new Map,i))}style(e,t,r){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.tree.findPos(e),i=this.tree.findPos(t),s=this.context.issueTimeTicket(),o=r?ta(r):void 0,[a,c]=this.tree.style([n,i],o,s);for(let e of c)this.context.registerGCPair(e);this.context.push(ro.create(this.tree.getCreatedAt(),n,i,a,o?new Map(Object.entries(o)):new Map,s))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.tree.findPos(e),i=this.tree.findPos(t),s=this.context.issueTimeTicket(),[o,a]=this.tree.removeStyle([n,i],r,s);for(let e of a)this.context.registerGCPair(e);this.context.push(ro.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),n,i,o,r,s))}editInternal(e,t,r){var n;let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(0!==r.length&&r[0]&&(r5(r),r[0].type!==tM))for(let e of r){let{children:t=[]}=e;r5(t)}let s=this.context.getLastTimeTicket(),o=[];if((null===(n=r[0])||void 0===n?void 0:n.type)===tM){let e="";for(let t of r){let{value:r}=t;e+=r}o.push(tY.create(tH.of(this.context.issueTimeTicket(),0),tM,e))}else o=r.map(e=>e&&function(e,t){let r;let{type:n}=t,i=e.issueTimeTicket();if(t.type===tM){let{value:e}=t;r=tY.create(tH.of(i,0),n,e)}else if(t){let s;let{children:o=[]}=t,{attributes:a}=t;if("object"==typeof a&&!to(a)){let e=ta(a);for(let[t,r]of(s=new tO,Object.entries(e)))s.set(t,r,i)}for(let t of(r=tY.create(tH.of(e.issueTimeTicket(),0),n,void 0,s),o))r4(t,r,e)}return r}(this.context,e)).filter(e=>e);let[,a,c]=this.tree.edit([e,t],o.length?o.map(e=>null==e?void 0:e.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(let e of a)this.context.registerGCPair(e);return this.context.push(t$.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,i,c,s)),!0}editByPath(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ti(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ti(x.ErrInvalidArgument,"path should not be empty");let i=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(i,s,r?[r]:[],n)}editBulkByPath(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ti(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ti(x.ErrInvalidArgument,"path should not be empty");let i=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(i,s,r,n)}edit(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(i,s,r?[r]:[],n)}editBulk(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(i,s,r,n)}toXML(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(t);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[tG.fromStruct(e[0]),tG.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[tG.fromStruct(e[0]),tG.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}constructor(e){this.initialRoot=e}}function r7(e,t){if(t){if(t instanceof tC)return t;if(t instanceof tw)return r0(e,t);if(t instanceof tE)return function(e,t){let r=new r2(e,t);return new Proxy(t,r.getHandlers())}(e,t);if(t instanceof tJ)return new r3(e,t);else if(t instanceof ri){let r=new r9(N.IntegerCnt,0);return r.initialize(e,t),r}else if(t instanceof tQ){let r=new r6;return r.initialize(e,t),r}throw TypeError("Unsupported type of element: ".concat(typeof t))}}function ne(e,t){let r=r7(e,t);return r instanceof tC?r.getValue():r}function nt(e,t,r){let n;if(tC.isSupport(t))n=tC.of(t,r);else if(Array.isArray(t))n=tE.create(r,r2.buildArrayElements(e,t));else if("object"==typeof t)t instanceof r3?(n=tJ.create(rr.create(),r),t.initialize(e,n)):t instanceof r9?(n=ri.create(t.getValueType(),t.getValue(),r),t.initialize(e,n)):t instanceof r6?(n=tQ.create(t.buildRoot(e),r),t.initialize(e,n)):n=tw.create(r,r1.buildObjectMembers(e,t));else throw TypeError("Unsupported type of value: ".concat(typeof t));return n}class nr{hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=50&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=50&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}constructor(){this.undoStack=[],this.redoStack=[]}}let nn="disconnected",ni=new Map,ns=new Map;function no(e,t){((null==t?void 0:t.force)||"disconnected"!==nn)&&window.postMessage({source:"yorkie-devtools-sdk",...e},"*")}window.transactionEventsByDocKey=ns,(m=B||(B={})).Detached="detached",m.Attached="attached",m.Removed="removed",(p=J||(J={})).StatusChanged="status-changed",p.ConnectionChanged="connection-changed",p.SyncStatusChanged="sync-status-changed",p.Snapshot="snapshot",p.LocalChange="local-change",p.RemoteChange="remote-change",p.Initialized="initialized",p.Watched="watched",p.Unwatched="unwatched",p.PresenceChanged="presence-changed",p.Broadcast="broadcast",p.LocalBroadcast="local-broadcast",(y=L||(L={})).Connected="connected",y.Disconnected="disconnected",(v=_||(_={})).Synced="synced",v.SyncFailed="sync-failed";class na{update(e,t){if("removed"===this.getStatus())throw new ti(x.ErrDocumentRemoved,"".concat(this.key," is removed"));this.ensureClone();let r=this.changeID.getActorID(),n=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{var i;let t=(i=this.clone.root.getObject(),r0(n,i));this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(t,new tl(n,this.clone.presences.get(r)))}catch(e){throw this.clone=void 0,e}finally{this.isUpdating=!1}if(n.hasChange()){rG.isEnabled(O.Trivial)&&rG.trivial("trying to update a local change: ".concat(this.toJSON()));let e=n.getChange(),{opInfos:t,reverseOps:i}=e.execute(this.root,this.presences,E.Local),s=n.getReversePresence();s&&i.push({type:"presence",value:s}),this.localChanges.push(e),i.length>0&&this.internalHistory.pushUndo(i),t.length>0&&this.internalHistory.clearRedo(),this.changeID=e.getID();let o=[];t.length>0&&o.push({type:"local-change",source:E.Local,value:{message:e.getMessage()||"",operations:t,actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq()},rawChange:this.isEnableDevtools()?e.toStruct():void 0}),e.hasPresenceChange()&&o.push({type:"presence-changed",source:E.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(o),rG.isEnabled(O.Trivial)&&rG.trivial("after update a local change: ".concat(this.toJSON()))}}subscribe(e,t,r,n){if("string"==typeof e){if("function"!=typeof t)throw new ti(x.ErrInvalidArgument,"Second argument must be a callback function");return"presence"===e?this.eventStream.subscribe(e=>{for(let r of e)("initialized"===r.type||"watched"===r.type||"unwatched"===r.type||"presence-changed"===r.type)&&t(r)},r,n):"my-presence"===e?this.eventStream.subscribe(e=>{for(let r of e)("initialized"===r.type||"presence-changed"===r.type)&&("presence-changed"!==r.type||r.value.clientID===this.changeID.getActorID())&&t(r)},r,n):"others"===e?this.eventStream.subscribe(e=>{for(let r of e)("watched"===r.type||"unwatched"===r.type||"presence-changed"===r.type)&&r.value.clientID!==this.changeID.getActorID()&&t(r)},r,n):"connection"===e?this.eventStream.subscribe(e=>{for(let r of e)"connection-changed"===r.type&&t(r)},r,n):"status"===e?this.eventStream.subscribe(e=>{for(let r of e)"status-changed"===r.type&&t(r)},r,n):"sync"===e?this.eventStream.subscribe(e=>{for(let r of e)"sync-status-changed"===r.type&&t(r)},r,n):"local-broadcast"===e?this.eventStream.subscribe(e=>{for(let r of e)"local-broadcast"===r.type&&t(r)},r):"broadcast"===e?this.eventStream.subscribe(e=>{for(let r of e)"broadcast"===r.type&&t(r)},r):"all"===e?this.eventStream.subscribe(t,r,n):this.eventStream.subscribe(r=>{for(let n of r){if("local-change"!==n.type&&"remote-change"!==n.type)continue;let r=[];for(let t of n.value.operations)this.isSameElementOrChildOf(t.path,e)&&r.push(t);r.length&&t({...n,value:{...n.value,operations:r}})}},r,n)}if("function"==typeof e)return this.eventStream.subscribe(t=>{for(let r of t)("snapshot"===r.type||"local-change"===r.type||"remote-change"===r.type)&&e(r)},t,r);throw new ti(x.ErrInvalidArgument,'"'.concat(e,'" is not a valid'))}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;let r=e.split(".");return t.split(".").every((e,t)=>e===r[t])}applyChangePack(e){let t=e.hasSnapshot();for(t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),E.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();t&&this.applyChanges(this.localChanges,E.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),rG.isEnabled(O.Trivial)&&rG.trivial("".concat(this.root.toJSON()))}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:ts(this.presences)})}createChangePack(){let e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return t4.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(let t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){return this.ensureClone(),r0(rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{}),this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r){let{root:n,presences:i}=rU.bytesToSnapshot(r);this.root=new r$(n),this.presences=i,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.publish([{type:"snapshot",source:E.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?rU.bytesToHex(r):void 0,snapshotVector:rU.versionVectorToHex(t)}}])}applyChanges(e,t){for(let r of(rG.isEnabled(O.Debug)&&rG.debug("trying to apply ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+"removeds:".concat(this.root.getGarbageElementSetSize())),rG.isEnabled(O.Trivial)&&rG.trivial(e.map(e=>"".concat(e.getID().toTestString()," ").concat(e.toTestString())).join("\n")),e))this.applyChange(r,t);rG.isEnabled(O.Debug)&&rG.debug("after appling ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+" removeds:".concat(this.root.getGarbageElementSetSize()))}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);let r=[],n=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(n)){let i=e.getPresenceChange();switch(i.type){case P.Put:r.push(this.presences.has(n)?{type:"presence-changed",source:t,value:{clientID:n,presence:i.presence}}:{type:"watched",source:E.Remote,value:{clientID:n,presence:i.presence}});break;case P.Clear:r.push({type:"unwatched",source:E.Remote,value:{clientID:n,presence:this.getPresence(n)}}),this.removeOnlineClient(n)}}let{opInfos:i}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),i.length>0){let s=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===E.Remote?{type:"remote-change",source:t,value:{actor:n,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:s}:{type:"local-change",source:t,value:{actor:n,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:s})}r.length>0&&this.publish(r)}applyWatchStream(e){if("initialization"===e.body.case){let t=e.body.value.clientIds,r=new Set;for(let e of t)e!==this.changeID.getActorID()&&r.add(e);this.setOnlineClients(r),this.publish([{type:"initialized",source:E.Local,value:this.getPresences()}]);return}if("event"===e.body.case){let{type:t,publisher:r}=e.body.value,n=[];if(t===I.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&n.push({type:"watched",source:E.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===I.DOCUMENT_UNWATCHED){let e=this.getPresence(r);this.removeOnlineClient(r),e&&n.push({type:"unwatched",source:E.Remote,value:{clientID:r,presence:e}})}else if(t===I.DOCUMENT_BROADCAST&&e.body.value.body){let{topic:t,payload:i}=e.body.value.body,s=new TextDecoder;n.push({type:"broadcast",value:{clientID:r,topic:t,payload:JSON.parse(s.decode(i))}})}n.length>0&&this.publish(n)}}applyStatus(e){this.status=e,"detached"===e&&this.setActor(th),this.publish([{source:"removed"===e?E.Remote:E.Local,type:"status-changed",value:"attached"===e?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if("status-changed"===e.type){this.applyStatus(e.value.status),"attached"===e.value.status&&this.setActor(e.value.actorID);return}if("snapshot"===e.type){let{snapshot:t,serverSeq:r,snapshotVector:n}=e.value;if(!t)return;this.applySnapshot(BigInt(r),rU.hexToVersionVector(n),rU.hexToBytes(t));return}if("local-change"===e.type||"remote-change"===e.type){if(!e.rawChange)return;let t=t9.fromStruct(e.rawChange);this.applyChange(t,e.source)}if("initialized"===e.type){let t=new Set;for(let{clientID:r,presence:n}of e.value)t.add(r),this.presences.set(r,n);this.setOnlineClients(t);return}if("watched"===e.type){let{clientID:t,presence:r}=e.value;this.addOnlineClient(t),this.presences.set(t,r);return}if("unwatched"===e.type){let{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if("presence-changed"===e.type){let{clientID:t,presence:r}=e.value;this.presences.set(t,r)}}applyTransactionEvent(e){for(let t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new ti(x.ErrInvalidArgument,'path must start with "$"');let t=e.split(".");t.shift();let r=this.getRoot();for(let e of t)if(void 0===(r=r[e]))return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if("attached"!==this.status)return{};let e=this.presences.get(this.changeID.getActorID());return e?ts(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;let t=this.presences.get(e);return t?ts(t):void 0}getPresenceForTest(e){let t=this.presences.get(e);return t?ts(t):void 0}getPresences(){let e=[];for(let t of(e.push({clientID:this.changeID.getActorID(),presence:ts(this.getMyPresence())}),this.onlineClients))this.presences.has(t)&&e.push({clientID:t,presence:ts(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){let e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((e,t)=>e.clientID>t.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){let t=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(t)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new ti(x.ErrRefused,"Undo is not allowed during an update");let e=this.internalHistory.popUndo();if(void 0===e)throw new ti(x.ErrRefused,"There is no operation to be undone");this.ensureClone();let t=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tA)){new tl(t,ts(this.clone.presences.get(this.changeID.getActorID()))).set(r.value,{addToHistory:!0});continue}let e=t.issueTimeTicket();r.setExecutedAt(e),t.push(r)}let r=t.getChange();r.execute(this.clone.root,this.clone.presences,E.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,E.UndoRedo),s=t.getReversePresence();if(s&&i.push({type:"presence",value:s}),i.length>0&&this.internalHistory.pushRedo(i),!r.hasPresenceChange()&&0===n.length)return;this.localChanges.push(r),this.changeID=r.getID();let o=this.changeID.getActorID(),a=[];n.length>0&&a.push({type:"local-change",source:E.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:o,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&a.push({type:"presence-changed",source:E.UndoRedo,value:{clientID:o,presence:this.getPresence(o)}}),this.publish(a)}redo(){if(this.isUpdating)throw new ti(x.ErrRefused,"Redo is not allowed during an update");let e=this.internalHistory.popRedo();if(void 0===e)throw new ti(x.ErrRefused,"There is no operation to be redone");this.ensureClone();let t=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tA)){new tl(t,ts(this.clone.presences.get(this.changeID.getActorID()))).set(r.value,{addToHistory:!0});continue}let e=t.issueTimeTicket();r.setExecutedAt(e),t.push(r)}let r=t.getChange();r.execute(this.clone.root,this.clone.presences,E.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,E.UndoRedo),s=t.getReversePresence();if(s&&i.push({type:"presence",value:s}),i.length>0&&this.internalHistory.pushUndo(i),!r.hasPresenceChange()&&0===n.length)return;this.localChanges.push(r),this.changeID=r.getID();let o=this.changeID.getActorID(),a=[];n.length>0&&a.push({type:"local-change",source:E.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:o,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&a.push({type:"presence-changed",source:E.UndoRedo,value:{clientID:o,presence:this.getPresence(o)}}),this.publish(a)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){this.publish([{type:"local-broadcast",value:{topic:e,payload:t},options:r}])}getVersionVector(){return this.changeID.getVersionVector()}constructor(e,t){this.opts=t||{},this.key=e,this.status="detached",this.root=r$.create(),this.changeID=t3,this.checkpoint=t5,this.localChanges=[],this.eventStream=function(e){let t=new rX(e);return{subscribe:t.subscribe.bind(t),getProxy:()=>t}}(e=>{this.eventStreamObserver=e}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new nr,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},function(e){if(!e.isEnableDevtools()||ni.has(e.getKey()))return;ns.set(e.getKey(),[]);let t=e.subscribe("all",t=>{t.some(e=>e.type!==J.StatusChanged&&e.type!==J.Snapshot&&e.type!==J.LocalChange&&e.type!==J.RemoteChange&&e.type!==J.Initialized&&e.type!==J.Watched&&e.type!==J.Unwatched&&e.type!==J.PresenceChanged)||(ns.get(e.getKey()).push(t),"synced"===nn&&no({msg:"doc::sync::partial",docKey:e.getKey(),event:t}))});ni.set(e.getKey(),[t]),no({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if((null===(r=t.data)||void 0===r?void 0:r.source)==="yorkie-devtools-panel")switch(t.data.msg){case"devtools::connect":if("disconnected"!==nn)break;nn="connected",no({msg:"doc::available",docKey:e.getKey()}),rG.info("[YD] Devtools connected. Doc: ".concat(e.getKey()));break;case"devtools::disconnect":nn="disconnected",rG.info("[YD] Devtools disconnected. Doc: ".concat(e.getKey()));break;case"devtools::subscribe":nn="synced",no({msg:"doc::sync::full",docKey:e.getKey(),events:ns.get(e.getKey())}),rG.info("[YD] Devtools subscribed. Doc: ".concat(e.getKey()))}})}(this)}}var nc=JSON.parse('{"u2":"yorkie-js-sdk","i8":"0.5.4"}');let nl=e=>{try{let t=JSON.stringify(e);if(void 0===t)return!1}catch(e){return!1}return!0};(w=M||(M={})).Manual="manual",w.Realtime="realtime",w.RealtimePushOnly="realtime-pushonly",w.RealtimeSyncOff="realtime-syncoff",(A=q||(q={})).Deactivated="deactivated",A.Activated="activated",(T=z||(z={})).SyncLoop="SyncLoop",T.WatchLoop="WatchLoop";let nh={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},nd={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class nu{activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),rG.info('[AC] c:"'.concat(this.getKey(),'" activated, id:"').concat(this.id,'"'))}).catch(e=>{throw rG.error('[AC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}deactivate(){return"deactivated"===this.status?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),rG.info('[DC] c"'.concat(this.getKey(),'" deactivated'))}).catch(e=>{throw rG.error('[DC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}attach(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e.getStatus()!==B.Detached)throw new ti(x.ErrDocumentNotDetached,"".concat(e.getKey()," is not detached"));e.setActor(this.id),e.update((e,t)=>t.set(r.initialPresence||{}));let n=e.subscribe("local-broadcast",async t=>{var r;let{topic:n,payload:i}=t.value,s=null===(r=t.options)||void 0===r?void 0:r.error,o=t.options;try{await this.broadcast(e.getKey(),n,i,o)}catch(e){e instanceof Error&&(null==s||s(e))}}),i=null!==(t=r.syncMode)&&void 0!==t?t:"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:rU.toChangePack(e.createChangePack())},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(async t=>{let s=rU.fromChangePack(t.changePack);if(e.applyChangePack(s),e.getStatus()===B.Removed)return e;e.applyStatus(B.Attached),this.attachmentMap.set(e.getKey(),new rY(this.reconnectStreamDelay,e,t.documentId,i,n)),"manual"!==i&&await this.runWatchLoop(e.getKey()),rG.info('[AD] c:"'.concat(this.getKey(),'" attaches d:"').concat(e.getKey(),'"'));let o=e.getRootObject();if(r.initialRoot){let t=r.initialRoot;e.update(e=>{for(let[r,n]of Object.entries(t))o.has(r)||(e[r]=n)})}return e}).catch(e=>{throw rG.error('[AD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}detach(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return e.update((e,t)=>t.clear()),this.enqueueTask(async()=>{var n;return this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:rU.toChangePack(e.createChangePack()),removeIfNotAttached:null!==(n=t.removeIfNotAttached)&&void 0!==n&&n},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(t=>{let r=rU.fromChangePack(t.changePack);return e.applyChangePack(r),e.getStatus()!==B.Removed&&e.applyStatus(B.Detached),this.detachInternal(e.getKey()),rG.info('[DD] c:"'.concat(this.getKey(),'" detaches d:"').concat(e.getKey(),'"')),e}).catch(e=>{throw rG.error('[DD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}async changeSyncMode(e,t){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));let n=r.syncMode;return n===t||((r.changeSyncMode(t),"manual"===t)?r.cancelWatchStream():("realtime"===t&&(r.remoteChangeEventReceived=!0),"manual"===n&&await this.runWatchLoop(e.getKey()))),e}sync(e){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e){let t=this.attachmentMap.get(e.getKey());if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(e=>{throw rG.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}return this.enqueueTask(async()=>{let e=[];for(let[,t]of this.attachmentMap)e.push(this.syncInternal(t,t.syncMode));return Promise.all(e).catch(e=>{throw rG.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}remove(e){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let t=this.attachmentMap.get(e.getKey());if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));e.setActor(this.id);let r=rU.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:r},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(t=>{let r=rU.fromChangePack(t.changePack);e.applyChangePack(r),this.detachInternal(e.getKey()),rG.info('[RD] c:"'.concat(this.getKey(),'" removes d:"').concat(e.getKey(),'"'))}).catch(e=>{throw rG.error('[RD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}getID(){return this.id}getKey(){return this.key}isActive(){return"activated"===this.status}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,n){var i;if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let s=this.attachmentMap.get(e);if(!s)throw new ti(x.ErrDocumentNotAttached,"".concat(e," is not attached"));if(!nl(r))throw new ti(x.ErrInvalidArgument,"payload is not serializable");let o=null!==(i=null==n?void 0:n.maxRetries)&&void 0!==i?i:nd.maxRetries,a=nd.maxBackoff,c=0,l=e=>Math.min(nd.initialRetryInterval*2**e,a),h=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e)}}).then(()=>{rG.info('[BC] c:"'.concat(this.getKey(),'" broadcasts d:"').concat(e,'" t:"').concat(t,'"'))}).catch(e=>{if(rG.error('[BC] c:"'.concat(this.getKey(),'" err:'),e),this.handleConnectError(e)){if(ch(),l(++c-1)),rG.info('[BC] c:"'.concat(this.getKey(),'" retry attempt ').concat(c,"/").concat(o));else throw rG.error('[BC] c:"'.concat(this.getKey(),'" exceeded maximum retry attempts')),e}else throw e}));return h()}runSyncLoop(){let e=()=>{if(!this.isActive()){rG.debug('[SL] c:"'.concat(this.getKey(),'" exit sync loop')),this.conditions.SyncLoop=!1;return}let t=[];for(let[,e]of this.attachmentMap)e.needRealtimeSync()&&(e.remoteChangeEventReceived=!1,t.push(this.syncInternal(e,e.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(t=>{rG.error('[SL] c:"'.concat(this.getKey(),'" sync failed:'),t),this.handleConnectError(t)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};rG.debug('[SL] c:"'.concat(this.getKey(),'" run sync loop')),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){let t=this.attachmentMap.get(e);if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e," is not attached"));return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new ti(x.ErrClientNotActivated,"".concat(this.key," is not active")));let n=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e)},signal:n.signal});return t.doc.publish([{type:J.ConnectionChanged,value:L.Connected}]),rG.info('[WD] c:"'.concat(this.getKey(),'" watches d:"').concat(e,'"')),new Promise((e,s)=>{(async()=>{try{for await(let r of i)this.handleWatchDocumentsResponse(t,r),"initialization"===r.body.case&&e([i,n])}catch(e){t.doc.resetOnlineClients(),t.doc.publish([{type:J.Initialized,source:E.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:J.ConnectionChanged,value:L.Disconnected}]),rG.debug('[WD] c:"'.concat(this.getKey(),'" unwatches')),this.handleConnectError(e)?r():this.conditions.WatchLoop=!1,s(e)}})()})})}handleWatchDocumentsResponse(e,t){if("event"===t.body.case&&t.body.value.type===I.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){for(let[e,t]of(this.status="deactivated",this.attachmentMap))this.detachInternal(e),t.doc.applyStatus(B.Detached)}detachInternal(e){let t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){let{doc:r,docID:n}=e,i=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:n,changePack:rU.toChangePack(i),pushOnly:"realtime-pushonly"===t},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(r.getKey())}}).then(t=>{let n=rU.fromChangePack(t.changePack);if(n.hasChanges()&&("realtime-pushonly"===e.syncMode||"realtime-syncoff"===e.syncMode))return r;r.applyChangePack(n),e.doc.publish([{type:J.SyncStatusChanged,value:_.Synced}]),r.getStatus()===B.Removed&&this.detachInternal(r.getKey());let s=r.getKey(),o=n.getChangeSize();return rG.info('[PP] c:"'.concat(this.getKey(),'" sync d:"').concat(s,'", push:').concat(i.getChangeSize()," pull:").concat(o," cp:").concat(n.getCheckpoint().toTestString())),r}).catch(e=>{throw r.publish([{type:J.SyncStatusChanged,value:_.SyncFailed}]),rG.error('[PP] c:"'.concat(this.getKey(),'" err :'),e),e})}handleConnectError(e){return e instanceof G.K&&(e.code===H.E.Canceled||e.code===H.E.Unknown||e.code===H.E.ResourceExhausted||e.code===H.E.Unavailable||((rT(e)===x.ErrClientNotActivated||rT(e)===x.ErrClientNotFound)&&this.deactivateInternal(),!1))}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(0===this.taskQueue.length){this.processing=!1;return}try{this.processing=!0;let e=this.taskQueue.shift();await e()}catch(e){rG.error('[TQ] c:"'.concat(this.getKey(),'" process failed, id:"').concat(this.id,'"'))}this.processNext()}constructor(e,t){var r,n;this.processing=!1,t=t||nh,this.key=t.key?t.key:rH(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||nh.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||nh.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||nh.retrySyncLoopDelay,this.rpcClient=(0,Y.Hb)(tr,(0,Z.u)({baseUrl:e,interceptors:[(r=t.apiKey,n=t.token,e=>async t=>(r&&t.header.set("x-api-key",r),n&&t.header.set("authorization",n),await e(t))),e=>async t=>(t.header.set("x-yorkie-user-agent",nc.u2+"/"+nc.i8),await e(t))]})),this.taskQueue=[]}}var ng={Client:nu,Document:na,Primitive:tC,Text:r3,Counter:r9,Tree:r6,LogLevel:O,setLogLevel:rW,IntType:N.IntegerCnt,LongType:N.LongCnt};"undefined"!=typeof globalThis&&(globalThis.yorkie={Client:nu,Document:na,Primitive:tC,Text:r3,Counter:r9,Tree:r6,LogLevel:O,setLogLevel:rW,IntType:N.IntegerCnt,LongType:N.LongCnt}),r(109);var nf=r(6182);function nm(e){let{content:t,actions:r}=e,[n,i]=(0,U.useState)(new Date),[s,o]=(0,U.useState)("Enter text here!"),a=n?W(new Date(n.toString())):"",c=e=>{let n=!1;switch(e){case"PUSH":n=!1,t.forEach(e=>{if(e.date===a)return n=!n,0}),n?r.updateContent(a,s):r.addContent(a,s),o("Enter text here!");break;case"DELETE":r.deleteContent(a)}};return(0,K.jsx)("article",{children:(0,K.jsxs)("div",{children:[(0,K.jsx)(nf.ZP,{onChange:i,value:n,locale:"en-EN",showNeighboringMonth:!1,formatDay:(e,t)=>t.toLocaleString("en",{day:"numeric"}),tileClassName:e=>{let{date:r}=e;return t.find(e=>e.date===W(r))?"highlight":""}}),(0,K.jsxs)("p",{children:["selected day : ",a]}),(0,K.jsx)("div",{className:V().memo,children:t.map((e,t)=>{if(e.date===a)return(0,K.jsx)("p",{children:e.text},t)})}),(0,K.jsxs)("div",{className:V().inputForm_editor,children:[(0,K.jsx)("h3",{children:"input form"}),(0,K.jsx)("textarea",{className:V().textArea,value:s,onChange:e=>o(e.target.value)})]}),(0,K.jsx)("button",{className:"button",onClick:()=>c("PUSH"),children:"push"}),(0,K.jsx)("button",{className:"button",onClick:()=>c("DELETE"),children:"pop"})]})})}let np=[{date:W(new Date).replace(/^\d{2}/,"01"),text:"payday"},{date:W(new Date).replace(/^\d{2}/,"17"),text:"Garry's birthday"}],ny="next.js-Scheduler-".concat(W(new Date));function nv(){let[e,t]=(0,U.useState)([]),[r,n]=(0,U.useState)(np),[i]=(0,U.useState)(()=>new ng.Document(ny));return(0,U.useEffect)(()=>{let e=new ng.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});i.subscribe("presence",e=>{e.type!==J.PresenceChanged&&t(function(e){let t=[];for(let{presence:r}of e)t.push(r.userName);return t}(i.getPresences()))}),async function(t,r){await e.activate(),await e.attach(t,{initialPresence:{userName:function(){let e=Math.floor(Math.random()*j.length);return j[e]}()}}),t.update(e=>{e.content||(e.content=np)},"create default content if not exists"),t.subscribe(()=>{r(t.getRoot().content)}),r(t.getRoot().content)}(i,e=>n(e))},[]),(0,K.jsxs)("main",{className:V().main,children:[(0,K.jsxs)("p",{children:["peers : [",e.map((e,t)=>(0,K.jsxs)("span",{children:[" ",e,", "]},t))," ","]"]}),(0,K.jsx)(nm,{content:r,actions:{addContent(e,t){i.update(r=>{r.content.push({date:e,text:t})})},deleteContent(e){i.update(t=>{let r;for(let n of t.content)if(n.date===e){r=n;break}r&&t.content.deleteByID(r.getID())})},updateContent(e,t){i.update(r=>{let n;for(let t of r.content)if(t.date===e){n=t;break}n&&(n.text=t)})}}})]})}},109:function(){},7397:function(e){e.exports={main:"page_main__s_E_L",textArea:"page_textArea__sVKfA",memo:"page_memo__V0Ipn",inputForm_editor:"page_inputForm_editor__Tk7dD"}}},function(e){e.O(0,[662,828,852,744],function(){return e(e.s=4629)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/examples/nextjs-scheduler/index.html b/examples/nextjs-scheduler/index.html index 2646418d5..44612c273 100644 --- a/examples/nextjs-scheduler/index.html +++ b/examples/nextjs-scheduler/index.html @@ -1 +1 @@ -Next.js react-calendar example

    peers : [ ]

    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
    Sun

    selected day : 28-10-24

    input form

    \ No newline at end of file +Next.js react-calendar example

    peers : [ ]

    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
    Sun

    selected day : 04-11-24

    input form

    \ No newline at end of file diff --git a/examples/nextjs-scheduler/index.txt b/examples/nextjs-scheduler/index.txt index 2dc02a6e5..0710c3562 100644 --- a/examples/nextjs-scheduler/index.txt +++ b/examples/nextjs-scheduler/index.txt @@ -1,7 +1,7 @@ 2:I[9974,[],""] -3:I[1802,["662","static/chunks/662-2ca4b8930a4bf5cf.js","931","static/chunks/app/page-344366f5b41338b3.js"],""] +3:I[1802,["662","static/chunks/662-2ca4b8930a4bf5cf.js","931","static/chunks/app/page-a4871ed0264d2385.js"],""] 4:I[4926,[],""] 5:I[4582,[],""] -0:["bkgGMaTsh79HkOzLjOPfM",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},["$L1",["$","$L2",null,{"propsForComponent":{"params":{}},"Component":"$3","isStaticGeneration":true}],null]]},[null,["$","html",null,{"lang":"en","children":["$","body",null,{"children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":["$","h1",null,{"children":"404 not found"}],"notFoundStyles":[],"styles":[["$","link","0",{"rel":"stylesheet","href":"/yorkie-js-sdk/examples/nextjs-scheduler/_next/static/css/0b8518b4fc95b726.css","precedence":"next","crossOrigin":""}]]}]}]}],null]],[[["$","link","0",{"rel":"stylesheet","href":"/yorkie-js-sdk/examples/nextjs-scheduler/_next/static/css/55c28824c4a39011.css","precedence":"next","crossOrigin":""}]],"$L6"]]]] +0:["6_IyhgbJWQCmw1jrIomT-",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},["$L1",["$","$L2",null,{"propsForComponent":{"params":{}},"Component":"$3","isStaticGeneration":true}],null]]},[null,["$","html",null,{"lang":"en","children":["$","body",null,{"children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":["$","h1",null,{"children":"404 not found"}],"notFoundStyles":[],"styles":[["$","link","0",{"rel":"stylesheet","href":"/yorkie-js-sdk/examples/nextjs-scheduler/_next/static/css/0b8518b4fc95b726.css","precedence":"next","crossOrigin":""}]]}]}]}],null]],[[["$","link","0",{"rel":"stylesheet","href":"/yorkie-js-sdk/examples/nextjs-scheduler/_next/static/css/55c28824c4a39011.css","precedence":"next","crossOrigin":""}]],"$L6"]]]] 6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"Next.js react-calendar example"}],["$","meta","3",{"name":"description","content":"example of yorkie-js-sdk with next.js & react-calendar"}],["$","link","4",{"rel":"icon","href":"/yorkie-js-sdk/examples/nextjs-scheduler/favicon.ico","type":"image/x-icon","sizes":"64x64"}]] 1:null diff --git a/examples/profile-stack/assets/index-Cj6zDQ1C.js b/examples/profile-stack/assets/index-DCwEJGaT.js similarity index 92% rename from examples/profile-stack/assets/index-Cj6zDQ1C.js rename to examples/profile-stack/assets/index-DCwEJGaT.js index 59a18a398..71de13e9d 100644 --- a/examples/profile-stack/assets/index-Cj6zDQ1C.js +++ b/examples/profile-stack/assets/index-DCwEJGaT.js @@ -20,7 +20,7 @@ var ca=Object.defineProperty;var ua=(n,t,e)=>t in n?ca(n,t,{enumerable:!0,config * * SPDX-License-Identifier: Apache-2.0 */var we=null;try{we=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function O(n,t,e){this.low=n|0,this.high=t|0,this.unsigned=!!e}O.prototype.__isLong__;Object.defineProperty(O.prototype,"__isLong__",{value:!0});function Z(n){return(n&&n.__isLong__)===!0}function Li(n){var t=Math.clz32(n&-n);return n?31-t:t}O.isLong=Z;var Ji={},Fi={};function Tr(n,t){var e,r,s;return t?(n>>>=0,(s=0<=n&&n<256)&&(r=Fi[n],r)?r:(e=B(n,0,!0),s&&(Fi[n]=e),e)):(n|=0,(s=-128<=n&&n<128)&&(r=Ji[n],r)?r:(e=B(n,n<0?-1:0,!1),s&&(Ji[n]=e),e))}O.fromInt=Tr;function Te(n,t){if(isNaN(n))return t?Wt:Se;if(t){if(n<0)return Wt;if(n>=Po)return Bo}else{if(n<=-$i)return te;if(n+1>=$i)return Oo}return n<0?Te(-n,t).neg():B(n%Br|0,n/Br|0,t)}O.fromNumber=Te;function B(n,t,e){return new O(n,t,e)}O.fromBits=B;var Un=Math.pow;function Ks(n,t,e){if(n.length===0)throw Error("empty string");if(typeof t=="number"?(e=t,t=!1):t=!!t,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return t?Wt:Se;if(e=e||10,e<2||360)throw Error("interior hyphen");if(r===0)return Ks(n.substring(1),t,e).neg();for(var s=Te(Un(e,8)),i=Se,o=0;o>>0:this.low};T.toNumber=function(){return this.unsigned?(this.high>>>0)*Br+(this.low>>>0):this.high*Br+(this.low>>>0)};T.toString=function(t){if(t=t||10,t<2||36>>0,f=h.toString(t);if(o=l,o.isZero())return f+c;for(;f.length<6;)f="0"+f;c=""+f+c}};T.getHighBits=function(){return this.high};T.getHighBitsUnsigned=function(){return this.high>>>0};T.getLowBits=function(){return this.low};T.getLowBitsUnsigned=function(){return this.low>>>0};T.getNumBitsAbs=function(){if(this.isNegative())return this.eq(te)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,e=31;e>0&&!(t&1<=0};T.isOdd=function(){return(this.low&1)===1};T.isEven=function(){return(this.low&1)===0};T.equals=function(t){return Z(t)||(t=Ce(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};T.eq=T.equals;T.notEquals=function(t){return!this.eq(t)};T.neq=T.notEquals;T.ne=T.notEquals;T.lessThan=function(t){return this.comp(t)<0};T.lt=T.lessThan;T.lessThanOrEqual=function(t){return this.comp(t)<=0};T.lte=T.lessThanOrEqual;T.le=T.lessThanOrEqual;T.greaterThan=function(t){return this.comp(t)>0};T.gt=T.greaterThan;T.greaterThanOrEqual=function(t){return this.comp(t)>=0};T.gte=T.greaterThanOrEqual;T.ge=T.greaterThanOrEqual;T.compare=function(t){if(Z(t)||(t=Ce(t)),this.eq(t))return 0;var e=this.isNegative(),r=t.isNegative();return e&&!r?-1:!e&&r?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};T.comp=T.compare;T.negate=function(){return!this.unsigned&&this.eq(te)?te:this.not().add(Sr)};T.neg=T.negate;T.add=function(t){Z(t)||(t=Ce(t));var e=this.high>>>16,r=this.high&65535,s=this.low>>>16,i=this.low&65535,o=t.high>>>16,c=t.high&65535,l=t.low>>>16,h=t.low&65535,f=0,p=0,v=0,m=0;return m+=i+h,v+=m>>>16,m&=65535,v+=s+l,p+=v>>>16,v&=65535,p+=r+c,f+=p>>>16,p&=65535,f+=e+o,f&=65535,B(v<<16|m,f<<16|p,this.unsigned)};T.subtract=function(t){return Z(t)||(t=Ce(t)),this.add(t.neg())};T.sub=T.subtract;T.multiply=function(t){if(this.isZero())return this;if(Z(t)||(t=Ce(t)),we){var e=we.mul(this.low,this.high,t.low,t.high);return B(e,we.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Wt:Se;if(this.eq(te))return t.isOdd()?te:Se;if(t.eq(te))return this.isOdd()?te:Se;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Ui)&&t.lt(Ui))return Te(this.toNumber()*t.toNumber(),this.unsigned);var r=this.high>>>16,s=this.high&65535,i=this.low>>>16,o=this.low&65535,c=t.high>>>16,l=t.high&65535,h=t.low>>>16,f=t.low&65535,p=0,v=0,m=0,w=0;return w+=o*f,m+=w>>>16,w&=65535,m+=i*f,v+=m>>>16,m&=65535,m+=o*h,v+=m>>>16,m&=65535,v+=s*f,p+=v>>>16,v&=65535,v+=i*h,p+=v>>>16,v&=65535,v+=o*l,p+=v>>>16,v&=65535,p+=r*f+s*h+i*l+o*c,p&=65535,B(m<<16|w,p<<16|v,this.unsigned)};T.mul=T.multiply;T.divide=function(t){if(Z(t)||(t=Ce(t)),t.isZero())throw Error("division by zero");if(we){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?we.div_u:we.div_s)(this.low,this.high,t.low,t.high);return B(e,we.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Wt:Se;var r,s,i;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Wt;if(t.gt(this.shru(1)))return Do;i=Wt}else{if(this.eq(te)){if(t.eq(Sr)||t.eq(Bs))return te;if(t.eq(te))return Sr;var o=this.shr(1);return r=o.div(t).shl(1),r.eq(Se)?t.isNegative()?Sr:Bs:(s=this.sub(t.mul(r)),i=r.add(s.div(t)),i)}else if(t.eq(te))return this.unsigned?Wt:Se;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();i=Se}for(s=this;s.gte(t);){r=Math.max(1,Math.floor(s.toNumber()/t.toNumber()));for(var c=Math.ceil(Math.log(r)/Math.LN2),l=c<=48?1:Un(2,c-48),h=Te(r),f=h.mul(t);f.isNegative()||f.gt(s);)r-=l,h=Te(r,this.unsigned),f=h.mul(t);h.isZero()&&(h=Sr),i=i.add(h),s=s.sub(f)}return i};T.div=T.divide;T.modulo=function(t){if(Z(t)||(t=Ce(t)),we){var e=(this.unsigned?we.rem_u:we.rem_s)(this.low,this.high,t.low,t.high);return B(e,we.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};T.mod=T.modulo;T.rem=T.modulo;T.not=function(){return B(~this.low,~this.high,this.unsigned)};T.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};T.clz=T.countLeadingZeros;T.countTrailingZeros=function(){return this.low?Li(this.low):Li(this.high)+32};T.ctz=T.countTrailingZeros;T.and=function(t){return Z(t)||(t=Ce(t)),B(this.low&t.low,this.high&t.high,this.unsigned)};T.or=function(t){return Z(t)||(t=Ce(t)),B(this.low|t.low,this.high|t.high,this.unsigned)};T.xor=function(t){return Z(t)||(t=Ce(t)),B(this.low^t.low,this.high^t.high,this.unsigned)};T.shiftLeft=function(t){return Z(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?B(this.low<>>32-t,this.unsigned):B(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):B(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};T.shr=T.shiftRight;T.shiftRightUnsigned=function(t){return Z(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?B(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?B(this.high,0,this.unsigned):B(this.high>>>t-32,0,this.unsigned)};T.shru=T.shiftRightUnsigned;T.shr_u=T.shiftRightUnsigned;T.rotateLeft=function(t){var e;return Z(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?B(this.high,this.low,this.unsigned):t<32?(e=32-t,B(this.low<>>e,this.high<>>e,this.unsigned)):(t-=32,e=32-t,B(this.high<>>e,this.low<>>e,this.unsigned))};T.rotl=T.rotateLeft;T.rotateRight=function(t){var e;return Z(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?B(this.high,this.low,this.unsigned):t<32?(e=32-t,B(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,e=32-t,B(this.low<>>t,this.high<>>t,this.unsigned))};T.rotr=T.rotateRight;T.toSigned=function(){return this.unsigned?B(this.low,this.high,!1):this};T.toUnsigned=function(){return this.unsigned?this:B(this.low,this.high,!0)};T.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};T.toBytesLE=function(){var t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};T.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]};O.fromBytes=function(t,e,r){return r?O.fromBytesLE(t,e):O.fromBytesBE(t,e)};O.fromBytesLE=function(t,e){return new O(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)};O.fromBytesBE=function(t,e){return new O(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)};var W=(n=>(n[n.Null=0]="Null",n[n.Boolean=1]="Boolean",n[n.Integer=2]="Integer",n[n.Long=3]="Long",n[n.Double=4]="Double",n[n.String=5]="String",n[n.Bytes=6]="Bytes",n[n.Date=7]="Date",n))(W||{});class $ extends en{constructor(e,r){super(r);a(this,"valueType");a(this,"value");this.valueType=$.getPrimitiveType(e),this.value=e===void 0?null:e}static of(e,r){return new $(e,r)}static valueFromBytes(e,r){switch(e){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const s=new DataView(r.buffer);return r.forEach(function(i,o){s.setUint8(o,i)}),s.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return O.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(O.fromBytesLE(Array.from(r),!0).toNumber());default:throw new g(d.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return this.valueType===5?`"${qe(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const e=$.of(this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e.setRemovedAt(this.getRemovedAt()),e}getType(){return this.valueType}static getPrimitiveType(e){switch(typeof e){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(e)?2:4;case"string":return 5;case"object":if(e===null)return 0;if(e instanceof O)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return $.getPrimitiveType(e)!==void 0}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===2||e===3||e===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 4:{const e=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,e,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const e=this.value,r=O.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new g(d.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class qn extends Co{constructor(e){super(e);a(this,"prev");a(this,"next");this.value=e}static createAfter(e,r){const s=new qn(r),i=e.next;return e.next=s,s.prev=e,s.next=i,i&&(i.prev=s),s}remove(e){return this.value.remove(e)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class Xr{constructor(){a(this,"dummyHead");a(this,"last");a(this,"nodeMapByIndex");a(this,"nodeMapByCreatedAt");const t=$.of(0,xe);t.setRemovedAt(xe),this.dummyHead=new qn(t),this.last=this.dummyHead,this.nodeMapByIndex=new Yr,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Xr}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,e){let r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new g(d.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(e);)r=r.getNext();return r}release(t){this.last===t&&(this.last=t.getPrev()),t.release(),this.nodeMapByIndex.delete(t),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}insertAfter(t,e,r=e.getCreatedAt()){const s=this.findNextBeforeExecutedAt(t,r),i=qn.createAfter(s,e);s===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(s,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(t,e,r){const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new g(d.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new g(d.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);s!==i&&(!i.getValue().getMovedAt()||r.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(s.getCreatedAt(),i.getValue(),r),i.getValue().setMovedAt(r))}insert(t){this.insertAfter(this.last.getCreatedAt(),t)}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}subPathOf(t){const e=this.nodeMapByCreatedAt.get(t.toIDString());if(e)return String(this.nodeMapByIndex.indexOf(e))}purge(t){const e=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!e)throw new g(d.ErrInvalidArgument,`fail to find the given createdAt: ${t.getCreatedAt().toIDString()}`);this.release(e)}getByIndex(t){if(t>=this.length)return;const[e,r]=this.nodeMapByIndex.find(t);let s=e;if(t===0&&e===this.dummyHead||r>0)do s&&(s=s.getNext());while(s&&s.isRemoved());return s}getPrevCreatedAt(t){let e=this.nodeMapByCreatedAt.get(t.toIDString());do e=e.getPrev();while(this.dummyHead!==e&&e.isRemoved());return e.getValue().getCreatedAt()}delete(t,e){const r=this.nodeMapByCreatedAt.get(t.toIDString()),s=r.isRemoved();return r.remove(e)&&!s&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(t,e){const r=this.getByIndex(t);if(r)return r.remove(e)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const t=[];for(const e of this){const r=`${e.getCreatedAt().toIDString()}:${e.getValue().toJSON()}`;e.isRemoved()?t.push(`{${r}}`):t.push(`[${r}]`)}return t.join("")}*[Symbol.iterator](){let t=this.dummyHead.getNext();for(;t;)yield t,t=t.getNext()}}class ae extends ir{constructor(e,r){super(e);a(this,"elements");this.elements=r}static create(e,r){if(!r)return new ae(e,Xr.create());const s=Xr.create();for(const i of r)s.insertAfter(s.getLastCreatedAt(),i.deepcopy());return new ae(e,s)}subPathOf(e){return this.elements.subPathOf(e)}purge(e){this.elements.purge(e)}insertAfter(e,r){this.elements.insertAfter(e,r)}moveAfter(e,r,s){this.elements.moveAfter(e,r,s)}get(e){const r=this.elements.getByIndex(e);return r==null?void 0:r.getValue()}getByID(e){const r=this.elements.getByID(e);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(e){return this.elements.getPrevCreatedAt(e)}delete(e,r){return this.elements.delete(e,r)}deleteByIndex(e,r){return this.elements.deleteByIndex(e,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const e of this.elements)e.isRemoved()||(yield e.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(e){for(const r of this.elements){const s=r.getValue();if(e(s,this))return;s instanceof ir&&s.getDescendants(e)}}toJSON(){const e=[];for(const r of this)e.push(r.toJSON());return`[${e.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const e={};for(let r=0;r({...m,value:m.value?{attributes:xr(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[h,v,f,[l,l]]}setStyle(e,r,s,i){const[,o]=this.rgaTreeSplit.findNodeWithSplit(e[1],s),[,c]=this.rgaTreeSplit.findNodeWithSplit(e[0],s),l=[],h=this.rgaTreeSplit.findBetween(c,o),f=new Map,p=[];for(const m of h){const w=m.getCreatedAt().getActorID(),k=i!=null&&i.size?i.has(w)?i.get(w):xe:qr;if(m.canStyle(s,k)){const E=f.get(w),C=m.getCreatedAt();(!E||C.after(E))&&f.set(w,C),p.push(m)}}const v=[];for(const m of p){if(m.isRemoved())continue;const[w,k]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());l.push({type:"style",actor:s.getActorID(),from:w,to:k,value:{attributes:xr(r)}});for(const[E,C]of Object.entries(r)){const[P]=m.getValue().setAttr(E,C,s);P!==void 0&&v.push({parent:m.getValue(),child:P})}}return[f,v,l]}indexRangeToPosRange(e,r){const s=this.rgaTreeSplit.indexToPos(e);return e===r?[s,s]:[s,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const e=[];for(const r of this.rgaTreeSplit)r.isRemoved()||e.push(r.getValue().toJSON());return`[${e.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const e=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const s=r.getValue();e.push({attributes:xr(s.getAttributes()),content:s.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const e=new Ae(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return e.remove(this.getRemovedAt()),e}findIndexesFromRange(e){return this.rgaTreeSplit.findIndexesFromRange(e)}getGCPairs(){const e=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&e.push({parent:this.rgaTreeSplit,child:r});for(const s of r.getValue().getGCPairs())e.push(s)}return e}}class rn extends Ne{constructor(e,r,s,i,o,c,l){super(e,l);a(this,"fromPos");a(this,"toPos");a(this,"maxCreatedAtMapByActor");a(this,"content");a(this,"attributes");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.content=o,this.attributes=c}static create(e,r,s,i,o,c,l){return new rn(e,r,s,i,o,c,l)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ae))throw new g(d.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=r,[,i,o]=s.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const c of o)e.registerGCPair(c);return{opInfos:i.map(({from:c,to:l,value:h})=>({type:"edit",from:c,to:l,value:h,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.content;return`${e}.EDIT(${r},${s},${i})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class nn extends Ne{constructor(e,r,s,i,o,c){super(e,c);a(this,"fromPos");a(this,"toPos");a(this,"maxCreatedAtMapByActor");a(this,"attributes");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o}static create(e,r,s,i,o,c){return new nn(e,r,s,i,o,c)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ae))throw new g(d.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=r,[,i,o]=s.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const c of i)e.registerGCPair(c);return{opInfos:o.map(({from:c,to:l,value:h})=>({type:"style",from:c,to:l,value:h,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.attributes;return`${e}.STYL(${r},${s},${JSON.stringify(i)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const qc=2,Vc="root",Ht="text";function Mr(n,t){let e=0;const r=n.children;for(let s=0;s0)throw new g(d.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let t=this.parent;const e=this.isRemoved?-1:1;for(;t&&(t.size+=this.paddedSize*e,!t.isRemoved);)t=t.parent}updateDescendantsSize(){let t=0;for(const e of this._children){const r=e.updateDescendantsSize();e.isRemoved||(t+=r)}return this.size+=t,this.paddedSize}get isText(){return this.type===Ht}get paddedSize(){return this.size+(this.isText?0:qc)}isAncestorOf(t){return Kc(this,t)}get nextSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t+1];if(e)return e}get prevSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t-1];if(e)return e}splitText(t,e){if(t===0||t===this.size)return;const r=this.value.slice(0,t),s=this.value.slice(t);if(!s.length)return;this.value=r;const i=this.cloneText(t+e);return i.value=s,this.parent.insertAfterInternal(i,this),i}get children(){return this._children.filter(t=>!t.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(t=>t.isText)}append(...t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");this._children.push(...t);for(const e of t)e.parent=this,e.updateAncestorsSize()}prepend(...t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");this._children.unshift(...t);for(const e of t)e.parent=this}insertBefore(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new g(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r),t.updateAncestorsSize()}insertAfter(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new g(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1),t.updateAncestorsSize()}insertAt(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,e),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");const e=this._children.indexOf(t);if(e===-1)throw new g(d.ErrInvalidArgument,"child not found");this._children.splice(e,1),t.parent=void 0}splitElement(t,e){const r=this.cloneElement(e);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const s=this.children.slice(0,t),i=this.children.slice(t);this._children=s,r._children=i,this.size=this._children.reduce((o,c)=>o+c.paddedSize,0),r.size=r._children.reduce((o,c)=>o+c.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new g(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1)}insertAtInternal(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");this._children.splice(e,0,t),t.parent=this}findOffset(t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");if(t.isRemoved){const e=this._children.indexOf(t);return this.allChildren.splice(0,e).filter(s=>!s.isRemoved).length}return this.children.indexOf(t)}findBranchOffset(t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");let e=t;for(;e;){const r=this._children.indexOf(e);if(r!==-1)return r;e=e.parent}return-1}}function Kc(n,t){if(n===t)return!1;for(;t.parent;){if(t.parent===n)return!0;t=t.parent}return!1}var j=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(j||{});function Ro(n,t,e,r){if(t>e)throw new g(d.ErrInvalidArgument,`from is greater than to: ${t} > ${e}`);if(t>n.size)throw new g(d.ErrInvalidArgument,`from is out of range: ${t} > ${n.size}`);if(e>n.size)throw new g(d.ErrInvalidArgument,`to is out of range: ${e} > ${n.size}`);if(t===e)return;let s=0;for(const i of n.children){if(t-i.paddedSizei.size;(i.isText||l)&&r([i,i.isText?"Text":"Start"],h),Ro(i,Math.max(0,o),Math.min(c,i.size),r),h&&r([i,"End"],h)}s+=i.paddedSize}}function Lo(n,t,e=0){for(const r of n.children)Lo(r,t,e+1);t(n,e)}function Wn(n,t,e=0){for(const r of n._children)Wn(r,t,e+1);t(n,e)}function Rs(n,t,e=!0){if(t>n.size)throw new g(d.ErrInvalidArgument,`index is out of range: ${t} > ${n.size}`);if(n.isText)return{node:n,offset:t};let r=0,s=0;for(const i of n.children){if(e&&i.isText&&i.size>=t-s)return Rs(i,t-s,e);if(t===s)return{node:n,offset:r};if(!e&&i.paddedSize===t-s)return{node:n,offset:r+1};if(i.paddedSize>t-s)return Rs(i,t-s-1,e);s+=i.paddedSize,r+=1}return{node:n,offset:r}}function Jo(n){return n.isText||n.children.length===0?n:Jo(n.children[0])}function jc(n,t){if(n.sizen===t?0:n0)if(e.right)e.right.parent=e,e=e.right;else return e;else if(r<0)if(e.left)e.left.parent=e,e=e.left;else{let s=e.parent,i=e;for(;s&&i===s.left;)i=s,s=s.parent;return s}else return e}}lastEntry(){if(!this.root)return this.root;let t=this.root;for(;t.right;)t=t.right;return t}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(t,e){for(;e;){const r=this.comparator(t,e.key);if(r===0)return e;r<0?e=e.left:r>0&&(e=e.right)}}putInternal(t,e,r){if(!r)return this.counter+=1,new Hc(t,e,!0);const s=this.comparator(t,r.key);return s<0?r.left=this.putInternal(t,e,r.left):s>0?r.right=this.putInternal(t,e,r.right):r.value=e,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(t,e){if(this.comparator(e,t.key)<0)!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeInternal(t.left,e);else{if(this.isRed(t.left)&&(t=this.rotateRight(t)),this.comparator(e,t.key)===0&&!t.right){this.counter-=1;return}if(!this.isRed(t.right)&&!this.isRed(t.right.left)&&(t=this.moveRedRight(t)),this.comparator(e,t.key)===0){this.counter-=1;const r=this.min(t.right);t.value=r.value,t.key=r.key,t.right=this.removeMin(t.right)}else t.right=this.removeInternal(t.right,e)}return this.fixUp(t)}min(t){return t.left?this.min(t.left):t}removeMin(t){if(t.left)return!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeMin(t.left),this.fixUp(t)}fixUp(t){return this.isRed(t.right)&&(t=this.rotateLeft(t)),this.isRed(t.left)&&this.isRed(t.left.left)&&(t=this.rotateRight(t)),this.isRed(t.left)&&this.isRed(t.right)&&this.flipColors(t),t}moveRedLeft(t){return this.flipColors(t),this.isRed(t.right.left)&&(t.right=this.rotateRight(t.right),t=this.rotateLeft(t),this.flipColors(t)),t}moveRedRight(t){return this.flipColors(t),this.isRed(t.left.left)&&(t=this.rotateRight(t),this.flipColors(t)),t}isRed(t){return t&&t.isRed}rotateLeft(t){const e=t.right;return t.right=e.left,e.left=t,e.isRed=e.left.isRed,e.left.isRed=!0,e}rotateRight(t){const e=t.left;return t.left=e.right,e.right=t,e.isRed=e.right.isRed,e.right.isRed=!0,e}flipColors(t){t.isRed=!t.isRed,t.left.isRed=!t.left.isRed,t.right.isRed=!t.right.isRed}}class ke{constructor(t,e){a(this,"parentID");a(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=e}static of(t,e){return new ke(t,e)}static fromTreePos(t){const{offset:e}=t;let{node:r}=t,s;return r.isText?(r.parent.children[0]===r&&e===0?s=r.parent:s=r,r=r.parent):e===0?s=r:s=r.children[e-1],ke.of(r.id,Y.of(s.getCreatedAt(),s.getOffset()+e))}getParentID(){return this.parentID}static fromStruct(t){return ke.of(Y.of(oe.fromStruct(t.parentID.createdAt),t.parentID.offset),Y.of(oe.fromStruct(t.leftSiblingID.createdAt),t.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(t){const e=this.getParentID(),r=this.getLeftSiblingID(),s=t.findFloorNode(e);let i=t.findFloorNode(r);if(!s||!i)throw new g(d.ErrRefused,`cannot find node of CRDTTreePos(${e.toTestString()}, ${r.toTestString()})`);return!r.equals(e)&&r.getOffset()>0&&r.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=t.findFloorNode(i.insPrevID)),[s,i]}getLeftSiblingID(){return this.leftSiblingID}equals(t){return this.getParentID().getCreatedAt().equals(t.getParentID().getCreatedAt())&&this.getParentID().getOffset()===t.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(t.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===t.getLeftSiblingID().getOffset()}}class Y{constructor(t,e){a(this,"createdAt");a(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new Y(t,e)}static fromStruct(t){return Y.of(oe.fromStruct(t.createdAt),t.offset)}static createComparator(){return(t,e)=>{const r=t.getCreatedAt().compare(e.getCreatedAt());return r!==0?r:t.getOffset()>e.getOffset()?1:t.getOffset(){const i=s.deepcopy();return i.parent=e,i}),e.insPrevID=this.insPrevID,e.insNextID=this.insNextID,e}get value(){if(!this.isText)throw new g(d.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(e){if(!this.isText)throw new g(d.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=e,this.size=e.length}get isRemoved(){return!!this.removedAt}remove(e){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(e)>0)&&(this.removedAt=e),r&&this.updateAncestorsSize()}cloneText(e){return new ie(Y.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new ie(Y.of(e(),0),this.type,void 0,void 0,this.removedAt)}split(e,r,s){const i=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,s);if(i){if(i.insPrevID=this.id,this.insNextID){const o=e.findFloorNode(this.insNextID);o.insPrevID=i.id,i.insNextID=this.insNextID}this.insNextID=i.id,e.registerNode(i)}return i}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(e,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,r){this.attrs||(this.attrs=new Zt);const s=new Array;for(const[i,o]of Object.entries(e))s.push(this.attrs.set(i,o,r));return s}purge(e){this.attrs&&this.attrs.purge(e)}getGCPairs(){const e=[];if(!this.attrs)return e;for(const r of this.attrs)r.getRemovedAt()&&e.push({parent:this,child:r});return e}}function Ls(n){var e;if(n.isText){const r=n;return{type:r.type,value:r.value}}const t={type:n.type,children:n.children.map(Ls)};return n.attrs&&(t.attributes=xr((e=n.attrs)==null?void 0:e.toObject())),t}function js(n){if(n.isText)return n.value;let t="";return n.attrs&&n.attrs.size()&&(t=" "+Array.from(n.attrs).filter(e=>!e.isRemoved()).sort((e,r)=>e.getKey().localeCompare(r.getKey())).map(e=>{const r=JSON.parse(e.getValue());return typeof r=="string"?`${e.getKey()}="${r}"`:`${e.getKey()}="${qe(e.getValue())}"`}).join(" ")),`<${n.type}${t}>${n.children.map(e=>js(e)).join("")}`}function Mo(n){if(n.isText){const t=n;return{type:t.type,value:t.value,size:t.size,isRemoved:t.isRemoved}}return{type:n.type,children:n.children.map(Mo),size:n.size,isRemoved:n.isRemoved}}class be extends en{constructor(e,r){super(r);a(this,"indexTree");a(this,"nodeMapByID");this.indexTree=new Gc(e),this.nodeMapByID=new Fo(Y.createComparator()),this.indexTree.traverseAll(s=>{this.nodeMapByID.put(s.id,s)})}static create(e,r){return new be(e,r)}findFloorNode(e){const r=this.nodeMapByID.floorEntry(e);if(!(!r||!r.key.getCreatedAt().equals(e.getCreatedAt())))return r.value}registerNode(e){this.nodeMapByID.put(e.id,e)}findNodesAndSplitText(e,r){const[s,i]=e.toTreeNodePair(this);let o=i;const c=s===o,l=o.parent&&!c?o.parent:s;if(o.isText&&o.split(this,e.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const h=l.allChildren,f=c?0:h.indexOf(o)+1;for(let p=f;p{const k=w.getCreatedAt().getActorID(),E=i?i.has(k)?i.get(k):xe:qr;if(w.canStyle(s,E)&&r){const C=v.get(k),P=w.getCreatedAt();(!C||P.after(C))&&v.set(k,P);const H=w.setAttrs(r,s),D=H.reduce((K,[,_t])=>(_t&&(K[_t.getKey()]=p[_t.getKey()]),K),{}),L=w.parent,F=w.prevSibling||w.parent;Object.keys(D).length>0&&f.push({type:"style",from:this.toIndex(L,F),to:this.toIndex(w,w),fromPath:this.toPath(L,F),toPath:this.toPath(w,w),actor:s.getActorID(),value:D});for(const[K]of H)K&&m.push({parent:w,child:K})}}),[v,m,f]}removeStyle(e,r,s,i){const[o,c]=this.findNodesAndSplitText(e[0],s),[l,h]=this.findNodesAndSplitText(e[1],s),f=[],p=new Map,v=[];return this.traverseInPosRange(o,c,l,h,([m])=>{const w=m.getCreatedAt().getActorID(),k=i?i.has(w)?i.get(w):xe:qr;if(m.canStyle(s,k)&&r){const E=p.get(w),C=m.getCreatedAt();(!E||C.after(E))&&p.set(w,C),m.attrs||(m.attrs=new Zt);for(const D of r){const L=m.attrs.remove(D,s);for(const F of L)v.push({parent:m,child:F})}const P=m.parent,H=m.prevSibling||m.parent;f.push({actor:s.getActorID(),type:"removeStyle",from:this.toIndex(P,H),to:this.toIndex(m,m),fromPath:this.toPath(P,H),toPath:this.toPath(m,m),value:r})}}),[p,v,f]}edit(e,r,s,i,o,c){const[l,h]=this.findNodesAndSplitText(e[0],i),[f,p]=this.findNodesAndSplitText(e[1],i),v=this.toIndex(l,h),m=this.toPath(l,h),w=[],k=[],E=[],C=new Map;this.traverseInPosRange(l,h,f,p,([D,L],F)=>{if(L===j.Start&&!F)for(const lr of D.children)E.push(lr);const K=D.getCreatedAt().getActorID(),_t=c?c.has(K)?c.get(K):xe:qr;if(D.canDelete(i,_t)||w.includes(D.parent)){const lr=C.get(K),on=D.getCreatedAt();(!lr||on.after(lr))&&C.set(K,on),(L===j.Text||L===j.Start)&&w.push(D),k.push([D,L])}});const P=this.makeDeletionChanges(k,i),H=[];for(const D of w)D.remove(i),D.isRemoved&&H.push({parent:this,child:D});for(const D of E)D.removedAt||l.append(D);if(s>0){let D=0,L=l,F=h;for(;D{l.isRemoved&&(K.remove(i),H.push({parent:this,child:K})),this.nodeMapByID.put(K.id,K)}),F.isRemoved||D.push(F);if(D.length){const F=D.map(K=>Ls(K));P.length&&P[P.length-1].from===v?P[P.length-1].value=F:P.push({type:"content",from:v,to:v,fromPath:m,toPath:m,actor:i.getActorID(),value:F})}}return[P,H,C]}editT(e,r,s,i,o){const c=this.findPos(e[0]),l=this.findPos(e[1]);this.edit([c,l],r,s,i,o)}move(e,r,s){throw new g(d.ErrUnimplemented,`not implemented: ${e}, ${r}, ${s}`)}purge(e){var i;(i=e.parent)==null||i.removeChild(e),this.nodeMapByID.remove(e.id);const r=e.insPrevID,s=e.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=s}if(s){const o=this.findFloorNode(s);o.insPrevID=r}e.insPrevID=void 0,e.insNextID=void 0}getGCPairs(){const e=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&e.push({parent:this,child:r});for(const s of r.getGCPairs())e.push(s)}),e}findPos(e,r=!0){const s=this.indexTree.findTreePos(e,r);return ke.fromTreePos(s)}pathToPosRange(e){const r=this.pathToIndex(e);return[this.findPos(r),this.findPos(r+1)]}pathToPos(e){const r=this.indexTree.pathToIndex(e);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return js(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const e=this.indexTree.getRoot(),r=(s,i=void 0,o=void 0,c=0)=>{var m,w,k,E;let l,h,f;const p=s.isText?{node:s,offset:0}:i&&o?this.toTreePos(i,o):null;p&&(l=this.indexTree.indexOf(p),h=this.indexTree.treePosToPath(p),f=ke.fromTreePos(p).toStruct());const v={type:s.type,parent:i==null?void 0:i.id.toTestString(),size:s.size,id:s.id.toTestString(),removedAt:(m=s.removedAt)==null?void 0:m.toTestString(),insPrev:(w=s.insPrevID)==null?void 0:w.toTestString(),insNext:(k=s.insNextID)==null?void 0:k.toTestString(),value:s.isText?s.value:void 0,isRemoved:s.isRemoved,children:[],depth:c,attributes:s.attrs?xr((E=s.attrs)==null?void 0:E.toObject()):void 0,index:l,path:h,pos:f};for(let C=0;C0&&C===s[s.length-1].to?(s[s.length-1].to=P,s[s.length-1].toPath=this.toPath(E,m)):s.push({type:"content",from:C,to:P,fromPath:this.toPath(k,p),toPath:this.toPath(E,m),actor:r.getActorID()}))}return s.reverse()}findRightToken([e,r]){if(r===j.Start){const l=e.allChildren;return l.length>0?[l[0],l[0].isText?j.Text:j.Start]:[e,j.End]}const s=e.parent,i=s.allChildren,o=i.indexOf(e);if(s&&o===i.length-1)return[s,j.End];const c=i[o+1];return[c,c.isText?j.Text:j.Start]}findLeftToken([e,r]){if(r===j.End){const l=e.allChildren;if(l.length>0){const h=l[l.length-1];return[h,h.isText?j.Text:j.End]}return[e,j.Start]}const s=e.parent,i=s.allChildren,o=i.indexOf(e);if(s&&o===0)return[s,j.Start];const c=i[o-1];return[c,c.isText?j.Text:j.End]}}class sn extends Ne{constructor(e,r,s,i,o,c,l){super(e,l);a(this,"fromPos");a(this,"toPos");a(this,"contents");a(this,"splitLevel");a(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=s,this.contents=i,this.splitLevel=o,this.maxCreatedAtMapByActor=c}static create(e,r,s,i,o,c,l){return new sn(e,r,s,i,o,c,l)}execute(e){var l;const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof be))throw new g(d.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=this.getExecutedAt(),i=r,[o,c]=i.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(h=>h.deepcopy()),this.splitLevel,s,(()=>{let h=s.getDelimiter();return this.contents!==void 0&&(h+=this.contents.length),()=>oe.of(s.getLamport(),++h,s.getActorID())})(),this.maxCreatedAtMapByActor);for(const h of c)e.registerGCPair(h);return{opInfos:o.map(({from:h,to:f,value:p,splitLevel:v,fromPath:m,toPath:w})=>({type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:h,to:f,value:p,splitLevel:v,fromPath:m,toPath:w}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,i=this.contents||[];return`${e}.EDIT(${r},${s},${i.map(o=>js(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Er{constructor(t){a(this,"vector");this.vector=t||new Map}set(t,e){this.vector.set(t,e)}get(t){return this.vector.get(t)}maxLamport(){let t=BigInt(0);for(const[,e]of this)e>t&&(t=e);return t}max(t){const e=new Map;for(const[r,s]of t){const i=this.vector.get(r),o=i&&i>s?i:s;e.set(r,o)}for(const[r,s]of this){const i=t.get(r),o=i&&i>s?i:s;e.set(r,o)}return new Er(e)}afterOrEqual(t){const e=this.vector.get(t.getActorID());return e===void 0?!1:e>=t.getLamport()}deepcopy(){const t=new Map;for(const[e,r]of this.vector)t.set(e,r);return new Er(t)}filter(t){const e=new Map;for(const[r]of t){const s=this.vector.get(r);s!==void 0&&e.set(r,s)}return new Er(e)}size(){return this.vector.size}*[Symbol.iterator](){for(const[t,e]of this.vector)yield[t,e]}}const Xc=new Er(new Map);class zt{constructor(t,e,r,s,i){a(this,"clientSeq");a(this,"serverSeq");a(this,"lamport");a(this,"actor");a(this,"versionVector");this.clientSeq=t,this.serverSeq=i,this.lamport=e,this.versionVector=s,this.actor=r}static of(t,e,r,s,i){return new zt(t,e,r,s,i)}next(){const t=this.versionVector.deepcopy();return t.set(this.actor,this.lamport+1n),new zt(this.clientSeq+1,this.lamport+1n,this.actor,t)}syncClocks(t){const e=t.lamport>this.lamport?t.lamport+1n:this.lamport+1n,r=this.versionVector.max(t.versionVector),s=new zt(this.clientSeq,e,this.actor,r);return s.versionVector.set(this.actor,e),s}setClocks(t,e){const r=t>this.lamport?t:this.lamport+1n,s=this.versionVector.max(e);return s.set(this.actor,r),zt.of(this.clientSeq,r,this.actor,s)}createTimeTicket(t){return oe.of(this.lamport,t,this.actor)}setActor(t){return new zt(this.clientSeq,this.lamport,t,this.versionVector,this.serverSeq)}setVersionVector(t){return new zt(this.clientSeq,this.lamport,this.actor,t,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Zc=new zt(0,0n,Vs,Xc);class Rr{constructor({id:t,operations:e,presenceChange:r,message:s}){a(this,"id");a(this,"operations");a(this,"presenceChange");a(this,"message");this.id=t,this.operations=e||[],this.presenceChange=r,this.message=s}static create({id:t,operations:e,presenceChange:r,message:s}){return new Rr({id:t,operations:e,presenceChange:r,message:s})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(t){for(const e of this.operations)e.setActor(t);this.id=this.id.setActor(t)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(t,e,r){const s=[],i=[];for(const o of this.operations){const c=o.execute(t,r);if(!c)continue;const{opInfos:l,reverseOp:h}=c;s.push(...l),h&&i.unshift(h)}return this.presenceChange&&(this.presenceChange.type===cr.Put?e.set(this.id.getActorID(),Ie(this.presenceChange.presence)):e.delete(this.id.getActorID())),{opInfos:s,reverseOps:i}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:V.bytesToHex(V.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>V.bytesToHex(V.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:e,operations:r,presenceChange:s,message:i}=t;return Rr.create({id:V.bytesToChangeID(V.hexToBytes(e)),operations:r==null?void 0:r.map(o=>V.bytesToOperation(V.hexToBytes(o))),presenceChange:s,message:i})}}class Hn{constructor(t,e,r,s,i,o,c){a(this,"documentKey");a(this,"checkpoint");a(this,"isRemoved");a(this,"changes");a(this,"snapshot");a(this,"minSyncedTicket");a(this,"versionVector");this.documentKey=t,this.checkpoint=e,this.isRemoved=r,this.changes=s,this.snapshot=o,this.minSyncedTicket=c,this.versionVector=i}static create(t,e,r,s,i,o,c){return new Hn(t,e,r,s,i,o,c)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class Nr{constructor(t,e){a(this,"serverSeq");a(this,"clientSeq");this.serverSeq=t,this.clientSeq=e}static of(t,e){return new Nr(t,e)}increaseClientSeq(t){return t===0?this:new Nr(this.serverSeq,this.clientSeq+t)}forward(t){if(this.equals(t))return this;const e=this.serverSeq>t.serverSeq?this.serverSeq:t.serverSeq,r=Math.max(this.clientSeq,t.clientSeq);return Nr.of(e,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(t){return this.clientSeq===t.clientSeq&&this.serverSeq==t.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Qc=new Nr(0n,0);class Ve{constructor(t,e){a(this,"createdAt");a(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new Ve(t,e)}static fromStruct(t){return Ve.of(oe.fromStruct(t.createdAt),t.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(t){return this.createdAt.compare(t.createdAt)===0&&this.offset===t.offset}hasSameCreatedAt(t){return this.createdAt.compare(t.createdAt)===0}split(t){return new Ve(this.createdAt,this.offset+t)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const _c=Ve.of(xe,0);class Ee{constructor(t,e){a(this,"id");a(this,"relativeOffset");this.id=t,this.relativeOffset=e}static of(t,e){return new Ee(t,e)}static fromStruct(t){const e=Ve.fromStruct(t.id);return Ee.of(e,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Ve.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(t){return this.id.equals(t.id)?this.relativeOffset===t.relativeOffset:!1}}class or extends Co{constructor(e,r,s){super(r);a(this,"id");a(this,"removedAt");a(this,"prev");a(this,"next");a(this,"insPrev");a(this,"insNext");this.id=e,this.removedAt=s}static create(e,r){return new or(e,r)}static createComparator(){return(e,r)=>{const s=e.getCreatedAt().compare(r.getCreatedAt());return s!==0?s:e.getOffset()>r.getOffset()?1:e.getOffset()0&&e.getID().getOffset()==t.getOffset()){if(!e.hasInsPrev())return e;e=e.getInsPrev()}return e}findFloorNode(t){const e=this.treeByID.floorEntry(t);if(e&&!(!e.key.equals(t)&&!e.key.hasSameCreatedAt(t)))return e.value}findBetween(t,e){const r=[];let s=t;for(;s&&s!==e;)r.push(s),s=s.getNext();return r}splitNode(t,e){if(e>t.getContentLength())throw new g(d.ErrInvalidArgument,"offset should be less than or equal to length");if(e===0)return t;if(e===t.getContentLength())return t.getNext();const r=t.split(e);this.treeByIndex.updateWeight(r),this.insertAfter(t,r);const s=t.getInsNext();return s&&s.setInsPrev(r),r.setInsPrev(t),r}deleteNodes(t,e,r){if(!t.length)return[[],new Map,new Map];const[s,i]=this.filterNodes(t,e,r),o=new Map,c=new Map,l=this.makeChanges(i,e);for(const h of s){const f=h.getCreatedAt().getActorID();(!o.has(f)||h.getID().getCreatedAt().after(o.get(f)))&&o.set(f,h.getID().getCreatedAt()),c.set(h.getID().toIDString(),h),h.remove(e)}return this.deleteIndexNodes(i),[l,o,c]}filterNodes(t,e,r){const s=!!r,i=[],o=[],[c,l]=this.findEdgesOfCandidates(t);o.push(c);for(const h of t){const f=h.getCreatedAt().getActorID(),p=s?r.has(f)?r.get(f):xe:qr;h.canDelete(e,p)?i.push(h):o.push(h)}return o.push(l),[i,o]}findEdgesOfCandidates(t){return[t[0].getPrev(),t[t.length-1].getNext()]}makeChanges(t,e){const r=[];let s,i;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var ze=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(ze||{});class ce extends en{constructor(e,r,s){super(s);a(this,"valueType");a(this,"value");switch(this.valueType=e,e){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=O.fromNumber(r).toInt():this.value=qi(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=O.fromNumber(r):this.value=r;break;default:throw new g(d.ErrUnimplemented,`unimplemented type: ${e}`)}}static create(e,r,s){return new ce(e,r,s)}static valueFromBytes(e,r){switch(e){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return O.fromBytesLE(Array.from(r));default:throw new g(d.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const e=ce.create(this.valueType,this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e}getType(){return this.valueType}static getCounterType(e){switch(typeof e){case"object":return e instanceof O?1:void 0;case"number":return e>Math.pow(2,31)-1||e<-Math.pow(2,31)?1:0;default:return}}static isSupport(e){return!!ce.getCounterType(e)}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===0||e===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new g(d.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(e){function r(s){if(!s.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof s.getValue()}`)}return r(this),r(e),this.valueType===1?this.value=this.value.add(e.getValue()):e.getType()===W.Long?this.value=this.value+e.getValue().toInt():this.value=O.fromNumber(this.value+qi(e.getValue())).toInt(),this}}class Jr extends Ne{constructor(e,r,s){super(e,s);a(this,"value");this.value=r}static create(e,r,s){return new Jr(e,r,s)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof ce))throw new g(d.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const s=r,i=this.value.deepcopy();return s.increase(i),{opInfos:[{type:"increase",path:e.createPath(this.getParentCreatedAt()),value:i.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const e=this.value.deepcopy(),s=e.getType()===W.Long?e.getValue().multiply(-1):e.getValue()*-1;return Jr.create(this.getParentCreatedAt(),$.of(s,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Yt extends Ne{constructor(e,r,s,i,o,c,l){super(e,l);a(this,"fromPos");a(this,"toPos");a(this,"maxCreatedAtMapByActor");a(this,"attributes");a(this,"attributesToRemove");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o,this.attributesToRemove=c}static create(e,r,s,i,o,c){return new Yt(e,r,s,i,o,new Array,c)}static createTreeRemoveStyleOperation(e,r,s,i,o,c){return new Yt(e,r,s,i,new Map,o,c)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof be))throw new g(d.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=r;let i,o;if(this.attributes.size){const c={};[...this.attributes].forEach(([l,h])=>c[l]=h),[,o,i]=s.style([this.fromPos,this.toPos],c,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const c=this.attributesToRemove;[,o,i]=s.removeStyle([this.fromPos,this.toPos],c,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const c of o)e.registerGCPair(c);return{opInfos:i.map(({from:c,to:l,value:h,fromPath:f,toPath:p})=>({type:"tree-style",from:c,to:l,value:this.attributes.size?{attributes:h}:{attributesToRemove:h},fromPath:f,toPath:p,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${e}.STYLE(${r},${s},${Object.entries(this.attributes||{}).map(([i,o])=>`${i}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function eu(n){const t=new qs,e=t.data;for(const[r,s]of Object.entries(n))e[r]=JSON.stringify(s);return t}function tu(n){if(n.type===cr.Put)return new Wr({type:vr.PUT,presence:eu(n.presence)});if(n.type===cr.Clear)return new Wr({type:vr.CLEAR});throw new g(d.ErrUnimplemented,"unimplemented type")}function ru(n){return new xo({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function $o(n){return new jn({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:ri(n.getActorID()),versionVector:Gs(n.getVersionVector())})}function I(n){if(n)return new b({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:ri(n.getActorID())})}function Gs(n){if(!n)return;const t=new Gn;for(const[e,r]of n)t.vector[e]=BigInt(r.toString());return t}function Uo(n){switch(n){case W.Null:return N.NULL;case W.Boolean:return N.BOOLEAN;case W.Integer:return N.INTEGER;case W.Long:return N.LONG;case W.Double:return N.DOUBLE;case W.String:return N.STRING;case W.Bytes:return N.BYTES;case W.Date:return N.DATE;default:throw new g(d.ErrInvalidType,`unsupported type: ${n}`)}}function qo(n){switch(n){case ze.IntegerCnt:return N.INTEGER_CNT;case ze.LongCnt:return N.LONG_CNT;default:throw new g(d.ErrInvalidType,`unsupported type: ${n}`)}}function ns(n){if(n instanceof re)return new ue({type:N.JSON_OBJECT,createdAt:I(n.getCreatedAt()),value:ea(n)});if(n instanceof ae)return new ue({type:N.JSON_ARRAY,createdAt:I(n.getCreatedAt()),value:Bu(n)});if(n instanceof Ae)return new ue({type:N.TEXT,createdAt:I(n.getCreatedAt())});if(n instanceof $)return new ue({type:Uo(n.getType()),createdAt:I(n.getCreatedAt()),value:n.toBytes()});if(n instanceof ce)return new ue({type:qo(n.getType()),createdAt:I(n.getCreatedAt()),value:n.toBytes()});if(n instanceof be)return new ue({type:N.TREE,createdAt:I(n.getCreatedAt()),value:Lu(n)});throw new g(d.ErrUnimplemented,"unimplemented element")}function nu(n){return new jr({createdAt:I(n.getCreatedAt()),offset:n.getOffset()})}function cn(n){return new Xt({createdAt:I(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function un(n){return new yr({parentId:Vr(n.getParentID()),leftSiblingId:Vr(n.getLeftSiblingID())})}function Vr(n){return new sr({createdAt:I(n.getCreatedAt()),offset:n.getOffset()})}function Vo(n){const t=new Us;if(n instanceof wr){const e=n,r=new bn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.key=e.getKey(),r.value=ns(e.getValue()),r.executedAt=I(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(n instanceof tn){const e=n,r=new In;r.parentCreatedAt=I(e.getParentCreatedAt()),r.prevCreatedAt=I(e.getPrevCreatedAt()),r.value=ns(e.getValue()),r.executedAt=I(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(n instanceof nr){const e=n,r=new Sn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.prevCreatedAt=I(e.getPrevCreatedAt()),r.createdAt=I(e.getCreatedAt()),r.executedAt=I(e.getExecutedAt()),t.body.case="move",t.body.value=r}else if(n instanceof ur){const e=n,r=new kn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.createdAt=I(e.getCreatedAt()),r.executedAt=I(e.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(n instanceof rn){const e=n,r=new xn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.from=cn(e.getFromPos()),r.to=cn(e.getToPos());const s=r.createdAtMapByActor;for(const[o,c]of e.getMaxCreatedAtMapByActor())s[o]=I(c);r.content=e.getContent();const i=r.attributes;for(const[o,c]of e.getAttributes())i[o]=c;r.executedAt=I(e.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(n instanceof nn){const e=n,r=new En;r.parentCreatedAt=I(e.getParentCreatedAt()),r.from=cn(e.getFromPos()),r.to=cn(e.getToPos());const s=r.createdAtMapByActor;for(const[o,c]of e.getMaxCreatedAtMapByActor())s[o]=I(c);const i=r.attributes;for(const[o,c]of e.getAttributes())i[o]=c;r.executedAt=I(e.getExecutedAt()),t.body.case="style",t.body.value=r}else if(n instanceof Jr){const e=n,r=new Nn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.value=ns(e.getValue()),r.executedAt=I(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(n instanceof sn){const e=n,r=new Cn,s=r.createdAtMapByActor;for(const[i,o]of e.getMaxCreatedAtMapByActor())s[i]=I(o);r.parentCreatedAt=I(e.getParentCreatedAt()),r.from=un(e.getFromPos()),r.to=un(e.getToPos()),r.contents=lu(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=I(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(n instanceof Yt){const e=n,r=new Pn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.from=un(e.getFromPos()),r.to=un(e.getToPos());const s=r.createdAtMapByActor;for(const[o,c]of e.getMaxCreatedAtMapByActor())s[o]=I(c);const i=e.getAttributesToRemove();if(i.length>0)r.attributesToRemove=i;else{const o=r.attributes;for(const[c,l]of e.getAttributes())o[c]=l}r.executedAt=I(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new g(d.ErrUnimplemented,"unimplemented operation");return t}function su(n){const t=[];for(const e of n)t.push(Vo(e));return t}function iu(n){const t=new So({id:$o(n.getID()),message:n.getMessage()});return n.hasOperations()&&(t.operations=su(n.getOperations())),n.hasPresenceChange()&&(t.presenceChange=tu(n.getPresenceChange())),t}function ou(n){const t=[];for(const e of n)t.push(iu(e));return t}function au(n){const t=[];for(const e of n)t.push(new ko({key:e.getStrKey(),element:Hs(e.getValue())}));return t}function cu(n){const t=[];for(const e of n)t.push(new Fn({element:Hs(e.getValue())}));return t}function uu(n){const t=[];for(const e of n){const r=new Mn;r.id=nu(e.getID()),r.value=e.getValue().getContent(),r.removedAt=I(e.getRemovedAt());const s=r.attributes,i=e.getValue().getAttrs();for(const o of i){const c=new Dr;c.value=o.getValue(),c.updatedAt=I(o.getUpdatedAt()),s[o.getKey()]=c}t.push(r)}return t}function lu(n){const t=[];if(!n||!n.length)return t;for(const e of n)t.push(new $n({content:Ws(e)}));return t}function hu(n){const t={};for(const e of n)t[e.getKey()]=new Dr({value:e.getValue(),updatedAt:I(e.getUpdatedAt()),isRemoved:e.isRemoved()});return t}function Ws(n){if(!n)return[];const t=[];return Wn(n,(e,r)=>{const s=new Gr({id:Vr(e.id),type:e.type,removedAt:I(e.removedAt),depth:r});e.isText&&(s.value=e.value),e.insPrevID&&(s.insPrevId=Vr(e.insPrevID)),e.insNextID&&(s.insNextId=Vr(e.insNextID)),e.attrs&&(s.attributes=hu(e.attrs)),t.push(s)}),t}function fu(n){const t=new ne;return t.body.case="jsonObject",t.body.value=new Dn({nodes:au(n.getRHT()),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function zo(n){const t=new ne;return t.body.case="jsonArray",t.body.value=new On({nodes:cu(n.getElements()),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function du(n){const t=new ne;return t.body.case="primitive",t.body.value=new Bn({type:Uo(n.getType()),value:n.toBytes(),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function gu(n){const t=new ne;return t.body.case="text",t.body.value=new Rn({nodes:uu(n.getRGATreeSplit()),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function mu(n){const t=new ne;return t.body.case="counter",t.body.value=new Ln({type:qo(n.getType()),value:n.toBytes(),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function Ko(n){const t=new ne;return t.body.case="tree",t.body.value=new Jn({nodes:Ws(n.getRoot()),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function Hs(n){if(n instanceof re)return fu(n);if(n instanceof ae)return zo(n);if(n instanceof $)return du(n);if(n instanceof Ae)return gu(n);if(n instanceof ce)return mu(n);if(n instanceof be)return Ko(n);throw new g(d.ErrUnimplemented,"unimplemented element")}function pu(n){return new Qt({documentKey:n.getDocumentKey(),checkpoint:ru(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:ou(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Gs(n.getVersionVector()),minSyncedTicket:I(n.getMinSyncedTicket())})}function Vi(n){const t=n.findDetails(Oc);for(const e of t)if(e.metadata.code)return e.metadata.code;return""}function jo(n){return zt.of(n.clientSeq,BigInt(n.lamport),ei(n.actorId),Ys(n.versionVector),BigInt(n.serverSeq))}function Ys(n){if(!n)return;const t=new Er;return Object.entries(n.vector).forEach(([e,r])=>{t.set(e,BigInt(r.toString()))}),t}function S(n){if(n)return oe.of(BigInt(n.lamport),n.delimiter,ei(n.actorId))}function Xs(n){const t={};return Object.entries(n.data).forEach(([e,r])=>{t[e]=JSON.parse(r)}),t}function yu(n){const t=n.type;if(t===vr.PUT){const e=Xs(n.presence);return{type:cr.Put,presence:e}}if(t===vr.CLEAR)return{type:cr.Clear};throw new g(d.ErrInvalidType,`unsupported type: ${t}`)}function vu(n){const t=new Map;return Object.entries(n).forEach(([e,r])=>{t.set(e,Xs(r))}),t}function Go(n){switch(n){case N.NULL:return W.Null;case N.BOOLEAN:return W.Boolean;case N.INTEGER:return W.Integer;case N.LONG:return W.Long;case N.DOUBLE:return W.Double;case N.STRING:return W.String;case N.BYTES:return W.Bytes;case N.DATE:return W.Date}throw new g(d.ErrUnimplemented,`unimplemented value type: ${n}`)}function Vn(n){switch(n){case N.INTEGER_CNT:return ze.IntegerCnt;case N.LONG_CNT:return ze.LongCnt}throw new g(d.ErrUnimplemented,`unimplemented value type: ${n}`)}function ss(n){switch(n.type){case N.JSON_OBJECT:return n.value?_o(n.value):re.create(S(n.createdAt));case N.JSON_ARRAY:return n.value?Ou(n.value):ae.create(S(n.createdAt));case N.TEXT:return Ae.create(Lr.create(),S(n.createdAt));case N.TREE:return Ru(n.value);case N.NULL:case N.BOOLEAN:case N.INTEGER:case N.LONG:case N.DOUBLE:case N.STRING:case N.BYTES:case N.DATE:return $.of($.valueFromBytes(Go(n.type),n.value),S(n.createdAt));case N.INTEGER_CNT:case N.LONG_CNT:return ce.create(Vn(n.type),ce.valueFromBytes(Vn(n.type),n.value),S(n.createdAt))}}function ln(n){return Ee.of(Ve.of(S(n.createdAt),n.offset),n.relativeOffset)}function Wo(n){return Ve.of(S(n.createdAt),n.offset)}function wu(n){const t=Zr.create(n.value);Object.entries(n.attributes).forEach(([r,s])=>{t.setAttr(r,s.value,S(s.updatedAt))});const e=or.create(Wo(n.id),t);return e.remove(S(n.removedAt)),e}function br(n){return ke.of(zr(n.parentId),zr(n.leftSiblingId))}function zr(n){return Y.of(S(n.createdAt),n.offset)}function Tu(n){if(!n.length)return;const t=[];return n.forEach(e=>{const r=Zs(e.content);t.push(r)}),t}function Zs(n){if(n.length===0)return;const t=[];for(const s of n)t.push(bu(s));const e=t[t.length-1],r=new Map;r.set(n[t.length-1].depth,t[t.length-1]);for(let s=t.length-2;s>=0;s--)r.get(n[s].depth-1).prepend(t[s]),r.set(n[s].depth,t[s]);return e.updateDescendantsSize(),be.create(e,xe).getRoot()}function Au(n){const t=Zt.create();for(const[e,r]of Object.entries(n))t.setInternal(e,r.value,S(r.updatedAt),r.isRemoved);return t}function bu(n){const t=zr(n.id),e=ie.create(t,n.type),r=Object.entries(n.attributes);return e.isText?e.value=n.value:r.length&&(e.attrs=Au(n.attributes)),n.insPrevId&&(e.insPrevID=zr(n.insPrevId)),n.insNextId&&(e.insNextID=zr(n.insNextId)),e.removedAt=S(n.removedAt),e}function Ho(n){if(n.body.case==="set"){const t=n.body.value;return wr.create(t.key,ss(t.value),S(t.parentCreatedAt),S(t.executedAt))}else if(n.body.case==="add"){const t=n.body.value;return tn.create(S(t.parentCreatedAt),S(t.prevCreatedAt),ss(t.value),S(t.executedAt))}else if(n.body.case==="move"){const t=n.body.value;return nr.create(S(t.parentCreatedAt),S(t.prevCreatedAt),S(t.createdAt),S(t.executedAt))}else if(n.body.case==="remove"){const t=n.body.value;return ur.create(S(t.parentCreatedAt),S(t.createdAt),S(t.executedAt))}else if(n.body.case==="edit"){const t=n.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([s,i])=>{e.set(s,S(i))});const r=new Map;return Object.entries(t.attributes).forEach(([s,i])=>{r.set(s,i)}),rn.create(S(t.parentCreatedAt),ln(t.from),ln(t.to),e,t.content,r,S(t.executedAt))}else if(n.body.case==="style"){const t=n.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([s,i])=>{e.set(s,S(i))});const r=new Map;return Object.entries(t.attributes).forEach(([s,i])=>{r.set(s,i)}),nn.create(S(t.parentCreatedAt),ln(t.from),ln(t.to),e,r,S(t.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const t=n.body.value;return Jr.create(S(t.parentCreatedAt),ss(t.value),S(t.executedAt))}else if(n.body.case==="treeEdit"){const t=n.body.value,e=new Map;return Object.entries(t.createdAtMapByActor).forEach(([r,s])=>{e.set(r,S(s))}),sn.create(S(t.parentCreatedAt),br(t.from),br(t.to),Tu(t.contents),t.splitLevel,e,S(t.executedAt))}else if(n.body.case==="treeStyle"){const t=n.body.value,e=new Map,r=t.attributesToRemove,s=new Map;return t!=null&&t.createdAtMapByActor&&Object.entries(t.createdAtMapByActor).forEach(([i,o])=>{s.set(i,S(o))}),(r==null?void 0:r.length)>0?Yt.createTreeRemoveStyleOperation(S(t.parentCreatedAt),br(t.from),br(t.to),s,r,S(t.executedAt)):(Object.entries(t.attributes).forEach(([i,o])=>{e.set(i,o)}),Yt.create(S(t.parentCreatedAt),br(t.from),br(t.to),s,e,S(t.executedAt)))}else throw new g(d.ErrUnimplemented,"unimplemented operation")}}function Iu(n){const t=[];for(const e of n){const r=Ho(e);r&&t.push(r)}return t}function Yo(n){const t=[];for(const e of n)t.push(Rr.create({id:jo(e.id),operations:Iu(e.operations),presenceChange:e.presenceChange?yu(e.presenceChange):void 0,message:e.message}));return t}function Su(n){return Nr.of(BigInt(n.serverSeq),n.clientSeq)}function ku(n){return Hn.create(n.documentKey,Su(n.checkpoint),n.isRemoved,Yo(n.changes),Ys(n.versionVector),n.snapshot,S(n.minSyncedTicket))}function Xo(n){const t=new Hr;for(const r of n.nodes){const s=Qs(r.element);t.set(r.key,s,s.getPositionedAt())}const e=new re(S(n.createdAt),t);return e.setMovedAt(S(n.movedAt)),e.setRemovedAt(S(n.removedAt)),e}function Zo(n){const t=new Xr;for(const r of n.nodes)t.insert(Qs(r.element));const e=new ae(S(n.createdAt),t);return e.setMovedAt(S(n.movedAt)),e.setRemovedAt(S(n.removedAt)),e}function xu(n){const t=$.of($.valueFromBytes(Go(n.type),n.value),S(n.createdAt));return t.setMovedAt(S(n.movedAt)),t.setRemovedAt(S(n.removedAt)),t}function Eu(n){const t=new Lr;let e=t.getHead();for(const s of n.nodes){const i=t.insertAfter(e,wu(s));s.insPrevId&&i.setInsPrev(t.findNode(Wo(s.insPrevId))),e=i}const r=new Ae(t,S(n.createdAt));return r.setMovedAt(S(n.movedAt)),r.setRemovedAt(S(n.removedAt)),r}function Nu(n){const t=ce.create(Vn(n.type),ce.valueFromBytes(Vn(n.type),n.value),S(n.createdAt));return t.setMovedAt(S(n.movedAt)),t.setRemovedAt(S(n.removedAt)),t}function Qo(n){const t=Zs(n.nodes);return be.create(t,S(n.createdAt))}function Qs(n){if(n.body.case==="jsonObject")return Xo(n.body.value);if(n.body.case==="jsonArray")return Zo(n.body.value);if(n.body.case==="primitive")return xu(n.body.value);if(n.body.case==="text")return Eu(n.body.value);if(n.body.case==="counter")return Nu(n.body.value);if(n.body.case==="tree")return Qo(n.body.value);throw new g(d.ErrUnimplemented,"unimplemented element")}function Cu(n){if(!n)return{root:re.create(xe),presences:new Map};const t=ls.fromBinary(n);return{root:Qs(t.root),presences:vu(t.presences)}}function Pu(n){const t=Gs(n);return _s(t.toBinary())}function Du(n){const t=ti(n),e=Gn.fromBinary(t);return Ys(e)}function _o(n){if(!n)throw new g(d.ErrInvalidArgument,"bytes is empty");const t=ne.fromBinary(n);return Xo(t.body.value)}function ea(n){return Hs(n).toBinary()}function Ou(n){if(!n)throw new g(d.ErrInvalidArgument,"bytes is empty");const t=ne.fromBinary(n);return Zo(t.body.value)}function Bu(n){return zo(n).toBinary()}function Ru(n){if(!n)throw new g(d.ErrInvalidArgument,"bytes is empty");const t=ne.fromBinary(n);return Qo(t.body.value)}function Lu(n){return Ko(n).toBinary()}function _s(n){return n?Array.from(n).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function ei(n){return _s(n)}function ti(n){return new Uint8Array(n.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function ri(n){return ti(n)}function Ju(n){const t=jn.fromBinary(n);return jo(t)}function Fu(n){const t=Us.fromBinary(n);return Ho(t)}const V={fromPresence:Xs,toChangePack:pu,fromChangePack:ku,fromChanges:Yo,toTreeNodes:Ws,fromTreeNodes:Zs,objectToBytes:ea,bytesToObject:_o,bytesToSnapshot:Cu,bytesToHex:_s,hexToBytes:ti,toHexString:ei,toUint8Array:ri,toOperation:Vo,toChangeID:$o,PbChangeID:jn,bytesToChangeID:Ju,bytesToOperation:Fu,versionVectorToHex:Pu,hexToVersionVector:Du};var ee=(n=>(n[n.Trivial=0]="Trivial",n[n.Debug=1]="Debug",n[n.Info=2]="Info",n[n.Warn=3]="Warn",n[n.Error=4]="Error",n[n.Fatal=5]="Fatal",n))(ee||{});let hr=3;function ta(n){hr=n}const x={trivial:(...n)=>{hr>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{hr>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{hr>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{hr>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{hr>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...n):console.log("YORKIE E:",...n))},fatal:(...n)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...n):console.log("YORKIE F:",...n))},isEnabled:n=>hr<=n};function ra(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const t=Math.random()*16|0;return(n==="x"?t:t&3|8).toString(16)})}class Mu{constructor(t,e,r,s,i){a(this,"reconnectStreamDelay");a(this,"doc");a(this,"docID");a(this,"syncMode");a(this,"remoteChangeEventReceived");a(this,"watchStream");a(this,"watchLoopTimerID");a(this,"watchAbortController");a(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=t,this.doc=e,this.docID=r,this.syncMode=s,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}changeSyncMode(t){this.syncMode=t}needRealtimeSync(){return this.syncMode===wn.RealtimeSyncOff?!1:this.syncMode===wn.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==wn.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(t){const e=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await t(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(e,this.reconnectStreamDelay)})}catch{}};await e()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const is=()=>{};class $u{constructor(t){a(this,"finalized",!1);a(this,"observers",[]);a(this,"finalError");try{t(this)}catch(e){this.error(e)}}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,e,r){let s;if(!t)throw new g(d.ErrInvalidArgument,"missing observer");if(this.finalized)throw new g(d.ErrRefused,"observable is finalized due to previous error");typeof t=="object"?s=t:s={next:t,error:e,complete:r},s.next===void 0&&(s.next=is),s.error===void 0&&(s.error=is),s.complete===void 0&&(s.complete=is);const i=ra(),o=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:s}),this.finalized)try{this.finalError?s.error(this.finalError):s.complete()}catch(c){x.warn(c)}return o}unsubscribeOne(t){var e;this.observers=(e=this.observers)==null?void 0:e.filter(r=>r.subscriptionID!==t)}forEachObserver(t){if(!this.finalized)for(let e=0;et}}class kr{constructor(t,e,r,s){a(this,"id");a(this,"delimiter");a(this,"message");a(this,"root");a(this,"operations");a(this,"presenceChange");a(this,"previousPresence");a(this,"reversePresenceKeys");this.id=t,this.delimiter=No,this.root=e,this.operations=[],this.previousPresence=Ie(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=s}static create(t,e,r,s){return new kr(t,e,r,s)}push(t){this.operations.push(t)}registerElement(t,e){this.root.registerElement(t,e)}registerRemovedElement(t){this.root.registerRemovedElement(t)}registerGCPair(t){this.root.registerGCPair(t)}getChange(){return Rr.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(t){this.presenceChange=t}setReversePresence(t,e){for(const r of Object.keys(t))e!=null&&e.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const t={};for(const e of this.reversePresenceKeys)t[e]=this.previousPresence[e];return t}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class Qr{constructor(t){a(this,"rootObject");a(this,"elementPairMapByCreatedAt");a(this,"gcElementSetByCreatedAt");a(this,"gcPairMap");this.rootObject=t,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(t,void 0),t.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof Ae||e instanceof be)for(const r of e.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new Qr(re.create(xe))}findByCreatedAt(t){const e=this.elementPairMapByCreatedAt.get(t.toIDString());if(e)return e.element}findElementPairByCreatedAt(t){return this.elementPairMapByCreatedAt.get(t.toIDString())}createSubPaths(t){let e=this.elementPairMapByCreatedAt.get(t.toIDString());if(!e)return[];const r=[];for(;e.parent;){const s=e.element.getCreatedAt(),i=e.parent.subPathOf(s);if(i===void 0)throw new g(d.ErrInvalidArgument,`cant find the given element: ${s.toIDString()}`);r.unshift(i),e=this.elementPairMapByCreatedAt.get(e.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(t){return this.createSubPaths(t).join(".")}registerElement(t,e){this.elementPairMapByCreatedAt.set(t.getCreatedAt().toIDString(),{parent:e,element:t}),t instanceof ir&&t.getDescendants((r,s)=>(this.registerElement(r,s),!1))}deregisterElement(t){let e=0;const r=s=>{const i=s.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(i),this.gcElementSetByCreatedAt.delete(i),e++};return r(t),t instanceof ir&&t.getDescendants(s=>(r(s),!1)),e}registerRemovedElement(t){this.gcElementSetByCreatedAt.add(t.getCreatedAt().toIDString())}registerGCPair(t){if(this.gcPairMap.get(t.child.toIDString())){this.gcPairMap.delete(t.child.toIDString());return}this.gcPairMap.set(t.child.toIDString(),t)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const t=new Set;for(const e of this.gcElementSetByCreatedAt){t.add(e);const r=this.elementPairMapByCreatedAt.get(e);r.element instanceof ir&&r.element.getDescendants(s=>(t.add(s.getCreatedAt().toIDString()),!1))}return t.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new Qr(this.rootObject.deepcopy())}garbageCollect(t){let e=0;for(const r of this.gcElementSetByCreatedAt){const s=this.elementPairMapByCreatedAt.get(r),i=s.element.getRemovedAt();i&&(t!=null&&t.afterOrEqual(i))&&(s.parent.purge(s.element),e+=this.deregisterElement(s.element))}for(const[,r]of this.gcPairMap){const s=r.child.getRemovedAt();s&&(t!=null&&t.afterOrEqual(s))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),e+=1)}return e}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function na(n,t){const e=new _r(n);return new Proxy(t,e.getHandlers())}class _r{constructor(t){a(this,"context");a(this,"handlers");this.context=t,this.handlers={set:(e,r,s)=>(x.isEnabled(ee.Trivial)&&x.trivial(`obj[${r}]=${JSON.stringify(s)}`),_r.setInternal(t,e,r,s),!0),get:(e,r)=>(x.isEnabled(ee.Trivial)&&x.trivial(`obj[${r}]`),r==="getID"?()=>e.getCreatedAt():r==="toJSON"||r==="toString"?()=>e.toJSON():r==="toJS"?()=>e.toJS():r==="toJSForTest"?()=>e.toJSForTest():fr(t,e.get(r))),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(e,r)=>(x.isEnabled(ee.Trivial)&&x.trivial(`obj[${r}]`),_r.deleteInternal(t,e,r),!0)}}static setInternal(t,e,r,s){if(r.includes("."))throw new g(d.ErrInvalidObjectKey,"key must not contain the '.'.");const i=t.issueTimeTicket(),o=zn(t,s,i),c=e.set(r,o,i);t.registerElement(o,e),c&&t.registerRemovedElement(c),t.push(wr.create(r,o.deepcopy(),e.getCreatedAt(),i))}static buildObjectMembers(t,e){const r={};for(const[s,i]of Object.entries(e)){if(s.includes("."))throw new g(d.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),c=zn(t,i,o);r[s]=c}return r}static deleteInternal(t,e,r){const s=t.issueTimeTicket(),i=e.deleteByKey(r,s);i&&(t.push(ur.create(e.getCreatedAt(),i.getCreatedAt(),s)),t.registerRemovedElement(i))}getHandlers(){return this.handlers}}function qu(n,t){const e=new U(n,t);return new Proxy(t,e.getHandlers())}function Vu(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function zu(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class U{constructor(t,e){a(this,"context");a(this,"handlers");a(this,"array");this.context=t,this.array=e,this.handlers={get:(r,s,i)=>s==="getID"?()=>r.getCreatedAt():s==="getElementByID"?o=>{const c=r.getByID(o);if(!(!c||c.isRemoved()))return tr(t,c)}:s==="getElementByIndex"?o=>{const c=r.get(o);return tr(t,c)}:s==="getLast"?()=>tr(t,r.getLast()):s==="deleteByID"?o=>{const c=U.deleteInternalByID(t,r,o);return tr(t,c)}:s==="insertAfter"?(o,c)=>{const l=U.insertAfterInternal(t,r,o,c);return tr(t,l)}:s==="insertBefore"?(o,c)=>{const l=U.insertBeforeInternal(t,r,o,c);return tr(t,l)}:s==="moveBefore"?(o,c)=>{U.moveBeforeInternal(t,r,o,c)}:s==="moveAfter"?(o,c)=>{U.moveAfterInternal(t,r,o,c)}:s==="moveFront"?o=>{U.moveFrontInternal(t,r,o)}:s==="moveLast"?o=>{U.moveLastInternal(t,r,o)}:Vu(s)?fr(t,r.get(Number(s))):s==="push"?o=>U.pushInternal(t,r,o):s==="splice"?(o,c,...l)=>U.splice(t,r,o,c,...l):s==="length"?r.length:typeof s=="symbol"&&s===Symbol.iterator?U.iteratorInternal.bind(this,t,r):s==="includes"?(o,c)=>U.includes(t,r,o,c):s==="indexOf"?(o,c)=>U.indexOf(t,r,o,c):s==="lastIndexOf"?(o,c)=>U.lastIndexOf(t,r,o,c):s==="toJSForTest"?()=>r.toJSForTest():s==="toTestString"?()=>U.toTestString(r):typeof s=="string"&&zu(s)?(...o)=>{const c=Array.from(r).map(l=>fr(t,l));return Array.prototype[s].apply(c,o)}:Reflect.get(r,s,i),deleteProperty:(r,s)=>(x.isEnabled(ee.Trivial)&&x.trivial(`array[${s}]`),U.deleteInternalByIndex(t,r,Number.parseInt(s)),!0)}}static*iteratorInternal(t,e){for(const r of e)yield tr(t,r)}static buildArrayElements(t,e){const r=[];for(const s of e){const i=t.issueTimeTicket(),o=zn(t,s,i);r.push(o)}return r}static pushInternal(t,e,r){return U.insertAfterInternal(t,e,e.getLastCreatedAt(),r),e.length}static moveBeforeInternal(t,e,r,s){const i=t.issueTimeTicket(),o=e.getPrevCreatedAt(r);e.moveAfter(o,s,i),t.push(nr.create(e.getCreatedAt(),o,s,i))}static moveAfterInternal(t,e,r,s){const i=t.issueTimeTicket();e.moveAfter(r,s,i),t.push(nr.create(e.getCreatedAt(),r,s,i))}static moveFrontInternal(t,e,r){const s=t.issueTimeTicket(),i=e.getHead();e.moveAfter(i.getCreatedAt(),r,s),t.push(nr.create(e.getCreatedAt(),i.getCreatedAt(),r,s))}static moveLastInternal(t,e,r){const s=t.issueTimeTicket(),i=e.getLastCreatedAt();e.moveAfter(i,r,s),t.push(nr.create(e.getCreatedAt(),i,r,s))}static insertAfterInternal(t,e,r,s){const i=t.issueTimeTicket(),o=zn(t,s,i);return e.insertAfter(r,o),t.registerElement(o,e),t.push(tn.create(e.getCreatedAt(),r,o.deepcopy(),i)),o}static insertBeforeInternal(t,e,r,s){return U.insertAfterInternal(t,e,e.getPrevCreatedAt(r),s)}static deleteInternalByIndex(t,e,r){const s=t.issueTimeTicket(),i=e.deleteByIndex(r,s);if(i)return t.push(ur.create(e.getCreatedAt(),i.getCreatedAt(),s)),t.registerRemovedElement(i),i}static deleteInternalByID(t,e,r){const s=t.issueTimeTicket(),i=e.delete(r,s);return t.push(ur.create(e.getCreatedAt(),i.getCreatedAt(),s)),t.registerRemovedElement(i),i}static splice(t,e,r,s,...i){const o=e.length,c=r>=0?Math.min(r,o):Math.max(o+r,0),l=s===void 0?o:s<0?c:Math.min(c+s,o),h=[];for(let f=c;f=i)return!1;if($.isSupport(r))return Array.from(e).map(h=>fr(t,h)).includes(r,o);for(let l=o;l=i)return-1;if($.isSupport(r))return Array.from(e).map(h=>fr(t,h)).indexOf(r,o);for(let l=o;l=i?i-1:s<0?s+i:s;if(o<0)return-1;if($.isSupport(r))return Array.from(e).map(h=>fr(t,h)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((c=e.get(l))==null?void 0:c.getID())===r.getID())return l;return-1}static toTestString(t){return t.toTestString()}getHandlers(){return this.handlers}}class Yn{constructor(t,e){a(this,"context");a(this,"text");this.context=t,this.text=e}initialize(t,e){this.context=t,this.text=e}getID(){return this.text.getID()}edit(t,e,r,s){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(t,e);x.isEnabled(ee.Debug)&&x.debug(`EDIT: f:${t}->${i[0].toTestString()}, t:${e}->${i[1].toTestString()} c:${r}`);const o=s?Or(s):void 0,c=this.context.issueTimeTicket(),[l,,h,f]=this.text.edit(i,r,c,o);for(const p of h)this.context.registerGCPair(p);return this.context.push(new rn(this.text.getCreatedAt(),i[0],i[1],l,r,o?new Map(Object.entries(o)):new Map,c)),this.text.findIndexesFromRange(f)}delete(t,e){return this.edit(t,e,"")}empty(){return this.edit(0,this.length,"")}setStyle(t,e,r){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(t,e);x.isEnabled(ee.Debug)&&x.debug(`STYL: f:${t}->${s[0].toTestString()}, t:${e}->${s[1].toTestString()} a:${JSON.stringify(r)}`);const i=Or(r),o=this.context.issueTimeTicket(),[c,l]=this.text.setStyle(s,i,o);for(const h of l)this.context.registerGCPair(h);return this.context.push(new nn(this.text.getCreatedAt(),s[0],s[1],c,new Map(Object.entries(i)),o)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");const e=this.text.indexRangeToPosRange(t[0],t[1]);return[e[0].toStruct(),e[1].toStruct()]}posRangeToIndexRange(t){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");const e=this.text.findIndexesFromRange([Ee.fromStruct(t[0]),Ee.fromStruct(t[1])]);return[e[0],e[1]]}toTestString(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,e){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,e)}}class Xn{constructor(t,e){a(this,"valueType");a(this,"value");a(this,"context");a(this,"counter");this.valueType=t,this.value=e}initialize(t,e){this.valueType=e.getValueType(),this.context=t,this.counter=e,this.value=e.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(t){if(!this.context||!this.counter)throw new g(d.ErrNotInitialized,"Counter is not initialized yet");const e=this.context.issueTimeTicket(),r=$.of(t,e);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(Jr.create(this.counter.getCreatedAt(),r,e)),this}toJSForTest(){if(!this.context||!this.counter)throw new g(d.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function ni(n,t,e){const{type:r}=n,s=e.issueTimeTicket();if(r===Ht){sa(n);const{value:i}=n,o=ie.create(Y.of(s,0),r,i);t.append(o)}else{const{children:i=[]}=n,{attributes:o}=n;let c;if(typeof o=="object"&&!Eo(o)){const h=Or(o);c=new Zt;for(const[f,p]of Object.entries(h))c.set(f,p,s)}const l=ie.create(Y.of(s,0),r,void 0,c);t.append(l);for(const h of i)ni(h,l,e)}}function Ku(n,t){const{type:e}=t,r=n.issueTimeTicket();let s;if(t.type===Ht){const{value:i}=t;s=ie.create(Y.of(r,0),e,i)}else if(t){const{children:i=[]}=t,{attributes:o}=t;let c;if(typeof o=="object"&&!Eo(o)){const l=Or(o);c=new Zt;for(const[h,f]of Object.entries(l))c.set(h,f,r)}s=ie.create(Y.of(n.issueTimeTicket(),0),e,void 0,c);for(const l of i)ni(l,s,n)}return s}function sa(n){if(!n.value.length)throw new g(d.ErrInvalidArgument,"text node cannot have empty value");return!0}function zi(n){if(!n.length)return!0;if(n[0].type===Ht)for(const e of n){const{type:r}=e;if(r!==Ht)throw new g(d.ErrInvalidArgument,"element node and text node cannot be passed together");sa(e)}else for(const e of n){const{type:r}=e;if(r===Ht)throw new g(d.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Zn{constructor(t){a(this,"initialRoot");a(this,"context");a(this,"tree");this.initialRoot=t}initialize(t,e){this.context=t,this.tree=e}getID(){return this.tree.getID()}buildRoot(t){if(!this.initialRoot)return ie.create(Y.of(t.issueTimeTicket(),0),Vc);const e=ie.create(Y.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)ni(r,e,t);return e}getSize(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,e){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new g(d.ErrInvalidArgument,"path should not be empty");const[r,s]=this.tree.pathToPosRange(t),i=this.context.issueTimeTicket(),o=e?Or(e):void 0,[c]=this.tree.style([r,s],o,i);this.context.push(Yt.create(this.tree.getCreatedAt(),r,s,c,o?new Map(Object.entries(o)):new Map,i))}style(t,e,r){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(t),i=this.tree.findPos(e),o=this.context.issueTimeTicket(),c=r?Or(r):void 0,[l,h]=this.tree.style([s,i],c,o);for(const f of h)this.context.registerGCPair(f);this.context.push(Yt.create(this.tree.getCreatedAt(),s,i,l,c?new Map(Object.entries(c)):new Map,o))}removeStyle(t,e,r){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(t),i=this.tree.findPos(e),o=this.context.issueTimeTicket(),[c,l]=this.tree.removeStyle([s,i],r,o);for(const h of l)this.context.registerGCPair(h);this.context.push(Yt.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),s,i,c,r,o))}editInternal(t,e,r,s=0){var h;if(r.length!==0&&r[0]&&(zi(r),r[0].type!==Ht))for(const f of r){const{children:p=[]}=f;zi(p)}const i=this.context.getLastTimeTicket();let o=new Array;if(((h=r[0])==null?void 0:h.type)===Ht){let f="";for(const p of r){const{value:v}=p;f+=v}o.push(ie.create(Y.of(this.context.issueTimeTicket(),0),Ht,f))}else o=r.map(f=>f&&Ku(this.context,f)).filter(f=>f);const[,c,l]=this.tree.edit([t,e],o.length?o.map(f=>f==null?void 0:f.deepcopy()):void 0,s,i,()=>this.context.issueTimeTicket());for(const f of c)this.context.registerGCPair(f);return this.context.push(sn.create(this.tree.getCreatedAt(),t,e,o.length?o:void 0,s,l,i)),!0}editByPath(t,e,r,s=0){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new g(d.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new g(d.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(t),o=this.tree.pathToPos(e);return this.editInternal(i,o,r?[r]:[],s)}editBulkByPath(t,e,r,s=0){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new g(d.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new g(d.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(t),o=this.tree.pathToPos(e);return this.editInternal(i,o,r,s)}edit(t,e,r,s=0){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(e);return this.editInternal(i,o,r?[r]:[],s)}editBulk(t,e,r,s=0){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(e);return this.editInternal(i,o,r,s)}toXML(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");const e=[this.tree.pathToIndex(t[0]),this.tree.pathToIndex(t[1])],r=this.tree.indexRangeToPosRange(e);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");const e=[ke.fromStruct(t[0]),ke.fromStruct(t[1])];return this.tree.posRangeToIndexRange(e)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");const e=[ke.fromStruct(t[0]),ke.fromStruct(t[1])];return this.tree.posRangeToPathRange(e)}}function Ki(n,t){return na(n,t)}function tr(n,t){if(t){if(t instanceof $)return t;if(t instanceof re)return na(n,t);if(t instanceof ae)return qu(n,t);if(t instanceof Ae)return new Yn(n,t);if(t instanceof ce){const e=new Xn(ze.IntegerCnt,0);return e.initialize(n,t),e}else if(t instanceof be){const e=new Zn;return e.initialize(n,t),e}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function fr(n,t){const e=tr(n,t);return e instanceof $?e.getValue():e}function zn(n,t,e){let r;if($.isSupport(t))r=$.of(t,e);else if(Array.isArray(t))r=ae.create(e,U.buildArrayElements(n,t));else if(typeof t=="object")t instanceof Yn?(r=Ae.create(Lr.create(),e),t.initialize(n,r)):t instanceof Xn?(r=ce.create(t.getValueType(),t.getValue(),e),t.initialize(n,r)):t instanceof Zn?(r=be.create(t.buildRoot(n),e),t.initialize(n,r)):r=re.create(e,_r.buildObjectMembers(n,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return r}const ji=50;class ju{constructor(){a(this,"undoStack",[]);a(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=ji&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=ji&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const Gu="yorkie-devtools-panel",Wu="yorkie-devtools-sdk";let Ir="disconnected";const Gi=new Map,vn=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=vn);function hn(n,t){(t!=null&&t.force||Ir!=="disconnected")&&window.postMessage({source:Wu,...n},"*")}function Hu(n){if(!n.isEnableDevtools()||typeof window>"u"||Gi.has(n.getKey()))return;vn.set(n.getKey(),[]);const t=n.subscribe("all",e=>{e.some(r=>r.type!==_.StatusChanged&&r.type!==_.Snapshot&&r.type!==_.LocalChange&&r.type!==_.RemoteChange&&r.type!==_.Initialized&&r.type!==_.Watched&&r.type!==_.Unwatched&&r.type!==_.PresenceChanged)||(vn.get(n.getKey()).push(e),Ir==="synced"&&hn({msg:"doc::sync::partial",docKey:n.getKey(),event:e}))});Gi.set(n.getKey(),[t]),hn({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",e=>{var s;if(((s=e.data)==null?void 0:s.source)!==Gu)return;switch(e.data.msg){case"devtools::connect":if(Ir!=="disconnected")break;Ir="connected",hn({msg:"doc::available",docKey:n.getKey()}),x.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Ir="disconnected",x.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Ir="synced",hn({msg:"doc::sync::full",docKey:n.getKey(),events:vn.get(n.getKey())}),x.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var rr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(rr||{}),_=(n=>(n.StatusChanged="status-changed",n.ConnectionChanged="connection-changed",n.SyncStatusChanged="sync-status-changed",n.Snapshot="snapshot",n.LocalChange="local-change",n.RemoteChange="remote-change",n.Initialized="initialized",n.Watched="watched",n.Unwatched="unwatched",n.PresenceChanged="presence-changed",n.Broadcast="broadcast",n.LocalBroadcast="local-broadcast",n))(_||{}),Js=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(Js||{}),Fs=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Fs||{});class ia{constructor(t,e){a(this,"key");a(this,"status");a(this,"opts");a(this,"changeID");a(this,"checkpoint");a(this,"localChanges");a(this,"root");a(this,"clone");a(this,"eventStream");a(this,"eventStreamObserver");a(this,"onlineClients");a(this,"presences");a(this,"history");a(this,"internalHistory");a(this,"isUpdating");this.opts=e||{},this.key=t,this.status="detached",this.root=Qr.create(),this.changeID=Zc,this.checkpoint=Qc,this.localChanges=[],this.eventStream=Uu(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new ju,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},Hu(this)}update(t,e){if(this.getStatus()==="removed")throw new g(d.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),s=kr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},e);try{const i=Ki(s,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,t(i,new rs(s,this.clone.presences.get(r)))}catch(i){throw this.clone=void 0,i}finally{this.isUpdating=!1}if(s.hasChange()){x.isEnabled(ee.Trivial)&&x.trivial(`trying to update a local change: ${this.toJSON()}`);const i=s.getChange(),{opInfos:o,reverseOps:c}=i.execute(this.root,this.presences,J.Local),l=s.getReversePresence();l&&c.push({type:"presence",value:l}),this.localChanges.push(i),c.length>0&&this.internalHistory.pushUndo(c),o.length>0&&this.internalHistory.clearRedo(),this.changeID=i.getID();const h=[];o.length>0&&h.push({type:"local-change",source:J.Local,value:{message:i.getMessage()||"",operations:o,actor:r,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&h.push({type:"presence-changed",source:J.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(h),x.isEnabled(ee.Trivial)&&x.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,e,r,s){if(typeof t=="string"){if(typeof e!="function")throw new g(d.ErrInvalidArgument,"Second argument must be a callback function");if(t==="presence"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||c(h)},r,s)}if(t==="my-presence"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="presence-changed"||h.type==="presence-changed"&&h.value.clientID!==this.changeID.getActorID()||c(h)},r,s)}if(t==="others"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||h.value.clientID!==this.changeID.getActorID()&&c(h)},r,s)}if(t==="connection"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="connection-changed"&&c(h)},r,s)}if(t==="status"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="status-changed"&&c(h)},r,s)}if(t==="sync"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="sync-status-changed"&&c(h)},r,s)}if(t==="local-broadcast"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="local-broadcast"&&c(h)},r)}if(t==="broadcast"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="broadcast"&&c(h)},r)}if(t==="all"){const c=e;return this.eventStream.subscribe(c,r,s)}const i=t,o=e;return this.eventStream.subscribe(c=>{for(const l of c){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const h=[];for(const f of l.value.operations)this.isSameElementOrChildOf(f.path,i)&&h.push(f);h.length&&o({...l,value:{...l.value,operations:h}})}},r,s)}if(typeof t=="function"){const i=t,o=e,c=r;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="snapshot"&&h.type!=="local-change"&&h.type!=="remote-change"||i(h)},o,c)}throw new g(d.ErrInvalidArgument,`"${t}" is not a valid`)}publish(t){this.eventStreamObserver&&this.eventStreamObserver.next(t)}isSameElementOrChildOf(t,e){if(e===t)return!0;const r=t.split(".");return e.split(".").every((i,o)=>i===r[o])}applyChangePack(t){const e=t.hasSnapshot();for(e?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getVersionVector(),t.getSnapshot()):t.hasChanges()&&this.applyChanges(t.getChanges(),J.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t.getCheckpoint().getClientSeq());)this.localChanges.shift();e&&this.applyChanges(this.localChanges,J.Remote),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),e||this.garbageCollect(t.getVersionVector()),e||this.filterVersionVector(t.getVersionVector()),t.getIsRemoved()&&this.applyStatus("removed"),x.isEnabled(ee.Trivial)&&x.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Ie(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),e=this.checkpoint.increaseClientSeq(t.length);return Hn.create(this.key,e,!1,t,this.getVersionVector())}setActor(t){for(const e of this.localChanges)e.setActor(t);this.changeID=this.changeID.setActor(t)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const t=kr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Ki(t,this.clone.root.getObject())}garbageCollect(t){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(t),this.root.garbageCollect(t))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,e,r){const{root:s,presences:i}=V.bytesToSnapshot(r);this.root=new Qr(s),this.presences=i,this.changeID=this.changeID.setClocks(t,e),this.clone=void 0,this.publish([{type:"snapshot",source:J.Remote,value:{serverSeq:t.toString(),snapshot:this.isEnableDevtools()?V.bytesToHex(r):void 0,snapshotVector:V.versionVectorToHex(e)}}])}applyChanges(t,e){x.isEnabled(ee.Debug)&&x.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),x.isEnabled(ee.Trivial)&&x.trivial(t.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` -`));for(const r of t)this.applyChange(r,e);x.isEnabled(ee.Debug)&&x.debug(`after appling ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(t,e){this.ensureClone(),t.execute(this.clone.root,this.clone.presences,e);const r=[],s=t.getID().getActorID();if(t.hasPresenceChange()&&this.onlineClients.has(s)){const o=t.getPresenceChange();switch(o.type){case cr.Put:r.push(this.presences.has(s)?{type:"presence-changed",source:e,value:{clientID:s,presence:o.presence}}:{type:"watched",source:J.Remote,value:{clientID:s,presence:o.presence}});break;case cr.Clear:r.push({type:"unwatched",source:J.Remote,value:{clientID:s,presence:this.getPresence(s)}}),this.removeOnlineClient(s);break}}const{opInfos:i}=t.execute(this.root,this.presences,e);if(this.changeID=this.changeID.syncClocks(t.getID()),i.length>0){const o=this.isEnableDevtools()?t.toStruct():void 0;r.push(e===J.Remote?{type:"remote-change",source:e,value:{actor:s,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:i},rawChange:o}:{type:"local-change",source:e,value:{actor:s,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:i},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(t){if(t.body.case==="initialization"){const e=t.body.value.clientIds,r=new Set;for(const s of e)s!==this.changeID.getActorID()&&r.add(s);this.setOnlineClients(r),this.publish([{type:"initialized",source:J.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:e,publisher:r}=t.body.value,s=[];if(e===pr.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&s.push({type:"watched",source:J.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(e===pr.DOCUMENT_UNWATCHED){const i=this.getPresence(r);this.removeOnlineClient(r),i&&s.push({type:"unwatched",source:J.Remote,value:{clientID:r,presence:i}})}else if(e===pr.DOCUMENT_BROADCAST&&t.body.value.body){const{topic:i,payload:o}=t.body.value.body,c=new TextDecoder;s.push({type:"broadcast",value:{clientID:r,topic:i,payload:JSON.parse(c.decode(o))}})}s.length>0&&this.publish(s)}}applyStatus(t){this.status=t,t==="detached"&&this.setActor(Vs),this.publish([{source:t==="removed"?J.Remote:J.Local,type:"status-changed",value:t==="attached"?{status:t,actorID:this.changeID.getActorID()}:{status:t}}])}applyDocEvent(t){if(t.type==="status-changed"){this.applyStatus(t.value.status),t.value.status==="attached"&&this.setActor(t.value.actorID);return}if(t.type==="snapshot"){const{snapshot:e,serverSeq:r,snapshotVector:s}=t.value;if(!e)return;this.applySnapshot(BigInt(r),V.hexToVersionVector(s),V.hexToBytes(e));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const e=Rr.fromStruct(t.rawChange);this.applyChange(e,t.source)}if(t.type==="initialized"){const e=new Set;for(const{clientID:r,presence:s}of t.value)e.add(r),this.presences.set(r,s);this.setOnlineClients(e);return}if(t.type==="watched"){const{clientID:e,presence:r}=t.value;this.addOnlineClient(e),this.presences.set(e,r);return}if(t.type==="unwatched"){const{clientID:e}=t.value;this.removeOnlineClient(e),this.presences.delete(e)}if(t.type==="presence-changed"){const{clientID:e,presence:r}=t.value;this.presences.set(e,r)}}applyTransactionEvent(t){for(const e of t)this.applyDocEvent(e)}getValueByPath(t){if(!t.startsWith("$"))throw new g(d.ErrInvalidArgument,'path must start with "$"');const e=t.split(".");e.shift();let r=this.getRoot();for(const s of e)if(r=r[s],r===void 0)return;return r}setOnlineClients(t){this.onlineClients=t}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(t){this.onlineClients.add(t)}removeOnlineClient(t){this.onlineClients.delete(t)}hasPresence(t){return this.presences.has(t)}getMyPresence(){if(this.status!=="attached")return{};const t=this.presences.get(this.changeID.getActorID());return t?Ie(t):{}}getPresence(t){if(t===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(t))return;const e=this.presences.get(t);return e?Ie(e):void 0}getPresenceForTest(t){const e=this.presences.get(t);return e?Ie(e):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:Ie(this.getMyPresence())});for(const e of this.onlineClients)this.presences.has(e)&&t.push({clientID:e,presence:Ie(this.presences.get(e))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(e=>e.clientID!==t).sort((e,r)=>e.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(t){const r=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new g(d.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new g(d.ErrRefused,"There is no operation to be undone");this.ensureClone();const e=kr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of t){if(!(h instanceof Ne)){new rs(e,Ie(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const f=e.issueTimeTicket();h.setExecutedAt(f),e.push(h)}const r=e.getChange();r.execute(this.clone.root,this.clone.presences,J.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,J.UndoRedo),o=e.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushRedo(i),!r.hasPresenceChange()&&s.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const c=this.changeID.getActorID(),l=[];s.length>0&&l.push({type:"local-change",source:J.UndoRedo,value:{message:r.getMessage()||"",operations:s,actor:c,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:J.UndoRedo,value:{clientID:c,presence:this.getPresence(c)}}),this.publish(l)}redo(){if(this.isUpdating)throw new g(d.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new g(d.ErrRefused,"There is no operation to be redone");this.ensureClone();const e=kr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of t){if(!(h instanceof Ne)){new rs(e,Ie(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const f=e.issueTimeTicket();h.setExecutedAt(f),e.push(h)}const r=e.getChange();r.execute(this.clone.root,this.clone.presences,J.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,J.UndoRedo),o=e.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushUndo(i),!r.hasPresenceChange()&&s.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const c=this.changeID.getActorID(),l=[];s.length>0&&l.push({type:"local-change",source:J.UndoRedo,value:{message:r.getMessage()||"",operations:s,actor:c,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:J.UndoRedo,value:{clientID:c,presence:this.getPresence(c)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(t,e,r){const s={type:"local-broadcast",value:{topic:t,payload:e},options:r};this.publish([s])}getVersionVector(){return this.changeID.getVersionVector()}}function Yu(n,t){return e=>async r=>(n&&r.header.set("x-api-key",n),t&&r.header.set("authorization",t),await e(r))}const Xu="yorkie-js-sdk",Zu="0.5.4",Qu="Yorkie JS SDK",_u="./src/yorkie.ts",el={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},tl=["dist"],rl={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},nl={node:">=18.0.0",npm:">=7.1.0"},sl={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},il={name:"hackerwins",email:"susukang98@gmail.com"},ol="Apache-2.0",al={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},cl="https://github.com/yorkie-team/yorkie-js-sdk#readme",ul={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},ll={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Wi={name:Xu,version:Zu,description:Qu,main:_u,publishConfig:el,files:tl,scripts:rl,engines:nl,repository:sl,author:il,license:ol,bugs:al,homepage:cl,devDependencies:ul,dependencies:ll};function hl(){return n=>async t=>(t.header.set("x-yorkie-user-agent",Wi.name+"/"+Wi.version),await n(t))}const fl=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var wn=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(wn||{});const fn={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},os={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class oa{constructor(t,e){a(this,"id");a(this,"key");a(this,"status");a(this,"attachmentMap");a(this,"apiKey");a(this,"conditions");a(this,"syncLoopDuration");a(this,"reconnectStreamDelay");a(this,"retrySyncLoopDelay");a(this,"rpcClient");a(this,"taskQueue");a(this,"processing",!1);e=e||fn,this.key=e.key?e.key:ra(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=e.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=e.syncLoopDuration||fn.syncLoopDuration,this.reconnectStreamDelay=e.reconnectStreamDelay||fn.reconnectStreamDelay,this.retrySyncLoopDelay=e.retrySyncLoopDelay||fn.retrySyncLoopDelay,this.rpcClient=cc(Dc,Pc({baseUrl:t,interceptors:[Yu(e.apiKey,e.token),hl()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),x.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw x.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),x.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw x.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,e={}){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==rr.Detached)throw new g(d.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((i,o)=>o.set(e.initialPresence||{}));const r=t.subscribe("local-broadcast",async i=>{var f;const{topic:o,payload:c}=i.value,l=(f=i.options)==null?void 0:f.error,h=i.options;try{await this.broadcast(t.getKey(),o,c,h)}catch(p){p instanceof Error&&(l==null||l(p))}}),s=e.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:V.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async i=>{const o=V.fromChangePack(i.changePack);if(t.applyChangePack(o),t.getStatus()===rr.Removed)return t;t.applyStatus(rr.Attached),this.attachmentMap.set(t.getKey(),new Mu(this.reconnectStreamDelay,t,i.documentId,s,r)),s!=="manual"&&await this.runWatchLoop(t.getKey()),x.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const c=t.getRootObject();if(e.initialRoot){const l=e.initialRoot;t.update(h=>{for(const[f,p]of Object.entries(l))if(!c.has(f)){const v=f;h[v]=p}})}return t}).catch(i=>{throw x.error(`[AD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}detach(t,e={}){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((s,i)=>i.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:V.toChangePack(t.createChangePack()),removeIfNotAttached:e.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(s=>{const i=V.fromChangePack(s.changePack);return t.applyChangePack(i),t.getStatus()!==rr.Removed&&t.applyStatus(rr.Detached),this.detachInternal(t.getKey()),x.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(s=>{throw x.error(`[DD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}async changeSyncMode(t,e){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const s=r.syncMode;return s===e?t:(r.changeSyncMode(e),e==="manual"?(r.cancelWatchStream(),t):(e==="realtime"&&(r.remoteChangeEventReceived=!0),s==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);if(t){const e=this.attachmentMap.get(t.getKey());if(!e)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(e,"realtime").catch(r=>{throw x.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const e=[];for(const[,r]of this.attachmentMap)e.push(this.syncInternal(r,r.syncMode));return Promise.all(e).catch(r=>{throw x.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const e=this.attachmentMap.get(t.getKey());if(!e)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=V.toChangePack(t.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:e.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(s=>{const i=V.fromChangePack(s.changePack);t.applyChangePack(i),this.detachInternal(t.getKey()),x.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(s=>{throw x.error(`[RD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(t){return this.conditions[t]}broadcast(t,e,r,s){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(t);if(!i)throw new g(d.ErrDocumentNotAttached,`${t} is not attached`);if(!fl(r))throw new g(d.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??os.maxRetries,c=os.maxBackoff;let l=0;const h=p=>Math.min(os.initialRetryInterval*2**p,c),f=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:i.docID,topic:e,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{x.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${e}"`)}).catch(p=>{if(x.error(`[BC] c:"${this.getKey()}" err:`,p),this.handleConnectError(p))if(lf(),h(l-1)),x.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw x.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),p;else throw p}));return f()}runSyncLoop(){const t=()=>{if(!this.isActive()){x.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const e=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,e.push(this.syncInternal(r,r.syncMode)));Promise.all(e).then(()=>setTimeout(t,this.syncLoopDuration)).catch(r=>{x.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};x.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,t()}async runWatchLoop(t){const e=this.attachmentMap.get(t);if(!e)throw new g(d.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,e.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new g(d.ErrClientNotActivated,`${this.key} is not active`));const s=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:e.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:s.signal});return e.doc.publish([{type:_.ConnectionChanged,value:Js.Connected}]),x.info(`[WD] c:"${this.getKey()}" watches d:"${t}"`),new Promise((o,c)=>{(async()=>{try{for await(const h of i)this.handleWatchDocumentsResponse(e,h),h.body.case==="initialization"&&o([i,s])}catch(h){e.doc.resetOnlineClients(),e.doc.publish([{type:_.Initialized,source:J.Local,value:e.doc.getPresences()}]),e.doc.publish([{type:_.ConnectionChanged,value:Js.Disconnected}]),x.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(h)?r():this.conditions.WatchLoop=!1,c(h)}})()})})}handleWatchDocumentsResponse(t,e){if(e.body.case==="event"&&e.body.value.type===pr.DOCUMENT_CHANGED){t.remoteChangeEventReceived=!0;return}t.doc.applyWatchStream(e)}deactivateInternal(){this.status="deactivated";for(const[t,e]of this.attachmentMap)this.detachInternal(t),e.doc.applyStatus(rr.Detached)}detachInternal(t){const e=this.attachmentMap.get(t);e&&(e.cancelWatchStream(),e.unsubscribeBroadcastEvent(),this.attachmentMap.delete(t))}syncInternal(t,e){const{doc:r,docID:s}=t,i=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:s,changePack:V.toChangePack(i),pushOnly:e==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const c=V.fromChangePack(o.changePack);if(c.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(c),t.doc.publish([{type:_.SyncStatusChanged,value:Fs.Synced}]),r.getStatus()===rr.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),h=c.getChangeSize();return x.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${i.getChangeSize()} pull:${h} cp:${c.getCheckpoint().toTestString()}`),r}).catch(o=>{throw r.publish([{type:_.SyncStatusChanged,value:Fs.SyncFailed}]),x.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(t){return t instanceof G?t.code===R.Canceled||t.code===R.Unknown||t.code===R.ResourceExhausted||t.code===R.Unavailable?!0:((Vi(t)===d.ErrClientNotActivated||Vi(t)===d.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(t){return new Promise((e,r)=>{this.taskQueue.push(()=>t().then(e).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{x.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Hi={Client:oa,Document:ia,Primitive:$,Text:Yn,Counter:Xn,Tree:Zn,LogLevel:ee,setLogLevel:ta,IntType:ze.IntegerCnt,LongType:ze.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:oa,Document:ia,Primitive:$,Text:Yn,Counter:Xn,Tree:Zn,LogLevel:ee,setLogLevel:ta,IntType:ze.IntegerCnt,LongType:ze.LongCnt});const Yi=["Ali","Beatriz","Charles","Diya","Eric","Fatima","Gabriel","Hanna","Johnson","Perry","Parker","Kelly"],dl=()=>{const n=Math.floor(Math.random()*Yi.length);return Yi[n]},Xi=["red","yellow","orange","green","blue","purple"],gl=()=>{const n=Math.floor(Math.random()*Xi.length);return Xi[n]};async function ml(){const n=new Hi.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});await n.activate();const t=new Hi.Document("profile-stack",{enableDevtools:!0});t.subscribe("presence",e=>{e.type!==_.PresenceChanged&&pl(t.getPresences(),n.getID())}),await n.attach(t,{initialPresence:{name:dl(),color:gl()}}),window.addEventListener("beforeunload",()=>{n.deactivate()})}const as=4,cs=(n,t,e)=>{const r=document.createElement("div");return r.className="peer",e==="main"?r.innerHTML=` +`));for(const r of t)this.applyChange(r,e);x.isEnabled(ee.Debug)&&x.debug(`after appling ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(t,e){this.ensureClone(),t.execute(this.clone.root,this.clone.presences,e);const r=[],s=t.getID().getActorID();if(t.hasPresenceChange()&&this.onlineClients.has(s)){const o=t.getPresenceChange();switch(o.type){case cr.Put:r.push(this.presences.has(s)?{type:"presence-changed",source:e,value:{clientID:s,presence:o.presence}}:{type:"watched",source:J.Remote,value:{clientID:s,presence:o.presence}});break;case cr.Clear:r.push({type:"unwatched",source:J.Remote,value:{clientID:s,presence:this.getPresence(s)}}),this.removeOnlineClient(s);break}}const{opInfos:i}=t.execute(this.root,this.presences,e);if(this.changeID=this.changeID.syncClocks(t.getID()),i.length>0){const o=this.isEnableDevtools()?t.toStruct():void 0;r.push(e===J.Remote?{type:"remote-change",source:e,value:{actor:s,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:i},rawChange:o}:{type:"local-change",source:e,value:{actor:s,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:i},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(t){if(t.body.case==="initialization"){const e=t.body.value.clientIds,r=new Set;for(const s of e)s!==this.changeID.getActorID()&&r.add(s);this.setOnlineClients(r),this.publish([{type:"initialized",source:J.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:e,publisher:r}=t.body.value,s=[];if(e===pr.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&s.push({type:"watched",source:J.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(e===pr.DOCUMENT_UNWATCHED){const i=this.getPresence(r);this.removeOnlineClient(r),i&&s.push({type:"unwatched",source:J.Remote,value:{clientID:r,presence:i}})}else if(e===pr.DOCUMENT_BROADCAST&&t.body.value.body){const{topic:i,payload:o}=t.body.value.body,c=new TextDecoder;s.push({type:"broadcast",value:{clientID:r,topic:i,payload:JSON.parse(c.decode(o))}})}s.length>0&&this.publish(s)}}applyStatus(t){this.status=t,t==="detached"&&this.setActor(Vs),this.publish([{source:t==="removed"?J.Remote:J.Local,type:"status-changed",value:t==="attached"?{status:t,actorID:this.changeID.getActorID()}:{status:t}}])}applyDocEvent(t){if(t.type==="status-changed"){this.applyStatus(t.value.status),t.value.status==="attached"&&this.setActor(t.value.actorID);return}if(t.type==="snapshot"){const{snapshot:e,serverSeq:r,snapshotVector:s}=t.value;if(!e)return;this.applySnapshot(BigInt(r),V.hexToVersionVector(s),V.hexToBytes(e));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const e=Rr.fromStruct(t.rawChange);this.applyChange(e,t.source)}if(t.type==="initialized"){const e=new Set;for(const{clientID:r,presence:s}of t.value)e.add(r),this.presences.set(r,s);this.setOnlineClients(e);return}if(t.type==="watched"){const{clientID:e,presence:r}=t.value;this.addOnlineClient(e),this.presences.set(e,r);return}if(t.type==="unwatched"){const{clientID:e}=t.value;this.removeOnlineClient(e),this.presences.delete(e)}if(t.type==="presence-changed"){const{clientID:e,presence:r}=t.value;this.presences.set(e,r)}}applyTransactionEvent(t){for(const e of t)this.applyDocEvent(e)}getValueByPath(t){if(!t.startsWith("$"))throw new g(d.ErrInvalidArgument,'path must start with "$"');const e=t.split(".");e.shift();let r=this.getRoot();for(const s of e)if(r=r[s],r===void 0)return;return r}setOnlineClients(t){this.onlineClients=t}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(t){this.onlineClients.add(t)}removeOnlineClient(t){this.onlineClients.delete(t)}hasPresence(t){return this.presences.has(t)}getMyPresence(){if(this.status!=="attached")return{};const t=this.presences.get(this.changeID.getActorID());return t?Ie(t):{}}getPresence(t){if(t===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(t))return;const e=this.presences.get(t);return e?Ie(e):void 0}getPresenceForTest(t){const e=this.presences.get(t);return e?Ie(e):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:Ie(this.getMyPresence())});for(const e of this.onlineClients)this.presences.has(e)&&t.push({clientID:e,presence:Ie(this.presences.get(e))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(e=>e.clientID!==t).sort((e,r)=>e.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(t){const r=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new g(d.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new g(d.ErrRefused,"There is no operation to be undone");this.ensureClone();const e=kr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of t){if(!(h instanceof Ne)){new rs(e,Ie(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const f=e.issueTimeTicket();h.setExecutedAt(f),e.push(h)}const r=e.getChange();r.execute(this.clone.root,this.clone.presences,J.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,J.UndoRedo),o=e.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushRedo(i),!r.hasPresenceChange()&&s.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const c=this.changeID.getActorID(),l=[];s.length>0&&l.push({type:"local-change",source:J.UndoRedo,value:{message:r.getMessage()||"",operations:s,actor:c,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:J.UndoRedo,value:{clientID:c,presence:this.getPresence(c)}}),this.publish(l)}redo(){if(this.isUpdating)throw new g(d.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new g(d.ErrRefused,"There is no operation to be redone");this.ensureClone();const e=kr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of t){if(!(h instanceof Ne)){new rs(e,Ie(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const f=e.issueTimeTicket();h.setExecutedAt(f),e.push(h)}const r=e.getChange();r.execute(this.clone.root,this.clone.presences,J.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,J.UndoRedo),o=e.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushUndo(i),!r.hasPresenceChange()&&s.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const c=this.changeID.getActorID(),l=[];s.length>0&&l.push({type:"local-change",source:J.UndoRedo,value:{message:r.getMessage()||"",operations:s,actor:c,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:J.UndoRedo,value:{clientID:c,presence:this.getPresence(c)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(t,e,r){const s={type:"local-broadcast",value:{topic:t,payload:e},options:r};this.publish([s])}getVersionVector(){return this.changeID.getVersionVector()}}function Yu(n,t){return e=>async r=>(n&&r.header.set("x-api-key",n),t&&r.header.set("authorization",t),await e(r))}const Xu="yorkie-js-sdk",Zu="0.5.4",Qu="Yorkie JS SDK",_u="./src/yorkie.ts",el={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},tl=["dist"],rl={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},nl={node:">=18.0.0",npm:">=7.1.0"},sl={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},il={name:"hackerwins",email:"susukang98@gmail.com"},ol="Apache-2.0",al={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},cl="https://github.com/yorkie-team/yorkie-js-sdk#readme",ul={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},ll={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Wi={name:Xu,version:Zu,description:Qu,main:_u,publishConfig:el,files:tl,scripts:rl,engines:nl,repository:sl,author:il,license:ol,bugs:al,homepage:cl,devDependencies:ul,dependencies:ll};function hl(){return n=>async t=>(t.header.set("x-yorkie-user-agent",Wi.name+"/"+Wi.version),await n(t))}const fl=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var wn=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(wn||{});const fn={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},os={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class oa{constructor(t,e){a(this,"id");a(this,"key");a(this,"status");a(this,"attachmentMap");a(this,"apiKey");a(this,"conditions");a(this,"syncLoopDuration");a(this,"reconnectStreamDelay");a(this,"retrySyncLoopDelay");a(this,"rpcClient");a(this,"taskQueue");a(this,"processing",!1);e=e||fn,this.key=e.key?e.key:ra(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=e.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=e.syncLoopDuration||fn.syncLoopDuration,this.reconnectStreamDelay=e.reconnectStreamDelay||fn.reconnectStreamDelay,this.retrySyncLoopDelay=e.retrySyncLoopDelay||fn.retrySyncLoopDelay,this.rpcClient=cc(Dc,Pc({baseUrl:t,interceptors:[Yu(e.apiKey,e.token),hl()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),x.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw x.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),x.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw x.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,e={}){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==rr.Detached)throw new g(d.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((i,o)=>o.set(e.initialPresence||{}));const r=t.subscribe("local-broadcast",async i=>{var f;const{topic:o,payload:c}=i.value,l=(f=i.options)==null?void 0:f.error,h=i.options;try{await this.broadcast(t.getKey(),o,c,h)}catch(p){p instanceof Error&&(l==null||l(p))}}),s=e.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:V.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async i=>{const o=V.fromChangePack(i.changePack);if(t.applyChangePack(o),t.getStatus()===rr.Removed)return t;t.applyStatus(rr.Attached),this.attachmentMap.set(t.getKey(),new Mu(this.reconnectStreamDelay,t,i.documentId,s,r)),s!=="manual"&&await this.runWatchLoop(t.getKey()),x.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const c=t.getRootObject();if(e.initialRoot){const l=e.initialRoot;t.update(h=>{for(const[f,p]of Object.entries(l))if(!c.has(f)){const v=f;h[v]=p}})}return t}).catch(i=>{throw x.error(`[AD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}detach(t,e={}){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((s,i)=>i.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:V.toChangePack(t.createChangePack()),removeIfNotAttached:e.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(s=>{const i=V.fromChangePack(s.changePack);return t.applyChangePack(i),t.getStatus()!==rr.Removed&&t.applyStatus(rr.Detached),this.detachInternal(t.getKey()),x.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(s=>{throw x.error(`[DD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}async changeSyncMode(t,e){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const s=r.syncMode;return s===e?t:(r.changeSyncMode(e),e==="manual"?(r.cancelWatchStream(),t):(e==="realtime"&&(r.remoteChangeEventReceived=!0),s==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);if(t){const e=this.attachmentMap.get(t.getKey());if(!e)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(e,"realtime").catch(r=>{throw x.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const e=[];for(const[,r]of this.attachmentMap)e.push(this.syncInternal(r,r.syncMode));return Promise.all(e).catch(r=>{throw x.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const e=this.attachmentMap.get(t.getKey());if(!e)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=V.toChangePack(t.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:e.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(s=>{const i=V.fromChangePack(s.changePack);t.applyChangePack(i),this.detachInternal(t.getKey()),x.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(s=>{throw x.error(`[RD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(t){return this.conditions[t]}broadcast(t,e,r,s){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(t);if(!i)throw new g(d.ErrDocumentNotAttached,`${t} is not attached`);if(!fl(r))throw new g(d.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??os.maxRetries,c=os.maxBackoff;let l=0;const h=p=>Math.min(os.initialRetryInterval*2**p,c),f=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:i.docID,topic:e,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{x.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${e}"`)}).catch(p=>{if(x.error(`[BC] c:"${this.getKey()}" err:`,p),this.handleConnectError(p))if(lf(),h(l-1)),x.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw x.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),p;else throw p}));return f()}runSyncLoop(){const t=()=>{if(!this.isActive()){x.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const e=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,e.push(this.syncInternal(r,r.syncMode)));Promise.all(e).then(()=>setTimeout(t,this.syncLoopDuration)).catch(r=>{x.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};x.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,t()}async runWatchLoop(t){const e=this.attachmentMap.get(t);if(!e)throw new g(d.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,e.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new g(d.ErrClientNotActivated,`${this.key} is not active`));const s=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:e.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:s.signal});return e.doc.publish([{type:_.ConnectionChanged,value:Js.Connected}]),x.info(`[WD] c:"${this.getKey()}" watches d:"${t}"`),new Promise((o,c)=>{(async()=>{try{for await(const h of i)this.handleWatchDocumentsResponse(e,h),h.body.case==="initialization"&&o([i,s])}catch(h){e.doc.resetOnlineClients(),e.doc.publish([{type:_.Initialized,source:J.Local,value:e.doc.getPresences()}]),e.doc.publish([{type:_.ConnectionChanged,value:Js.Disconnected}]),x.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(h)?r():this.conditions.WatchLoop=!1,c(h)}})()})})}handleWatchDocumentsResponse(t,e){if(e.body.case==="event"&&e.body.value.type===pr.DOCUMENT_CHANGED){t.remoteChangeEventReceived=!0;return}t.doc.applyWatchStream(e)}deactivateInternal(){this.status="deactivated";for(const[t,e]of this.attachmentMap)this.detachInternal(t),e.doc.applyStatus(rr.Detached)}detachInternal(t){const e=this.attachmentMap.get(t);e&&(e.cancelWatchStream(),e.unsubscribeBroadcastEvent(),this.attachmentMap.delete(t))}syncInternal(t,e){const{doc:r,docID:s}=t,i=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:s,changePack:V.toChangePack(i),pushOnly:e==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const c=V.fromChangePack(o.changePack);if(c.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(c),t.doc.publish([{type:_.SyncStatusChanged,value:Fs.Synced}]),r.getStatus()===rr.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),h=c.getChangeSize();return x.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${i.getChangeSize()} pull:${h} cp:${c.getCheckpoint().toTestString()}`),r}).catch(o=>{throw r.publish([{type:_.SyncStatusChanged,value:Fs.SyncFailed}]),x.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(t){return t instanceof G?t.code===R.Canceled||t.code===R.Unknown||t.code===R.ResourceExhausted||t.code===R.Unavailable?!0:((Vi(t)===d.ErrClientNotActivated||Vi(t)===d.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(t){return new Promise((e,r)=>{this.taskQueue.push(()=>t().then(e).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{x.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Hi={Client:oa,Document:ia,Primitive:$,Text:Yn,Counter:Xn,Tree:Zn,LogLevel:ee,setLogLevel:ta,IntType:ze.IntegerCnt,LongType:ze.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:oa,Document:ia,Primitive:$,Text:Yn,Counter:Xn,Tree:Zn,LogLevel:ee,setLogLevel:ta,IntType:ze.IntegerCnt,LongType:ze.LongCnt});const Yi=["Ali","Beatriz","Charles","Diya","Eric","Fatima","Gabriel","Hanna","Johnson","Perry","Parker","Kelly"],dl=()=>{const n=Math.floor(Math.random()*Yi.length);return Yi[n]},Xi=["red","yellow","orange","green","blue","purple"],gl=()=>{const n=Math.floor(Math.random()*Xi.length);return Xi[n]};async function ml(){const n=new Hi.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});await n.activate();const t=new Hi.Document("profile-stack",{enableDevtools:!0});t.subscribe("presence",e=>{e.type!==_.PresenceChanged&&pl(t.getPresences(),n.getID())}),await n.attach(t,{initialPresence:{name:dl(),color:gl()}}),window.addEventListener("beforeunload",()=>{n.deactivate()})}const as=4,cs=(n,t,e)=>{const r=document.createElement("div");return r.className="peer",e==="main"?r.innerHTML=`
    profile
    diff --git a/examples/profile-stack/index.html b/examples/profile-stack/index.html index 65c24a666..c344aeac8 100644 --- a/examples/profile-stack/index.html +++ b/examples/profile-stack/index.html @@ -5,7 +5,7 @@ Profile Stack - Yorkie Example - + diff --git a/examples/react-tldraw/assets/index-Bdmi0lkB.js b/examples/react-tldraw/assets/index-Bx94zqRc.js similarity index 98% rename from examples/react-tldraw/assets/index-Bdmi0lkB.js rename to examples/react-tldraw/assets/index-Bx94zqRc.js index 0479b8149..ed3e0184d 100644 --- a/examples/react-tldraw/assets/index-Bdmi0lkB.js +++ b/examples/react-tldraw/assets/index-Bx94zqRc.js @@ -548,7 +548,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/alert- * * SPDX-License-Identifier: Apache-2.0 */var wi=null;try{wi=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function at(e,t,n){this.low=e|0,this.high=t|0,this.unsigned=!!n}at.prototype.__isLong__;Object.defineProperty(at.prototype,"__isLong__",{value:!0});function qn(e){return(e&&e.__isLong__)===!0}function Sx(e){var t=Math.clz32(e&-e);return e?31-t:t}at.isLong=qn;var xx={},Ax={};function _l(e,t){var n,r,i;return t?(e>>>=0,(i=0<=e&&e<256)&&(r=Ax[e],r)?r:(n=ct(e,0,!0),i&&(Ax[e]=n),n)):(e|=0,(i=-128<=e&&e<128)&&(r=xx[e],r)?r:(n=ct(e,e<0?-1:0,!1),i&&(xx[e]=n),n))}at.fromInt=_l;function Si(e,t){if(isNaN(e))return t?hs:qi;if(t){if(e<0)return hs;if(e>=FP)return _P}else{if(e<=-Dx)return yr;if(e+1>=Dx)return OP}return e<0?Si(-e,t).neg():ct(e%ld|0,e/ld|0,t)}at.fromNumber=Si;function ct(e,t,n){return new at(e,t,n)}at.fromBits=ct;var om=Math.pow;function OC(e,t,n){if(e.length===0)throw Error("empty string");if(typeof t=="number"?(n=t,t=!1):t=!!t,e==="NaN"||e==="Infinity"||e==="+Infinity"||e==="-Infinity")return t?hs:qi;if(n=n||10,n<2||360)throw Error("interior hyphen");if(r===0)return OC(e.substring(1),t,n).neg();for(var i=Si(om(n,8)),o=qi,a=0;a>>0:this.low};he.toNumber=function(){return this.unsigned?(this.high>>>0)*ld+(this.low>>>0):this.high*ld+(this.low>>>0)};he.toString=function(t){if(t=t||10,t<2||36>>0,h=d.toString(t);if(a=u,a.isZero())return h+s;for(;h.length<6;)h="0"+h;s=""+h+s}};he.getHighBits=function(){return this.high};he.getHighBitsUnsigned=function(){return this.high>>>0};he.getLowBits=function(){return this.low};he.getLowBitsUnsigned=function(){return this.low>>>0};he.getNumBitsAbs=function(){if(this.isNegative())return this.eq(yr)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,n=31;n>0&&!(t&1<=0};he.isOdd=function(){return(this.low&1)===1};he.isEven=function(){return(this.low&1)===0};he.equals=function(t){return qn(t)||(t=co(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};he.eq=he.equals;he.notEquals=function(t){return!this.eq(t)};he.neq=he.notEquals;he.ne=he.notEquals;he.lessThan=function(t){return this.comp(t)<0};he.lt=he.lessThan;he.lessThanOrEqual=function(t){return this.comp(t)<=0};he.lte=he.lessThanOrEqual;he.le=he.lessThanOrEqual;he.greaterThan=function(t){return this.comp(t)>0};he.gt=he.greaterThan;he.greaterThanOrEqual=function(t){return this.comp(t)>=0};he.gte=he.greaterThanOrEqual;he.ge=he.greaterThanOrEqual;he.compare=function(t){if(qn(t)||(t=co(t)),this.eq(t))return 0;var n=this.isNegative(),r=t.isNegative();return n&&!r?-1:!n&&r?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};he.comp=he.compare;he.negate=function(){return!this.unsigned&&this.eq(yr)?yr:this.not().add(Ic)};he.neg=he.negate;he.add=function(t){qn(t)||(t=co(t));var n=this.high>>>16,r=this.high&65535,i=this.low>>>16,o=this.low&65535,a=t.high>>>16,s=t.high&65535,u=t.low>>>16,d=t.low&65535,h=0,p=0,g=0,m=0;return m+=o+d,g+=m>>>16,m&=65535,g+=i+u,p+=g>>>16,g&=65535,p+=r+s,h+=p>>>16,p&=65535,h+=n+a,h&=65535,ct(g<<16|m,h<<16|p,this.unsigned)};he.subtract=function(t){return qn(t)||(t=co(t)),this.add(t.neg())};he.sub=he.subtract;he.multiply=function(t){if(this.isZero())return this;if(qn(t)||(t=co(t)),wi){var n=wi.mul(this.low,this.high,t.low,t.high);return ct(n,wi.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?hs:qi;if(this.eq(yr))return t.isOdd()?yr:qi;if(t.eq(yr))return this.isOdd()?yr:qi;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Ix)&&t.lt(Ix))return Si(this.toNumber()*t.toNumber(),this.unsigned);var r=this.high>>>16,i=this.high&65535,o=this.low>>>16,a=this.low&65535,s=t.high>>>16,u=t.high&65535,d=t.low>>>16,h=t.low&65535,p=0,g=0,m=0,v=0;return v+=a*h,m+=v>>>16,v&=65535,m+=o*h,g+=m>>>16,m&=65535,m+=a*d,g+=m>>>16,m&=65535,g+=i*h,p+=g>>>16,g&=65535,g+=o*d,p+=g>>>16,g&=65535,g+=a*u,p+=g>>>16,g&=65535,p+=r*h+i*d+o*u+a*s,p&=65535,ct(m<<16|v,p<<16|g,this.unsigned)};he.mul=he.multiply;he.divide=function(t){if(qn(t)||(t=co(t)),t.isZero())throw Error("division by zero");if(wi){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var n=(this.unsigned?wi.div_u:wi.div_s)(this.low,this.high,t.low,t.high);return ct(n,wi.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?hs:qi;var r,i,o;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return hs;if(t.gt(this.shru(1)))return LP;o=hs}else{if(this.eq(yr)){if(t.eq(Ic)||t.eq(gy))return yr;if(t.eq(yr))return Ic;var a=this.shr(1);return r=a.div(t).shl(1),r.eq(qi)?t.isNegative()?Ic:gy:(i=this.sub(t.mul(r)),o=r.add(i.div(t)),o)}else if(t.eq(yr))return this.unsigned?hs:qi;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();o=qi}for(i=this;i.gte(t);){r=Math.max(1,Math.floor(i.toNumber()/t.toNumber()));for(var s=Math.ceil(Math.log(r)/Math.LN2),u=s<=48?1:om(2,s-48),d=Si(r),h=d.mul(t);h.isNegative()||h.gt(i);)r-=u,d=Si(r,this.unsigned),h=d.mul(t);d.isZero()&&(d=Ic),o=o.add(d),i=i.sub(h)}return o};he.div=he.divide;he.modulo=function(t){if(qn(t)||(t=co(t)),wi){var n=(this.unsigned?wi.rem_u:wi.rem_s)(this.low,this.high,t.low,t.high);return ct(n,wi.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};he.mod=he.modulo;he.rem=he.modulo;he.not=function(){return ct(~this.low,~this.high,this.unsigned)};he.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};he.clz=he.countLeadingZeros;he.countTrailingZeros=function(){return this.low?Sx(this.low):Sx(this.high)+32};he.ctz=he.countTrailingZeros;he.and=function(t){return qn(t)||(t=co(t)),ct(this.low&t.low,this.high&t.high,this.unsigned)};he.or=function(t){return qn(t)||(t=co(t)),ct(this.low|t.low,this.high|t.high,this.unsigned)};he.xor=function(t){return qn(t)||(t=co(t)),ct(this.low^t.low,this.high^t.high,this.unsigned)};he.shiftLeft=function(t){return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?ct(this.low<>>32-t,this.unsigned):ct(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):ct(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};he.shr=he.shiftRight;he.shiftRightUnsigned=function(t){return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?ct(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?ct(this.high,0,this.unsigned):ct(this.high>>>t-32,0,this.unsigned)};he.shru=he.shiftRightUnsigned;he.shr_u=he.shiftRightUnsigned;he.rotateLeft=function(t){var n;return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?ct(this.high,this.low,this.unsigned):t<32?(n=32-t,ct(this.low<>>n,this.high<>>n,this.unsigned)):(t-=32,n=32-t,ct(this.high<>>n,this.low<>>n,this.unsigned))};he.rotl=he.rotateLeft;he.rotateRight=function(t){var n;return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?ct(this.high,this.low,this.unsigned):t<32?(n=32-t,ct(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,n=32-t,ct(this.low<>>t,this.high<>>t,this.unsigned))};he.rotr=he.rotateRight;he.toSigned=function(){return this.unsigned?ct(this.low,this.high,!1):this};he.toUnsigned=function(){return this.unsigned?this:ct(this.low,this.high,!0)};he.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};he.toBytesLE=function(){var t=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};he.toBytesBE=function(){var t=this.high,n=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,n>>>24,n>>>16&255,n>>>8&255,n&255]};at.fromBytes=function(t,n,r){return r?at.fromBytesLE(t,n):at.fromBytesBE(t,n)};at.fromBytesLE=function(t,n){return new at(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,n)};at.fromBytesBE=function(t,n){return new at(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],n)};var Cn=(e=>(e[e.Null=0]="Null",e[e.Boolean=1]="Boolean",e[e.Integer=2]="Integer",e[e.Long=3]="Long",e[e.Double=4]="Double",e[e.String=5]="String",e[e.Bytes=6]="Bytes",e[e.Date=7]="Date",e))(Cn||{});class Gt extends Fh{constructor(n,r){super(r);A(this,"valueType");A(this,"value");this.valueType=Gt.getPrimitiveType(n),this.value=n===void 0?null:n}static of(n,r){return new Gt(n,r)}static valueFromBytes(n,r){switch(n){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(o,a){i.setUint8(a,o)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return at.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(at.fromBytesLE(Array.from(r),!0).toNumber());default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return this.valueType===5?`"${Oo(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const n=Gt.of(this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n.setRemovedAt(this.getRemovedAt()),n}getType(){return this.valueType}static getPrimitiveType(n){switch(typeof n){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(n)?2:4;case"string":return 5;case"object":if(n===null)return 0;if(n instanceof at)return 3;if(n instanceof Uint8Array)return 6;if(n instanceof Date)return 7}}static isSupport(n){return Gt.getPrimitiveType(n)!==void 0}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===2||n===3||n===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 4:{const n=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,n,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const n=this.value,r=at.fromNumber(n.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class am extends RP{constructor(n){super(n);A(this,"prev");A(this,"next");this.value=n}static createAfter(n,r){const i=new am(r),o=n.next;return n.next=i,i.prev=n,i.next=o,o&&(o.prev=i),i}remove(n){return this.value.remove(n)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class dh{constructor(){A(this,"dummyHead");A(this,"last");A(this,"nodeMapByIndex");A(this,"nodeMapByCreatedAt");const t=Gt.of(0,to);t.setRemovedAt(to),this.dummyHead=new am(t),this.last=this.dummyHead,this.nodeMapByIndex=new ch,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new dh}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,n){let r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(n);)r=r.getNext();return r}release(t){this.last===t&&(this.last=t.getPrev()),t.release(),this.nodeMapByIndex.delete(t),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}insertAfter(t,n,r=n.getCreatedAt()){const i=this.findNextBeforeExecutedAt(t,r),o=am.createAfter(i,n);i===this.last&&(this.last=o),this.nodeMapByIndex.insertAfter(i,o),this.nodeMapByCreatedAt.set(o.getCreatedAt().toIDString(),o)}moveAfter(t,n,r){const i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const o=this.nodeMapByCreatedAt.get(n.toIDString());if(!o)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${n.toIDString()}`);i!==o&&(!o.getValue().getMovedAt()||r.after(o.getValue().getMovedAt()))&&(this.release(o),this.insertAfter(i.getCreatedAt(),o.getValue(),r),o.getValue().setMovedAt(r))}insert(t){this.insertAfter(this.last.getCreatedAt(),t)}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}subPathOf(t){const n=this.nodeMapByCreatedAt.get(t.toIDString());if(n)return String(this.nodeMapByIndex.indexOf(n))}purge(t){const n=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!n)throw new Y(W.ErrInvalidArgument,`fail to find the given createdAt: ${t.getCreatedAt().toIDString()}`);this.release(n)}getByIndex(t){if(t>=this.length)return;const[n,r]=this.nodeMapByIndex.find(t);let i=n;if(t===0&&n===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(t){let n=this.nodeMapByCreatedAt.get(t.toIDString());do n=n.getPrev();while(this.dummyHead!==n&&n.isRemoved());return n.getValue().getCreatedAt()}delete(t,n){const r=this.nodeMapByCreatedAt.get(t.toIDString()),i=r.isRemoved();return r.remove(n)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(t,n){const r=this.getByIndex(t);if(r)return r.remove(n)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const t=[];for(const n of this){const r=`${n.getCreatedAt().toIDString()}:${n.getValue().toJSON()}`;n.isRemoved()?t.push(`{${r}}`):t.push(`[${r}]`)}return t.join("")}*[Symbol.iterator](){let t=this.dummyHead.getNext();for(;t;)yield t,t=t.getNext()}}class Ur extends vu{constructor(n,r){super(n);A(this,"elements");this.elements=r}static create(n,r){if(!r)return new Ur(n,dh.create());const i=dh.create();for(const o of r)i.insertAfter(i.getLastCreatedAt(),o.deepcopy());return new Ur(n,i)}subPathOf(n){return this.elements.subPathOf(n)}purge(n){this.elements.purge(n)}insertAfter(n,r){this.elements.insertAfter(n,r)}moveAfter(n,r,i){this.elements.moveAfter(n,r,i)}get(n){const r=this.elements.getByIndex(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.elements.getByID(n);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(n){return this.elements.getPrevCreatedAt(n)}delete(n,r){return this.elements.delete(n,r)}deleteByIndex(n,r){return this.elements.deleteByIndex(n,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const n of this.elements)n.isRemoved()||(yield n.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(n){for(const r of this.elements){const i=r.getValue();if(n(i,this))return;i instanceof vu&&i.getDescendants(n)}}toJSON(){const n=[];for(const r of this)n.push(r.toJSON());return`[${n.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(let r=0;r({...m,value:m.value?{attributes:zc(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[d,g,h,[u,u]]}setStyle(n,r,i,o){const[,a]=this.rgaTreeSplit.findNodeWithSplit(n[1],i),[,s]=this.rgaTreeSplit.findNodeWithSplit(n[0],i),u=[],d=this.rgaTreeSplit.findBetween(s,a),h=new Map,p=[];for(const m of d){const v=m.getCreatedAt().getActorID(),E=o!=null&&o.size?o.has(v)?o.get(v):to:M0;if(m.canStyle(i,E)){const w=h.get(v),C=m.getCreatedAt();(!w||C.after(w))&&h.set(v,C),p.push(m)}}const g=[];for(const m of p){if(m.isRemoved())continue;const[v,E]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());u.push({type:"style",actor:i.getActorID(),from:v,to:E,value:{attributes:zc(r)}});for(const[w,C]of Object.entries(r)){const[b]=m.getValue().setAttr(w,C,i);b!==void 0&&g.push({parent:m.getValue(),child:b})}}return[h,g,u]}indexRangeToPosRange(n,r){const i=this.rgaTreeSplit.indexToPos(n);return n===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const n=[];for(const r of this.rgaTreeSplit)r.isRemoved()||n.push(r.getValue().toJSON());return`[${n.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const n=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();n.push({attributes:zc(i.getAttributes()),content:i.getContent()})}return n}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const n=new Ti(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return n.remove(this.getRemovedAt()),n}findIndexesFromRange(n){return this.rgaTreeSplit.findIndexesFromRange(n)}getGCPairs(){const n=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&n.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())n.push(i)}return n}}class Oh extends so{constructor(n,r,i,o,a,s,u){super(n,u);A(this,"fromPos");A(this,"toPos");A(this,"maxCreatedAtMapByActor");A(this,"content");A(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.content=a,this.attributes=s}static create(n,r,i,o,a,s,u){return new Oh(n,r,i,o,a,s,u)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ti))throw new Y(W.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,o,a]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const s of a)n.registerGCPair(s);return{opInfos:o.map(({from:s,to:u,value:d})=>({type:"edit",from:s,to:u,value:d,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),o=this.content;return`${n}.EDIT(${r},${i},${o})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class _h extends so{constructor(n,r,i,o,a,s){super(n,s);A(this,"fromPos");A(this,"toPos");A(this,"maxCreatedAtMapByActor");A(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.attributes=a}static create(n,r,i,o,a,s){return new _h(n,r,i,o,a,s)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ti))throw new Y(W.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,o,a]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const s of o)n.registerGCPair(s);return{opInfos:a.map(({from:s,to:u,value:d})=>({type:"style",from:s,to:u,value:d,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),o=this.attributes;return`${n}.STYL(${r},${i},${JSON.stringify(o)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const mKe=2,vKe="root",vs="text";function a0(e,t){let n=0;const r=e.children;for(let i=0;i0)throw new Y(W.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let t=this.parent;const n=this.isRemoved?-1:1;for(;t&&(t.size+=this.paddedSize*n,!t.isRemoved);)t=t.parent}updateDescendantsSize(){let t=0;for(const n of this._children){const r=n.updateDescendantsSize();n.isRemoved||(t+=r)}return this.size+=t,this.paddedSize}get isText(){return this.type===vs}get paddedSize(){return this.size+(this.isText?0:mKe)}isAncestorOf(t){return EKe(this,t)}get nextSibling(){const t=this.parent.findOffset(this),n=this.parent.children[t+1];if(n)return n}get prevSibling(){const t=this.parent.findOffset(this),n=this.parent.children[t-1];if(n)return n}splitText(t,n){if(t===0||t===this.size)return;const r=this.value.slice(0,t),i=this.value.slice(t);if(!i.length)return;this.value=r;const o=this.cloneText(t+n);return o.value=i,this.parent.insertAfterInternal(o,this),o}get children(){return this._children.filter(t=>!t.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(t=>t.isText)}append(...t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.push(...t);for(const n of t)n.parent=this,n.updateAncestorsSize()}prepend(...t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.unshift(...t);for(const n of t)n.parent=this}insertBefore(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r),t.updateAncestorsSize()}insertAfter(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1),t.updateAncestorsSize()}insertAt(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,n),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new Y(W.ErrInvalidArgument,"child not found");this._children.splice(n,1),t.parent=void 0}splitElement(t,n){const r=this.cloneElement(n);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,t),o=this.children.slice(t);this._children=i,r._children=o,this.size=this._children.reduce((a,s)=>a+s.paddedSize,0),r.size=r._children.reduce((a,s)=>a+s.paddedSize,0);for(const a of r._children)a.parent=r;return r}insertAfterInternal(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1)}insertAtInternal(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.splice(n,0,t),t.parent=this}findOffset(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");if(t.isRemoved){const n=this._children.indexOf(t);return this.allChildren.splice(0,n).filter(i=>!i.isRemoved).length}return this.children.indexOf(t)}findBranchOffset(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");let n=t;for(;n;){const r=this._children.indexOf(n);if(r!==-1)return r;n=n.parent}return-1}}function EKe(e,t){if(e===t)return!1;for(;t.parent;){if(t.parent===e)return!0;t=t.parent}return!1}var sn=(e=>(e.Start="Start",e.End="End",e.Text="Text",e))(sn||{});function NP(e,t,n,r){if(t>n)throw new Y(W.ErrInvalidArgument,`from is greater than to: ${t} > ${n}`);if(t>e.size)throw new Y(W.ErrInvalidArgument,`from is out of range: ${t} > ${e.size}`);if(n>e.size)throw new Y(W.ErrInvalidArgument,`to is out of range: ${n} > ${e.size}`);if(t===n)return;let i=0;for(const o of e.children){if(t-o.paddedSizeo.size;(o.isText||u)&&r([o,o.isText?"Text":"Start"],d),NP(o,Math.max(0,a),Math.min(s,o.size),r),d&&r([o,"End"],d)}i+=o.paddedSize}}function zP(e,t,n=0){for(const r of e.children)zP(r,t,n+1);t(e,n)}function y1(e,t,n=0){for(const r of e._children)y1(r,t,n+1);t(e,n)}function my(e,t,n=!0){if(t>e.size)throw new Y(W.ErrInvalidArgument,`index is out of range: ${t} > ${e.size}`);if(e.isText)return{node:e,offset:t};let r=0,i=0;for(const o of e.children){if(n&&o.isText&&o.size>=t-i)return my(o,t-i,n);if(t===i)return{node:e,offset:r};if(!n&&o.paddedSize===t-i)return{node:e,offset:r+1};if(o.paddedSize>t-i)return my(o,t-i-1,n);i+=o.paddedSize,r+=1}return{node:e,offset:r}}function HP(e){return e.isText||e.children.length===0?e:HP(e.children[0])}function CKe(e,t){if(e.sizee===t?0:e0)if(n.right)n.right.parent=n,n=n.right;else return n;else if(r<0)if(n.left)n.left.parent=n,n=n.left;else{let i=n.parent,o=n;for(;i&&o===i.left;)o=i,i=i.parent;return i}else return n}}lastEntry(){if(!this.root)return this.root;let t=this.root;for(;t.right;)t=t.right;return t}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(t,n){for(;n;){const r=this.comparator(t,n.key);if(r===0)return n;r<0?n=n.left:r>0&&(n=n.right)}}putInternal(t,n,r){if(!r)return this.counter+=1,new SKe(t,n,!0);const i=this.comparator(t,r.key);return i<0?r.left=this.putInternal(t,n,r.left):i>0?r.right=this.putInternal(t,n,r.right):r.value=n,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(t,n){if(this.comparator(n,t.key)<0)!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeInternal(t.left,n);else{if(this.isRed(t.left)&&(t=this.rotateRight(t)),this.comparator(n,t.key)===0&&!t.right){this.counter-=1;return}if(!this.isRed(t.right)&&!this.isRed(t.right.left)&&(t=this.moveRedRight(t)),this.comparator(n,t.key)===0){this.counter-=1;const r=this.min(t.right);t.value=r.value,t.key=r.key,t.right=this.removeMin(t.right)}else t.right=this.removeInternal(t.right,n)}return this.fixUp(t)}min(t){return t.left?this.min(t.left):t}removeMin(t){if(t.left)return!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeMin(t.left),this.fixUp(t)}fixUp(t){return this.isRed(t.right)&&(t=this.rotateLeft(t)),this.isRed(t.left)&&this.isRed(t.left.left)&&(t=this.rotateRight(t)),this.isRed(t.left)&&this.isRed(t.right)&&this.flipColors(t),t}moveRedLeft(t){return this.flipColors(t),this.isRed(t.right.left)&&(t.right=this.rotateRight(t.right),t=this.rotateLeft(t),this.flipColors(t)),t}moveRedRight(t){return this.flipColors(t),this.isRed(t.left.left)&&(t=this.rotateRight(t),this.flipColors(t)),t}isRed(t){return t&&t.isRed}rotateLeft(t){const n=t.right;return t.right=n.left,n.left=t,n.isRed=n.left.isRed,n.left.isRed=!0,n}rotateRight(t){const n=t.left;return t.left=n.right,n.right=t,n.isRed=n.right.isRed,n.right.isRed=!0,n}flipColors(t){t.isRed=!t.isRed,t.left.isRed=!t.left.isRed,t.right.isRed=!t.right.isRed}}class Xi{constructor(t,n){A(this,"parentID");A(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=n}static of(t,n){return new Xi(t,n)}static fromTreePos(t){const{offset:n}=t;let{node:r}=t,i;return r.isText?(r.parent.children[0]===r&&n===0?i=r.parent:i=r,r=r.parent):n===0?i=r:i=r.children[n-1],Xi.of(r.id,Rn.of(i.getCreatedAt(),i.getOffset()+n))}getParentID(){return this.parentID}static fromStruct(t){return Xi.of(Rn.of(jr.fromStruct(t.parentID.createdAt),t.parentID.offset),Rn.of(jr.fromStruct(t.leftSiblingID.createdAt),t.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(t){const n=this.getParentID(),r=this.getLeftSiblingID(),i=t.findFloorNode(n);let o=t.findFloorNode(r);if(!i||!o)throw new Y(W.ErrRefused,`cannot find node of CRDTTreePos(${n.toTestString()}, ${r.toTestString()})`);return!r.equals(n)&&r.getOffset()>0&&r.getOffset()===o.id.getOffset()&&o.insPrevID&&(o=t.findFloorNode(o.insPrevID)),[i,o]}getLeftSiblingID(){return this.leftSiblingID}equals(t){return this.getParentID().getCreatedAt().equals(t.getParentID().getCreatedAt())&&this.getParentID().getOffset()===t.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(t.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===t.getLeftSiblingID().getOffset()}}class Rn{constructor(t,n){A(this,"createdAt");A(this,"offset");this.createdAt=t,this.offset=n}static of(t,n){return new Rn(t,n)}static fromStruct(t){return Rn.of(jr.fromStruct(t.createdAt),t.offset)}static createComparator(){return(t,n)=>{const r=t.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:t.getOffset()>n.getOffset()?1:t.getOffset(){const o=i.deepcopy();return o.parent=n,o}),n.insPrevID=this.insPrevID,n.insNextID=this.insNextID,n}get value(){if(!this.isText)throw new Y(W.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(n){if(!this.isText)throw new Y(W.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=n,this.size=n.length}get isRemoved(){return!!this.removedAt}remove(n){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(n)>0)&&(this.removedAt=n),r&&this.updateAncestorsSize()}cloneText(n){return new Nr(Rn.of(this.id.getCreatedAt(),n),this.type,void 0,void 0,this.removedAt)}cloneElement(n){return new Nr(Rn.of(n(),0),this.type,void 0,void 0,this.removedAt)}split(n,r,i){const o=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(o){if(o.insPrevID=this.id,this.insNextID){const a=n.findFloorNode(this.insNextID);a.insPrevID=o.id,o.insNextID=this.insNextID}this.insNextID=o.id,n.registerNode(o)}return o}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(n,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}canStyle(n,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}setAttrs(n,r){this.attrs||(this.attrs=new Is);const i=new Array;for(const[o,a]of Object.entries(n))i.push(this.attrs.set(o,a,r));return i}purge(n){this.attrs&&this.attrs.purge(n)}getGCPairs(){const n=[];if(!this.attrs)return n;for(const r of this.attrs)r.getRemovedAt()&&n.push({parent:this,child:r});return n}}function vy(e){var n;if(e.isText){const r=e;return{type:r.type,value:r.value}}const t={type:e.type,children:e.children.map(vy)};return e.attrs&&(t.attributes=zc((n=e.attrs)==null?void 0:n.toObject())),t}function _C(e){if(e.isText)return e.value;let t="";return e.attrs&&e.attrs.size()&&(t=" "+Array.from(e.attrs).filter(n=>!n.isRemoved()).sort((n,r)=>n.getKey().localeCompare(r.getKey())).map(n=>{const r=JSON.parse(n.getValue());return typeof r=="string"?`${n.getKey()}="${r}"`:`${n.getKey()}="${Oo(n.getValue())}"`}).join(" ")),`<${e.type}${t}>${e.children.map(n=>_C(n)).join("")}`}function UP(e){if(e.isText){const t=e;return{type:t.type,value:t.value,size:t.size,isRemoved:t.isRemoved}}return{type:e.type,children:e.children.map(UP),size:e.size,isRemoved:e.isRemoved}}class Pi extends Fh{constructor(n,r){super(r);A(this,"indexTree");A(this,"nodeMapByID");this.indexTree=new bKe(n),this.nodeMapByID=new jP(Rn.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(n,r){return new Pi(n,r)}findFloorNode(n){const r=this.nodeMapByID.floorEntry(n);if(!(!r||!r.key.getCreatedAt().equals(n.getCreatedAt())))return r.value}registerNode(n){this.nodeMapByID.put(n.id,n)}findNodesAndSplitText(n,r){const[i,o]=n.toTreeNodePair(this);let a=o;const s=i===a,u=a.parent&&!s?a.parent:i;if(a.isText&&a.split(this,n.getLeftSiblingID().getOffset()-a.id.getOffset()),r){const d=u.allChildren,h=s?0:d.indexOf(a)+1;for(let p=h;p{const E=v.getCreatedAt().getActorID(),w=o?o.has(E)?o.get(E):to:M0;if(v.canStyle(i,w)&&r){const C=g.get(E),b=v.getCreatedAt();(!C||b.after(C))&&g.set(E,b);const k=v.setAttrs(r,i),I=k.reduce((D,[,$])=>($&&(D[$.getKey()]=p[$.getKey()]),D),{}),B=v.parent,T=v.prevSibling||v.parent;Object.keys(I).length>0&&h.push({type:"style",from:this.toIndex(B,T),to:this.toIndex(v,v),fromPath:this.toPath(B,T),toPath:this.toPath(v,v),actor:i.getActorID(),value:I});for(const[D]of k)D&&m.push({parent:v,child:D})}}),[g,m,h]}removeStyle(n,r,i,o){const[a,s]=this.findNodesAndSplitText(n[0],i),[u,d]=this.findNodesAndSplitText(n[1],i),h=[],p=new Map,g=[];return this.traverseInPosRange(a,s,u,d,([m])=>{const v=m.getCreatedAt().getActorID(),E=o?o.has(v)?o.get(v):to:M0;if(m.canStyle(i,E)&&r){const w=p.get(v),C=m.getCreatedAt();(!w||C.after(w))&&p.set(v,C),m.attrs||(m.attrs=new Is);for(const I of r){const B=m.attrs.remove(I,i);for(const T of B)g.push({parent:m,child:T})}const b=m.parent,k=m.prevSibling||m.parent;h.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(b,k),to:this.toIndex(m,m),fromPath:this.toPath(b,k),toPath:this.toPath(m,m),value:r})}}),[p,g,h]}edit(n,r,i,o,a,s){const[u,d]=this.findNodesAndSplitText(n[0],o),[h,p]=this.findNodesAndSplitText(n[1],o),g=this.toIndex(u,d),m=this.toPath(u,d),v=[],E=[],w=[],C=new Map;this.traverseInPosRange(u,d,h,p,([I,B],T)=>{if(B===sn.Start&&!T)for(const O of I.children)w.push(O);const D=I.getCreatedAt().getActorID(),$=s?s.has(D)?s.get(D):to:M0;if(I.canDelete(o,$)||v.includes(I.parent)){const O=C.get(D),H=I.getCreatedAt();(!O||H.after(O))&&C.set(D,H),(B===sn.Text||B===sn.Start)&&v.push(I),E.push([I,B])}});const b=this.makeDeletionChanges(E,o),k=[];for(const I of v)I.remove(o),I.isRemoved&&k.push({parent:this,child:I});for(const I of w)I.removedAt||u.append(I);if(i>0){let I=0,B=u,T=d;for(;I{u.isRemoved&&(D.remove(o),k.push({parent:this,child:D})),this.nodeMapByID.put(D.id,D)}),T.isRemoved||I.push(T);if(I.length){const T=I.map(D=>vy(D));b.length&&b[b.length-1].from===g?b[b.length-1].value=T:b.push({type:"content",from:g,to:g,fromPath:m,toPath:m,actor:o.getActorID(),value:T})}}return[b,k,C]}editT(n,r,i,o,a){const s=this.findPos(n[0]),u=this.findPos(n[1]);this.edit([s,u],r,i,o,a)}move(n,r,i){throw new Y(W.ErrUnimplemented,`not implemented: ${n}, ${r}, ${i}`)}purge(n){var o;(o=n.parent)==null||o.removeChild(n),this.nodeMapByID.remove(n.id);const r=n.insPrevID,i=n.insNextID;if(r){const a=this.findFloorNode(r);a.insNextID=i}if(i){const a=this.findFloorNode(i);a.insPrevID=r}n.insPrevID=void 0,n.insNextID=void 0}getGCPairs(){const n=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&n.push({parent:this,child:r});for(const i of r.getGCPairs())n.push(i)}),n}findPos(n,r=!0){const i=this.indexTree.findTreePos(n,r);return Xi.fromTreePos(i)}pathToPosRange(n){const r=this.pathToIndex(n);return[this.findPos(r),this.findPos(r+1)]}pathToPos(n){const r=this.indexTree.pathToIndex(n);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return _C(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const n=this.indexTree.getRoot(),r=(i,o=void 0,a=void 0,s=0)=>{var m,v,E,w;let u,d,h;const p=i.isText?{node:i,offset:0}:o&&a?this.toTreePos(o,a):null;p&&(u=this.indexTree.indexOf(p),d=this.indexTree.treePosToPath(p),h=Xi.fromTreePos(p).toStruct());const g={type:i.type,parent:o==null?void 0:o.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(m=i.removedAt)==null?void 0:m.toTestString(),insPrev:(v=i.insPrevID)==null?void 0:v.toTestString(),insNext:(E=i.insNextID)==null?void 0:E.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:s,attributes:i.attrs?zc((w=i.attrs)==null?void 0:w.toObject()):void 0,index:u,path:d,pos:h};for(let C=0;C0&&C===i[i.length-1].to?(i[i.length-1].to=b,i[i.length-1].toPath=this.toPath(w,m)):i.push({type:"content",from:C,to:b,fromPath:this.toPath(E,p),toPath:this.toPath(w,m),actor:r.getActorID()}))}return i.reverse()}findRightToken([n,r]){if(r===sn.Start){const u=n.allChildren;return u.length>0?[u[0],u[0].isText?sn.Text:sn.Start]:[n,sn.End]}const i=n.parent,o=i.allChildren,a=o.indexOf(n);if(i&&a===o.length-1)return[i,sn.End];const s=o[a+1];return[s,s.isText?sn.Text:sn.Start]}findLeftToken([n,r]){if(r===sn.End){const u=n.allChildren;if(u.length>0){const d=u[u.length-1];return[d,d.isText?sn.Text:sn.End]}return[n,sn.Start]}const i=n.parent,o=i.allChildren,a=o.indexOf(n);if(i&&a===0)return[i,sn.Start];const s=o[a-1];return[s,s.isText?sn.Text:sn.End]}}class Nh extends so{constructor(n,r,i,o,a,s,u){super(n,u);A(this,"fromPos");A(this,"toPos");A(this,"contents");A(this,"splitLevel");A(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=o,this.splitLevel=a,this.maxCreatedAtMapByActor=s}static create(n,r,i,o,a,s,u){return new Nh(n,r,i,o,a,s,u)}execute(n){var u;const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Pi))throw new Y(W.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),o=r,[a,s]=o.edit([this.fromPos,this.toPos],(u=this.contents)==null?void 0:u.map(d=>d.deepcopy()),this.splitLevel,i,(()=>{let d=i.getDelimiter();return this.contents!==void 0&&(d+=this.contents.length),()=>jr.of(i.getLamport(),++d,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const d of s)n.registerGCPair(d);return{opInfos:a.map(({from:d,to:h,value:p,splitLevel:g,fromPath:m,toPath:v})=>({type:"tree-edit",path:n.createPath(this.getParentCreatedAt()),from:d,to:h,value:p,splitLevel:g,fromPath:m,toPath:v}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,o=this.contents||[];return`${n}.EDIT(${r},${i},${o.map(a=>_C(a)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Hc{constructor(t){A(this,"vector");this.vector=t||new Map}set(t,n){this.vector.set(t,n)}get(t){return this.vector.get(t)}maxLamport(){let t=BigInt(0);for(const[,n]of this)n>t&&(t=n);return t}max(t){const n=new Map;for(const[r,i]of t){const o=this.vector.get(r),a=o&&o>i?o:i;n.set(r,a)}for(const[r,i]of this){const o=t.get(r),a=o&&o>i?o:i;n.set(r,a)}return new Hc(n)}afterOrEqual(t){const n=this.vector.get(t.getActorID());return n===void 0?!1:n>=t.getLamport()}deepcopy(){const t=new Map;for(const[n,r]of this.vector)t.set(n,r);return new Hc(t)}filter(t){const n=new Map;for(const[r]of t){const i=this.vector.get(r);i!==void 0&&n.set(r,i)}return new Hc(n)}size(){return this.vector.size}*[Symbol.iterator](){for(const[t,n]of this.vector)yield[t,n]}}const AKe=new Hc(new Map);class as{constructor(t,n,r,i,o){A(this,"clientSeq");A(this,"serverSeq");A(this,"lamport");A(this,"actor");A(this,"versionVector");this.clientSeq=t,this.serverSeq=o,this.lamport=n,this.versionVector=i,this.actor=r}static of(t,n,r,i,o){return new as(t,n,r,i,o)}next(){const t=this.versionVector.deepcopy();return t.set(this.actor,this.lamport+1n),new as(this.clientSeq+1,this.lamport+1n,this.actor,t)}syncClocks(t){const n=t.lamport>this.lamport?t.lamport+1n:this.lamport+1n,r=this.versionVector.max(t.versionVector),i=new as(this.clientSeq,n,this.actor,r);return i.versionVector.set(this.actor,n),i}setClocks(t,n){const r=t>this.lamport?t:this.lamport+1n,i=this.versionVector.max(n);return i.set(this.actor,r),as.of(this.clientSeq,r,this.actor,i)}createTimeTicket(t){return jr.of(this.lamport,t,this.actor)}setActor(t){return new as(this.clientSeq,this.lamport,t,this.versionVector,this.serverSeq)}setVersionVector(t){return new as(this.clientSeq,this.lamport,this.actor,t,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const kKe=new as(0,0n,FC,AKe);class cd{constructor({id:t,operations:n,presenceChange:r,message:i}){A(this,"id");A(this,"operations");A(this,"presenceChange");A(this,"message");this.id=t,this.operations=n||[],this.presenceChange=r,this.message=i}static create({id:t,operations:n,presenceChange:r,message:i}){return new cd({id:t,operations:n,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(t){for(const n of this.operations)n.setActor(t);this.id=this.id.setActor(t)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(t,n,r){const i=[],o=[];for(const a of this.operations){const s=a.execute(t,r);if(!s)continue;const{opInfos:u,reverseOp:d}=s;i.push(...u),d&&o.unshift(d)}return this.presenceChange&&(this.presenceChange.type===Iu.Put?n.set(this.id.getActorID(),Gi(this.presenceChange.presence)):n.delete(this.id.getActorID())),{opInfos:i,reverseOps:o}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:rn.bytesToHex(rn.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>rn.bytesToHex(rn.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:n,operations:r,presenceChange:i,message:o}=t;return cd.create({id:rn.bytesToChangeID(rn.hexToBytes(n)),operations:r==null?void 0:r.map(a=>rn.bytesToOperation(rn.hexToBytes(a))),presenceChange:i,message:o})}}class E1{constructor(t,n,r,i,o,a,s){A(this,"documentKey");A(this,"checkpoint");A(this,"isRemoved");A(this,"changes");A(this,"snapshot");A(this,"minSyncedTicket");A(this,"versionVector");this.documentKey=t,this.checkpoint=n,this.isRemoved=r,this.changes=i,this.snapshot=a,this.minSyncedTicket=s,this.versionVector=o}static create(t,n,r,i,o,a,s){return new E1(t,n,r,i,o,a,s)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class jc{constructor(t,n){A(this,"serverSeq");A(this,"clientSeq");this.serverSeq=t,this.clientSeq=n}static of(t,n){return new jc(t,n)}increaseClientSeq(t){return t===0?this:new jc(this.serverSeq,this.clientSeq+t)}forward(t){if(this.equals(t))return this;const n=this.serverSeq>t.serverSeq?this.serverSeq:t.serverSeq,r=Math.max(this.clientSeq,t.clientSeq);return jc.of(n,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(t){return this.clientSeq===t.clientSeq&&this.serverSeq==t.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const DKe=new jc(0n,0);class zo{constructor(t,n){A(this,"createdAt");A(this,"offset");this.createdAt=t,this.offset=n}static of(t,n){return new zo(t,n)}static fromStruct(t){return zo.of(jr.fromStruct(t.createdAt),t.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(t){return this.createdAt.compare(t.createdAt)===0&&this.offset===t.offset}hasSameCreatedAt(t){return this.createdAt.compare(t.createdAt)===0}split(t){return new zo(this.createdAt,this.offset+t)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const IKe=zo.of(to,0);class no{constructor(t,n){A(this,"id");A(this,"relativeOffset");this.id=t,this.relativeOffset=n}static of(t,n){return new no(t,n)}static fromStruct(t){const n=zo.fromStruct(t.id);return no.of(n,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return zo.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(t){return this.id.equals(t.id)?this.relativeOffset===t.relativeOffset:!1}}class yu extends RP{constructor(n,r,i){super(r);A(this,"id");A(this,"removedAt");A(this,"prev");A(this,"next");A(this,"insPrev");A(this,"insNext");this.id=n,this.removedAt=i}static create(n,r){return new yu(n,r)}static createComparator(){return(n,r)=>{const i=n.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:n.getOffset()>r.getOffset()?1:n.getOffset()0&&n.getID().getOffset()==t.getOffset()){if(!n.hasInsPrev())return n;n=n.getInsPrev()}return n}findFloorNode(t){const n=this.treeByID.floorEntry(t);if(n&&!(!n.key.equals(t)&&!n.key.hasSameCreatedAt(t)))return n.value}findBetween(t,n){const r=[];let i=t;for(;i&&i!==n;)r.push(i),i=i.getNext();return r}splitNode(t,n){if(n>t.getContentLength())throw new Y(W.ErrInvalidArgument,"offset should be less than or equal to length");if(n===0)return t;if(n===t.getContentLength())return t.getNext();const r=t.split(n);this.treeByIndex.updateWeight(r),this.insertAfter(t,r);const i=t.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(t),r}deleteNodes(t,n,r){if(!t.length)return[[],new Map,new Map];const[i,o]=this.filterNodes(t,n,r),a=new Map,s=new Map,u=this.makeChanges(o,n);for(const d of i){const h=d.getCreatedAt().getActorID();(!a.has(h)||d.getID().getCreatedAt().after(a.get(h)))&&a.set(h,d.getID().getCreatedAt()),s.set(d.getID().toIDString(),d),d.remove(n)}return this.deleteIndexNodes(o),[u,a,s]}filterNodes(t,n,r){const i=!!r,o=[],a=[],[s,u]=this.findEdgesOfCandidates(t);a.push(s);for(const d of t){const h=d.getCreatedAt().getActorID(),p=i?r.has(h)?r.get(h):to:M0;d.canDelete(n,p)?o.push(d):a.push(d)}return a.push(u),[o,a]}findEdgesOfCandidates(t){return[t[0].getPrev(),t[t.length-1].getNext()]}makeChanges(t,n){const r=[];let i,o;for(let a=0;ae<0?Math.ceil(e):Math.floor(e);var Ko=(e=>(e[e.IntegerCnt=0]="IntegerCnt",e[e.LongCnt=1]="LongCnt",e))(Ko||{});class Kr extends Fh{constructor(n,r,i){super(i);A(this,"valueType");A(this,"value");switch(this.valueType=n,n){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=at.fromNumber(r).toInt():this.value=Tx(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=at.fromNumber(r):this.value=r;break;default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}static create(n,r,i){return new Kr(n,r,i)}static valueFromBytes(n,r){switch(n){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return at.fromBytesLE(Array.from(r));default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const n=Kr.create(this.valueType,this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n}getType(){return this.valueType}static getCounterType(n){switch(typeof n){case"object":return n instanceof at?1:void 0;case"number":return n>Math.pow(2,31)-1||n<-Math.pow(2,31)?1:0;default:return}}static isSupport(n){return!!Kr.getCounterType(n)}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===0||n===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(n){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(n),this.valueType===1?this.value=this.value.add(n.getValue()):n.getType()===Cn.Long?this.value=this.value+n.getValue().toInt():this.value=at.fromNumber(this.value+Tx(n.getValue())).toInt(),this}}class hd extends so{constructor(n,r,i){super(n,i);A(this,"value");this.value=r}static create(n,r,i){return new hd(n,r,i)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Kr))throw new Y(W.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,o=this.value.deepcopy();return i.increase(o),{opInfos:[{type:"increase",path:n.createPath(this.getParentCreatedAt()),value:o.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const n=this.value.deepcopy(),i=n.getType()===Cn.Long?n.getValue().multiply(-1):n.getValue()*-1;return hd.create(this.getParentCreatedAt(),Gt.of(i,n.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class ys extends so{constructor(n,r,i,o,a,s,u){super(n,u);A(this,"fromPos");A(this,"toPos");A(this,"maxCreatedAtMapByActor");A(this,"attributes");A(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.attributes=a,this.attributesToRemove=s}static create(n,r,i,o,a,s){return new ys(n,r,i,o,a,new Array,s)}static createTreeRemoveStyleOperation(n,r,i,o,a,s){return new ys(n,r,i,o,new Map,a,s)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Pi))throw new Y(W.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let o,a;if(this.attributes.size){const s={};[...this.attributes].forEach(([u,d])=>s[u]=d),[,a,o]=i.style([this.fromPos,this.toPos],s,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const s=this.attributesToRemove;[,a,o]=i.removeStyle([this.fromPos,this.toPos],s,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const s of a)n.registerGCPair(s);return{opInfos:o.map(({from:s,to:u,value:d,fromPath:h,toPath:p})=>({type:"tree-style",from:s,to:u,value:this.attributes.size?{attributes:d}:{attributesToRemove:d},fromPath:h,toPath:p,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${n}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([o,a])=>`${o}:"${a}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function TKe(e){const t=new RC,n=t.data;for(const[r,i]of Object.entries(e))n[r]=JSON.stringify(i);return t}function PKe(e){if(e.type===Iu.Put)return new uh({type:Il.PUT,presence:TKe(e.presence)});if(e.type===Iu.Clear)return new uh({type:Il.CLEAR});throw new Y(W.ErrUnimplemented,"unimplemented type")}function BKe(e){return new BP({serverSeq:e.getServerSeq(),clientSeq:e.getClientSeq()})}function KP(e){return new m1({clientSeq:e.getClientSeq(),lamport:e.getLamport(),actorId:YC(e.getActorID()),versionVector:NC(e.getVersionVector())})}function Te(e){if(e)return new De({lamport:e.getLamport(),delimiter:e.getDelimiter(),actorId:YC(e.getActorID())})}function NC(e){if(!e)return;const t=new v1;for(const[n,r]of e)t.vector[n]=BigInt(r.toString());return t}function VP(e){switch(e){case Cn.Null:return Ve.NULL;case Cn.Boolean:return Ve.BOOLEAN;case Cn.Integer:return Ve.INTEGER;case Cn.Long:return Ve.LONG;case Cn.Double:return Ve.DOUBLE;case Cn.String:return Ve.STRING;case Cn.Bytes:return Ve.BYTES;case Cn.Date:return Ve.DATE;default:throw new Y(W.ErrInvalidType,`unsupported type: ${e}`)}}function GP(e){switch(e){case Ko.IntegerCnt:return Ve.INTEGER_CNT;case Ko.LongCnt:return Ve.LONG_CNT;default:throw new Y(W.ErrInvalidType,`unsupported type: ${e}`)}}function t2(e){if(e instanceof wr)return new ci({type:Ve.JSON_OBJECT,createdAt:Te(e.getCreatedAt()),value:oB(e)});if(e instanceof Ur)return new ci({type:Ve.JSON_ARRAY,createdAt:Te(e.getCreatedAt()),value:uVe(e)});if(e instanceof Ti)return new ci({type:Ve.TEXT,createdAt:Te(e.getCreatedAt())});if(e instanceof Gt)return new ci({type:VP(e.getType()),createdAt:Te(e.getCreatedAt()),value:e.toBytes()});if(e instanceof Kr)return new ci({type:GP(e.getType()),createdAt:Te(e.getCreatedAt()),value:e.toBytes()});if(e instanceof Pi)return new ci({type:Ve.TREE,createdAt:Te(e.getCreatedAt()),value:cVe(e)});throw new Y(W.ErrUnimplemented,"unimplemented element")}function MKe(e){return new ah({createdAt:Te(e.getCreatedAt()),offset:e.getOffset()})}function bp(e){return new Ds({createdAt:Te(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function wp(e){return new Dl({parentId:$0(e.getParentID()),leftSiblingId:$0(e.getLeftSiblingID())})}function $0(e){return new mu({createdAt:Te(e.getCreatedAt()),offset:e.getOffset()})}function JP(e){const t=new $C;if(e instanceof Tl){const n=e,r=new Hg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.key=n.getKey(),r.value=t2(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof Lh){const n=e,r=new jg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.prevCreatedAt=Te(n.getPrevCreatedAt()),r.value=t2(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof au){const n=e,r=new Ug;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.prevCreatedAt=Te(n.getPrevCreatedAt()),r.createdAt=Te(n.getCreatedAt()),r.executedAt=Te(n.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof Tu){const n=e,r=new Kg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.createdAt=Te(n.getCreatedAt()),r.executedAt=Te(n.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof Oh){const n=e,r=new Vg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=bp(n.getFromPos()),r.to=bp(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=Te(s);r.content=n.getContent();const o=r.attributes;for(const[a,s]of n.getAttributes())o[a]=s;r.executedAt=Te(n.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof _h){const n=e,r=new Gg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=bp(n.getFromPos()),r.to=bp(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=Te(s);const o=r.attributes;for(const[a,s]of n.getAttributes())o[a]=s;r.executedAt=Te(n.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof hd){const n=e,r=new Jg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.value=t2(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof Nh){const n=e,r=new Wg,i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=Te(a);r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=wp(n.getFromPos()),r.to=wp(n.getToPos()),r.contents=NKe(n.getContents()),r.splitLevel=n.getSplitLevel(),r.executedAt=Te(n.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof ys){const n=e,r=new Yg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=wp(n.getFromPos()),r.to=wp(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=Te(s);const o=n.getAttributesToRemove();if(o.length>0)r.attributesToRemove=o;else{const a=r.attributes;for(const[s,u]of n.getAttributes())a[s]=u}r.executedAt=Te(n.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new Y(W.ErrUnimplemented,"unimplemented operation");return t}function $Ke(e){const t=[];for(const n of e)t.push(JP(n));return t}function RKe(e){const t=new TP({id:KP(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=$Ke(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=PKe(e.getPresenceChange())),t}function FKe(e){const t=[];for(const n of e)t.push(RKe(n));return t}function LKe(e){const t=[];for(const n of e)t.push(new PP({key:n.getStrKey(),element:HC(n.getValue())}));return t}function OKe(e){const t=[];for(const n of e)t.push(new nm({element:HC(n.getValue())}));return t}function _Ke(e){const t=[];for(const n of e){const r=new rm;r.id=MKe(n.getID()),r.value=n.getValue().getContent(),r.removedAt=Te(n.getRemovedAt());const i=r.attributes,o=n.getValue().getAttrs();for(const a of o){const s=new sd;s.value=a.getValue(),s.updatedAt=Te(a.getUpdatedAt()),i[a.getKey()]=s}t.push(r)}return t}function NKe(e){const t=[];if(!e||!e.length)return t;for(const n of e)t.push(new im({content:zC(n)}));return t}function zKe(e){const t={};for(const n of e)t[n.getKey()]=new sd({value:n.getValue(),updatedAt:Te(n.getUpdatedAt()),isRemoved:n.isRemoved()});return t}function zC(e){if(!e)return[];const t=[];return y1(e,(n,r)=>{const i=new sh({id:$0(n.id),type:n.type,removedAt:Te(n.removedAt),depth:r});n.isText&&(i.value=n.value),n.insPrevID&&(i.insPrevId=$0(n.insPrevID)),n.insNextID&&(i.insNextId=$0(n.insNextID)),n.attrs&&(i.attributes=zKe(n.attrs)),t.push(i)}),t}function HKe(e){const t=new Sr;return t.body.case="jsonObject",t.body.value=new qg({nodes:LKe(e.getRHT()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function WP(e){const t=new Sr;return t.body.case="jsonArray",t.body.value=new Xg({nodes:OKe(e.getElements()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function jKe(e){const t=new Sr;return t.body.case="primitive",t.body.value=new Zg({type:VP(e.getType()),value:e.toBytes(),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function UKe(e){const t=new Sr;return t.body.case="text",t.body.value=new Qg({nodes:_Ke(e.getRGATreeSplit()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function KKe(e){const t=new Sr;return t.body.case="counter",t.body.value=new em({type:GP(e.getType()),value:e.toBytes(),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function YP(e){const t=new Sr;return t.body.case="tree",t.body.value=new tm({nodes:zC(e.getRoot()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function HC(e){if(e instanceof wr)return HKe(e);if(e instanceof Ur)return WP(e);if(e instanceof Gt)return jKe(e);if(e instanceof Ti)return UKe(e);if(e instanceof Kr)return KKe(e);if(e instanceof Pi)return YP(e);throw new Y(W.ErrUnimplemented,"unimplemented element")}function VKe(e){return new Rs({documentKey:e.getDocumentKey(),checkpoint:BKe(e.getCheckpoint()),isRemoved:e.getIsRemoved(),changes:FKe(e.getChanges()),snapshot:e.getSnapshot(),versionVector:NC(e.getVersionVector()),minSyncedTicket:Te(e.getMinSyncedTicket())})}function Px(e){const t=e.findDetails(sKe);for(const n of t)if(n.metadata.code)return n.metadata.code;return""}function qP(e){return as.of(e.clientSeq,BigInt(e.lamport),JC(e.actorId),jC(e.versionVector),BigInt(e.serverSeq))}function jC(e){if(!e)return;const t=new Hc;return Object.entries(e.vector).forEach(([n,r])=>{t.set(n,BigInt(r.toString()))}),t}function Pe(e){if(e)return jr.of(BigInt(e.lamport),e.delimiter,JC(e.actorId))}function UC(e){const t={};return Object.entries(e.data).forEach(([n,r])=>{t[n]=JSON.parse(r)}),t}function GKe(e){const t=e.type;if(t===Il.PUT){const n=UC(e.presence);return{type:Iu.Put,presence:n}}if(t===Il.CLEAR)return{type:Iu.Clear};throw new Y(W.ErrInvalidType,`unsupported type: ${t}`)}function JKe(e){const t=new Map;return Object.entries(e).forEach(([n,r])=>{t.set(n,UC(r))}),t}function XP(e){switch(e){case Ve.NULL:return Cn.Null;case Ve.BOOLEAN:return Cn.Boolean;case Ve.INTEGER:return Cn.Integer;case Ve.LONG:return Cn.Long;case Ve.DOUBLE:return Cn.Double;case Ve.STRING:return Cn.String;case Ve.BYTES:return Cn.Bytes;case Ve.DATE:return Cn.Date}throw new Y(W.ErrUnimplemented,`unimplemented value type: ${e}`)}function sm(e){switch(e){case Ve.INTEGER_CNT:return Ko.IntegerCnt;case Ve.LONG_CNT:return Ko.LongCnt}throw new Y(W.ErrUnimplemented,`unimplemented value type: ${e}`)}function n2(e){switch(e.type){case Ve.JSON_OBJECT:return e.value?iB(e.value):wr.create(Pe(e.createdAt));case Ve.JSON_ARRAY:return e.value?sVe(e.value):Ur.create(Pe(e.createdAt));case Ve.TEXT:return Ti.create(dd.create(),Pe(e.createdAt));case Ve.TREE:return lVe(e.value);case Ve.NULL:case Ve.BOOLEAN:case Ve.INTEGER:case Ve.LONG:case Ve.DOUBLE:case Ve.STRING:case Ve.BYTES:case Ve.DATE:return Gt.of(Gt.valueFromBytes(XP(e.type),e.value),Pe(e.createdAt));case Ve.INTEGER_CNT:case Ve.LONG_CNT:return Kr.create(sm(e.type),Kr.valueFromBytes(sm(e.type),e.value),Pe(e.createdAt))}}function Sp(e){return no.of(zo.of(Pe(e.createdAt),e.offset),e.relativeOffset)}function ZP(e){return zo.of(Pe(e.createdAt),e.offset)}function WKe(e){const t=hh.create(e.value);Object.entries(e.attributes).forEach(([r,i])=>{t.setAttr(r,i.value,Pe(i.updatedAt))});const n=yu.create(ZP(e.id),t);return n.remove(Pe(e.removedAt)),n}function dc(e){return Xi.of(R0(e.parentId),R0(e.leftSiblingId))}function R0(e){return Rn.of(Pe(e.createdAt),e.offset)}function YKe(e){if(!e.length)return;const t=[];return e.forEach(n=>{const r=KC(n.content);t.push(r)}),t}function KC(e){if(e.length===0)return;const t=[];for(const i of e)t.push(XKe(i));const n=t[t.length-1],r=new Map;r.set(e[t.length-1].depth,t[t.length-1]);for(let i=t.length-2;i>=0;i--)r.get(e[i].depth-1).prepend(t[i]),r.set(e[i].depth,t[i]);return n.updateDescendantsSize(),Pi.create(n,to).getRoot()}function qKe(e){const t=Is.create();for(const[n,r]of Object.entries(e))t.setInternal(n,r.value,Pe(r.updatedAt),r.isRemoved);return t}function XKe(e){const t=R0(e.id),n=Nr.create(t,e.type),r=Object.entries(e.attributes);return n.isText?n.value=e.value:r.length&&(n.attrs=qKe(e.attributes)),e.insPrevId&&(n.insPrevID=R0(e.insPrevId)),e.insNextId&&(n.insNextID=R0(e.insNextId)),n.removedAt=Pe(e.removedAt),n}function QP(e){if(e.body.case==="set"){const t=e.body.value;return Tl.create(t.key,n2(t.value),Pe(t.parentCreatedAt),Pe(t.executedAt))}else if(e.body.case==="add"){const t=e.body.value;return Lh.create(Pe(t.parentCreatedAt),Pe(t.prevCreatedAt),n2(t.value),Pe(t.executedAt))}else if(e.body.case==="move"){const t=e.body.value;return au.create(Pe(t.parentCreatedAt),Pe(t.prevCreatedAt),Pe(t.createdAt),Pe(t.executedAt))}else if(e.body.case==="remove"){const t=e.body.value;return Tu.create(Pe(t.parentCreatedAt),Pe(t.createdAt),Pe(t.executedAt))}else if(e.body.case==="edit"){const t=e.body.value,n=new Map;Object.entries(t.createdAtMapByActor).forEach(([i,o])=>{n.set(i,Pe(o))});const r=new Map;return Object.entries(t.attributes).forEach(([i,o])=>{r.set(i,o)}),Oh.create(Pe(t.parentCreatedAt),Sp(t.from),Sp(t.to),n,t.content,r,Pe(t.executedAt))}else if(e.body.case==="style"){const t=e.body.value,n=new Map;Object.entries(t.createdAtMapByActor).forEach(([i,o])=>{n.set(i,Pe(o))});const r=new Map;return Object.entries(t.attributes).forEach(([i,o])=>{r.set(i,o)}),_h.create(Pe(t.parentCreatedAt),Sp(t.from),Sp(t.to),n,r,Pe(t.executedAt))}else{if(e.body.case==="select")return;if(e.body.case==="increase"){const t=e.body.value;return hd.create(Pe(t.parentCreatedAt),n2(t.value),Pe(t.executedAt))}else if(e.body.case==="treeEdit"){const t=e.body.value,n=new Map;return Object.entries(t.createdAtMapByActor).forEach(([r,i])=>{n.set(r,Pe(i))}),Nh.create(Pe(t.parentCreatedAt),dc(t.from),dc(t.to),YKe(t.contents),t.splitLevel,n,Pe(t.executedAt))}else if(e.body.case==="treeStyle"){const t=e.body.value,n=new Map,r=t.attributesToRemove,i=new Map;return t!=null&&t.createdAtMapByActor&&Object.entries(t.createdAtMapByActor).forEach(([o,a])=>{i.set(o,Pe(a))}),(r==null?void 0:r.length)>0?ys.createTreeRemoveStyleOperation(Pe(t.parentCreatedAt),dc(t.from),dc(t.to),i,r,Pe(t.executedAt)):(Object.entries(t.attributes).forEach(([o,a])=>{n.set(o,a)}),ys.create(Pe(t.parentCreatedAt),dc(t.from),dc(t.to),i,n,Pe(t.executedAt)))}else throw new Y(W.ErrUnimplemented,"unimplemented operation")}}function ZKe(e){const t=[];for(const n of e){const r=QP(n);r&&t.push(r)}return t}function eB(e){const t=[];for(const n of e)t.push(cd.create({id:qP(n.id),operations:ZKe(n.operations),presenceChange:n.presenceChange?GKe(n.presenceChange):void 0,message:n.message}));return t}function QKe(e){return jc.of(BigInt(e.serverSeq),e.clientSeq)}function eVe(e){return E1.create(e.documentKey,QKe(e.checkpoint),e.isRemoved,eB(e.changes),jC(e.versionVector),e.snapshot,Pe(e.minSyncedTicket))}function tB(e){const t=new lh;for(const r of e.nodes){const i=VC(r.element);t.set(r.key,i,i.getPositionedAt())}const n=new wr(Pe(e.createdAt),t);return n.setMovedAt(Pe(e.movedAt)),n.setRemovedAt(Pe(e.removedAt)),n}function nB(e){const t=new dh;for(const r of e.nodes)t.insert(VC(r.element));const n=new Ur(Pe(e.createdAt),t);return n.setMovedAt(Pe(e.movedAt)),n.setRemovedAt(Pe(e.removedAt)),n}function tVe(e){const t=Gt.of(Gt.valueFromBytes(XP(e.type),e.value),Pe(e.createdAt));return t.setMovedAt(Pe(e.movedAt)),t.setRemovedAt(Pe(e.removedAt)),t}function nVe(e){const t=new dd;let n=t.getHead();for(const i of e.nodes){const o=t.insertAfter(n,WKe(i));i.insPrevId&&o.setInsPrev(t.findNode(ZP(i.insPrevId))),n=o}const r=new Ti(t,Pe(e.createdAt));return r.setMovedAt(Pe(e.movedAt)),r.setRemovedAt(Pe(e.removedAt)),r}function rVe(e){const t=Kr.create(sm(e.type),Kr.valueFromBytes(sm(e.type),e.value),Pe(e.createdAt));return t.setMovedAt(Pe(e.movedAt)),t.setRemovedAt(Pe(e.removedAt)),t}function rB(e){const t=KC(e.nodes);return Pi.create(t,Pe(e.createdAt))}function VC(e){if(e.body.case==="jsonObject")return tB(e.body.value);if(e.body.case==="jsonArray")return nB(e.body.value);if(e.body.case==="primitive")return tVe(e.body.value);if(e.body.case==="text")return nVe(e.body.value);if(e.body.case==="counter")return rVe(e.body.value);if(e.body.case==="tree")return rB(e.body.value);throw new Y(W.ErrUnimplemented,"unimplemented element")}function iVe(e){if(!e)return{root:wr.create(to),presences:new Map};const t=G3.fromBinary(e);return{root:VC(t.root),presences:JKe(t.presences)}}function oVe(e){const t=NC(e);return GC(t.toBinary())}function aVe(e){const t=WC(e),n=v1.fromBinary(t);return jC(n)}function iB(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return tB(t.body.value)}function oB(e){return HC(e).toBinary()}function sVe(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return nB(t.body.value)}function uVe(e){return WP(e).toBinary()}function lVe(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return rB(t.body.value)}function cVe(e){return YP(e).toBinary()}function GC(e){return e?Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function JC(e){return GC(e)}function WC(e){return new Uint8Array(e.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function YC(e){return WC(e)}function dVe(e){const t=m1.fromBinary(e);return qP(t)}function hVe(e){const t=$C.fromBinary(e);return QP(t)}const rn={fromPresence:UC,toChangePack:VKe,fromChangePack:eVe,fromChanges:eB,toTreeNodes:zC,fromTreeNodes:KC,objectToBytes:oB,bytesToObject:iB,bytesToSnapshot:iVe,bytesToHex:GC,hexToBytes:WC,toHexString:JC,toUint8Array:YC,toOperation:JP,toChangeID:KP,PbChangeID:m1,bytesToChangeID:dVe,bytesToOperation:hVe,versionVectorToHex:oVe,hexToVersionVector:aVe};var or=(e=>(e[e.Trivial=0]="Trivial",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warn=3]="Warn",e[e.Error=4]="Error",e[e.Fatal=5]="Fatal",e))(or||{});let tl=3;function aB(e){tl=e}const $e={trivial:(...e)=>{tl>0||typeof console<"u"&&console.log("YORKIE T:",...e)},debug:(...e)=>{tl>1||typeof console<"u"&&console.log("YORKIE D:",...e)},info:(...e)=>{tl>2||typeof console<"u"&&console.log("YORKIE I:",...e)},warn:(...e)=>{tl>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...e):console.log("YORKIE W:",...e))},error:(...e)=>{tl>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...e):console.log("YORKIE E:",...e))},fatal:(...e)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...e):console.log("YORKIE F:",...e))},isEnabled:e=>tl<=e};function sB(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}class fVe{constructor(t,n,r,i,o){A(this,"reconnectStreamDelay");A(this,"doc");A(this,"docID");A(this,"syncMode");A(this,"remoteChangeEventReceived");A(this,"watchStream");A(this,"watchLoopTimerID");A(this,"watchAbortController");A(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=t,this.doc=n,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=o}changeSyncMode(t){this.syncMode=t}needRealtimeSync(){return this.syncMode===Yp.RealtimeSyncOff?!1:this.syncMode===Yp.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Yp.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(t){const n=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await t(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(n,this.reconnectStreamDelay)})}catch{}};await n()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const r2=()=>{};class pVe{constructor(t){A(this,"finalized",!1);A(this,"observers",[]);A(this,"finalError");try{t(this)}catch(n){this.error(n)}}next(t){this.forEachObserver(n=>{n.next(t)})}error(t){this.forEachObserver(n=>{n.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,n,r){let i;if(!t)throw new Y(W.ErrInvalidArgument,"missing observer");if(this.finalized)throw new Y(W.ErrRefused,"observable is finalized due to previous error");typeof t=="object"?i=t:i={next:t,error:n,complete:r},i.next===void 0&&(i.next=r2),i.error===void 0&&(i.error=r2),i.complete===void 0&&(i.complete=r2);const o=sB(),a=this.unsubscribeOne.bind(this,o);if(this.observers.push({subscriptionID:o,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(s){$e.warn(s)}return a}unsubscribeOne(t){var n;this.observers=(n=this.observers)==null?void 0:n.filter(r=>r.subscriptionID!==t)}forEachObserver(t){if(!this.finalized)for(let n=0;nt}}class Tc{constructor(t,n,r,i){A(this,"id");A(this,"delimiter");A(this,"message");A(this,"root");A(this,"operations");A(this,"presenceChange");A(this,"previousPresence");A(this,"reversePresenceKeys");this.id=t,this.delimiter=$P,this.root=n,this.operations=[],this.previousPresence=Gi(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(t,n,r,i){return new Tc(t,n,r,i)}push(t){this.operations.push(t)}registerElement(t,n){this.root.registerElement(t,n)}registerRemovedElement(t){this.root.registerRemovedElement(t)}registerGCPair(t){this.root.registerGCPair(t)}getChange(){return cd.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(t){this.presenceChange=t}setReversePresence(t,n){for(const r of Object.keys(t))n!=null&&n.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const t={};for(const n of this.reversePresenceKeys)t[n]=this.previousPresence[n];return t}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class fh{constructor(t){A(this,"rootObject");A(this,"elementPairMapByCreatedAt");A(this,"gcElementSetByCreatedAt");A(this,"gcPairMap");this.rootObject=t,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(t,void 0),t.getDescendants(n=>{if(n.getRemovedAt()&&this.registerRemovedElement(n),n instanceof Ti||n instanceof Pi)for(const r of n.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new fh(wr.create(to))}findByCreatedAt(t){const n=this.elementPairMapByCreatedAt.get(t.toIDString());if(n)return n.element}findElementPairByCreatedAt(t){return this.elementPairMapByCreatedAt.get(t.toIDString())}createSubPaths(t){let n=this.elementPairMapByCreatedAt.get(t.toIDString());if(!n)return[];const r=[];for(;n.parent;){const i=n.element.getCreatedAt(),o=n.parent.subPathOf(i);if(o===void 0)throw new Y(W.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(o),n=this.elementPairMapByCreatedAt.get(n.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(t){return this.createSubPaths(t).join(".")}registerElement(t,n){this.elementPairMapByCreatedAt.set(t.getCreatedAt().toIDString(),{parent:n,element:t}),t instanceof vu&&t.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(t){let n=0;const r=i=>{const o=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(o),this.gcElementSetByCreatedAt.delete(o),n++};return r(t),t instanceof vu&&t.getDescendants(i=>(r(i),!1)),n}registerRemovedElement(t){this.gcElementSetByCreatedAt.add(t.getCreatedAt().toIDString())}registerGCPair(t){if(this.gcPairMap.get(t.child.toIDString())){this.gcPairMap.delete(t.child.toIDString());return}this.gcPairMap.set(t.child.toIDString(),t)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const t=new Set;for(const n of this.gcElementSetByCreatedAt){t.add(n);const r=this.elementPairMapByCreatedAt.get(n);r.element instanceof vu&&r.element.getDescendants(i=>(t.add(i.getCreatedAt().toIDString()),!1))}return t.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new fh(this.rootObject.deepcopy())}garbageCollect(t){let n=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r),o=i.element.getRemovedAt();o&&(t!=null&&t.afterOrEqual(o))&&(i.parent.purge(i.element),n+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i&&(t!=null&&t.afterOrEqual(i))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),n+=1)}return n}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function uB(e,t){const n=new ph(e);return new Proxy(t,n.getHandlers())}class ph{constructor(t){A(this,"context");A(this,"handlers");this.context=t,this.handlers={set:(n,r,i)=>($e.isEnabled(or.Trivial)&&$e.trivial(`obj[${r}]=${JSON.stringify(i)}`),ph.setInternal(t,n,r,i),!0),get:(n,r)=>($e.isEnabled(or.Trivial)&&$e.trivial(`obj[${r}]`),r==="getID"?()=>n.getCreatedAt():r==="toJSON"||r==="toString"?()=>n.toJSON():r==="toJS"?()=>n.toJS():r==="toJSForTest"?()=>n.toJSForTest():nl(t,n.get(r))),ownKeys:n=>n.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(n,r)=>($e.isEnabled(or.Trivial)&&$e.trivial(`obj[${r}]`),ph.deleteInternal(t,n,r),!0)}}static setInternal(t,n,r,i){if(r.includes("."))throw new Y(W.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),a=um(t,i,o),s=n.set(r,a,o);t.registerElement(a,n),s&&t.registerRemovedElement(s),t.push(Tl.create(r,a.deepcopy(),n.getCreatedAt(),o))}static buildObjectMembers(t,n){const r={};for(const[i,o]of Object.entries(n)){if(i.includes("."))throw new Y(W.ErrInvalidObjectKey,"key must not contain the '.'.");const a=t.issueTimeTicket(),s=um(t,o,a);r[i]=s}return r}static deleteInternal(t,n,r){const i=t.issueTimeTicket(),o=n.deleteByKey(r,i);o&&(t.push(Tu.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o))}getHandlers(){return this.handlers}}function mVe(e,t){const n=new qt(e,t);return new Proxy(t,n.getHandlers())}function vVe(e){return typeof e=="string"||e instanceof String?!isNaN(e):!1}function yVe(e){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(e)}class qt{constructor(t,n){A(this,"context");A(this,"handlers");A(this,"array");this.context=t,this.array=n,this.handlers={get:(r,i,o)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?a=>{const s=r.getByID(a);if(!(!s||s.isRemoved()))return Xs(t,s)}:i==="getElementByIndex"?a=>{const s=r.get(a);return Xs(t,s)}:i==="getLast"?()=>Xs(t,r.getLast()):i==="deleteByID"?a=>{const s=qt.deleteInternalByID(t,r,a);return Xs(t,s)}:i==="insertAfter"?(a,s)=>{const u=qt.insertAfterInternal(t,r,a,s);return Xs(t,u)}:i==="insertBefore"?(a,s)=>{const u=qt.insertBeforeInternal(t,r,a,s);return Xs(t,u)}:i==="moveBefore"?(a,s)=>{qt.moveBeforeInternal(t,r,a,s)}:i==="moveAfter"?(a,s)=>{qt.moveAfterInternal(t,r,a,s)}:i==="moveFront"?a=>{qt.moveFrontInternal(t,r,a)}:i==="moveLast"?a=>{qt.moveLastInternal(t,r,a)}:vVe(i)?nl(t,r.get(Number(i))):i==="push"?a=>qt.pushInternal(t,r,a):i==="splice"?(a,s,...u)=>qt.splice(t,r,a,s,...u):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?qt.iteratorInternal.bind(this,t,r):i==="includes"?(a,s)=>qt.includes(t,r,a,s):i==="indexOf"?(a,s)=>qt.indexOf(t,r,a,s):i==="lastIndexOf"?(a,s)=>qt.lastIndexOf(t,r,a,s):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>qt.toTestString(r):typeof i=="string"&&yVe(i)?(...a)=>{const s=Array.from(r).map(u=>nl(t,u));return Array.prototype[i].apply(s,a)}:Reflect.get(r,i,o),deleteProperty:(r,i)=>($e.isEnabled(or.Trivial)&&$e.trivial(`array[${i}]`),qt.deleteInternalByIndex(t,r,Number.parseInt(i)),!0)}}static*iteratorInternal(t,n){for(const r of n)yield Xs(t,r)}static buildArrayElements(t,n){const r=[];for(const i of n){const o=t.issueTimeTicket(),a=um(t,i,o);r.push(a)}return r}static pushInternal(t,n,r){return qt.insertAfterInternal(t,n,n.getLastCreatedAt(),r),n.length}static moveBeforeInternal(t,n,r,i){const o=t.issueTimeTicket(),a=n.getPrevCreatedAt(r);n.moveAfter(a,i,o),t.push(au.create(n.getCreatedAt(),a,i,o))}static moveAfterInternal(t,n,r,i){const o=t.issueTimeTicket();n.moveAfter(r,i,o),t.push(au.create(n.getCreatedAt(),r,i,o))}static moveFrontInternal(t,n,r){const i=t.issueTimeTicket(),o=n.getHead();n.moveAfter(o.getCreatedAt(),r,i),t.push(au.create(n.getCreatedAt(),o.getCreatedAt(),r,i))}static moveLastInternal(t,n,r){const i=t.issueTimeTicket(),o=n.getLastCreatedAt();n.moveAfter(o,r,i),t.push(au.create(n.getCreatedAt(),o,r,i))}static insertAfterInternal(t,n,r,i){const o=t.issueTimeTicket(),a=um(t,i,o);return n.insertAfter(r,a),t.registerElement(a,n),t.push(Lh.create(n.getCreatedAt(),r,a.deepcopy(),o)),a}static insertBeforeInternal(t,n,r,i){return qt.insertAfterInternal(t,n,n.getPrevCreatedAt(r),i)}static deleteInternalByIndex(t,n,r){const i=t.issueTimeTicket(),o=n.deleteByIndex(r,i);if(o)return t.push(Tu.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o),o}static deleteInternalByID(t,n,r){const i=t.issueTimeTicket(),o=n.delete(r,i);return t.push(Tu.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o),o}static splice(t,n,r,i,...o){const a=n.length,s=r>=0?Math.min(r,a):Math.max(a+r,0),u=i===void 0?a:i<0?s:Math.min(s+i,a),d=[];for(let h=s;h=o)return!1;if(Gt.isSupport(r))return Array.from(n).map(d=>nl(t,d)).includes(r,a);for(let u=a;u=o)return-1;if(Gt.isSupport(r))return Array.from(n).map(d=>nl(t,d)).indexOf(r,a);for(let u=a;u=o?o-1:i<0?i+o:i;if(a<0)return-1;if(Gt.isSupport(r))return Array.from(n).map(d=>nl(t,d)).lastIndexOf(r,a);for(let u=a;u>0;u--)if(((s=n.get(u))==null?void 0:s.getID())===r.getID())return u;return-1}static toTestString(t){return t.toTestString()}getHandlers(){return this.handlers}}class C1{constructor(t,n){A(this,"context");A(this,"text");this.context=t,this.text=n}initialize(t,n){this.context=t,this.text=n}getID(){return this.text.getID()}edit(t,n,r,i){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.text.indexRangeToPosRange(t,n);$e.isEnabled(or.Debug)&&$e.debug(`EDIT: f:${t}->${o[0].toTestString()}, t:${n}->${o[1].toTestString()} c:${r}`);const a=i?ud(i):void 0,s=this.context.issueTimeTicket(),[u,,d,h]=this.text.edit(o,r,s,a);for(const p of d)this.context.registerGCPair(p);return this.context.push(new Oh(this.text.getCreatedAt(),o[0],o[1],u,r,a?new Map(Object.entries(a)):new Map,s)),this.text.findIndexesFromRange(h)}delete(t,n){return this.edit(t,n,"")}empty(){return this.edit(0,this.length,"")}setStyle(t,n,r){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(t,n);$e.isEnabled(or.Debug)&&$e.debug(`STYL: f:${t}->${i[0].toTestString()}, t:${n}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const o=ud(r),a=this.context.issueTimeTicket(),[s,u]=this.text.setStyle(i,o,a);for(const d of u)this.context.registerGCPair(d);return this.context.push(new _h(this.text.getCreatedAt(),i[0],i[1],s,new Map(Object.entries(o)),a)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");const n=this.text.indexRangeToPosRange(t[0],t[1]);return[n[0].toStruct(),n[1].toStruct()]}posRangeToIndexRange(t){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");const n=this.text.findIndexesFromRange([no.fromStruct(t[0]),no.fromStruct(t[1])]);return[n[0],n[1]]}toTestString(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,n){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,n)}}class b1{constructor(t,n){A(this,"valueType");A(this,"value");A(this,"context");A(this,"counter");this.valueType=t,this.value=n}initialize(t,n){this.valueType=n.getValueType(),this.context=t,this.counter=n,this.value=n.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(t){if(!this.context||!this.counter)throw new Y(W.ErrNotInitialized,"Counter is not initialized yet");const n=this.context.issueTimeTicket(),r=Gt.of(t,n);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(hd.create(this.counter.getCreatedAt(),r,n)),this}toJSForTest(){if(!this.context||!this.counter)throw new Y(W.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function qC(e,t,n){const{type:r}=e,i=n.issueTimeTicket();if(r===vs){lB(e);const{value:o}=e,a=Nr.create(Rn.of(i,0),r,o);t.append(a)}else{const{children:o=[]}=e,{attributes:a}=e;let s;if(typeof a=="object"&&!MP(a)){const d=ud(a);s=new Is;for(const[h,p]of Object.entries(d))s.set(h,p,i)}const u=Nr.create(Rn.of(i,0),r,void 0,s);t.append(u);for(const d of o)qC(d,u,n)}}function EVe(e,t){const{type:n}=t,r=e.issueTimeTicket();let i;if(t.type===vs){const{value:o}=t;i=Nr.create(Rn.of(r,0),n,o)}else if(t){const{children:o=[]}=t,{attributes:a}=t;let s;if(typeof a=="object"&&!MP(a)){const u=ud(a);s=new Is;for(const[d,h]of Object.entries(u))s.set(d,h,r)}i=Nr.create(Rn.of(e.issueTimeTicket(),0),n,void 0,s);for(const u of o)qC(u,i,e)}return i}function lB(e){if(!e.value.length)throw new Y(W.ErrInvalidArgument,"text node cannot have empty value");return!0}function Bx(e){if(!e.length)return!0;if(e[0].type===vs)for(const n of e){const{type:r}=n;if(r!==vs)throw new Y(W.ErrInvalidArgument,"element node and text node cannot be passed together");lB(n)}else for(const n of e){const{type:r}=n;if(r===vs)throw new Y(W.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class w1{constructor(t){A(this,"initialRoot");A(this,"context");A(this,"tree");this.initialRoot=t}initialize(t,n){this.context=t,this.tree=n}getID(){return this.tree.getID()}buildRoot(t){if(!this.initialRoot)return Nr.create(Rn.of(t.issueTimeTicket(),0),vKe);const n=Nr.create(Rn.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)qC(r,n,t);return n}getSize(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,n){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(t),o=this.context.issueTimeTicket(),a=n?ud(n):void 0,[s]=this.tree.style([r,i],a,o);this.context.push(ys.create(this.tree.getCreatedAt(),r,i,s,a?new Map(Object.entries(a)):new Map,o))}style(t,n,r){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(n),a=this.context.issueTimeTicket(),s=r?ud(r):void 0,[u,d]=this.tree.style([i,o],s,a);for(const h of d)this.context.registerGCPair(h);this.context.push(ys.create(this.tree.getCreatedAt(),i,o,u,s?new Map(Object.entries(s)):new Map,a))}removeStyle(t,n,r){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(n),a=this.context.issueTimeTicket(),[s,u]=this.tree.removeStyle([i,o],r,a);for(const d of u)this.context.registerGCPair(d);this.context.push(ys.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,o,s,r,a))}editInternal(t,n,r,i=0){var d;if(r.length!==0&&r[0]&&(Bx(r),r[0].type!==vs))for(const h of r){const{children:p=[]}=h;Bx(p)}const o=this.context.getLastTimeTicket();let a=new Array;if(((d=r[0])==null?void 0:d.type)===vs){let h="";for(const p of r){const{value:g}=p;h+=g}a.push(Nr.create(Rn.of(this.context.issueTimeTicket(),0),vs,h))}else a=r.map(h=>h&&EVe(this.context,h)).filter(h=>h);const[,s,u]=this.tree.edit([t,n],a.length?a.map(h=>h==null?void 0:h.deepcopy()):void 0,i,o,()=>this.context.issueTimeTicket());for(const h of s)this.context.registerGCPair(h);return this.context.push(Nh.create(this.tree.getCreatedAt(),t,n,a.length?a:void 0,i,u,o)),!0}editByPath(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==n.length)throw new Y(W.ErrInvalidArgument,"path length should be equal");if(!t.length||!n.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),a=this.tree.pathToPos(n);return this.editInternal(o,a,r?[r]:[],i)}editBulkByPath(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==n.length)throw new Y(W.ErrInvalidArgument,"path length should be equal");if(!t.length||!n.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),a=this.tree.pathToPos(n);return this.editInternal(o,a,r,i)}edit(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),a=this.tree.findPos(n);return this.editInternal(o,a,r?[r]:[],i)}editBulk(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),a=this.tree.findPos(n);return this.editInternal(o,a,r,i)}toXML(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[this.tree.pathToIndex(t[0]),this.tree.pathToIndex(t[1])],r=this.tree.indexRangeToPosRange(n);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[Xi.fromStruct(t[0]),Xi.fromStruct(t[1])];return this.tree.posRangeToIndexRange(n)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[Xi.fromStruct(t[0]),Xi.fromStruct(t[1])];return this.tree.posRangeToPathRange(n)}}function Mx(e,t){return uB(e,t)}function Xs(e,t){if(t){if(t instanceof Gt)return t;if(t instanceof wr)return uB(e,t);if(t instanceof Ur)return mVe(e,t);if(t instanceof Ti)return new C1(e,t);if(t instanceof Kr){const n=new b1(Ko.IntegerCnt,0);return n.initialize(e,t),n}else if(t instanceof Pi){const n=new w1;return n.initialize(e,t),n}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function nl(e,t){const n=Xs(e,t);return n instanceof Gt?n.getValue():n}function um(e,t,n){let r;if(Gt.isSupport(t))r=Gt.of(t,n);else if(Array.isArray(t))r=Ur.create(n,qt.buildArrayElements(e,t));else if(typeof t=="object")t instanceof C1?(r=Ti.create(dd.create(),n),t.initialize(e,r)):t instanceof b1?(r=Kr.create(t.getValueType(),t.getValue(),n),t.initialize(e,r)):t instanceof w1?(r=Pi.create(t.buildRoot(e),n),t.initialize(e,r)):r=wr.create(n,ph.buildObjectMembers(e,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return r}const $x=50;class CVe{constructor(){A(this,"undoStack",[]);A(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=$x&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=$x&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const bVe="yorkie-devtools-panel",wVe="yorkie-devtools-sdk";let fc="disconnected";const Rx=new Map,Wp=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Wp);function xp(e,t){(t!=null&&t.force||fc!=="disconnected")&&window.postMessage({source:wVe,...e},"*")}function SVe(e){if(!e.isEnableDevtools()||typeof window>"u"||Rx.has(e.getKey()))return;Wp.set(e.getKey(),[]);const t=e.subscribe("all",n=>{n.some(r=>r.type!==Un.StatusChanged&&r.type!==Un.Snapshot&&r.type!==Un.LocalChange&&r.type!==Un.RemoteChange&&r.type!==Un.Initialized&&r.type!==Un.Watched&&r.type!==Un.Unwatched&&r.type!==Un.PresenceChanged)||(Wp.get(e.getKey()).push(n),fc==="synced"&&xp({msg:"doc::sync::partial",docKey:e.getKey(),event:n}))});Rx.set(e.getKey(),[t]),xp({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.source)!==bVe)return;switch(n.data.msg){case"devtools::connect":if(fc!=="disconnected")break;fc="connected",xp({msg:"doc::available",docKey:e.getKey()}),$e.info(`[YD] Devtools connected. Doc: ${e.getKey()}`);break;case"devtools::disconnect":fc="disconnected",$e.info(`[YD] Devtools disconnected. Doc: ${e.getKey()}`);break;case"devtools::subscribe":fc="synced",xp({msg:"doc::sync::full",docKey:e.getKey(),events:Wp.get(e.getKey())}),$e.info(`[YD] Devtools subscribed. Doc: ${e.getKey()}`);break}})}var Zs=(e=>(e.Detached="detached",e.Attached="attached",e.Removed="removed",e))(Zs||{}),Un=(e=>(e.StatusChanged="status-changed",e.ConnectionChanged="connection-changed",e.SyncStatusChanged="sync-status-changed",e.Snapshot="snapshot",e.LocalChange="local-change",e.RemoteChange="remote-change",e.Initialized="initialized",e.Watched="watched",e.Unwatched="unwatched",e.PresenceChanged="presence-changed",e.Broadcast="broadcast",e.LocalBroadcast="local-broadcast",e))(Un||{}),yy=(e=>(e.Connected="connected",e.Disconnected="disconnected",e))(yy||{}),Ey=(e=>(e.Synced="synced",e.SyncFailed="sync-failed",e))(Ey||{});class XC{constructor(t,n){A(this,"key");A(this,"status");A(this,"opts");A(this,"changeID");A(this,"checkpoint");A(this,"localChanges");A(this,"root");A(this,"clone");A(this,"eventStream");A(this,"eventStreamObserver");A(this,"onlineClients");A(this,"presences");A(this,"history");A(this,"internalHistory");A(this,"isUpdating");this.opts=n||{},this.key=t,this.status="detached",this.root=fh.create(),this.changeID=kKe,this.checkpoint=DKe,this.localChanges=[],this.eventStream=gVe(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new CVe,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},SVe(this)}update(t,n){if(this.getStatus()==="removed")throw new Y(W.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Tc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},n);try{const o=Mx(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,t(o,new e2(i,this.clone.presences.get(r)))}catch(o){throw this.clone=void 0,o}finally{this.isUpdating=!1}if(i.hasChange()){$e.isEnabled(or.Trivial)&&$e.trivial(`trying to update a local change: ${this.toJSON()}`);const o=i.getChange(),{opInfos:a,reverseOps:s}=o.execute(this.root,this.presences,xt.Local),u=i.getReversePresence();u&&s.push({type:"presence",value:u}),this.localChanges.push(o),s.length>0&&this.internalHistory.pushUndo(s),a.length>0&&this.internalHistory.clearRedo(),this.changeID=o.getID();const d=[];a.length>0&&d.push({type:"local-change",source:xt.Local,value:{message:o.getMessage()||"",operations:a,actor:r,clientSeq:o.getID().getClientSeq(),serverSeq:o.getID().getServerSeq()},rawChange:this.isEnableDevtools()?o.toStruct():void 0}),o.hasPresenceChange()&&d.push({type:"presence-changed",source:xt.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(d),$e.isEnabled(or.Trivial)&&$e.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,n,r,i){if(typeof t=="string"){if(typeof n!="function")throw new Y(W.ErrInvalidArgument,"Second argument must be a callback function");if(t==="presence"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="initialized"&&d.type!=="watched"&&d.type!=="unwatched"&&d.type!=="presence-changed"||s(d)},r,i)}if(t==="my-presence"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="initialized"&&d.type!=="presence-changed"||d.type==="presence-changed"&&d.value.clientID!==this.changeID.getActorID()||s(d)},r,i)}if(t==="others"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="watched"&&d.type!=="unwatched"&&d.type!=="presence-changed"||d.value.clientID!==this.changeID.getActorID()&&s(d)},r,i)}if(t==="connection"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="connection-changed"&&s(d)},r,i)}if(t==="status"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="status-changed"&&s(d)},r,i)}if(t==="sync"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="sync-status-changed"&&s(d)},r,i)}if(t==="local-broadcast"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="local-broadcast"&&s(d)},r)}if(t==="broadcast"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="broadcast"&&s(d)},r)}if(t==="all"){const s=n;return this.eventStream.subscribe(s,r,i)}const o=t,a=n;return this.eventStream.subscribe(s=>{for(const u of s){if(u.type!=="local-change"&&u.type!=="remote-change")continue;const d=[];for(const h of u.value.operations)this.isSameElementOrChildOf(h.path,o)&&d.push(h);d.length&&a({...u,value:{...u.value,operations:d}})}},r,i)}if(typeof t=="function"){const o=t,a=n,s=r;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="snapshot"&&d.type!=="local-change"&&d.type!=="remote-change"||o(d)},a,s)}throw new Y(W.ErrInvalidArgument,`"${t}" is not a valid`)}publish(t){this.eventStreamObserver&&this.eventStreamObserver.next(t)}isSameElementOrChildOf(t,n){if(n===t)return!0;const r=t.split(".");return n.split(".").every((o,a)=>o===r[a])}applyChangePack(t){const n=t.hasSnapshot();for(n?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getVersionVector(),t.getSnapshot()):t.hasChanges()&&this.applyChanges(t.getChanges(),xt.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t.getCheckpoint().getClientSeq());)this.localChanges.shift();n&&this.applyChanges(this.localChanges,xt.Remote),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),n||this.garbageCollect(t.getVersionVector()),n||this.filterVersionVector(t.getVersionVector()),t.getIsRemoved()&&this.applyStatus("removed"),$e.isEnabled(or.Trivial)&&$e.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Gi(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),n=this.checkpoint.increaseClientSeq(t.length);return E1.create(this.key,n,!1,t,this.getVersionVector())}setActor(t){for(const n of this.localChanges)n.setActor(t);this.changeID=this.changeID.setActor(t)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const t=Tc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Mx(t,this.clone.root.getObject())}garbageCollect(t){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(t),this.root.garbageCollect(t))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,n,r){const{root:i,presences:o}=rn.bytesToSnapshot(r);this.root=new fh(i),this.presences=o,this.changeID=this.changeID.setClocks(t,n),this.clone=void 0,this.publish([{type:"snapshot",source:xt.Remote,value:{serverSeq:t.toString(),snapshot:this.isEnableDevtools()?rn.bytesToHex(r):void 0,snapshotVector:rn.versionVectorToHex(n)}}])}applyChanges(t,n){$e.isEnabled(or.Debug)&&$e.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),$e.isEnabled(or.Trivial)&&$e.trivial(t.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` -`));for(const r of t)this.applyChange(r,n);$e.isEnabled(or.Debug)&&$e.debug(`after appling ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(t,n){this.ensureClone(),t.execute(this.clone.root,this.clone.presences,n);const r=[],i=t.getID().getActorID();if(t.hasPresenceChange()&&this.onlineClients.has(i)){const a=t.getPresenceChange();switch(a.type){case Iu.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:n,value:{clientID:i,presence:a.presence}}:{type:"watched",source:xt.Remote,value:{clientID:i,presence:a.presence}});break;case Iu.Clear:r.push({type:"unwatched",source:xt.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:o}=t.execute(this.root,this.presences,n);if(this.changeID=this.changeID.syncClocks(t.getID()),o.length>0){const a=this.isEnableDevtools()?t.toStruct():void 0;r.push(n===xt.Remote?{type:"remote-change",source:n,value:{actor:i,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:a}:{type:"local-change",source:n,value:{actor:i,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:a})}r.length>0&&this.publish(r)}applyWatchStream(t){if(t.body.case==="initialization"){const n=t.body.value.clientIds,r=new Set;for(const i of n)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:xt.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:n,publisher:r}=t.body.value,i=[];if(n===ml.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:xt.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(n===ml.DOCUMENT_UNWATCHED){const o=this.getPresence(r);this.removeOnlineClient(r),o&&i.push({type:"unwatched",source:xt.Remote,value:{clientID:r,presence:o}})}else if(n===ml.DOCUMENT_BROADCAST&&t.body.value.body){const{topic:o,payload:a}=t.body.value.body,s=new TextDecoder;i.push({type:"broadcast",value:{clientID:r,topic:o,payload:JSON.parse(s.decode(a))}})}i.length>0&&this.publish(i)}}applyStatus(t){this.status=t,t==="detached"&&this.setActor(FC),this.publish([{source:t==="removed"?xt.Remote:xt.Local,type:"status-changed",value:t==="attached"?{status:t,actorID:this.changeID.getActorID()}:{status:t}}])}applyDocEvent(t){if(t.type==="status-changed"){this.applyStatus(t.value.status),t.value.status==="attached"&&this.setActor(t.value.actorID);return}if(t.type==="snapshot"){const{snapshot:n,serverSeq:r,snapshotVector:i}=t.value;if(!n)return;this.applySnapshot(BigInt(r),rn.hexToVersionVector(i),rn.hexToBytes(n));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const n=cd.fromStruct(t.rawChange);this.applyChange(n,t.source)}if(t.type==="initialized"){const n=new Set;for(const{clientID:r,presence:i}of t.value)n.add(r),this.presences.set(r,i);this.setOnlineClients(n);return}if(t.type==="watched"){const{clientID:n,presence:r}=t.value;this.addOnlineClient(n),this.presences.set(n,r);return}if(t.type==="unwatched"){const{clientID:n}=t.value;this.removeOnlineClient(n),this.presences.delete(n)}if(t.type==="presence-changed"){const{clientID:n,presence:r}=t.value;this.presences.set(n,r)}}applyTransactionEvent(t){for(const n of t)this.applyDocEvent(n)}getValueByPath(t){if(!t.startsWith("$"))throw new Y(W.ErrInvalidArgument,'path must start with "$"');const n=t.split(".");n.shift();let r=this.getRoot();for(const i of n)if(r=r[i],r===void 0)return;return r}setOnlineClients(t){this.onlineClients=t}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(t){this.onlineClients.add(t)}removeOnlineClient(t){this.onlineClients.delete(t)}hasPresence(t){return this.presences.has(t)}getMyPresence(){if(this.status!=="attached")return{};const t=this.presences.get(this.changeID.getActorID());return t?Gi(t):{}}getPresence(t){if(t===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(t))return;const n=this.presences.get(t);return n?Gi(n):void 0}getPresenceForTest(t){const n=this.presences.get(t);return n?Gi(n):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:Gi(this.getMyPresence())});for(const n of this.onlineClients)this.presences.has(n)&&t.push({clientID:n,presence:Gi(this.presences.get(n))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(n=>n.clientID!==t).sort((n,r)=>n.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(t){const r=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new Y(W.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new Y(W.ErrRefused,"There is no operation to be undone");this.ensureClone();const n=Tc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof so)){new e2(n,Gi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const h=n.issueTimeTicket();d.setExecutedAt(h),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,xt.UndoRedo);const{opInfos:i,reverseOps:o}=r.execute(this.root,this.presences,xt.UndoRedo),a=n.getReversePresence();if(a&&o.push({type:"presence",value:a}),o.length>0&&this.internalHistory.pushRedo(o),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const s=this.changeID.getActorID(),u=[];i.length>0&&u.push({type:"local-change",source:xt.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:s,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&u.push({type:"presence-changed",source:xt.UndoRedo,value:{clientID:s,presence:this.getPresence(s)}}),this.publish(u)}redo(){if(this.isUpdating)throw new Y(W.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new Y(W.ErrRefused,"There is no operation to be redone");this.ensureClone();const n=Tc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof so)){new e2(n,Gi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const h=n.issueTimeTicket();d.setExecutedAt(h),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,xt.UndoRedo);const{opInfos:i,reverseOps:o}=r.execute(this.root,this.presences,xt.UndoRedo),a=n.getReversePresence();if(a&&o.push({type:"presence",value:a}),o.length>0&&this.internalHistory.pushUndo(o),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const s=this.changeID.getActorID(),u=[];i.length>0&&u.push({type:"local-change",source:xt.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:s,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&u.push({type:"presence-changed",source:xt.UndoRedo,value:{clientID:s,presence:this.getPresence(s)}}),this.publish(u)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(t,n,r){const i={type:"local-broadcast",value:{topic:t,payload:n},options:r};this.publish([i])}getVersionVector(){return this.changeID.getVersionVector()}}function xVe(e,t){return n=>async r=>(e&&r.header.set("x-api-key",e),t&&r.header.set("authorization",t),await n(r))}const AVe="yorkie-js-sdk",kVe="0.5.4",DVe="Yorkie JS SDK",IVe="./src/yorkie.ts",TVe={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},PVe=["dist"],BVe={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},MVe={node:">=18.0.0",npm:">=7.1.0"},$Ve={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},RVe={name:"hackerwins",email:"susukang98@gmail.com"},FVe="Apache-2.0",LVe={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},OVe="https://github.com/yorkie-team/yorkie-js-sdk#readme",_Ve={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},NVe={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Fx={name:AVe,version:kVe,description:DVe,main:IVe,publishConfig:TVe,files:PVe,scripts:BVe,engines:MVe,repository:$Ve,author:RVe,license:FVe,bugs:LVe,homepage:OVe,devDependencies:_Ve,dependencies:NVe};function zVe(){return e=>async t=>(t.header.set("x-yorkie-user-agent",Fx.name+"/"+Fx.version),await e(t))}const HVe=e=>{try{if(JSON.stringify(e)===void 0)return!1}catch{return!1}return!0};var Yp=(e=>(e.Manual="manual",e.Realtime="realtime",e.RealtimePushOnly="realtime-pushonly",e.RealtimeSyncOff="realtime-syncoff",e))(Yp||{});const Ap={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},i2={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class ZC{constructor(t,n){A(this,"id");A(this,"key");A(this,"status");A(this,"attachmentMap");A(this,"apiKey");A(this,"conditions");A(this,"syncLoopDuration");A(this,"reconnectStreamDelay");A(this,"retrySyncLoopDelay");A(this,"rpcClient");A(this,"taskQueue");A(this,"processing",!1);n=n||Ap,this.key=n.key?n.key:sB(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=n.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=n.syncLoopDuration||Ap.syncLoopDuration,this.reconnectStreamDelay=n.reconnectStreamDelay||Ap.reconnectStreamDelay,this.retrySyncLoopDelay=n.retrySyncLoopDelay||Ap.retrySyncLoopDelay,this.rpcClient=OUe(aKe,oKe({baseUrl:t,interceptors:[xVe(n.apiKey,n.token),zVe()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),$e.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw $e.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),$e.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw $e.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,n={}){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==Zs.Detached)throw new Y(W.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((o,a)=>a.set(n.initialPresence||{}));const r=t.subscribe("local-broadcast",async o=>{var h;const{topic:a,payload:s}=o.value,u=(h=o.options)==null?void 0:h.error,d=o.options;try{await this.broadcast(t.getKey(),a,s,d)}catch(p){p instanceof Error&&(u==null||u(p))}}),i=n.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:rn.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const a=rn.fromChangePack(o.changePack);if(t.applyChangePack(a),t.getStatus()===Zs.Removed)return t;t.applyStatus(Zs.Attached),this.attachmentMap.set(t.getKey(),new fVe(this.reconnectStreamDelay,t,o.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(t.getKey()),$e.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const s=t.getRootObject();if(n.initialRoot){const u=n.initialRoot;t.update(d=>{for(const[h,p]of Object.entries(u))if(!s.has(h)){const g=h;d[g]=p}})}return t}).catch(o=>{throw $e.error(`[AD] c:"${this.getKey()}" err :`,o),this.handleConnectError(o),o}))}detach(t,n={}){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((i,o)=>o.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:rn.toChangePack(t.createChangePack()),removeIfNotAttached:n.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(i=>{const o=rn.fromChangePack(i.changePack);return t.applyChangePack(o),t.getStatus()!==Zs.Removed&&t.applyStatus(Zs.Detached),this.detachInternal(t.getKey()),$e.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(i=>{throw $e.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(t,n){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const i=r.syncMode;return i===n?t:(r.changeSyncMode(n),n==="manual"?(r.cancelWatchStream(),t):(n==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);if(t){const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(n,"realtime").catch(r=>{throw $e.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const n=[];for(const[,r]of this.attachmentMap)n.push(this.syncInternal(r,r.syncMode));return Promise.all(n).catch(r=>{throw $e.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=rn.toChangePack(t.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:n.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(i=>{const o=rn.fromChangePack(i.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),$e.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(i=>{throw $e.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(t){return this.conditions[t]}broadcast(t,n,r,i){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const o=this.attachmentMap.get(t);if(!o)throw new Y(W.ErrDocumentNotAttached,`${t} is not attached`);if(!HVe(r))throw new Y(W.ErrInvalidArgument,"payload is not serializable");const a=(i==null?void 0:i.maxRetries)??i2.maxRetries,s=i2.maxBackoff;let u=0;const d=p=>Math.min(i2.initialRetryInterval*2**p,s),h=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:o.docID,topic:n,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{$e.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${n}"`)}).catch(p=>{if($e.error(`[BC] c:"${this.getKey()}" err:`,p),this.handleConnectError(p))if(uh(),d(u-1)),$e.info(`[BC] c:"${this.getKey()}" retry attempt ${u}/${a}`);else throw $e.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),p;else throw p}));return h()}runSyncLoop(){const t=()=>{if(!this.isActive()){$e.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const n=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,n.push(this.syncInternal(r,r.syncMode)));Promise.all(n).then(()=>setTimeout(t,this.syncLoopDuration)).catch(r=>{$e.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};$e.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,t()}async runWatchLoop(t){const n=this.attachmentMap.get(t);if(!n)throw new Y(W.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,n.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new Y(W.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,o=this.rpcClient.watchDocument({clientId:this.id,documentId:n.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:i.signal});return n.doc.publish([{type:Un.ConnectionChanged,value:yy.Connected}]),$e.info(`[WD] c:"${this.getKey()}" watches d:"${t}"`),new Promise((a,s)=>{(async()=>{try{for await(const d of o)this.handleWatchDocumentsResponse(n,d),d.body.case==="initialization"&&a([o,i])}catch(d){n.doc.resetOnlineClients(),n.doc.publish([{type:Un.Initialized,source:xt.Local,value:n.doc.getPresences()}]),n.doc.publish([{type:Un.ConnectionChanged,value:yy.Disconnected}]),$e.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(d)?r():this.conditions.WatchLoop=!1,s(d)}})()})})}handleWatchDocumentsResponse(t,n){if(n.body.case==="event"&&n.body.value.type===ml.DOCUMENT_CHANGED){t.remoteChangeEventReceived=!0;return}t.doc.applyWatchStream(n)}deactivateInternal(){this.status="deactivated";for(const[t,n]of this.attachmentMap)this.detachInternal(t),n.doc.applyStatus(Zs.Detached)}detachInternal(t){const n=this.attachmentMap.get(t);n&&(n.cancelWatchStream(),n.unsubscribeBroadcastEvent(),this.attachmentMap.delete(t))}syncInternal(t,n){const{doc:r,docID:i}=t,o=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:rn.toChangePack(o),pushOnly:n==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(a=>{const s=rn.fromChangePack(a.changePack);if(s.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(s),t.doc.publish([{type:Un.SyncStatusChanged,value:Ey.Synced}]),r.getStatus()===Zs.Removed&&this.detachInternal(r.getKey());const u=r.getKey(),d=s.getChangeSize();return $e.info(`[PP] c:"${this.getKey()}" sync d:"${u}", push:${o.getChangeSize()} pull:${d} cp:${s.getCheckpoint().toTestString()}`),r}).catch(a=>{throw r.publish([{type:Un.SyncStatusChanged,value:Ey.SyncFailed}]),$e.error(`[PP] c:"${this.getKey()}" err :`,a),a})}handleConnectError(t){return t instanceof fn?t.code===vt.Canceled||t.code===vt.Unknown||t.code===vt.ResourceExhausted||t.code===vt.Unavailable?!0:((Px(t)===W.ErrClientNotActivated||Px(t)===W.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(t){return new Promise((n,r)=>{this.taskQueue.push(()=>t().then(n).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{$e.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}Ko.IntegerCnt,Ko.LongCnt;typeof globalThis<"u"&&(globalThis.yorkie={Client:ZC,Document:XC,Primitive:Gt,Text:C1,Counter:b1,Tree:w1,LogLevel:or,setLogLevel:aB,IntType:Ko.IntegerCnt,LongType:Ko.LongCnt});var Cy={exports:{}};(function(e,t){(function(n,r){{var i=r();e&&e.exports&&(t=e.exports=i),t.randomColor=i}})(hc,function(){var n=null,r={};C();var i=[],o=function(D){if(D=D||{},D.seed!==void 0&&D.seed!==null&&D.seed===parseInt(D.seed,10))n=D.seed;else if(typeof D.seed=="string")n=B(D.seed);else{if(D.seed!==void 0&&D.seed!==null)throw new TypeError("The seed value must be an integer or string");n=null}var $,O,H;if(D.count!==null&&D.count!==void 0){for(var K=D.count,Z=[],X=0;XZ.length;){var pe=o(D);n!==null&&(D.seed=n),Z.push(pe)}return D.count=K,Z}return $=a(D),O=s($,D),H=u($,O,D),d([$,O,H],D)};function a(D){if(i.length>0){var $=T(D.hue),O=v($),H=($[1]-$[0])/i.length,K=parseInt((O-$[0])/H);i[K]===!0?K=(K+2)%i.length:i[K]=!0;var Z=($[0]+K*H)%359,X=($[0]+(K+1)*H)%359;return $=[Z,X],O=v($),O<0&&(O=360+O),O}else{var $=p(D.hue);return O=v($),O<0&&(O=360+O),O}}function s(D,$){if($.hue==="monochrome")return 0;if($.luminosity==="random")return v([0,100]);var O=g(D),H=O[0],K=O[1];switch($.luminosity){case"bright":H=55;break;case"dark":H=K-10;break;case"light":K=55;break}return v([H,K])}function u(D,$,O){var H=h(D,$),K=100;switch(O.luminosity){case"dark":K=H+20;break;case"light":H=(K+H)/2;break;case"random":H=0,K=100;break}return v([H,K])}function d(D,$){switch($.format){case"hsvArray":return D;case"hslArray":return I(D);case"hsl":var O=I(D);return"hsl("+O[0]+", "+O[1]+"%, "+O[2]+"%)";case"hsla":var H=I(D),X=$.alpha||Math.random();return"hsla("+H[0]+", "+H[1]+"%, "+H[2]+"%, "+X+")";case"rgbArray":return b(D);case"rgb":var K=b(D);return"rgb("+K.join(", ")+")";case"rgba":var Z=b(D),X=$.alpha||Math.random();return"rgba("+Z.join(", ")+", "+X+")";default:return E(D)}}function h(D,$){for(var O=m(D).lowerBounds,H=0;H=K&&$<=X){var me=(pe-Z)/(X-K),Ce=Z-me*K;return me*$+Ce}}return 0}function p(D){if(typeof parseInt(D)=="number"){var $=parseInt(D);if($<360&&$>0)return[$,$]}if(typeof D=="string"){if(r[D]){var O=r[D];if(O.hueRange)return O.hueRange}else if(D.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var H=k(D)[0];return[H,H]}}return[0,360]}function g(D){return m(D).saturationRange}function m(D){D>=334&&D<=360&&(D-=360);for(var $ in r){var O=r[$];if(O.hueRange&&D>=O.hueRange[0]&&D<=O.hueRange[1])return r[$]}return"Color not found"}function v(D){if(n===null){var $=.618033988749895,O=Math.random();return O+=$,O%=1,Math.floor(D[0]+O*(D[1]+1-D[0]))}else{var H=D[1]||1,K=D[0]||0;n=(n*9301+49297)%233280;var Z=n/233280;return Math.floor(K+Z*(H-K))}}function E(D){var $=b(D);function O(K){var Z=K.toString(16);return Z.length==1?"0"+Z:Z}var H="#"+O($[0])+O($[1])+O($[2]);return H}function w(D,$,O){var H=O[0][0],K=O[O.length-1][0],Z=O[O.length-1][1],X=O[0][1];r[D]={hueRange:$,lowerBounds:O,saturationRange:[H,K],brightnessRange:[Z,X]}}function C(){w("monochrome",null,[[0,0],[100,0]]),w("red",[-26,18],[[20,100],[30,92],[40,89],[50,85],[60,78],[70,70],[80,60],[90,55],[100,50]]),w("orange",[18,46],[[20,100],[30,93],[40,88],[50,86],[60,85],[70,70],[100,70]]),w("yellow",[46,62],[[25,100],[40,94],[50,89],[60,86],[70,84],[80,82],[90,80],[100,75]]),w("green",[62,178],[[30,100],[40,90],[50,85],[60,81],[70,74],[80,64],[90,50],[100,40]]),w("blue",[178,257],[[20,100],[30,86],[40,80],[50,74],[60,60],[70,52],[80,44],[90,39],[100,35]]),w("purple",[257,282],[[20,100],[30,87],[40,79],[50,70],[60,65],[70,59],[80,52],[90,45],[100,42]]),w("pink",[282,334],[[20,100],[30,90],[40,86],[60,84],[80,80],[90,75],[100,73]])}function b(D){var $=D[0];$===0&&($=1),$===360&&($=359),$=$/360;var O=D[1]/100,H=D[2]/100,K=Math.floor($*6),Z=$*6-K,X=H*(1-O),pe=H*(1-Z*O),me=H*(1-(1-Z)*O),Ce=256,J=256,U=256;switch(K){case 0:Ce=H,J=me,U=X;break;case 1:Ce=pe,J=H,U=X;break;case 2:Ce=X,J=H,U=me;break;case 3:Ce=X,J=pe,U=H;break;case 4:Ce=me,J=X,U=H;break;case 5:Ce=H,J=X,U=pe;break}var ne=[Math.floor(Ce*255),Math.floor(J*255),Math.floor(U*255)];return ne}function k(D){D=D.replace(/^#/,""),D=D.length===3?D.replace(/(.)/g,"$1$1"):D;var $=parseInt(D.substr(0,2),16)/255,O=parseInt(D.substr(2,2),16)/255,H=parseInt(D.substr(4,2),16)/255,K=Math.max($,O,H),Z=K-Math.min($,O,H),X=K?Z/K:0;switch(K){case $:return[60*((O-H)/Z%6)||0,X,K];case O:return[60*((H-$)/Z+2)||0,X,K];case H:return[60*(($-O)/Z+4)||0,X,K]}}function I(D){var $=D[0],O=D[1]/100,H=D[2]/100,K=(2-O)*H;return[$,Math.round(O*H/(K<1?K:2-K)*1e4)/100,K/2*100]}function B(D){for(var $=0,O=0;O!==D.length&&!($>=Number.MAX_SAFE_INTEGER);O++)$+=D.charCodeAt(O);return $}function T(D){if(isNaN(D)){if(typeof D=="string"){if(r[D]){var O=r[D];if(O.hueRange)return O.hueRange}else if(D.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var H=k(D)[0];return m(H).hueRange}}}else{var $=parseInt(D);if($<360&&$>0)return m(D).hueRange}return[0,360]}return o})})(Cy,Cy.exports);var jVe=Cy.exports;const UVe=gh(jVe),Lx=e=>{e=1831565813+(e|=0)|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296};class KVe{constructor(t){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;const{length:n,separator:r,dictionaries:i,style:o,seed:a}=t;this.dictionaries=i,this.separator=r,this.length=n,this.style=o,this.seed=a}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries. +`));for(const r of t)this.applyChange(r,n);$e.isEnabled(or.Debug)&&$e.debug(`after appling ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(t,n){this.ensureClone(),t.execute(this.clone.root,this.clone.presences,n);const r=[],i=t.getID().getActorID();if(t.hasPresenceChange()&&this.onlineClients.has(i)){const a=t.getPresenceChange();switch(a.type){case Iu.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:n,value:{clientID:i,presence:a.presence}}:{type:"watched",source:xt.Remote,value:{clientID:i,presence:a.presence}});break;case Iu.Clear:r.push({type:"unwatched",source:xt.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:o}=t.execute(this.root,this.presences,n);if(this.changeID=this.changeID.syncClocks(t.getID()),o.length>0){const a=this.isEnableDevtools()?t.toStruct():void 0;r.push(n===xt.Remote?{type:"remote-change",source:n,value:{actor:i,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:a}:{type:"local-change",source:n,value:{actor:i,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:a})}r.length>0&&this.publish(r)}applyWatchStream(t){if(t.body.case==="initialization"){const n=t.body.value.clientIds,r=new Set;for(const i of n)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:xt.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:n,publisher:r}=t.body.value,i=[];if(n===ml.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:xt.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(n===ml.DOCUMENT_UNWATCHED){const o=this.getPresence(r);this.removeOnlineClient(r),o&&i.push({type:"unwatched",source:xt.Remote,value:{clientID:r,presence:o}})}else if(n===ml.DOCUMENT_BROADCAST&&t.body.value.body){const{topic:o,payload:a}=t.body.value.body,s=new TextDecoder;i.push({type:"broadcast",value:{clientID:r,topic:o,payload:JSON.parse(s.decode(a))}})}i.length>0&&this.publish(i)}}applyStatus(t){this.status=t,t==="detached"&&this.setActor(FC),this.publish([{source:t==="removed"?xt.Remote:xt.Local,type:"status-changed",value:t==="attached"?{status:t,actorID:this.changeID.getActorID()}:{status:t}}])}applyDocEvent(t){if(t.type==="status-changed"){this.applyStatus(t.value.status),t.value.status==="attached"&&this.setActor(t.value.actorID);return}if(t.type==="snapshot"){const{snapshot:n,serverSeq:r,snapshotVector:i}=t.value;if(!n)return;this.applySnapshot(BigInt(r),rn.hexToVersionVector(i),rn.hexToBytes(n));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const n=cd.fromStruct(t.rawChange);this.applyChange(n,t.source)}if(t.type==="initialized"){const n=new Set;for(const{clientID:r,presence:i}of t.value)n.add(r),this.presences.set(r,i);this.setOnlineClients(n);return}if(t.type==="watched"){const{clientID:n,presence:r}=t.value;this.addOnlineClient(n),this.presences.set(n,r);return}if(t.type==="unwatched"){const{clientID:n}=t.value;this.removeOnlineClient(n),this.presences.delete(n)}if(t.type==="presence-changed"){const{clientID:n,presence:r}=t.value;this.presences.set(n,r)}}applyTransactionEvent(t){for(const n of t)this.applyDocEvent(n)}getValueByPath(t){if(!t.startsWith("$"))throw new Y(W.ErrInvalidArgument,'path must start with "$"');const n=t.split(".");n.shift();let r=this.getRoot();for(const i of n)if(r=r[i],r===void 0)return;return r}setOnlineClients(t){this.onlineClients=t}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(t){this.onlineClients.add(t)}removeOnlineClient(t){this.onlineClients.delete(t)}hasPresence(t){return this.presences.has(t)}getMyPresence(){if(this.status!=="attached")return{};const t=this.presences.get(this.changeID.getActorID());return t?Gi(t):{}}getPresence(t){if(t===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(t))return;const n=this.presences.get(t);return n?Gi(n):void 0}getPresenceForTest(t){const n=this.presences.get(t);return n?Gi(n):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:Gi(this.getMyPresence())});for(const n of this.onlineClients)this.presences.has(n)&&t.push({clientID:n,presence:Gi(this.presences.get(n))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(n=>n.clientID!==t).sort((n,r)=>n.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(t){const r=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new Y(W.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new Y(W.ErrRefused,"There is no operation to be undone");this.ensureClone();const n=Tc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof so)){new e2(n,Gi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const h=n.issueTimeTicket();d.setExecutedAt(h),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,xt.UndoRedo);const{opInfos:i,reverseOps:o}=r.execute(this.root,this.presences,xt.UndoRedo),a=n.getReversePresence();if(a&&o.push({type:"presence",value:a}),o.length>0&&this.internalHistory.pushRedo(o),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const s=this.changeID.getActorID(),u=[];i.length>0&&u.push({type:"local-change",source:xt.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:s,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&u.push({type:"presence-changed",source:xt.UndoRedo,value:{clientID:s,presence:this.getPresence(s)}}),this.publish(u)}redo(){if(this.isUpdating)throw new Y(W.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new Y(W.ErrRefused,"There is no operation to be redone");this.ensureClone();const n=Tc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof so)){new e2(n,Gi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const h=n.issueTimeTicket();d.setExecutedAt(h),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,xt.UndoRedo);const{opInfos:i,reverseOps:o}=r.execute(this.root,this.presences,xt.UndoRedo),a=n.getReversePresence();if(a&&o.push({type:"presence",value:a}),o.length>0&&this.internalHistory.pushUndo(o),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const s=this.changeID.getActorID(),u=[];i.length>0&&u.push({type:"local-change",source:xt.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:s,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&u.push({type:"presence-changed",source:xt.UndoRedo,value:{clientID:s,presence:this.getPresence(s)}}),this.publish(u)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(t,n,r){const i={type:"local-broadcast",value:{topic:t,payload:n},options:r};this.publish([i])}getVersionVector(){return this.changeID.getVersionVector()}}function xVe(e,t){return n=>async r=>(e&&r.header.set("x-api-key",e),t&&r.header.set("authorization",t),await n(r))}const AVe="yorkie-js-sdk",kVe="0.5.4",DVe="Yorkie JS SDK",IVe="./src/yorkie.ts",TVe={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},PVe=["dist"],BVe={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},MVe={node:">=18.0.0",npm:">=7.1.0"},$Ve={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},RVe={name:"hackerwins",email:"susukang98@gmail.com"},FVe="Apache-2.0",LVe={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},OVe="https://github.com/yorkie-team/yorkie-js-sdk#readme",_Ve={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},NVe={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Fx={name:AVe,version:kVe,description:DVe,main:IVe,publishConfig:TVe,files:PVe,scripts:BVe,engines:MVe,repository:$Ve,author:RVe,license:FVe,bugs:LVe,homepage:OVe,devDependencies:_Ve,dependencies:NVe};function zVe(){return e=>async t=>(t.header.set("x-yorkie-user-agent",Fx.name+"/"+Fx.version),await e(t))}const HVe=e=>{try{if(JSON.stringify(e)===void 0)return!1}catch{return!1}return!0};var Yp=(e=>(e.Manual="manual",e.Realtime="realtime",e.RealtimePushOnly="realtime-pushonly",e.RealtimeSyncOff="realtime-syncoff",e))(Yp||{});const Ap={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},i2={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class ZC{constructor(t,n){A(this,"id");A(this,"key");A(this,"status");A(this,"attachmentMap");A(this,"apiKey");A(this,"conditions");A(this,"syncLoopDuration");A(this,"reconnectStreamDelay");A(this,"retrySyncLoopDelay");A(this,"rpcClient");A(this,"taskQueue");A(this,"processing",!1);n=n||Ap,this.key=n.key?n.key:sB(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=n.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=n.syncLoopDuration||Ap.syncLoopDuration,this.reconnectStreamDelay=n.reconnectStreamDelay||Ap.reconnectStreamDelay,this.retrySyncLoopDelay=n.retrySyncLoopDelay||Ap.retrySyncLoopDelay,this.rpcClient=OUe(aKe,oKe({baseUrl:t,interceptors:[xVe(n.apiKey,n.token),zVe()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),$e.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw $e.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),$e.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw $e.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,n={}){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==Zs.Detached)throw new Y(W.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((o,a)=>a.set(n.initialPresence||{}));const r=t.subscribe("local-broadcast",async o=>{var h;const{topic:a,payload:s}=o.value,u=(h=o.options)==null?void 0:h.error,d=o.options;try{await this.broadcast(t.getKey(),a,s,d)}catch(p){p instanceof Error&&(u==null||u(p))}}),i=n.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:rn.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const a=rn.fromChangePack(o.changePack);if(t.applyChangePack(a),t.getStatus()===Zs.Removed)return t;t.applyStatus(Zs.Attached),this.attachmentMap.set(t.getKey(),new fVe(this.reconnectStreamDelay,t,o.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(t.getKey()),$e.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const s=t.getRootObject();if(n.initialRoot){const u=n.initialRoot;t.update(d=>{for(const[h,p]of Object.entries(u))if(!s.has(h)){const g=h;d[g]=p}})}return t}).catch(o=>{throw $e.error(`[AD] c:"${this.getKey()}" err :`,o),this.handleConnectError(o),o}))}detach(t,n={}){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((i,o)=>o.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:rn.toChangePack(t.createChangePack()),removeIfNotAttached:n.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(i=>{const o=rn.fromChangePack(i.changePack);return t.applyChangePack(o),t.getStatus()!==Zs.Removed&&t.applyStatus(Zs.Detached),this.detachInternal(t.getKey()),$e.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(i=>{throw $e.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(t,n){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const i=r.syncMode;return i===n?t:(r.changeSyncMode(n),n==="manual"?(r.cancelWatchStream(),t):(n==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);if(t){const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(n,"realtime").catch(r=>{throw $e.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const n=[];for(const[,r]of this.attachmentMap)n.push(this.syncInternal(r,r.syncMode));return Promise.all(n).catch(r=>{throw $e.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=rn.toChangePack(t.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:n.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(i=>{const o=rn.fromChangePack(i.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),$e.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(i=>{throw $e.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(t){return this.conditions[t]}broadcast(t,n,r,i){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const o=this.attachmentMap.get(t);if(!o)throw new Y(W.ErrDocumentNotAttached,`${t} is not attached`);if(!HVe(r))throw new Y(W.ErrInvalidArgument,"payload is not serializable");const a=(i==null?void 0:i.maxRetries)??i2.maxRetries,s=i2.maxBackoff;let u=0;const d=p=>Math.min(i2.initialRetryInterval*2**p,s),h=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:o.docID,topic:n,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{$e.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${n}"`)}).catch(p=>{if($e.error(`[BC] c:"${this.getKey()}" err:`,p),this.handleConnectError(p))if(uh(),d(u-1)),$e.info(`[BC] c:"${this.getKey()}" retry attempt ${u}/${a}`);else throw $e.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),p;else throw p}));return h()}runSyncLoop(){const t=()=>{if(!this.isActive()){$e.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const n=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,n.push(this.syncInternal(r,r.syncMode)));Promise.all(n).then(()=>setTimeout(t,this.syncLoopDuration)).catch(r=>{$e.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};$e.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,t()}async runWatchLoop(t){const n=this.attachmentMap.get(t);if(!n)throw new Y(W.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,n.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new Y(W.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,o=this.rpcClient.watchDocument({clientId:this.id,documentId:n.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:i.signal});return n.doc.publish([{type:Un.ConnectionChanged,value:yy.Connected}]),$e.info(`[WD] c:"${this.getKey()}" watches d:"${t}"`),new Promise((a,s)=>{(async()=>{try{for await(const d of o)this.handleWatchDocumentsResponse(n,d),d.body.case==="initialization"&&a([o,i])}catch(d){n.doc.resetOnlineClients(),n.doc.publish([{type:Un.Initialized,source:xt.Local,value:n.doc.getPresences()}]),n.doc.publish([{type:Un.ConnectionChanged,value:yy.Disconnected}]),$e.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(d)?r():this.conditions.WatchLoop=!1,s(d)}})()})})}handleWatchDocumentsResponse(t,n){if(n.body.case==="event"&&n.body.value.type===ml.DOCUMENT_CHANGED){t.remoteChangeEventReceived=!0;return}t.doc.applyWatchStream(n)}deactivateInternal(){this.status="deactivated";for(const[t,n]of this.attachmentMap)this.detachInternal(t),n.doc.applyStatus(Zs.Detached)}detachInternal(t){const n=this.attachmentMap.get(t);n&&(n.cancelWatchStream(),n.unsubscribeBroadcastEvent(),this.attachmentMap.delete(t))}syncInternal(t,n){const{doc:r,docID:i}=t,o=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:rn.toChangePack(o),pushOnly:n==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(a=>{const s=rn.fromChangePack(a.changePack);if(s.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(s),t.doc.publish([{type:Un.SyncStatusChanged,value:Ey.Synced}]),r.getStatus()===Zs.Removed&&this.detachInternal(r.getKey());const u=r.getKey(),d=s.getChangeSize();return $e.info(`[PP] c:"${this.getKey()}" sync d:"${u}", push:${o.getChangeSize()} pull:${d} cp:${s.getCheckpoint().toTestString()}`),r}).catch(a=>{throw r.publish([{type:Un.SyncStatusChanged,value:Ey.SyncFailed}]),$e.error(`[PP] c:"${this.getKey()}" err :`,a),a})}handleConnectError(t){return t instanceof fn?t.code===vt.Canceled||t.code===vt.Unknown||t.code===vt.ResourceExhausted||t.code===vt.Unavailable?!0:((Px(t)===W.ErrClientNotActivated||Px(t)===W.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(t){return new Promise((n,r)=>{this.taskQueue.push(()=>t().then(n).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{$e.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}Ko.IntegerCnt,Ko.LongCnt;typeof globalThis<"u"&&(globalThis.yorkie={Client:ZC,Document:XC,Primitive:Gt,Text:C1,Counter:b1,Tree:w1,LogLevel:or,setLogLevel:aB,IntType:Ko.IntegerCnt,LongType:Ko.LongCnt});var Cy={exports:{}};(function(e,t){(function(n,r){{var i=r();e&&e.exports&&(t=e.exports=i),t.randomColor=i}})(hc,function(){var n=null,r={};C();var i=[],o=function(D){if(D=D||{},D.seed!==void 0&&D.seed!==null&&D.seed===parseInt(D.seed,10))n=D.seed;else if(typeof D.seed=="string")n=B(D.seed);else{if(D.seed!==void 0&&D.seed!==null)throw new TypeError("The seed value must be an integer or string");n=null}var $,O,H;if(D.count!==null&&D.count!==void 0){for(var K=D.count,Z=[],X=0;XZ.length;){var pe=o(D);n!==null&&(D.seed=n),Z.push(pe)}return D.count=K,Z}return $=a(D),O=s($,D),H=u($,O,D),d([$,O,H],D)};function a(D){if(i.length>0){var $=T(D.hue),O=v($),H=($[1]-$[0])/i.length,K=parseInt((O-$[0])/H);i[K]===!0?K=(K+2)%i.length:i[K]=!0;var Z=($[0]+K*H)%359,X=($[0]+(K+1)*H)%359;return $=[Z,X],O=v($),O<0&&(O=360+O),O}else{var $=p(D.hue);return O=v($),O<0&&(O=360+O),O}}function s(D,$){if($.hue==="monochrome")return 0;if($.luminosity==="random")return v([0,100]);var O=g(D),H=O[0],K=O[1];switch($.luminosity){case"bright":H=55;break;case"dark":H=K-10;break;case"light":K=55;break}return v([H,K])}function u(D,$,O){var H=h(D,$),K=100;switch(O.luminosity){case"dark":K=H+20;break;case"light":H=(K+H)/2;break;case"random":H=0,K=100;break}return v([H,K])}function d(D,$){switch($.format){case"hsvArray":return D;case"hslArray":return I(D);case"hsl":var O=I(D);return"hsl("+O[0]+", "+O[1]+"%, "+O[2]+"%)";case"hsla":var H=I(D),X=$.alpha||Math.random();return"hsla("+H[0]+", "+H[1]+"%, "+H[2]+"%, "+X+")";case"rgbArray":return b(D);case"rgb":var K=b(D);return"rgb("+K.join(", ")+")";case"rgba":var Z=b(D),X=$.alpha||Math.random();return"rgba("+Z.join(", ")+", "+X+")";default:return E(D)}}function h(D,$){for(var O=m(D).lowerBounds,H=0;H=K&&$<=X){var me=(pe-Z)/(X-K),Ce=Z-me*K;return me*$+Ce}}return 0}function p(D){if(typeof parseInt(D)=="number"){var $=parseInt(D);if($<360&&$>0)return[$,$]}if(typeof D=="string"){if(r[D]){var O=r[D];if(O.hueRange)return O.hueRange}else if(D.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var H=k(D)[0];return[H,H]}}return[0,360]}function g(D){return m(D).saturationRange}function m(D){D>=334&&D<=360&&(D-=360);for(var $ in r){var O=r[$];if(O.hueRange&&D>=O.hueRange[0]&&D<=O.hueRange[1])return r[$]}return"Color not found"}function v(D){if(n===null){var $=.618033988749895,O=Math.random();return O+=$,O%=1,Math.floor(D[0]+O*(D[1]+1-D[0]))}else{var H=D[1]||1,K=D[0]||0;n=(n*9301+49297)%233280;var Z=n/233280;return Math.floor(K+Z*(H-K))}}function E(D){var $=b(D);function O(K){var Z=K.toString(16);return Z.length==1?"0"+Z:Z}var H="#"+O($[0])+O($[1])+O($[2]);return H}function w(D,$,O){var H=O[0][0],K=O[O.length-1][0],Z=O[O.length-1][1],X=O[0][1];r[D]={hueRange:$,lowerBounds:O,saturationRange:[H,K],brightnessRange:[Z,X]}}function C(){w("monochrome",null,[[0,0],[100,0]]),w("red",[-26,18],[[20,100],[30,92],[40,89],[50,85],[60,78],[70,70],[80,60],[90,55],[100,50]]),w("orange",[18,46],[[20,100],[30,93],[40,88],[50,86],[60,85],[70,70],[100,70]]),w("yellow",[46,62],[[25,100],[40,94],[50,89],[60,86],[70,84],[80,82],[90,80],[100,75]]),w("green",[62,178],[[30,100],[40,90],[50,85],[60,81],[70,74],[80,64],[90,50],[100,40]]),w("blue",[178,257],[[20,100],[30,86],[40,80],[50,74],[60,60],[70,52],[80,44],[90,39],[100,35]]),w("purple",[257,282],[[20,100],[30,87],[40,79],[50,70],[60,65],[70,59],[80,52],[90,45],[100,42]]),w("pink",[282,334],[[20,100],[30,90],[40,86],[60,84],[80,80],[90,75],[100,73]])}function b(D){var $=D[0];$===0&&($=1),$===360&&($=359),$=$/360;var O=D[1]/100,H=D[2]/100,K=Math.floor($*6),Z=$*6-K,X=H*(1-O),pe=H*(1-Z*O),me=H*(1-(1-Z)*O),Ce=256,J=256,U=256;switch(K){case 0:Ce=H,J=me,U=X;break;case 1:Ce=pe,J=H,U=X;break;case 2:Ce=X,J=H,U=me;break;case 3:Ce=X,J=pe,U=H;break;case 4:Ce=me,J=X,U=H;break;case 5:Ce=H,J=X,U=pe;break}var ne=[Math.floor(Ce*255),Math.floor(J*255),Math.floor(U*255)];return ne}function k(D){D=D.replace(/^#/,""),D=D.length===3?D.replace(/(.)/g,"$1$1"):D;var $=parseInt(D.substr(0,2),16)/255,O=parseInt(D.substr(2,2),16)/255,H=parseInt(D.substr(4,2),16)/255,K=Math.max($,O,H),Z=K-Math.min($,O,H),X=K?Z/K:0;switch(K){case $:return[60*((O-H)/Z%6)||0,X,K];case O:return[60*((H-$)/Z+2)||0,X,K];case H:return[60*(($-O)/Z+4)||0,X,K]}}function I(D){var $=D[0],O=D[1]/100,H=D[2]/100,K=(2-O)*H;return[$,Math.round(O*H/(K<1?K:2-K)*1e4)/100,K/2*100]}function B(D){for(var $=0,O=0;O!==D.length&&!($>=Number.MAX_SAFE_INTEGER);O++)$+=D.charCodeAt(O);return $}function T(D){if(isNaN(D)){if(typeof D=="string"){if(r[D]){var O=r[D];if(O.hueRange)return O.hueRange}else if(D.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var H=k(D)[0];return m(H).hueRange}}}else{var $=parseInt(D);if($<360&&$>0)return m(D).hueRange}return[0,360]}return o})})(Cy,Cy.exports);var jVe=Cy.exports;const UVe=gh(jVe),Lx=e=>{e=1831565813+(e|=0)|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296};class KVe{constructor(t){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;const{length:n,separator:r,dictionaries:i,style:o,seed:a}=t;this.dictionaries=i,this.separator=r,this.length=n,this.style=o,this.seed=a}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries. Length provided: ${this.length}. Number of dictionaries provided: ${this.dictionaries.length}`);let t=this.seed;return this.dictionaries.slice(0,this.length).reduce((n,r)=>{let i;t?(i=(a=>{if(typeof a=="string"){const s=a.split("").map(d=>d.charCodeAt(0)).reduce((d,h)=>d+h,1),u=Math.floor(Number(s));return Lx(u)}return Lx(a)})(t),t=4294967296*i):i=Math.random();let o=r[Math.floor(i*r.length)]||"";if(this.style==="lowerCase")o=o.toLowerCase();else if(this.style==="capital"){const[a,...s]=o.split("");o=a.toUpperCase()+s.join("")}else this.style==="upperCase"&&(o=o.toUpperCase());return n?`${n}${this.separator}${o}`:`${o}`},"")}}const Ox={separator:"_",dictionaries:[]},VVe=e=>{const t=[...e&&e.dictionaries||Ox.dictionaries],n={...Ox,...e,length:e&&e.length||t.length,dictionaries:t};if(!e||!e.dictionaries||!e.dictionaries.length)throw new Error('A "dictionaries" array must be provided. This is a breaking change introduced starting from Unique Name Generator v4. Read more about the breaking change here: https://github.com/andreasonny83/unique-names-generator#migration-guide');return new KVe(n).generate()};var GVe=["Aaren","Aarika","Abagael","Abagail","Abbe","Abbey","Abbi","Abbie","Abby","Abbye","Abigael","Abigail","Abigale","Abra","Ada","Adah","Adaline","Adan","Adara","Adda","Addi","Addia","Addie","Addy","Adel","Adela","Adelaida","Adelaide","Adele","Adelheid","Adelice","Adelina","Adelind","Adeline","Adella","Adelle","Adena","Adey","Adi","Adiana","Adina","Adora","Adore","Adoree","Adorne","Adrea","Adria","Adriaens","Adrian","Adriana","Adriane","Adrianna","Adrianne","Adriena","Adrienne","Aeriel","Aeriela","Aeriell","Afton","Ag","Agace","Agata","Agatha","Agathe","Aggi","Aggie","Aggy","Agna","Agnella","Agnes","Agnese","Agnesse","Agneta","Agnola","Agretha","Aida","Aidan","Aigneis","Aila","Aile","Ailee","Aileen","Ailene","Ailey","Aili","Ailina","Ailis","Ailsun","Ailyn","Aime","Aimee","Aimil","Aindrea","Ainslee","Ainsley","Ainslie","Ajay","Alaine","Alameda","Alana","Alanah","Alane","Alanna","Alayne","Alberta","Albertina","Albertine","Albina","Alecia","Aleda","Aleece","Aleen","Alejandra","Alejandrina","Alena","Alene","Alessandra","Aleta","Alethea","Alex","Alexa","Alexandra","Alexandrina","Alexi","Alexia","Alexina","Alexine","Alexis","Alfi","Alfie","Alfreda","Alfy","Ali","Alia","Alica","Alice","Alicea","Alicia","Alida","Alidia","Alie","Alika","Alikee","Alina","Aline","Alis","Alisa","Alisha","Alison","Alissa","Alisun","Alix","Aliza","Alla","Alleen","Allegra","Allene","Alli","Allianora","Allie","Allina","Allis","Allison","Allissa","Allix","Allsun","Allx","Ally","Allyce","Allyn","Allys","Allyson","Alma","Almeda","Almeria","Almeta","Almira","Almire","Aloise","Aloisia","Aloysia","Alta","Althea","Alvera","Alverta","Alvina","Alvinia","Alvira","Alyce","Alyda","Alys","Alysa","Alyse","Alysia","Alyson","Alyss","Alyssa","Amabel","Amabelle","Amalea","Amalee","Amaleta","Amalia","Amalie","Amalita","Amalle","Amanda","Amandi","Amandie","Amandy","Amara","Amargo","Amata","Amber","Amberly","Ambur","Ame","Amelia","Amelie","Amelina","Ameline","Amelita","Ami","Amie","Amii","Amil","Amitie","Amity","Ammamaria","Amy","Amye","Ana","Anabal","Anabel","Anabella","Anabelle","Analiese","Analise","Anallese","Anallise","Anastasia","Anastasie","Anastassia","Anatola","Andee","Andeee","Anderea","Andi","Andie","Andra","Andrea","Andreana","Andree","Andrei","Andria","Andriana","Andriette","Andromache","Andy","Anestassia","Anet","Anett","Anetta","Anette","Ange","Angel","Angela","Angele","Angelia","Angelica","Angelika","Angelina","Angeline","Angelique","Angelita","Angelle","Angie","Angil","Angy","Ania","Anica","Anissa","Anita","Anitra","Anjanette","Anjela","Ann","Ann-marie","Anna","Anna-diana","Anna-diane","Anna-maria","Annabal","Annabel","Annabela","Annabell","Annabella","Annabelle","Annadiana","Annadiane","Annalee","Annaliese","Annalise","Annamaria","Annamarie","Anne","Anne-corinne","Anne-marie","Annecorinne","Anneliese","Annelise","Annemarie","Annetta","Annette","Anni","Annice","Annie","Annis","Annissa","Annmaria","Annmarie","Annnora","Annora","Anny","Anselma","Ansley","Anstice","Anthe","Anthea","Anthia","Anthiathia","Antoinette","Antonella","Antonetta","Antonia","Antonie","Antonietta","Antonina","Anya","Appolonia","April","Aprilette","Ara","Arabel","Arabela","Arabele","Arabella","Arabelle","Arda","Ardath","Ardeen","Ardelia","Ardelis","Ardella","Ardelle","Arden","Ardene","Ardenia","Ardine","Ardis","Ardisj","Ardith","Ardra","Ardyce","Ardys","Ardyth","Aretha","Ariadne","Ariana","Aridatha","Ariel","Ariela","Ariella","Arielle","Arlana","Arlee","Arleen","Arlen","Arlena","Arlene","Arleta","Arlette","Arleyne","Arlie","Arliene","Arlina","Arlinda","Arline","Arluene","Arly","Arlyn","Arlyne","Aryn","Ashely","Ashia","Ashien","Ashil","Ashla","Ashlan","Ashlee","Ashleigh","Ashlen","Ashley","Ashli","Ashlie","Ashly","Asia","Astra","Astrid","Astrix","Atalanta","Athena","Athene","Atlanta","Atlante","Auberta","Aubine","Aubree","Aubrette","Aubrey","Aubrie","Aubry","Audi","Audie","Audra","Audre","Audrey","Audrie","Audry","Audrye","Audy","Augusta","Auguste","Augustina","Augustine","Aundrea","Aura","Aurea","Aurel","Aurelea","Aurelia","Aurelie","Auria","Aurie","Aurilia","Aurlie","Auroora","Aurora","Aurore","Austin","Austina","Austine","Ava","Aveline","Averil","Averyl","Avie","Avis","Aviva","Avivah","Avril","Avrit","Ayn","Bab","Babara","Babb","Babbette","Babbie","Babette","Babita","Babs","Bambi","Bambie","Bamby","Barb","Barbabra","Barbara","Barbara-anne","Barbaraanne","Barbe","Barbee","Barbette","Barbey","Barbi","Barbie","Barbra","Barby","Bari","Barrie","Barry","Basia","Bathsheba","Batsheva","Bea","Beatrice","Beatrisa","Beatrix","Beatriz","Bebe","Becca","Becka","Becki","Beckie","Becky","Bee","Beilul","Beitris","Bekki","Bel","Belia","Belicia","Belinda","Belita","Bell","Bella","Bellanca","Belle","Bellina","Belva","Belvia","Bendite","Benedetta","Benedicta","Benedikta","Benetta","Benita","Benni","Bennie","Benny","Benoite","Berenice","Beret","Berget","Berna","Bernadene","Bernadette","Bernadina","Bernadine","Bernardina","Bernardine","Bernelle","Bernete","Bernetta","Bernette","Berni","Bernice","Bernie","Bernita","Berny","Berri","Berrie","Berry","Bert","Berta","Berte","Bertha","Berthe","Berti","Bertie","Bertina","Bertine","Berty","Beryl","Beryle","Bess","Bessie","Bessy","Beth","Bethanne","Bethany","Bethena","Bethina","Betsey","Betsy","Betta","Bette","Bette-ann","Betteann","Betteanne","Betti","Bettina","Bettine","Betty","Bettye","Beulah","Bev","Beverie","Beverlee","Beverley","Beverlie","Beverly","Bevvy","Bianca","Bianka","Bibbie","Bibby","Bibbye","Bibi","Biddie","Biddy","Bidget","Bili","Bill","Billi","Billie","Billy","Billye","Binni","Binnie","Binny","Bird","Birdie","Birgit","Birgitta","Blair","Blaire","Blake","Blakelee","Blakeley","Blanca","Blanch","Blancha","Blanche","Blinni","Blinnie","Blinny","Bliss","Blisse","Blithe","Blondell","Blondelle","Blondie","Blondy","Blythe","Bobbe","Bobbee","Bobbette","Bobbi","Bobbie","Bobby","Bobbye","Bobette","Bobina","Bobine","Bobinette","Bonita","Bonnee","Bonni","Bonnibelle","Bonnie","Bonny","Brana","Brandais","Brande","Brandea","Brandi","Brandice","Brandie","Brandise","Brandy","Breanne","Brear","Bree","Breena","Bren","Brena","Brenda","Brenn","Brenna","Brett","Bria","Briana","Brianna","Brianne","Bride","Bridget","Bridgette","Bridie","Brier","Brietta","Brigid","Brigida","Brigit","Brigitta","Brigitte","Brina","Briney","Brinn","Brinna","Briny","Brit","Brita","Britney","Britni","Britt","Britta","Brittan","Brittaney","Brittani","Brittany","Britte","Britteny","Brittne","Brittney","Brittni","Brook","Brooke","Brooks","Brunhilda","Brunhilde","Bryana","Bryn","Bryna","Brynn","Brynna","Brynne","Buffy","Bunni","Bunnie","Bunny","Cacilia","Cacilie","Cahra","Cairistiona","Caitlin","Caitrin","Cal","Calida","Calla","Calley","Calli","Callida","Callie","Cally","Calypso","Cam","Camala","Camel","Camella","Camellia","Cami","Camila","Camile","Camilla","Camille","Cammi","Cammie","Cammy","Candace","Candi","Candice","Candida","Candide","Candie","Candis","Candra","Candy","Caprice","Cara","Caralie","Caren","Carena","Caresa","Caressa","Caresse","Carey","Cari","Caria","Carie","Caril","Carilyn","Carin","Carina","Carine","Cariotta","Carissa","Carita","Caritta","Carla","Carlee","Carleen","Carlen","Carlene","Carley","Carlie","Carlin","Carlina","Carline","Carlita","Carlota","Carlotta","Carly","Carlye","Carlyn","Carlynn","Carlynne","Carma","Carmel","Carmela","Carmelia","Carmelina","Carmelita","Carmella","Carmelle","Carmen","Carmencita","Carmina","Carmine","Carmita","Carmon","Caro","Carol","Carol-jean","Carola","Carolan","Carolann","Carole","Carolee","Carolin","Carolina","Caroline","Caroljean","Carolyn","Carolyne","Carolynn","Caron","Carree","Carri","Carrie","Carrissa","Carroll","Carry","Cary","Caryl","Caryn","Casandra","Casey","Casi","Casie","Cass","Cassandra","Cassandre","Cassandry","Cassaundra","Cassey","Cassi","Cassie","Cassondra","Cassy","Catarina","Cate","Caterina","Catha","Catharina","Catharine","Cathe","Cathee","Catherin","Catherina","Catherine","Cathi","Cathie","Cathleen","Cathlene","Cathrin","Cathrine","Cathryn","Cathy","Cathyleen","Cati","Catie","Catina","Catlaina","Catlee","Catlin","Catrina","Catriona","Caty","Caye","Cayla","Cecelia","Cecil","Cecile","Ceciley","Cecilia","Cecilla","Cecily","Ceil","Cele","Celene","Celesta","Celeste","Celestia","Celestina","Celestine","Celestyn","Celestyna","Celia","Celie","Celina","Celinda","Celine","Celinka","Celisse","Celka","Celle","Cesya","Chad","Chanda","Chandal","Chandra","Channa","Chantal","Chantalle","Charil","Charin","Charis","Charissa","Charisse","Charita","Charity","Charla","Charlean","Charleen","Charlena","Charlene","Charline","Charlot","Charlotta","Charlotte","Charmain","Charmaine","Charmane","Charmian","Charmine","Charmion","Charo","Charyl","Chastity","Chelsae","Chelsea","Chelsey","Chelsie","Chelsy","Cher","Chere","Cherey","Cheri","Cherianne","Cherice","Cherida","Cherie","Cherilyn","Cherilynn","Cherin","Cherise","Cherish","Cherlyn","Cherri","Cherrita","Cherry","Chery","Cherye","Cheryl","Cheslie","Chiarra","Chickie","Chicky","Chiquia","Chiquita","Chlo","Chloe","Chloette","Chloris","Chris","Chrissie","Chrissy","Christa","Christabel","Christabella","Christal","Christalle","Christan","Christean","Christel","Christen","Christi","Christian","Christiana","Christiane","Christie","Christin","Christina","Christine","Christy","Christye","Christyna","Chrysa","Chrysler","Chrystal","Chryste","Chrystel","Cicely","Cicily","Ciel","Cilka","Cinda","Cindee","Cindelyn","Cinderella","Cindi","Cindie","Cindra","Cindy","Cinnamon","Cissiee","Cissy","Clair","Claire","Clara","Clarabelle","Clare","Claresta","Clareta","Claretta","Clarette","Clarey","Clari","Claribel","Clarice","Clarie","Clarinda","Clarine","Clarissa","Clarisse","Clarita","Clary","Claude","Claudelle","Claudetta","Claudette","Claudia","Claudie","Claudina","Claudine","Clea","Clem","Clemence","Clementia","Clementina","Clementine","Clemmie","Clemmy","Cleo","Cleopatra","Clerissa","Clio","Clo","Cloe","Cloris","Clotilda","Clovis","Codee","Codi","Codie","Cody","Coleen","Colene","Coletta","Colette","Colleen","Collen","Collete","Collette","Collie","Colline","Colly","Con","Concettina","Conchita","Concordia","Conni","Connie","Conny","Consolata","Constance","Constancia","Constancy","Constanta","Constantia","Constantina","Constantine","Consuela","Consuelo","Cookie","Cora","Corabel","Corabella","Corabelle","Coral","Coralie","Coraline","Coralyn","Cordelia","Cordelie","Cordey","Cordi","Cordie","Cordula","Cordy","Coreen","Corella","Corenda","Corene","Coretta","Corette","Corey","Cori","Corie","Corilla","Corina","Corine","Corinna","Corinne","Coriss","Corissa","Corliss","Corly","Cornela","Cornelia","Cornelle","Cornie","Corny","Correna","Correy","Corri","Corrianne","Corrie","Corrina","Corrine","Corrinne","Corry","Cortney","Cory","Cosetta","Cosette","Costanza","Courtenay","Courtnay","Courtney","Crin","Cris","Crissie","Crissy","Crista","Cristabel","Cristal","Cristen","Cristi","Cristie","Cristin","Cristina","Cristine","Cristionna","Cristy","Crysta","Crystal","Crystie","Cthrine","Cyb","Cybil","Cybill","Cymbre","Cynde","Cyndi","Cyndia","Cyndie","Cyndy","Cynthea","Cynthia","Cynthie","Cynthy","Dacey","Dacia","Dacie","Dacy","Dael","Daffi","Daffie","Daffy","Dagmar","Dahlia","Daile","Daisey","Daisi","Daisie","Daisy","Dale","Dalenna","Dalia","Dalila","Dallas","Daloris","Damara","Damaris","Damita","Dana","Danell","Danella","Danette","Dani","Dania","Danica","Danice","Daniela","Daniele","Daniella","Danielle","Danika","Danila","Danit","Danita","Danna","Danni","Dannie","Danny","Dannye","Danya","Danyelle","Danyette","Daphene","Daphna","Daphne","Dara","Darb","Darbie","Darby","Darcee","Darcey","Darci","Darcie","Darcy","Darda","Dareen","Darell","Darelle","Dari","Daria","Darice","Darla","Darleen","Darlene","Darline","Darlleen","Daron","Darrelle","Darryl","Darsey","Darsie","Darya","Daryl","Daryn","Dasha","Dasi","Dasie","Dasya","Datha","Daune","Daveen","Daveta","Davida","Davina","Davine","Davita","Dawn","Dawna","Dayle","Dayna","Ddene","De","Deana","Deane","Deanna","Deanne","Deb","Debbi","Debbie","Debby","Debee","Debera","Debi","Debor","Debora","Deborah","Debra","Dede","Dedie","Dedra","Dee","Deeann","Deeanne","Deedee","Deena","Deerdre","Deeyn","Dehlia","Deidre","Deina","Deirdre","Del","Dela","Delcina","Delcine","Delia","Delila","Delilah","Delinda","Dell","Della","Delly","Delora","Delores","Deloria","Deloris","Delphine","Delphinia","Demeter","Demetra","Demetria","Demetris","Dena","Deni","Denice","Denise","Denna","Denni","Dennie","Denny","Deny","Denys","Denyse","Deonne","Desdemona","Desirae","Desiree","Desiri","Deva","Devan","Devi","Devin","Devina","Devinne","Devon","Devondra","Devonna","Devonne","Devora","Di","Diahann","Dian","Diana","Diandra","Diane","Diane-marie","Dianemarie","Diann","Dianna","Dianne","Diannne","Didi","Dido","Diena","Dierdre","Dina","Dinah","Dinnie","Dinny","Dion","Dione","Dionis","Dionne","Dita","Dix","Dixie","Dniren","Dode","Dodi","Dodie","Dody","Doe","Doll","Dolley","Dolli","Dollie","Dolly","Dolores","Dolorita","Doloritas","Domeniga","Dominga","Domini","Dominica","Dominique","Dona","Donella","Donelle","Donetta","Donia","Donica","Donielle","Donna","Donnamarie","Donni","Donnie","Donny","Dora","Doralia","Doralin","Doralyn","Doralynn","Doralynne","Dore","Doreen","Dorelia","Dorella","Dorelle","Dorena","Dorene","Doretta","Dorette","Dorey","Dori","Doria","Dorian","Dorice","Dorie","Dorine","Doris","Dorisa","Dorise","Dorita","Doro","Dorolice","Dorolisa","Dorotea","Doroteya","Dorothea","Dorothee","Dorothy","Dorree","Dorri","Dorrie","Dorris","Dorry","Dorthea","Dorthy","Dory","Dosi","Dot","Doti","Dotti","Dottie","Dotty","Dre","Dreddy","Dredi","Drona","Dru","Druci","Drucie","Drucill","Drucy","Drusi","Drusie","Drusilla","Drusy","Dulce","Dulcea","Dulci","Dulcia","Dulciana","Dulcie","Dulcine","Dulcinea","Dulcy","Dulsea","Dusty","Dyan","Dyana","Dyane","Dyann","Dyanna","Dyanne","Dyna","Dynah","Eachelle","Eada","Eadie","Eadith","Ealasaid","Eartha","Easter","Eba","Ebba","Ebonee","Ebony","Eda","Eddi","Eddie","Eddy","Ede","Edee","Edeline","Eden","Edi","Edie","Edin","Edita","Edith","Editha","Edithe","Ediva","Edna","Edwina","Edy","Edyth","Edythe","Effie","Eileen","Eilis","Eimile","Eirena","Ekaterina","Elaina","Elaine","Elana","Elane","Elayne","Elberta","Elbertina","Elbertine","Eleanor","Eleanora","Eleanore","Electra","Eleen","Elena","Elene","Eleni","Elenore","Eleonora","Eleonore","Elfie","Elfreda","Elfrida","Elfrieda","Elga","Elianora","Elianore","Elicia","Elie","Elinor","Elinore","Elisa","Elisabet","Elisabeth","Elisabetta","Elise","Elisha","Elissa","Elita","Eliza","Elizabet","Elizabeth","Elka","Elke","Ella","Elladine","Elle","Ellen","Ellene","Ellette","Elli","Ellie","Ellissa","Elly","Ellyn","Ellynn","Elmira","Elna","Elnora","Elnore","Eloisa","Eloise","Elonore","Elora","Elsa","Elsbeth","Else","Elset","Elsey","Elsi","Elsie","Elsinore","Elspeth","Elsy","Elva","Elvera","Elvina","Elvira","Elwira","Elyn","Elyse","Elysee","Elysha","Elysia","Elyssa","Em","Ema","Emalee","Emalia","Emelda","Emelia","Emelina","Emeline","Emelita","Emelyne","Emera","Emilee","Emili","Emilia","Emilie","Emiline","Emily","Emlyn","Emlynn","Emlynne","Emma","Emmalee","Emmaline","Emmalyn","Emmalynn","Emmalynne","Emmeline","Emmey","Emmi","Emmie","Emmy","Emmye","Emogene","Emyle","Emylee","Engracia","Enid","Enrica","Enrichetta","Enrika","Enriqueta","Eolanda","Eolande","Eran","Erda","Erena","Erica","Ericha","Ericka","Erika","Erin","Erina","Erinn","Erinna","Erma","Ermengarde","Ermentrude","Ermina","Erminia","Erminie","Erna","Ernaline","Ernesta","Ernestine","Ertha","Eryn","Esma","Esmaria","Esme","Esmeralda","Essa","Essie","Essy","Esta","Estel","Estele","Estell","Estella","Estelle","Ester","Esther","Estrella","Estrellita","Ethel","Ethelda","Ethelin","Ethelind","Etheline","Ethelyn","Ethyl","Etta","Etti","Ettie","Etty","Eudora","Eugenia","Eugenie","Eugine","Eula","Eulalie","Eunice","Euphemia","Eustacia","Eva","Evaleen","Evangelia","Evangelin","Evangelina","Evangeline","Evania","Evanne","Eve","Eveleen","Evelina","Eveline","Evelyn","Evey","Evie","Evita","Evonne","Evvie","Evvy","Evy","Eyde","Eydie","Ezmeralda","Fae","Faina","Faith","Fallon","Fan","Fanchette","Fanchon","Fancie","Fancy","Fanechka","Fania","Fanni","Fannie","Fanny","Fanya","Fara","Farah","Farand","Farica","Farra","Farrah","Farrand","Faun","Faunie","Faustina","Faustine","Fawn","Fawne","Fawnia","Fay","Faydra","Faye","Fayette","Fayina","Fayre","Fayth","Faythe","Federica","Fedora","Felecia","Felicdad","Felice","Felicia","Felicity","Felicle","Felipa","Felisha","Felita","Feliza","Fenelia","Feodora","Ferdinanda","Ferdinande","Fern","Fernanda","Fernande","Fernandina","Ferne","Fey","Fiann","Fianna","Fidela","Fidelia","Fidelity","Fifi","Fifine","Filia","Filide","Filippa","Fina","Fiona","Fionna","Fionnula","Fiorenze","Fleur","Fleurette","Flo","Flor","Flora","Florance","Flore","Florella","Florence","Florencia","Florentia","Florenza","Florette","Flori","Floria","Florida","Florie","Florina","Florinda","Floris","Florri","Florrie","Florry","Flory","Flossi","Flossie","Flossy","Flss","Fran","Francene","Frances","Francesca","Francine","Francisca","Franciska","Francoise","Francyne","Frank","Frankie","Franky","Franni","Frannie","Franny","Frayda","Fred","Freda","Freddi","Freddie","Freddy","Fredelia","Frederica","Fredericka","Frederique","Fredi","Fredia","Fredra","Fredrika","Freida","Frieda","Friederike","Fulvia","Gabbey","Gabbi","Gabbie","Gabey","Gabi","Gabie","Gabriel","Gabriela","Gabriell","Gabriella","Gabrielle","Gabriellia","Gabrila","Gaby","Gae","Gael","Gail","Gale","Galina","Garland","Garnet","Garnette","Gates","Gavra","Gavrielle","Gay","Gaye","Gayel","Gayla","Gayle","Gayleen","Gaylene","Gaynor","Gelya","Gena","Gene","Geneva","Genevieve","Genevra","Genia","Genna","Genni","Gennie","Gennifer","Genny","Genovera","Genvieve","George","Georgeanna","Georgeanne","Georgena","Georgeta","Georgetta","Georgette","Georgia","Georgiana","Georgianna","Georgianne","Georgie","Georgina","Georgine","Geralda","Geraldine","Gerda","Gerhardine","Geri","Gerianna","Gerianne","Gerladina","Germain","Germaine","Germana","Gerri","Gerrie","Gerrilee","Gerry","Gert","Gerta","Gerti","Gertie","Gertrud","Gertruda","Gertrude","Gertrudis","Gerty","Giacinta","Giana","Gianina","Gianna","Gigi","Gilberta","Gilberte","Gilbertina","Gilbertine","Gilda","Gilemette","Gill","Gillan","Gilli","Gillian","Gillie","Gilligan","Gilly","Gina","Ginelle","Ginevra","Ginger","Ginni","Ginnie","Ginnifer","Ginny","Giorgia","Giovanna","Gipsy","Giralda","Gisela","Gisele","Gisella","Giselle","Giuditta","Giulia","Giulietta","Giustina","Gizela","Glad","Gladi","Gladys","Gleda","Glen","Glenda","Glenine","Glenn","Glenna","Glennie","Glennis","Glori","Gloria","Gloriana","Gloriane","Glory","Glyn","Glynda","Glynis","Glynnis","Gnni","Godiva","Golda","Goldarina","Goldi","Goldia","Goldie","Goldina","Goldy","Grace","Gracia","Gracie","Grata","Gratia","Gratiana","Gray","Grayce","Grazia","Greer","Greta","Gretal","Gretchen","Grete","Gretel","Grethel","Gretna","Gretta","Grier","Griselda","Grissel","Guendolen","Guenevere","Guenna","Guglielma","Gui","Guillema","Guillemette","Guinevere","Guinna","Gunilla","Gus","Gusella","Gussi","Gussie","Gussy","Gusta","Gusti","Gustie","Gusty","Gwen","Gwendolen","Gwendolin","Gwendolyn","Gweneth","Gwenette","Gwenneth","Gwenni","Gwennie","Gwenny","Gwenora","Gwenore","Gwyn","Gwyneth","Gwynne","Gypsy","Hadria","Hailee","Haily","Haleigh","Halette","Haley","Hali","Halie","Halimeda","Halley","Halli","Hallie","Hally","Hana","Hanna","Hannah","Hanni","Hannie","Hannis","Hanny","Happy","Harlene","Harley","Harli","Harlie","Harmonia","Harmonie","Harmony","Harri","Harrie","Harriet","Harriett","Harrietta","Harriette","Harriot","Harriott","Hatti","Hattie","Hatty","Hayley","Hazel","Heath","Heather","Heda","Hedda","Heddi","Heddie","Hedi","Hedvig","Hedvige","Hedwig","Hedwiga","Hedy","Heida","Heidi","Heidie","Helaina","Helaine","Helen","Helen-elizabeth","Helena","Helene","Helenka","Helga","Helge","Helli","Heloise","Helsa","Helyn","Hendrika","Henka","Henrie","Henrieta","Henrietta","Henriette","Henryetta","Hephzibah","Hermia","Hermina","Hermine","Herminia","Hermione","Herta","Hertha","Hester","Hesther","Hestia","Hetti","Hettie","Hetty","Hilary","Hilda","Hildagard","Hildagarde","Hilde","Hildegaard","Hildegarde","Hildy","Hillary","Hilliary","Hinda","Holli","Hollie","Holly","Holly-anne","Hollyanne","Honey","Honor","Honoria","Hope","Horatia","Hortense","Hortensia","Hulda","Hyacinth","Hyacintha","Hyacinthe","Hyacinthia","Hyacinthie","Hynda","Ianthe","Ibbie","Ibby","Ida","Idalia","Idalina","Idaline","Idell","Idelle","Idette","Ileana","Ileane","Ilene","Ilise","Ilka","Illa","Ilsa","Ilse","Ilysa","Ilyse","Ilyssa","Imelda","Imogen","Imogene","Imojean","Ina","Indira","Ines","Inesita","Inessa","Inez","Inga","Ingaberg","Ingaborg","Inge","Ingeberg","Ingeborg","Inger","Ingrid","Ingunna","Inna","Iolande","Iolanthe","Iona","Iormina","Ira","Irena","Irene","Irina","Iris","Irita","Irma","Isa","Isabel","Isabelita","Isabella","Isabelle","Isadora","Isahella","Iseabal","Isidora","Isis","Isobel","Issi","Issie","Issy","Ivett","Ivette","Ivie","Ivonne","Ivory","Ivy","Izabel","Jacenta","Jacinda","Jacinta","Jacintha","Jacinthe","Jackelyn","Jacki","Jackie","Jacklin","Jacklyn","Jackquelin","Jackqueline","Jacky","Jaclin","Jaclyn","Jacquelin","Jacqueline","Jacquelyn","Jacquelynn","Jacquenetta","Jacquenette","Jacquetta","Jacquette","Jacqui","Jacquie","Jacynth","Jada","Jade","Jaime","Jaimie","Jaine","Jami","Jamie","Jamima","Jammie","Jan","Jana","Janaya","Janaye","Jandy","Jane","Janean","Janeczka","Janeen","Janel","Janela","Janella","Janelle","Janene","Janenna","Janessa","Janet","Janeta","Janetta","Janette","Janeva","Janey","Jania","Janice","Janie","Janifer","Janina","Janine","Janis","Janith","Janka","Janna","Jannel","Jannelle","Janot","Jany","Jaquelin","Jaquelyn","Jaquenetta","Jaquenette","Jaquith","Jasmin","Jasmina","Jasmine","Jayme","Jaymee","Jayne","Jaynell","Jazmin","Jean","Jeana","Jeane","Jeanelle","Jeanette","Jeanie","Jeanine","Jeanna","Jeanne","Jeannette","Jeannie","Jeannine","Jehanna","Jelene","Jemie","Jemima","Jemimah","Jemmie","Jemmy","Jen","Jena","Jenda","Jenelle","Jeni","Jenica","Jeniece","Jenifer","Jeniffer","Jenilee","Jenine","Jenn","Jenna","Jennee","Jennette","Jenni","Jennica","Jennie","Jennifer","Jennilee","Jennine","Jenny","Jeralee","Jere","Jeri","Jermaine","Jerrie","Jerrilee","Jerrilyn","Jerrine","Jerry","Jerrylee","Jess","Jessa","Jessalin","Jessalyn","Jessamine","Jessamyn","Jesse","Jesselyn","Jessi","Jessica","Jessie","Jessika","Jessy","Jewel","Jewell","Jewelle","Jill","Jillana","Jillane","Jillayne","Jilleen","Jillene","Jilli","Jillian","Jillie","Jilly","Jinny","Jo","Jo-ann","Jo-anne","Joan","Joana","Joane","Joanie","Joann","Joanna","Joanne","Joannes","Jobey","Jobi","Jobie","Jobina","Joby","Jobye","Jobyna","Jocelin","Joceline","Jocelyn","Jocelyne","Jodee","Jodi","Jodie","Jody","Joeann","Joela","Joelie","Joell","Joella","Joelle","Joellen","Joelly","Joellyn","Joelynn","Joete","Joey","Johanna","Johannah","Johna","Johnath","Johnette","Johnna","Joice","Jojo","Jolee","Joleen","Jolene","Joletta","Joli","Jolie","Joline","Joly","Jolyn","Jolynn","Jonell","Joni","Jonie","Jonis","Jordain","Jordan","Jordana","Jordanna","Jorey","Jori","Jorie","Jorrie","Jorry","Joscelin","Josee","Josefa","Josefina","Josepha","Josephina","Josephine","Josey","Josi","Josie","Josselyn","Josy","Jourdan","Joy","Joya","Joyan","Joyann","Joyce","Joycelin","Joye","Jsandye","Juana","Juanita","Judi","Judie","Judith","Juditha","Judy","Judye","Juieta","Julee","Juli","Julia","Juliana","Juliane","Juliann","Julianna","Julianne","Julie","Julienne","Juliet","Julieta","Julietta","Juliette","Julina","Juline","Julissa","Julita","June","Junette","Junia","Junie","Junina","Justina","Justine","Justinn","Jyoti","Kacey","Kacie","Kacy","Kaela","Kai","Kaia","Kaila","Kaile","Kailey","Kaitlin","Kaitlyn","Kaitlynn","Kaja","Kakalina","Kala","Kaleena","Kali","Kalie","Kalila","Kalina","Kalinda","Kalindi","Kalli","Kally","Kameko","Kamila","Kamilah","Kamillah","Kandace","Kandy","Kania","Kanya","Kara","Kara-lynn","Karalee","Karalynn","Kare","Karee","Karel","Karen","Karena","Kari","Karia","Karie","Karil","Karilynn","Karin","Karina","Karine","Kariotta","Karisa","Karissa","Karita","Karla","Karlee","Karleen","Karlen","Karlene","Karlie","Karlotta","Karlotte","Karly","Karlyn","Karmen","Karna","Karol","Karola","Karole","Karolina","Karoline","Karoly","Karon","Karrah","Karrie","Karry","Kary","Karyl","Karylin","Karyn","Kasey","Kass","Kassandra","Kassey","Kassi","Kassia","Kassie","Kat","Kata","Katalin","Kate","Katee","Katerina","Katerine","Katey","Kath","Katha","Katharina","Katharine","Katharyn","Kathe","Katherina","Katherine","Katheryn","Kathi","Kathie","Kathleen","Kathlin","Kathrine","Kathryn","Kathryne","Kathy","Kathye","Kati","Katie","Katina","Katine","Katinka","Katleen","Katlin","Katrina","Katrine","Katrinka","Katti","Kattie","Katuscha","Katusha","Katy","Katya","Kay","Kaycee","Kaye","Kayla","Kayle","Kaylee","Kayley","Kaylil","Kaylyn","Keeley","Keelia","Keely","Kelcey","Kelci","Kelcie","Kelcy","Kelila","Kellen","Kelley","Kelli","Kellia","Kellie","Kellina","Kellsie","Kelly","Kellyann","Kelsey","Kelsi","Kelsy","Kendra","Kendre","Kenna","Keri","Keriann","Kerianne","Kerri","Kerrie","Kerrill","Kerrin","Kerry","Kerstin","Kesley","Keslie","Kessia","Kessiah","Ketti","Kettie","Ketty","Kevina","Kevyn","Ki","Kiah","Kial","Kiele","Kiersten","Kikelia","Kiley","Kim","Kimberlee","Kimberley","Kimberli","Kimberly","Kimberlyn","Kimbra","Kimmi","Kimmie","Kimmy","Kinna","Kip","Kipp","Kippie","Kippy","Kira","Kirbee","Kirbie","Kirby","Kiri","Kirsten","Kirsteni","Kirsti","Kirstin","Kirstyn","Kissee","Kissiah","Kissie","Kit","Kitti","Kittie","Kitty","Kizzee","Kizzie","Klara","Klarika","Klarrisa","Konstance","Konstanze","Koo","Kora","Koral","Koralle","Kordula","Kore","Korella","Koren","Koressa","Kori","Korie","Korney","Korrie","Korry","Kris","Krissie","Krissy","Krista","Kristal","Kristan","Kriste","Kristel","Kristen","Kristi","Kristien","Kristin","Kristina","Kristine","Kristy","Kristyn","Krysta","Krystal","Krystalle","Krystle","Krystyna","Kyla","Kyle","Kylen","Kylie","Kylila","Kylynn","Kym","Kynthia","Kyrstin","Lacee","Lacey","Lacie","Lacy","Ladonna","Laetitia","Laina","Lainey","Lana","Lanae","Lane","Lanette","Laney","Lani","Lanie","Lanita","Lanna","Lanni","Lanny","Lara","Laraine","Lari","Larina","Larine","Larisa","Larissa","Lark","Laryssa","Latashia","Latia","Latisha","Latrena","Latrina","Laura","Lauraine","Laural","Lauralee","Laure","Lauree","Laureen","Laurel","Laurella","Lauren","Laurena","Laurene","Lauretta","Laurette","Lauri","Laurianne","Laurice","Laurie","Lauryn","Lavena","Laverna","Laverne","Lavina","Lavinia","Lavinie","Layla","Layne","Layney","Lea","Leah","Leandra","Leann","Leanna","Leanor","Leanora","Lebbie","Leda","Lee","Leeann","Leeanne","Leela","Leelah","Leena","Leesa","Leese","Legra","Leia","Leigh","Leigha","Leila","Leilah","Leisha","Lela","Lelah","Leland","Lelia","Lena","Lenee","Lenette","Lenka","Lenna","Lenora","Lenore","Leodora","Leoine","Leola","Leoline","Leona","Leonanie","Leone","Leonelle","Leonie","Leonora","Leonore","Leontine","Leontyne","Leora","Leshia","Lesley","Lesli","Leslie","Lesly","Lesya","Leta","Lethia","Leticia","Letisha","Letitia","Letizia","Letta","Letti","Lettie","Letty","Lexi","Lexie","Lexine","Lexis","Lexy","Leyla","Lezlie","Lia","Lian","Liana","Liane","Lianna","Lianne","Lib","Libbey","Libbi","Libbie","Libby","Licha","Lida","Lidia","Liesa","Lil","Lila","Lilah","Lilas","Lilia","Lilian","Liliane","Lilias","Lilith","Lilla","Lilli","Lillian","Lillis","Lilllie","Lilly","Lily","Lilyan","Lin","Lina","Lind","Linda","Lindi","Lindie","Lindsay","Lindsey","Lindsy","Lindy","Linea","Linell","Linet","Linette","Linn","Linnea","Linnell","Linnet","Linnie","Linzy","Lira","Lisa","Lisabeth","Lisbeth","Lise","Lisetta","Lisette","Lisha","Lishe","Lissa","Lissi","Lissie","Lissy","Lita","Liuka","Liv","Liva","Livia","Livvie","Livvy","Livvyy","Livy","Liz","Liza","Lizabeth","Lizbeth","Lizette","Lizzie","Lizzy","Loella","Lois","Loise","Lola","Loleta","Lolita","Lolly","Lona","Lonee","Loni","Lonna","Lonni","Lonnie","Lora","Lorain","Loraine","Loralee","Loralie","Loralyn","Loree","Loreen","Lorelei","Lorelle","Loren","Lorena","Lorene","Lorenza","Loretta","Lorette","Lori","Loria","Lorianna","Lorianne","Lorie","Lorilee","Lorilyn","Lorinda","Lorine","Lorita","Lorna","Lorne","Lorraine","Lorrayne","Lorri","Lorrie","Lorrin","Lorry","Lory","Lotta","Lotte","Lotti","Lottie","Lotty","Lou","Louella","Louisa","Louise","Louisette","Loutitia","Lu","Luce","Luci","Lucia","Luciana","Lucie","Lucienne","Lucila","Lucilia","Lucille","Lucina","Lucinda","Lucine","Lucita","Lucky","Lucretia","Lucy","Ludovika","Luella","Luelle","Luisa","Luise","Lula","Lulita","Lulu","Lura","Lurette","Lurleen","Lurlene","Lurline","Lusa","Luz","Lyda","Lydia","Lydie","Lyn","Lynda","Lynde","Lyndel","Lyndell","Lyndsay","Lyndsey","Lyndsie","Lyndy","Lynea","Lynelle","Lynett","Lynette","Lynn","Lynna","Lynne","Lynnea","Lynnell","Lynnelle","Lynnet","Lynnett","Lynnette","Lynsey","Lyssa","Mab","Mabel","Mabelle","Mable","Mada","Madalena","Madalyn","Maddalena","Maddi","Maddie","Maddy","Madel","Madelaine","Madeleine","Madelena","Madelene","Madelin","Madelina","Madeline","Madella","Madelle","Madelon","Madelyn","Madge","Madlen","Madlin","Madonna","Mady","Mae","Maegan","Mag","Magda","Magdaia","Magdalen","Magdalena","Magdalene","Maggee","Maggi","Maggie","Maggy","Mahala","Mahalia","Maia","Maible","Maiga","Maighdiln","Mair","Maire","Maisey","Maisie","Maitilde","Mala","Malanie","Malena","Malia","Malina","Malinda","Malinde","Malissa","Malissia","Mallissa","Mallorie","Mallory","Malorie","Malory","Malva","Malvina","Malynda","Mame","Mamie","Manda","Mandi","Mandie","Mandy","Manon","Manya","Mara","Marabel","Marcela","Marcelia","Marcella","Marcelle","Marcellina","Marcelline","Marchelle","Marci","Marcia","Marcie","Marcile","Marcille","Marcy","Mareah","Maren","Marena","Maressa","Marga","Margalit","Margalo","Margaret","Margareta","Margarete","Margaretha","Margarethe","Margaretta","Margarette","Margarita","Margaux","Marge","Margeaux","Margery","Marget","Margette","Margi","Margie","Margit","Margo","Margot","Margret","Marguerite","Margy","Mari","Maria","Mariam","Marian","Mariana","Mariann","Marianna","Marianne","Maribel","Maribelle","Maribeth","Marice","Maridel","Marie","Marie-ann","Marie-jeanne","Marieann","Mariejeanne","Mariel","Mariele","Marielle","Mariellen","Marietta","Mariette","Marigold","Marijo","Marika","Marilee","Marilin","Marillin","Marilyn","Marin","Marina","Marinna","Marion","Mariquilla","Maris","Marisa","Mariska","Marissa","Marita","Maritsa","Mariya","Marj","Marja","Marje","Marji","Marjie","Marjorie","Marjory","Marjy","Marketa","Marla","Marlane","Marleah","Marlee","Marleen","Marlena","Marlene","Marley","Marlie","Marline","Marlo","Marlyn","Marna","Marne","Marney","Marni","Marnia","Marnie","Marquita","Marrilee","Marris","Marrissa","Marsha","Marsiella","Marta","Martelle","Martguerita","Martha","Marthe","Marthena","Marti","Martica","Martie","Martina","Martita","Marty","Martynne","Mary","Marya","Maryann","Maryanna","Maryanne","Marybelle","Marybeth","Maryellen","Maryjane","Maryjo","Maryl","Marylee","Marylin","Marylinda","Marylou","Marylynne","Maryrose","Marys","Marysa","Masha","Matelda","Mathilda","Mathilde","Matilda","Matilde","Matti","Mattie","Matty","Maud","Maude","Maudie","Maura","Maure","Maureen","Maureene","Maurene","Maurine","Maurise","Maurita","Maurizia","Mavis","Mavra","Max","Maxi","Maxie","Maxine","Maxy","May","Maybelle","Maye","Mead","Meade","Meagan","Meaghan","Meara","Mechelle","Meg","Megan","Megen","Meggi","Meggie","Meggy","Meghan","Meghann","Mehetabel","Mei","Mel","Mela","Melamie","Melania","Melanie","Melantha","Melany","Melba","Melesa","Melessa","Melicent","Melina","Melinda","Melinde","Melisa","Melisande","Melisandra","Melisenda","Melisent","Melissa","Melisse","Melita","Melitta","Mella","Melli","Mellicent","Mellie","Mellisa","Mellisent","Melloney","Melly","Melodee","Melodie","Melody","Melonie","Melony","Melosa","Melva","Mercedes","Merci","Mercie","Mercy","Meredith","Meredithe","Meridel","Meridith","Meriel","Merilee","Merilyn","Meris","Merissa","Merl","Merla","Merle","Merlina","Merline","Merna","Merola","Merralee","Merridie","Merrie","Merrielle","Merrile","Merrilee","Merrili","Merrill","Merrily","Merry","Mersey","Meryl","Meta","Mia","Micaela","Michaela","Michaelina","Michaeline","Michaella","Michal","Michel","Michele","Michelina","Micheline","Michell","Michelle","Micki","Mickie","Micky","Midge","Mignon","Mignonne","Miguela","Miguelita","Mikaela","Mil","Mildred","Mildrid","Milena","Milicent","Milissent","Milka","Milli","Millicent","Millie","Millisent","Milly","Milzie","Mimi","Min","Mina","Minda","Mindy","Minerva","Minetta","Minette","Minna","Minnaminnie","Minne","Minni","Minnie","Minnnie","Minny","Minta","Miquela","Mira","Mirabel","Mirabella","Mirabelle","Miran","Miranda","Mireielle","Mireille","Mirella","Mirelle","Miriam","Mirilla","Mirna","Misha","Missie","Missy","Misti","Misty","Mitzi","Modesta","Modestia","Modestine","Modesty","Moina","Moira","Moll","Mollee","Molli","Mollie","Molly","Mommy","Mona","Monah","Monica","Monika","Monique","Mora","Moreen","Morena","Morgan","Morgana","Morganica","Morganne","Morgen","Moria","Morissa","Morna","Moselle","Moyna","Moyra","Mozelle","Muffin","Mufi","Mufinella","Muire","Mureil","Murial","Muriel","Murielle","Myra","Myrah","Myranda","Myriam","Myrilla","Myrle","Myrlene","Myrna","Myrta","Myrtia","Myrtice","Myrtie","Myrtle","Nada","Nadean","Nadeen","Nadia","Nadine","Nadiya","Nady","Nadya","Nalani","Nan","Nana","Nananne","Nance","Nancee","Nancey","Nanci","Nancie","Nancy","Nanete","Nanette","Nani","Nanice","Nanine","Nannette","Nanni","Nannie","Nanny","Nanon","Naoma","Naomi","Nara","Nari","Nariko","Nat","Nata","Natala","Natalee","Natalie","Natalina","Nataline","Natalya","Natasha","Natassia","Nathalia","Nathalie","Natividad","Natka","Natty","Neala","Neda","Nedda","Nedi","Neely","Neila","Neile","Neilla","Neille","Nelia","Nelie","Nell","Nelle","Nelli","Nellie","Nelly","Nerissa","Nerita","Nert","Nerta","Nerte","Nerti","Nertie","Nerty","Nessa","Nessi","Nessie","Nessy","Nesta","Netta","Netti","Nettie","Nettle","Netty","Nevsa","Neysa","Nichol","Nichole","Nicholle","Nicki","Nickie","Nicky","Nicol","Nicola","Nicole","Nicolea","Nicolette","Nicoli","Nicolina","Nicoline","Nicolle","Nikaniki","Nike","Niki","Nikki","Nikkie","Nikoletta","Nikolia","Nina","Ninetta","Ninette","Ninnetta","Ninnette","Ninon","Nissa","Nisse","Nissie","Nissy","Nita","Nixie","Noami","Noel","Noelani","Noell","Noella","Noelle","Noellyn","Noelyn","Noemi","Nola","Nolana","Nolie","Nollie","Nomi","Nona","Nonah","Noni","Nonie","Nonna","Nonnah","Nora","Norah","Norean","Noreen","Norene","Norina","Norine","Norma","Norri","Norrie","Norry","Novelia","Nydia","Nyssa","Octavia","Odele","Odelia","Odelinda","Odella","Odelle","Odessa","Odetta","Odette","Odilia","Odille","Ofelia","Ofella","Ofilia","Ola","Olenka","Olga","Olia","Olimpia","Olive","Olivette","Olivia","Olivie","Oliy","Ollie","Olly","Olva","Olwen","Olympe","Olympia","Olympie","Ondrea","Oneida","Onida","Oona","Opal","Opalina","Opaline","Ophelia","Ophelie","Ora","Oralee","Oralia","Oralie","Oralla","Oralle","Orel","Orelee","Orelia","Orelie","Orella","Orelle","Oriana","Orly","Orsa","Orsola","Ortensia","Otha","Othelia","Othella","Othilia","Othilie","Ottilie","Page","Paige","Paloma","Pam","Pamela","Pamelina","Pamella","Pammi","Pammie","Pammy","Pandora","Pansie","Pansy","Paola","Paolina","Papagena","Pat","Patience","Patrica","Patrice","Patricia","Patrizia","Patsy","Patti","Pattie","Patty","Paula","Paule","Pauletta","Paulette","Pauli","Paulie","Paulina","Pauline","Paulita","Pauly","Pavia","Pavla","Pearl","Pearla","Pearle","Pearline","Peg","Pegeen","Peggi","Peggie","Peggy","Pen","Penelopa","Penelope","Penni","Pennie","Penny","Pepi","Pepita","Peri","Peria","Perl","Perla","Perle","Perri","Perrine","Perry","Persis","Pet","Peta","Petra","Petrina","Petronella","Petronia","Petronilla","Petronille","Petunia","Phaedra","Phaidra","Phebe","Phedra","Phelia","Phil","Philipa","Philippa","Philippe","Philippine","Philis","Phillida","Phillie","Phillis","Philly","Philomena","Phoebe","Phylis","Phyllida","Phyllis","Phyllys","Phylys","Pia","Pier","Pierette","Pierrette","Pietra","Piper","Pippa","Pippy","Polly","Pollyanna","Pooh","Poppy","Portia","Pris","Prisca","Priscella","Priscilla","Prissie","Pru","Prudence","Prudi","Prudy","Prue","Queenie","Quentin","Querida","Quinn","Quinta","Quintana","Quintilla","Quintina","Rachael","Rachel","Rachele","Rachelle","Rae","Raeann","Raf","Rafa","Rafaela","Rafaelia","Rafaelita","Rahal","Rahel","Raina","Raine","Rakel","Ralina","Ramona","Ramonda","Rana","Randa","Randee","Randene","Randi","Randie","Randy","Ranee","Rani","Rania","Ranice","Ranique","Ranna","Raphaela","Raquel","Raquela","Rasia","Rasla","Raven","Ray","Raychel","Raye","Rayna","Raynell","Rayshell","Rea","Reba","Rebbecca","Rebe","Rebeca","Rebecca","Rebecka","Rebeka","Rebekah","Rebekkah","Ree","Reeba","Reena","Reeta","Reeva","Regan","Reggi","Reggie","Regina","Regine","Reiko","Reina","Reine","Remy","Rena","Renae","Renata","Renate","Rene","Renee","Renell","Renelle","Renie","Rennie","Reta","Retha","Revkah","Rey","Reyna","Rhea","Rheba","Rheta","Rhetta","Rhiamon","Rhianna","Rhianon","Rhoda","Rhodia","Rhodie","Rhody","Rhona","Rhonda","Riane","Riannon","Rianon","Rica","Ricca","Rici","Ricki","Rickie","Ricky","Riki","Rikki","Rina","Risa","Rita","Riva","Rivalee","Rivi","Rivkah","Rivy","Roana","Roanna","Roanne","Robbi","Robbie","Robbin","Robby","Robbyn","Robena","Robenia","Roberta","Robin","Robina","Robinet","Robinett","Robinetta","Robinette","Robinia","Roby","Robyn","Roch","Rochell","Rochella","Rochelle","Rochette","Roda","Rodi","Rodie","Rodina","Rois","Romola","Romona","Romonda","Romy","Rona","Ronalda","Ronda","Ronica","Ronna","Ronni","Ronnica","Ronnie","Ronny","Roobbie","Rora","Rori","Rorie","Rory","Ros","Rosa","Rosabel","Rosabella","Rosabelle","Rosaleen","Rosalia","Rosalie","Rosalind","Rosalinda","Rosalinde","Rosaline","Rosalyn","Rosalynd","Rosamond","Rosamund","Rosana","Rosanna","Rosanne","Rose","Roseann","Roseanna","Roseanne","Roselia","Roselin","Roseline","Rosella","Roselle","Rosemaria","Rosemarie","Rosemary","Rosemonde","Rosene","Rosetta","Rosette","Roshelle","Rosie","Rosina","Rosita","Roslyn","Rosmunda","Rosy","Row","Rowe","Rowena","Roxana","Roxane","Roxanna","Roxanne","Roxi","Roxie","Roxine","Roxy","Roz","Rozalie","Rozalin","Rozamond","Rozanna","Rozanne","Roze","Rozele","Rozella","Rozelle","Rozina","Rubetta","Rubi","Rubia","Rubie","Rubina","Ruby","Ruperta","Ruth","Ruthann","Ruthanne","Ruthe","Ruthi","Ruthie","Ruthy","Ryann","Rycca","Saba","Sabina","Sabine","Sabra","Sabrina","Sacha","Sada","Sadella","Sadie","Sadye","Saidee","Sal","Salaidh","Sallee","Salli","Sallie","Sally","Sallyann","Sallyanne","Saloma","Salome","Salomi","Sam","Samantha","Samara","Samaria","Sammy","Sande","Sandi","Sandie","Sandra","Sandy","Sandye","Sapphira","Sapphire","Sara","Sara-ann","Saraann","Sarah","Sarajane","Saree","Sarena","Sarene","Sarette","Sari","Sarina","Sarine","Sarita","Sascha","Sasha","Sashenka","Saudra","Saundra","Savina","Sayre","Scarlet","Scarlett","Sean","Seana","Seka","Sela","Selena","Selene","Selestina","Selia","Selie","Selina","Selinda","Seline","Sella","Selle","Selma","Sena","Sephira","Serena","Serene","Shae","Shaina","Shaine","Shalna","Shalne","Shana","Shanda","Shandee","Shandeigh","Shandie","Shandra","Shandy","Shane","Shani","Shanie","Shanna","Shannah","Shannen","Shannon","Shanon","Shanta","Shantee","Shara","Sharai","Shari","Sharia","Sharity","Sharl","Sharla","Sharleen","Sharlene","Sharline","Sharon","Sharona","Sharron","Sharyl","Shaun","Shauna","Shawn","Shawna","Shawnee","Shay","Shayla","Shaylah","Shaylyn","Shaylynn","Shayna","Shayne","Shea","Sheba","Sheela","Sheelagh","Sheelah","Sheena","Sheeree","Sheila","Sheila-kathryn","Sheilah","Shel","Shela","Shelagh","Shelba","Shelbi","Shelby","Shelia","Shell","Shelley","Shelli","Shellie","Shelly","Shena","Sher","Sheree","Sheri","Sherie","Sherill","Sherilyn","Sherline","Sherri","Sherrie","Sherry","Sherye","Sheryl","Shina","Shir","Shirl","Shirlee","Shirleen","Shirlene","Shirley","Shirline","Shoshana","Shoshanna","Siana","Sianna","Sib","Sibbie","Sibby","Sibeal","Sibel","Sibella","Sibelle","Sibilla","Sibley","Sibyl","Sibylla","Sibylle","Sidoney","Sidonia","Sidonnie","Sigrid","Sile","Sileas","Silva","Silvana","Silvia","Silvie","Simona","Simone","Simonette","Simonne","Sindee","Siobhan","Sioux","Siouxie","Sisely","Sisile","Sissie","Sissy","Siusan","Sofia","Sofie","Sondra","Sonia","Sonja","Sonni","Sonnie","Sonnnie","Sonny","Sonya","Sophey","Sophi","Sophia","Sophie","Sophronia","Sorcha","Sosanna","Stace","Stacee","Stacey","Staci","Stacia","Stacie","Stacy","Stafani","Star","Starla","Starlene","Starlin","Starr","Stefa","Stefania","Stefanie","Steffane","Steffi","Steffie","Stella","Stepha","Stephana","Stephani","Stephanie","Stephannie","Stephenie","Stephi","Stephie","Stephine","Stesha","Stevana","Stevena","Stoddard","Storm","Stormi","Stormie","Stormy","Sue","Suellen","Sukey","Suki","Sula","Sunny","Sunshine","Susan","Susana","Susanetta","Susann","Susanna","Susannah","Susanne","Susette","Susi","Susie","Susy","Suzann","Suzanna","Suzanne","Suzette","Suzi","Suzie","Suzy","Sybil","Sybila","Sybilla","Sybille","Sybyl","Sydel","Sydelle","Sydney","Sylvia","Tabatha","Tabbatha","Tabbi","Tabbie","Tabbitha","Tabby","Tabina","Tabitha","Taffy","Talia","Tallia","Tallie","Tallou","Tallulah","Tally","Talya","Talyah","Tamar","Tamara","Tamarah","Tamarra","Tamera","Tami","Tamiko","Tamma","Tammara","Tammi","Tammie","Tammy","Tamqrah","Tamra","Tana","Tandi","Tandie","Tandy","Tanhya","Tani","Tania","Tanitansy","Tansy","Tanya","Tara","Tarah","Tarra","Tarrah","Taryn","Tasha","Tasia","Tate","Tatiana","Tatiania","Tatum","Tawnya","Tawsha","Ted","Tedda","Teddi","Teddie","Teddy","Tedi","Tedra","Teena","Teirtza","Teodora","Tera","Teresa","Terese","Teresina","Teresita","Teressa","Teri","Teriann","Terra","Terri","Terrie","Terrijo","Terry","Terrye","Tersina","Terza","Tess","Tessa","Tessi","Tessie","Tessy","Thalia","Thea","Theadora","Theda","Thekla","Thelma","Theo","Theodora","Theodosia","Theresa","Therese","Theresina","Theresita","Theressa","Therine","Thia","Thomasa","Thomasin","Thomasina","Thomasine","Tiena","Tierney","Tiertza","Tiff","Tiffani","Tiffanie","Tiffany","Tiffi","Tiffie","Tiffy","Tilda","Tildi","Tildie","Tildy","Tillie","Tilly","Tim","Timi","Timmi","Timmie","Timmy","Timothea","Tina","Tine","Tiphani","Tiphanie","Tiphany","Tish","Tisha","Tobe","Tobey","Tobi","Toby","Tobye","Toinette","Toma","Tomasina","Tomasine","Tomi","Tommi","Tommie","Tommy","Toni","Tonia","Tonie","Tony","Tonya","Tonye","Tootsie","Torey","Tori","Torie","Torrie","Tory","Tova","Tove","Tracee","Tracey","Traci","Tracie","Tracy","Trenna","Tresa","Trescha","Tressa","Tricia","Trina","Trish","Trisha","Trista","Trix","Trixi","Trixie","Trixy","Truda","Trude","Trudey","Trudi","Trudie","Trudy","Trula","Tuesday","Twila","Twyla","Tybi","Tybie","Tyne","Ula","Ulla","Ulrica","Ulrika","Ulrikaumeko","Ulrike","Umeko","Una","Ursa","Ursala","Ursola","Ursula","Ursulina","Ursuline","Uta","Val","Valaree","Valaria","Vale","Valeda","Valencia","Valene","Valenka","Valentia","Valentina","Valentine","Valera","Valeria","Valerie","Valery","Valerye","Valida","Valina","Valli","Vallie","Vally","Valma","Valry","Van","Vanda","Vanessa","Vania","Vanna","Vanni","Vannie","Vanny","Vanya","Veda","Velma","Velvet","Venita","Venus","Vera","Veradis","Vere","Verena","Verene","Veriee","Verile","Verina","Verine","Verla","Verna","Vernice","Veronica","Veronika","Veronike","Veronique","Vevay","Vi","Vicki","Vickie","Vicky","Victoria","Vida","Viki","Vikki","Vikky","Vilhelmina","Vilma","Vin","Vina","Vinita","Vinni","Vinnie","Vinny","Viola","Violante","Viole","Violet","Violetta","Violette","Virgie","Virgina","Virginia","Virginie","Vita","Vitia","Vitoria","Vittoria","Viv","Viva","Vivi","Vivia","Vivian","Viviana","Vivianna","Vivianne","Vivie","Vivien","Viviene","Vivienne","Viviyan","Vivyan","Vivyanne","Vonni","Vonnie","Vonny","Vyky","Wallie","Wallis","Walliw","Wally","Waly","Wanda","Wandie","Wandis","Waneta","Wanids","Wenda","Wendeline","Wendi","Wendie","Wendy","Wendye","Wenona","Wenonah","Whitney","Wileen","Wilhelmina","Wilhelmine","Wilie","Willa","Willabella","Willamina","Willetta","Willette","Willi","Willie","Willow","Willy","Willyt","Wilma","Wilmette","Wilona","Wilone","Wilow","Windy","Wini","Winifred","Winna","Winnah","Winne","Winni","Winnie","Winnifred","Winny","Winona","Winonah","Wren","Wrennie","Wylma","Wynn","Wynne","Wynnie","Wynny","Xaviera","Xena","Xenia","Xylia","Xylina","Yalonda","Yasmeen","Yasmin","Yelena","Yetta","Yettie","Yetty","Yevette","Ynes","Ynez","Yoko","Yolanda","Yolande","Yolane","Yolanthe","Yoshi","Yoshiko","Yovonnda","Ysabel","Yvette","Yvonne","Zabrina","Zahara","Zandra","Zaneta","Zara","Zarah","Zaria","Zarla","Zea","Zelda","Zelma","Zena","Zenia","Zia","Zilvia","Zita","Zitella","Zoe","Zola","Zonda","Zondra","Zonnya","Zora","Zorah","Zorana","Zorina","Zorine","Zsazsa","Zulema","Zuzana"],lm={exports:{}};/** * @license * Lodash diff --git a/examples/react-tldraw/index.html b/examples/react-tldraw/index.html index 2cf493343..d9090bec6 100644 --- a/examples/react-tldraw/index.html +++ b/examples/react-tldraw/index.html @@ -4,7 +4,7 @@ react-tldraw - + diff --git a/examples/react-todomvc/assets/index-BakcgfXy.js b/examples/react-todomvc/assets/index-q-5ISMOx.js similarity index 95% rename from examples/react-todomvc/assets/index-BakcgfXy.js rename to examples/react-todomvc/assets/index-q-5ISMOx.js index 12e1bc80e..c9d572ef6 100644 --- a/examples/react-todomvc/assets/index-BakcgfXy.js +++ b/examples/react-todomvc/assets/index-q-5ISMOx.js @@ -59,7 +59,7 @@ Error generating stack: `+s.message+` * * SPDX-License-Identifier: Apache-2.0 */var wt=null;try{wt=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function q(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}q.prototype.__isLong__;Object.defineProperty(q.prototype,"__isLong__",{value:!0});function Re(n){return(n&&n.__isLong__)===!0}function Yh(n){var e=Math.clz32(n&-n);return n?31-e:e}q.isLong=Re;var Qh={},Xh={};function Ci(n,e){var t,r,i;return e?(n>>>=0,(i=0<=n&&n<256)&&(r=Xh[n],r)?r:(t=W(n,0,!0),i&&(Xh[n]=t),t)):(n|=0,(i=-128<=n&&n<128)&&(r=Qh[n],r)?r:(t=W(n,n<0?-1:0,!1),i&&(Qh[n]=t),t))}q.fromInt=Ci;function St(n,e){if(isNaN(n))return e?hr:Ot;if(e){if(n<0)return hr;if(n>=ty)return iy}else{if(n<=-eg)return je;if(n+1>=eg)return ry}return n<0?St(-n,e).neg():W(n%ds|0,n/ds|0,e)}q.fromNumber=St;function W(n,e,t){return new q(n,e,t)}q.fromBits=W;var hl=Math.pow;function _f(n,e,t){if(n.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return e?hr:Ot;if(t=t||10,t<2||360)throw Error("interior hyphen");if(r===0)return _f(n.substring(1),e,t).neg();for(var i=St(hl(t,8)),s=Ot,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*ds+(this.low>>>0):this.high*ds+(this.low>>>0)};C.toString=function(e){if(e=e||10,e<2||36>>0,d=c.toString(e);if(o=l,o.isZero())return d+a;for(;d.length<6;)d="0"+d;a=""+d+a}};C.getHighBits=function(){return this.high};C.getHighBitsUnsigned=function(){return this.high>>>0};C.getLowBits=function(){return this.low};C.getLowBitsUnsigned=function(){return this.low>>>0};C.getNumBitsAbs=function(){if(this.isNegative())return this.eq(je)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};C.isOdd=function(){return(this.low&1)===1};C.isEven=function(){return(this.low&1)===0};C.equals=function(e){return Re(e)||(e=$t(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};C.eq=C.equals;C.notEquals=function(e){return!this.eq(e)};C.neq=C.notEquals;C.ne=C.notEquals;C.lessThan=function(e){return this.comp(e)<0};C.lt=C.lessThan;C.lessThanOrEqual=function(e){return this.comp(e)<=0};C.lte=C.lessThanOrEqual;C.le=C.lessThanOrEqual;C.greaterThan=function(e){return this.comp(e)>0};C.gt=C.greaterThan;C.greaterThanOrEqual=function(e){return this.comp(e)>=0};C.gte=C.greaterThanOrEqual;C.ge=C.greaterThanOrEqual;C.compare=function(e){if(Re(e)||(e=$t(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};C.comp=C.compare;C.negate=function(){return!this.unsigned&&this.eq(je)?je:this.not().add(qi)};C.neg=C.negate;C.add=function(e){Re(e)||(e=$t(e));var t=this.high>>>16,r=this.high&65535,i=this.low>>>16,s=this.low&65535,o=e.high>>>16,a=e.high&65535,l=e.low>>>16,c=e.low&65535,d=0,h=0,p=0,m=0;return m+=s+c,p+=m>>>16,m&=65535,p+=i+l,h+=p>>>16,p&=65535,h+=r+a,d+=h>>>16,h&=65535,d+=t+o,d&=65535,W(p<<16|m,d<<16|h,this.unsigned)};C.subtract=function(e){return Re(e)||(e=$t(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(Re(e)||(e=$t(e)),wt){var t=wt.mul(this.low,this.high,e.low,e.high);return W(t,wt.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?hr:Ot;if(this.eq(je))return e.isOdd()?je:Ot;if(e.eq(je))return this.isOdd()?je:Ot;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(tg)&&e.lt(tg))return St(this.toNumber()*e.toNumber(),this.unsigned);var r=this.high>>>16,i=this.high&65535,s=this.low>>>16,o=this.low&65535,a=e.high>>>16,l=e.high&65535,c=e.low>>>16,d=e.low&65535,h=0,p=0,m=0,w=0;return w+=o*d,m+=w>>>16,w&=65535,m+=s*d,p+=m>>>16,m&=65535,m+=o*c,p+=m>>>16,m&=65535,p+=i*d,h+=p>>>16,p&=65535,p+=s*c,h+=p>>>16,p&=65535,p+=o*l,h+=p>>>16,p&=65535,h+=r*d+i*c+s*l+o*a,h&=65535,W(m<<16|w,h<<16|p,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(Re(e)||(e=$t(e)),e.isZero())throw Error("division by zero");if(wt){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?wt.div_u:wt.div_s)(this.low,this.high,e.low,e.high);return W(t,wt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?hr:Ot;var r,i,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return hr;if(e.gt(this.shru(1)))return ny;s=hr}else{if(this.eq(je)){if(e.eq(qi)||e.eq(jc))return je;if(e.eq(je))return qi;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(Ot)?e.isNegative()?qi:jc:(i=this.sub(e.mul(r)),s=r.add(i.div(e)),s)}else if(e.eq(je))return this.unsigned?hr:Ot;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Ot}for(i=this;i.gte(e);){r=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(r)/Math.LN2),l=a<=48?1:hl(2,a-48),c=St(r),d=c.mul(e);d.isNegative()||d.gt(i);)r-=l,c=St(r,this.unsigned),d=c.mul(e);c.isZero()&&(c=qi),s=s.add(c),i=i.sub(d)}return s};C.div=C.divide;C.modulo=function(e){if(Re(e)||(e=$t(e)),wt){var t=(this.unsigned?wt.rem_u:wt.rem_s)(this.low,this.high,e.low,e.high);return W(t,wt.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};C.mod=C.modulo;C.rem=C.modulo;C.not=function(){return W(~this.low,~this.high,this.unsigned)};C.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};C.clz=C.countLeadingZeros;C.countTrailingZeros=function(){return this.low?Yh(this.low):Yh(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return Re(e)||(e=$t(e)),W(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return Re(e)||(e=$t(e)),W(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return Re(e)||(e=$t(e)),W(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low<>>32-e,this.unsigned):W(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):W(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?W(this.high,0,this.unsigned):W(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var t;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(t=32-e,W(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,W(this.high<>>t,this.low<>>t,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var t;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(t=32-e,W(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,W(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?W(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:W(this.low,this.high,!0)};C.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};C.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};C.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};q.fromBytes=function(e,t,r){return r?q.fromBytesLE(e,t):q.fromBytesBE(e,t)};q.fromBytesLE=function(e,t){return new q(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};q.fromBytesBE=function(e,t){return new q(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var ve=(n=>(n[n.Null=0]="Null",n[n.Boolean=1]="Boolean",n[n.Integer=2]="Integer",n[n.Long=3]="Long",n[n.Double=4]="Double",n[n.String=5]="String",n[n.Bytes=6]="Bytes",n[n.Date=7]="Date",n))(ve||{});class ie extends No{constructor(t,r){super(r);u(this,"valueType");u(this,"value");this.valueType=ie.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,r){return new ie(t,r)}static valueFromBytes(t,r){switch(t){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(s,o){i.setUint8(o,s)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return q.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(q.fromBytesLE(Array.from(r),!0).toNumber());default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${en(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=ie.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof q)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return ie.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,t,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const t=this.value,r=q.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class gl extends ey{constructor(t){super(t);u(this,"prev");u(this,"next");this.value=t}static createAfter(t,r){const i=new gl(r),s=t.next;return t.next=i,i.prev=t,i.next=s,s&&(s.prev=i),i}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class wo{constructor(){u(this,"dummyHead");u(this,"last");u(this,"nodeMapByIndex");u(this,"nodeMapByCreatedAt");const e=ie.of(0,bt);e.setRemovedAt(bt),this.dummyHead=new gl(e),this.last=this.dummyHead,this.nodeMapByIndex=new vo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new wo}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(t);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,r=t.getCreatedAt()){const i=this.findNextBeforeExecutedAt(e,r),s=gl.createAfter(i,t);i===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(i,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,t,r){const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new k(S.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);i!==s&&(!s.getValue().getMovedAt()||r.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(i.getCreatedAt(),s.getValue(),r),s.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new k(S.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,r]=this.nodeMapByIndex.find(e);let i=t;if(e===0&&t===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const r=this.nodeMapByCreatedAt.get(e.toIDString()),i=r.isRemoved();return r.remove(t)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,t){const r=this.getByIndex(e);if(r)return r.remove(t)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const r=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${r}}`):e.push(`[${r}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class tt extends Wr{constructor(t,r){super(t);u(this,"elements");this.elements=r}static create(t,r){if(!r)return new tt(t,wo.create());const i=wo.create();for(const s of r)i.insertAfter(i.getLastCreatedAt(),s.deepcopy());return new tt(t,i)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,r){this.elements.insertAfter(t,r)}moveAfter(t,r,i){this.elements.moveAfter(t,r,i)}get(t){const r=this.elements.getByIndex(t);return r==null?void 0:r.getValue()}getByID(t){const r=this.elements.getByID(t);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,r){return this.elements.delete(t,r)}deleteByIndex(t,r){return this.elements.deleteByIndex(t,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const r of this.elements){const i=r.getValue();if(t(i,this))return;i instanceof Wr&&i.getDescendants(t)}}toJSON(){const t=[];for(const r of this)t.push(r.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let r=0;r({...m,value:m.value?{attributes:Xi(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[c,p,d,[l,l]]}setStyle(t,r,i,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],i),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],i),l=[],c=this.rgaTreeSplit.findBetween(a,o),d=new Map,h=[];for(const m of c){const w=m.getCreatedAt().getActorID(),I=s!=null&&s.size?s.has(w)?s.get(w):bt:Ws;if(m.canStyle(i,I)){const O=d.get(w),y=m.getCreatedAt();(!O||y.after(O))&&d.set(w,y),h.push(m)}}const p=[];for(const m of h){if(m.isRemoved())continue;const[w,I]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());l.push({type:"style",actor:i.getActorID(),from:w,to:I,value:{attributes:Xi(r)}});for(const[O,y]of Object.entries(r)){const[g]=m.getValue().setAttr(O,y,i);g!==void 0&&p.push({parent:m.getValue(),child:g})}}return[d,p,l]}indexRangeToPosRange(t,r){const i=this.rgaTreeSplit.indexToPos(t);return t===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const r of this.rgaTreeSplit)r.isRemoved()||t.push(r.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();t.push({attributes:Xi(i.getAttributes()),content:i.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new It(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())t.push(i)}return t}}class Do extends Jt{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"content");u(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(t,r,i,s,o,a,l){return new Do(t,r,i,s,o,a,l)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof It))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c})=>({type:"edit",from:a,to:l,value:c,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.content;return`${t}.EDIT(${r},${i},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Oo extends Jt{constructor(t,r,i,s,o,a){super(t,a);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(t,r,i,s,o,a){return new Oo(t,r,i,s,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof It))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:c})=>({type:"style",from:a,to:l,value:c,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.attributes;return`${t}.STYL(${r},${i},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const z1=2,U1="root",mr="text";function Ds(n,e){let t=0;const r=n.children;for(let i=0;i0)throw new k(S.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const r=t.updateDescendantsSize();t.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===mr}get paddedSize(){return this.size+(this.isText?0:z1)}isAncestorOf(e){return V1(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const r=this.value.slice(0,e),i=this.value.slice(e);if(!i.length)return;this.value=r;const s=this.cloneText(e+t);return s.value=i,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new k(S.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const r=this.cloneElement(t);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,e),s=this.children.slice(e);this._children=i,r._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),r.size=r._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(i=>!i.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const r=this._children.indexOf(t);if(r!==-1)return r;t=t.parent}return-1}}function V1(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var ge=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(ge||{});function sy(n,e,t,r){if(e>t)throw new k(S.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new k(S.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new k(S.ErrInvalidArgument,`to is out of range: ${t} > ${n.size}`);if(e===t)return;let i=0;for(const s of n.children){if(e-s.paddedSizes.size;(s.isText||l)&&r([s,s.isText?"Text":"Start"],c),sy(s,Math.max(0,o),Math.min(a,s.size),r),c&&r([s,"End"],c)}i+=s.paddedSize}}function oy(n,e,t=0){for(const r of n.children)oy(r,e,t+1);e(n,t)}function Fl(n,e,t=0){for(const r of n._children)Fl(r,e,t+1);e(n,t)}function Vc(n,e,t=!0){if(e>n.size)throw new k(S.ErrInvalidArgument,`index is out of range: ${e} > ${n.size}`);if(n.isText)return{node:n,offset:e};let r=0,i=0;for(const s of n.children){if(t&&s.isText&&s.size>=e-i)return Vc(s,e-i,t);if(e===i)return{node:n,offset:r};if(!t&&s.paddedSize===e-i)return{node:n,offset:r+1};if(s.paddedSize>e-i)return Vc(s,e-i-1,t);i+=s.paddedSize,r+=1}return{node:n,offset:r}}function ay(n){return n.isText||n.children.length===0?n:ay(n.children[0])}function q1(n,e){if(n.sizen===e?0:n0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(r<0)if(t.left)t.left.parent=t,t=t.left;else{let i=t.parent,s=t;for(;i&&s===i.left;)s=i,i=i.parent;return i}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const r=this.comparator(e,t.key);if(r===0)return t;r<0?t=t.left:r>0&&(t=t.right)}}putInternal(e,t,r){if(!r)return this.counter+=1,new H1(e,t,!0);const i=this.comparator(e,r.key);return i<0?r.left=this.putInternal(e,t,r.left):i>0?r.right=this.putInternal(e,t,r.right):r.value=t,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const r=this.min(e.right);e.value=r.value,e.key=r.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class Rt{constructor(e,t){u(this,"parentID");u(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new Rt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:r}=e,i;return r.isText?(r.parent.children[0]===r&&t===0?i=r.parent:i=r,r=r.parent):t===0?i=r:i=r.children[t-1],Rt.of(r.id,Ee.of(i.getCreatedAt(),i.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return Rt.of(Ee.of(et.fromStruct(e.parentID.createdAt),e.parentID.offset),Ee.of(et.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),r=this.getLeftSiblingID(),i=e.findFloorNode(t);let s=e.findFloorNode(r);if(!i||!s)throw new k(S.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${r.toTestString()})`);return!r.equals(t)&&r.getOffset()>0&&r.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[i,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Ee{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ee(e,t)}static fromStruct(e){return Ee.of(et.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const r=e.getCreatedAt().compare(t.getCreatedAt());return r!==0?r:e.getOffset()>t.getOffset()?1:e.getOffset(){const s=i.deepcopy();return s.parent=t,s}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new k(S.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new k(S.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),r&&this.updateAncestorsSize()}cloneText(t){return new Xe(Ee.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new Xe(Ee.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,r,i){const s=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(s){if(s.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,t.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,r){this.attrs||(this.attrs=new Tr);const i=new Array;for(const[s,o]of Object.entries(t))i.push(this.attrs.set(s,o,r));return i}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const r of this.attrs)r.getRemovedAt()&&t.push({parent:this,child:r});return t}}function qc(n){var t;if(n.isText){const r=n;return{type:r.type,value:r.value}}const e={type:n.type,children:n.children.map(qc)};return n.attrs&&(e.attributes=Xi((t=n.attrs)==null?void 0:t.toObject())),e}function Gf(n){if(n.isText)return n.value;let e="";return n.attrs&&n.attrs.size()&&(e=" "+Array.from(n.attrs).filter(t=>!t.isRemoved()).sort((t,r)=>t.getKey().localeCompare(r.getKey())).map(t=>{const r=JSON.parse(t.getValue());return typeof r=="string"?`${t.getKey()}="${r}"`:`${t.getKey()}="${en(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>Gf(t)).join("")}`}function uy(n){if(n.isText){const e=n;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:n.type,children:n.children.map(uy),size:n.size,isRemoved:n.isRemoved}}class Et extends No{constructor(t,r){super(r);u(this,"indexTree");u(this,"nodeMapByID");this.indexTree=new K1(t),this.nodeMapByID=new ly(Ee.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(t,r){return new Et(t,r)}findFloorNode(t){const r=this.nodeMapByID.floorEntry(t);if(!(!r||!r.key.getCreatedAt().equals(t.getCreatedAt())))return r.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,r){const[i,s]=t.toTreeNodePair(this);let o=s;const a=i===o,l=o.parent&&!a?o.parent:i;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const c=l.allChildren,d=a?0:c.indexOf(o)+1;for(let h=d;h{const I=w.getCreatedAt().getActorID(),O=s?s.has(I)?s.get(I):bt:Ws;if(w.canStyle(i,O)&&r){const y=p.get(I),g=w.getCreatedAt();(!y||g.after(y))&&p.set(I,g);const v=w.setAttrs(r,i),T=v.reduce((P,[,B])=>(B&&(P[B.getKey()]=h[B.getKey()]),P),{}),x=w.parent,N=w.prevSibling||w.parent;Object.keys(T).length>0&&d.push({type:"style",from:this.toIndex(x,N),to:this.toIndex(w,w),fromPath:this.toPath(x,N),toPath:this.toPath(w,w),actor:i.getActorID(),value:T});for(const[P]of v)P&&m.push({parent:w,child:P})}}),[p,m,d]}removeStyle(t,r,i,s){const[o,a]=this.findNodesAndSplitText(t[0],i),[l,c]=this.findNodesAndSplitText(t[1],i),d=[],h=new Map,p=[];return this.traverseInPosRange(o,a,l,c,([m])=>{const w=m.getCreatedAt().getActorID(),I=s?s.has(w)?s.get(w):bt:Ws;if(m.canStyle(i,I)&&r){const O=h.get(w),y=m.getCreatedAt();(!O||y.after(O))&&h.set(w,y),m.attrs||(m.attrs=new Tr);for(const T of r){const x=m.attrs.remove(T,i);for(const N of x)p.push({parent:m,child:N})}const g=m.parent,v=m.prevSibling||m.parent;d.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(g,v),to:this.toIndex(m,m),fromPath:this.toPath(g,v),toPath:this.toPath(m,m),value:r})}}),[h,p,d]}edit(t,r,i,s,o,a){const[l,c]=this.findNodesAndSplitText(t[0],s),[d,h]=this.findNodesAndSplitText(t[1],s),p=this.toIndex(l,c),m=this.toPath(l,c),w=[],I=[],O=[],y=new Map;this.traverseInPosRange(l,c,d,h,([T,x],N)=>{if(x===ge.Start&&!N)for(const H of T.children)O.push(H);const P=T.getCreatedAt().getActorID(),B=a?a.has(P)?a.get(P):bt:Ws;if(T.canDelete(s,B)||w.includes(T.parent)){const H=y.get(P),U=T.getCreatedAt();(!H||U.after(H))&&y.set(P,U),(x===ge.Text||x===ge.Start)&&w.push(T),I.push([T,x])}});const g=this.makeDeletionChanges(I,s),v=[];for(const T of w)T.remove(s),T.isRemoved&&v.push({parent:this,child:T});for(const T of O)T.removedAt||l.append(T);if(i>0){let T=0,x=l,N=c;for(;T{l.isRemoved&&(P.remove(s),v.push({parent:this,child:P})),this.nodeMapByID.put(P.id,P)}),N.isRemoved||T.push(N);if(T.length){const N=T.map(P=>qc(P));g.length&&g[g.length-1].from===p?g[g.length-1].value=N:g.push({type:"content",from:p,to:p,fromPath:m,toPath:m,actor:s.getActorID(),value:N})}}return[g,v,y]}editT(t,r,i,s,o){const a=this.findPos(t[0]),l=this.findPos(t[1]);this.edit([a,l],r,i,s,o)}move(t,r,i){throw new k(S.ErrUnimplemented,`not implemented: ${t}, ${r}, ${i}`)}purge(t){var s;(s=t.parent)==null||s.removeChild(t),this.nodeMapByID.remove(t.id);const r=t.insPrevID,i=t.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=i}if(i){const o=this.findFloorNode(i);o.insPrevID=r}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&t.push({parent:this,child:r});for(const i of r.getGCPairs())t.push(i)}),t}findPos(t,r=!0){const i=this.indexTree.findTreePos(t,r);return Rt.fromTreePos(i)}pathToPosRange(t){const r=this.pathToIndex(t);return[this.findPos(r),this.findPos(r+1)]}pathToPos(t){const r=this.indexTree.pathToIndex(t);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Gf(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),r=(i,s=void 0,o=void 0,a=0)=>{var m,w,I,O;let l,c,d;const h=i.isText?{node:i,offset:0}:s&&o?this.toTreePos(s,o):null;h&&(l=this.indexTree.indexOf(h),c=this.indexTree.treePosToPath(h),d=Rt.fromTreePos(h).toStruct());const p={type:i.type,parent:s==null?void 0:s.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(m=i.removedAt)==null?void 0:m.toTestString(),insPrev:(w=i.insPrevID)==null?void 0:w.toTestString(),insNext:(I=i.insNextID)==null?void 0:I.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:a,attributes:i.attrs?Xi((O=i.attrs)==null?void 0:O.toObject()):void 0,index:l,path:c,pos:d};for(let y=0;y0&&y===i[i.length-1].to?(i[i.length-1].to=g,i[i.length-1].toPath=this.toPath(O,m)):i.push({type:"content",from:y,to:g,fromPath:this.toPath(I,h),toPath:this.toPath(O,m),actor:r.getActorID()}))}return i.reverse()}findRightToken([t,r]){if(r===ge.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?ge.Text:ge.Start]:[t,ge.End]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===s.length-1)return[i,ge.End];const a=s[o+1];return[a,a.isText?ge.Text:ge.Start]}findLeftToken([t,r]){if(r===ge.End){const l=t.allChildren;if(l.length>0){const c=l[l.length-1];return[c,c.isText?ge.Text:ge.End]}return[t,ge.Start]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===0)return[i,ge.Start];const a=s[o-1];return[a,a.isText?ge.Text:ge.End]}}class Ro extends Jt{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"contents");u(this,"splitLevel");u(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,r,i,s,o,a,l){return new Ro(t,r,i,s,o,a,l)}execute(t){var l;const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),s=r,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(c=>c.deepcopy()),this.splitLevel,i,(()=>{let c=i.getDelimiter();return this.contents!==void 0&&(c+=this.contents.length),()=>et.of(i.getLamport(),++c,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const c of a)t.registerGCPair(c);return{opInfos:o.map(({from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${t}.EDIT(${r},${i},${s.map(o=>Gf(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Zi{constructor(e){u(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[r,i]of e){const s=this.vector.get(r),o=s&&s>i?s:i;t.set(r,o)}for(const[r,i]of this){const s=e.get(r),o=s&&s>i?s:i;t.set(r,o)}return new Zi(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,r]of this.vector)e.set(t,r);return new Zi(e)}filter(e){const t=new Map;for(const[r]of e){const i=this.vector.get(r);i!==void 0&&t.set(r,i)}return new Zi(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const G1=new Zi(new Map);class ar{constructor(e,t,r,i,s){u(this,"clientSeq");u(this,"serverSeq");u(this,"lamport");u(this,"actor");u(this,"versionVector");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.versionVector=i,this.actor=r}static of(e,t,r,i,s){return new ar(e,t,r,i,s)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new ar(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,r=this.versionVector.max(e.versionVector),i=new ar(this.clientSeq,t,this.actor,r);return i.versionVector.set(this.actor,t),i}setClocks(e,t){const r=e>this.lamport?e:this.lamport+1n,i=this.versionVector.max(t);return i.set(this.actor,r),ar.of(this.clientSeq,r,this.actor,i)}createTimeTicket(e){return et.of(this.lamport,e,this.actor)}setActor(e){return new ar(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new ar(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Y1=new ar(0,0n,Wf,G1);class hs{constructor({id:e,operations:t,presenceChange:r,message:i}){u(this,"id");u(this,"operations");u(this,"presenceChange");u(this,"message");this.id=e,this.operations=t||[],this.presenceChange=r,this.message=i}static create({id:e,operations:t,presenceChange:r,message:i}){return new hs({id:e,operations:t,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,r){const i=[],s=[];for(const o of this.operations){const a=o.execute(e,r);if(!a)continue;const{opInfos:l,reverseOp:c}=a;i.push(...l),c&&s.unshift(c)}return this.presenceChange&&(this.presenceChange.type===Qr.Put?t.set(this.id.getActorID(),Nt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:i,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:fe.bytesToHex(fe.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>fe.bytesToHex(fe.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:r,presenceChange:i,message:s}=e;return hs.create({id:fe.bytesToChangeID(fe.hexToBytes(t)),operations:r==null?void 0:r.map(o=>fe.bytesToOperation(fe.hexToBytes(o))),presenceChange:i,message:s})}}class Ml{constructor(e,t,r,i,s,o,a){u(this,"documentKey");u(this,"checkpoint");u(this,"isRemoved");u(this,"changes");u(this,"snapshot");u(this,"minSyncedTicket");u(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=i,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=s}static create(e,t,r,i,s,o,a){return new Ml(e,t,r,i,s,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class es{constructor(e,t){u(this,"serverSeq");u(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new es(e,t)}increaseClientSeq(e){return e===0?this:new es(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return es.of(t,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Q1=new es(0n,0);class rn{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new rn(e,t)}static fromStruct(e){return rn.of(et.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new rn(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const X1=rn.of(bt,0);class Ft{constructor(e,t){u(this,"id");u(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Ft(e,t)}static fromStruct(e){const t=rn.fromStruct(e.id);return Ft.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return rn.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class Hr extends ey{constructor(t,r,i){super(r);u(this,"id");u(this,"removedAt");u(this,"prev");u(this,"next");u(this,"insPrev");u(this,"insNext");this.id=t,this.removedAt=i}static create(t,r){return new Hr(t,r)}static createComparator(){return(t,r)=>{const i=t.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:t.getOffset()>r.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const r=[];let i=e;for(;i&&i!==t;)r.push(i),i=i.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new k(S.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const r=e.split(t);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);const i=e.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r){if(!e.length)return[[],new Map,new Map];const[i,s]=this.filterNodes(e,t,r),o=new Map,a=new Map,l=this.makeChanges(s,t);for(const c of i){const d=c.getCreatedAt().getActorID();(!o.has(d)||c.getID().getCreatedAt().after(o.get(d)))&&o.set(d,c.getID().getCreatedAt()),a.set(c.getID().toIDString(),c),c.remove(t)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,t,r){const i=!!r,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const c of e){const d=c.getCreatedAt().getActorID(),h=i?r.has(d)?r.get(d):bt:Ws;c.canDelete(t,h)?s.push(c):o.push(c)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const r=[];let i,s;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var sn=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(sn||{});class nt extends No{constructor(t,r,i){super(i);u(this,"valueType");u(this,"value");switch(this.valueType=t,t){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=q.fromNumber(r).toInt():this.value=ng(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=q.fromNumber(r):this.value=r;break;default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,r,i){return new nt(t,r,i)}static valueFromBytes(t,r){switch(t){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return q.fromBytesLE(Array.from(r));default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=nt.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof q?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!nt.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===ve.Long?this.value=this.value+t.getValue().toInt():this.value=q.fromNumber(this.value+ng(t.getValue())).toInt(),this}}class ms extends Jt{constructor(t,r,i){super(t,i);u(this,"value");this.value=r}static create(t,r,i){return new ms(t,r,i)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof nt))throw new k(S.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,s=this.value.deepcopy();return i.increase(s),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),i=t.getType()===ve.Long?t.getValue().multiply(-1):t.getValue()*-1;return ms.create(this.getParentCreatedAt(),ie.of(i,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class pr extends Jt{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"attributes");u(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(t,r,i,s,o,a){return new pr(t,r,i,s,o,new Array,a)}static createTreeRemoveStyleOperation(t,r,i,s,o,a){return new pr(t,r,i,s,new Map,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,c])=>a[l]=c),[,o,s]=i.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=i.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c,fromPath:d,toPath:h})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:c}:{attributesToRemove:c},fromPath:d,toPath:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function Z1(n){const e=new Kf,t=e.data;for(const[r,i]of Object.entries(n))t[r]=JSON.stringify(i);return e}function eS(n){if(n.type===Qr.Put)return new po({type:Ai.PUT,presence:Z1(n.presence)});if(n.type===Qr.Clear)return new po({type:Ai.CLEAR});throw new k(S.ErrUnimplemented,"unimplemented type")}function tS(n){return new Qp({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function cy(n){return new Bl({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:od(n.getActorID()),versionVector:Yf(n.getVersionVector())})}function F(n){if(n)return new b({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:od(n.getActorID())})}function Yf(n){if(!n)return;const e=new bl;for(const[t,r]of n)e.vector[t]=BigInt(r.toString());return e}function fy(n){switch(n){case ve.Null:return $.NULL;case ve.Boolean:return $.BOOLEAN;case ve.Integer:return $.INTEGER;case ve.Long:return $.LONG;case ve.Double:return $.DOUBLE;case ve.String:return $.STRING;case ve.Bytes:return $.BYTES;case ve.Date:return $.DATE;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function dy(n){switch(n){case sn.IntegerCnt:return $.INTEGER_CNT;case sn.LongCnt:return $.LONG_CNT;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function ku(n){if(n instanceof We)return new lt({type:$.JSON_OBJECT,createdAt:F(n.getCreatedAt()),value:Ey(n)});if(n instanceof tt)return new lt({type:$.JSON_ARRAY,createdAt:F(n.getCreatedAt()),value:RS(n)});if(n instanceof It)return new lt({type:$.TEXT,createdAt:F(n.getCreatedAt())});if(n instanceof ie)return new lt({type:fy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof nt)return new lt({type:dy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof Et)return new lt({type:$.TREE,createdAt:F(n.getCreatedAt()),value:BS(n)});throw new k(S.ErrUnimplemented,"unimplemented element")}function nS(n){return new go({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function Zo(n){return new kr({createdAt:F(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function ea(n){return new Ti({parentId:Hs(n.getParentID()),leftSiblingId:Hs(n.getLeftSiblingID())})}function Hs(n){return new Kr({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function hy(n){const e=new qf;if(n instanceof Ii){const t=n,r=new Ga;r.parentCreatedAt=F(t.getParentCreatedAt()),r.key=t.getKey(),r.value=ku(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="set",e.body.value=r}else if(n instanceof Po){const t=n,r=new Ya;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.value=ku(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="add",e.body.value=r}else if(n instanceof br){const t=n,r=new Qa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="move",e.body.value=r}else if(n instanceof Xr){const t=n,r=new Xa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(n instanceof Do){const t=n,r=new Za;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=Zo(t.getFromPos()),r.to=Zo(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);r.content=t.getContent();const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(n instanceof Oo){const t=n,r=new el;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=Zo(t.getFromPos()),r.to=Zo(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="style",e.body.value=r}else if(n instanceof ms){const t=n,r=new tl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.value=ku(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(n instanceof Ro){const t=n,r=new nl,i=r.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())i[s]=F(o);r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ea(t.getFromPos()),r.to=ea(t.getToPos()),r.contents=uS(t.getContents()),r.splitLevel=t.getSplitLevel(),r.executedAt=F(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(n instanceof pr){const t=n,r=new rl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ea(t.getFromPos()),r.to=ea(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=t.getAttributesToRemove();if(s.length>0)r.attributesToRemove=s;else{const o=r.attributes;for(const[a,l]of t.getAttributes())o[a]=l}r.executedAt=F(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new k(S.ErrUnimplemented,"unimplemented operation");return e}function rS(n){const e=[];for(const t of n)e.push(hy(t));return e}function iS(n){const e=new Gp({id:cy(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=rS(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=eS(n.getPresenceChange())),e}function sS(n){const e=[];for(const t of n)e.push(iS(t));return e}function oS(n){const e=[];for(const t of n)e.push(new Yp({key:t.getStrKey(),element:Xf(t.getValue())}));return e}function aS(n){const e=[];for(const t of n)e.push(new cl({element:Xf(t.getValue())}));return e}function lS(n){const e=[];for(const t of n){const r=new fl;r.id=nS(t.getID()),r.value=t.getValue().getContent(),r.removedAt=F(t.getRemovedAt());const i=r.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new cs;a.value=o.getValue(),a.updatedAt=F(o.getUpdatedAt()),i[o.getKey()]=a}e.push(r)}return e}function uS(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new dl({content:Qf(t)}));return e}function cS(n){const e={};for(const t of n)e[t.getKey()]=new cs({value:t.getValue(),updatedAt:F(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function Qf(n){if(!n)return[];const e=[];return Fl(n,(t,r)=>{const i=new mo({id:Hs(t.id),type:t.type,removedAt:F(t.removedAt),depth:r});t.isText&&(i.value=t.value),t.insPrevID&&(i.insPrevId=Hs(t.insPrevID)),t.insNextID&&(i.insNextId=Hs(t.insNextID)),t.attrs&&(i.attributes=cS(t.attrs)),e.push(i)}),e}function fS(n){const e=new He;return e.body.case="jsonObject",e.body.value=new il({nodes:oS(n.getRHT()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function gy(n){const e=new He;return e.body.case="jsonArray",e.body.value=new sl({nodes:aS(n.getElements()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function dS(n){const e=new He;return e.body.case="primitive",e.body.value=new ol({type:fy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function hS(n){const e=new He;return e.body.case="text",e.body.value=new al({nodes:lS(n.getRGATreeSplit()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function gS(n){const e=new He;return e.body.case="counter",e.body.value=new ll({type:dy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function my(n){const e=new He;return e.body.case="tree",e.body.value=new ul({nodes:Qf(n.getRoot()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function Xf(n){if(n instanceof We)return fS(n);if(n instanceof tt)return gy(n);if(n instanceof ie)return dS(n);if(n instanceof It)return hS(n);if(n instanceof nt)return gS(n);if(n instanceof Et)return my(n);throw new k(S.ErrUnimplemented,"unimplemented element")}function mS(n){return new Ir({documentKey:n.getDocumentKey(),checkpoint:tS(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:sS(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Yf(n.getVersionVector()),minSyncedTicket:F(n.getMinSyncedTicket())})}function rg(n){const e=n.findDetails(O1);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function py(n){return ar.of(n.clientSeq,BigInt(n.lamport),id(n.actorId),Zf(n.versionVector),BigInt(n.serverSeq))}function Zf(n){if(!n)return;const e=new Zi;return Object.entries(n.vector).forEach(([t,r])=>{e.set(t,BigInt(r.toString()))}),e}function M(n){if(n)return et.of(BigInt(n.lamport),n.delimiter,id(n.actorId))}function ed(n){const e={};return Object.entries(n.data).forEach(([t,r])=>{e[t]=JSON.parse(r)}),e}function pS(n){const e=n.type;if(e===Ai.PUT){const t=ed(n.presence);return{type:Qr.Put,presence:t}}if(e===Ai.CLEAR)return{type:Qr.Clear};throw new k(S.ErrInvalidType,`unsupported type: ${e}`)}function yS(n){const e=new Map;return Object.entries(n).forEach(([t,r])=>{e.set(t,ed(r))}),e}function yy(n){switch(n){case $.NULL:return ve.Null;case $.BOOLEAN:return ve.Boolean;case $.INTEGER:return ve.Integer;case $.LONG:return ve.Long;case $.DOUBLE:return ve.Double;case $.STRING:return ve.String;case $.BYTES:return ve.Bytes;case $.DATE:return ve.Date}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function ml(n){switch(n){case $.INTEGER_CNT:return sn.IntegerCnt;case $.LONG_CNT:return sn.LongCnt}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function Tu(n){switch(n.type){case $.JSON_OBJECT:return n.value?Iy(n.value):We.create(M(n.createdAt));case $.JSON_ARRAY:return n.value?OS(n.value):tt.create(M(n.createdAt));case $.TEXT:return It.create(gs.create(),M(n.createdAt));case $.TREE:return LS(n.value);case $.NULL:case $.BOOLEAN:case $.INTEGER:case $.LONG:case $.DOUBLE:case $.STRING:case $.BYTES:case $.DATE:return ie.of(ie.valueFromBytes(yy(n.type),n.value),M(n.createdAt));case $.INTEGER_CNT:case $.LONG_CNT:return nt.create(ml(n.type),nt.valueFromBytes(ml(n.type),n.value),M(n.createdAt))}}function ta(n){return Ft.of(rn.of(M(n.createdAt),n.offset),n.relativeOffset)}function vy(n){return rn.of(M(n.createdAt),n.offset)}function vS(n){const e=So.create(n.value);Object.entries(n.attributes).forEach(([r,i])=>{e.setAttr(r,i.value,M(i.updatedAt))});const t=Hr.create(vy(n.id),e);return t.remove(M(n.removedAt)),t}function Di(n){return Rt.of(_s(n.parentId),_s(n.leftSiblingId))}function _s(n){return Ee.of(M(n.createdAt),n.offset)}function wS(n){if(!n.length)return;const e=[];return n.forEach(t=>{const r=td(t.content);e.push(r)}),e}function td(n){if(n.length===0)return;const e=[];for(const i of n)e.push(kS(i));const t=e[e.length-1],r=new Map;r.set(n[e.length-1].depth,e[e.length-1]);for(let i=e.length-2;i>=0;i--)r.get(n[i].depth-1).prepend(e[i]),r.set(n[i].depth,e[i]);return t.updateDescendantsSize(),Et.create(t,bt).getRoot()}function SS(n){const e=Tr.create();for(const[t,r]of Object.entries(n))e.setInternal(t,r.value,M(r.updatedAt),r.isRemoved);return e}function kS(n){const e=_s(n.id),t=Xe.create(e,n.type),r=Object.entries(n.attributes);return t.isText?t.value=n.value:r.length&&(t.attrs=SS(n.attributes)),n.insPrevId&&(t.insPrevID=_s(n.insPrevId)),n.insNextId&&(t.insNextID=_s(n.insNextId)),t.removedAt=M(n.removedAt),t}function wy(n){if(n.body.case==="set"){const e=n.body.value;return Ii.create(e.key,Tu(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Po.create(M(e.parentCreatedAt),M(e.prevCreatedAt),Tu(e.value),M(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return br.create(M(e.parentCreatedAt),M(e.prevCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="remove"){const e=n.body.value;return Xr.create(M(e.parentCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="edit"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Do.create(M(e.parentCreatedAt),ta(e.from),ta(e.to),t,e.content,r,M(e.executedAt))}else if(n.body.case==="style"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Oo.create(M(e.parentCreatedAt),ta(e.from),ta(e.to),t,r,M(e.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const e=n.body.value;return ms.create(M(e.parentCreatedAt),Tu(e.value),M(e.executedAt))}else if(n.body.case==="treeEdit"){const e=n.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([r,i])=>{t.set(r,M(i))}),Ro.create(M(e.parentCreatedAt),Di(e.from),Di(e.to),wS(e.contents),e.splitLevel,t,M(e.executedAt))}else if(n.body.case==="treeStyle"){const e=n.body.value,t=new Map,r=e.attributesToRemove,i=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{i.set(s,M(o))}),(r==null?void 0:r.length)>0?pr.createTreeRemoveStyleOperation(M(e.parentCreatedAt),Di(e.from),Di(e.to),i,r,M(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),pr.create(M(e.parentCreatedAt),Di(e.from),Di(e.to),i,t,M(e.executedAt)))}else throw new k(S.ErrUnimplemented,"unimplemented operation")}}function TS(n){const e=[];for(const t of n){const r=wy(t);r&&e.push(r)}return e}function Sy(n){const e=[];for(const t of n)e.push(hs.create({id:py(t.id),operations:TS(t.operations),presenceChange:t.presenceChange?pS(t.presenceChange):void 0,message:t.message}));return e}function AS(n){return es.of(BigInt(n.serverSeq),n.clientSeq)}function IS(n){return Ml.create(n.documentKey,AS(n.checkpoint),n.isRemoved,Sy(n.changes),Zf(n.versionVector),n.snapshot,M(n.minSyncedTicket))}function ky(n){const e=new yo;for(const r of n.nodes){const i=nd(r.element);e.set(r.key,i,i.getPositionedAt())}const t=new We(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Ty(n){const e=new wo;for(const r of n.nodes)e.insert(nd(r.element));const t=new tt(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function ES(n){const e=ie.of(ie.valueFromBytes(yy(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function xS(n){const e=new gs;let t=e.getHead();for(const i of n.nodes){const s=e.insertAfter(t,vS(i));i.insPrevId&&s.setInsPrev(e.findNode(vy(i.insPrevId))),t=s}const r=new It(e,M(n.createdAt));return r.setMovedAt(M(n.movedAt)),r.setRemovedAt(M(n.removedAt)),r}function CS(n){const e=nt.create(ml(n.type),nt.valueFromBytes(ml(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function Ay(n){const e=td(n.nodes);return Et.create(e,M(n.createdAt))}function nd(n){if(n.body.case==="jsonObject")return ky(n.body.value);if(n.body.case==="jsonArray")return Ty(n.body.value);if(n.body.case==="primitive")return ES(n.body.value);if(n.body.case==="text")return xS(n.body.value);if(n.body.case==="counter")return CS(n.body.value);if(n.body.case==="tree")return Ay(n.body.value);throw new k(S.ErrUnimplemented,"unimplemented element")}function NS(n){if(!n)return{root:We.create(bt),presences:new Map};const e=wc.fromBinary(n);return{root:nd(e.root),presences:yS(e.presences)}}function PS(n){const e=Yf(n);return rd(e.toBinary())}function DS(n){const e=sd(n),t=bl.fromBinary(e);return Zf(t)}function Iy(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(n);return ky(e.body.value)}function Ey(n){return Xf(n).toBinary()}function OS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(n);return Ty(e.body.value)}function RS(n){return gy(n).toBinary()}function LS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(n);return Ay(e.body.value)}function BS(n){return my(n).toBinary()}function rd(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function id(n){return rd(n)}function sd(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function od(n){return sd(n)}function bS(n){const e=Bl.fromBinary(n);return py(e)}function FS(n){const e=qf.fromBinary(n);return wy(e)}const fe={fromPresence:ed,toChangePack:mS,fromChangePack:IS,fromChanges:Sy,toTreeNodes:Qf,fromTreeNodes:td,objectToBytes:Ey,bytesToObject:Iy,bytesToSnapshot:NS,bytesToHex:rd,hexToBytes:sd,toHexString:id,toUint8Array:od,toOperation:hy,toChangeID:cy,PbChangeID:Bl,bytesToChangeID:bS,bytesToOperation:FS,versionVectorToHex:PS,hexToVersionVector:DS};var be=(n=>(n[n.Trivial=0]="Trivial",n[n.Debug=1]="Debug",n[n.Info=2]="Info",n[n.Warn=3]="Warn",n[n.Error=4]="Error",n[n.Fatal=5]="Fatal",n))(be||{});let oi=3;function xy(n){oi=n}const J={trivial:(...n)=>{oi>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{oi>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{oi>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{oi>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{oi>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...n):console.log("YORKIE E:",...n))},fatal:(...n)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...n):console.log("YORKIE F:",...n))},isEnabled:n=>oi<=n};function Cy(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}class MS{constructor(e,t,r,i,s){u(this,"reconnectStreamDelay");u(this,"doc");u(this,"docID");u(this,"syncMode");u(this,"remoteChangeEventReceived");u(this,"watchStream");u(this,"watchLoopTimerID");u(this,"watchAbortController");u(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Ta.RealtimeSyncOff?!1:this.syncMode===Ta.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Ta.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Au=()=>{};class JS{constructor(e){u(this,"finalized",!1);u(this,"observers",[]);u(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let i;if(!e)throw new k(S.ErrInvalidArgument,"missing observer");if(this.finalized)throw new k(S.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?i=e:i={next:e,error:t,complete:r},i.next===void 0&&(i.next=Au),i.error===void 0&&(i.error=Au),i.complete===void 0&&(i.complete=Au);const s=Cy(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(a){J.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(r=>r.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Ki{constructor(e,t,r,i){u(this,"id");u(this,"delimiter");u(this,"message");u(this,"root");u(this,"operations");u(this,"presenceChange");u(this,"previousPresence");u(this,"reversePresenceKeys");this.id=e,this.delimiter=Zp,this.root=t,this.operations=[],this.previousPresence=Nt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(e,t,r,i){return new Ki(e,t,r,i)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return hs.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const r of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class ko{constructor(e){u(this,"rootObject");u(this,"elementPairMapByCreatedAt");u(this,"gcElementSetByCreatedAt");u(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof It||t instanceof Et)for(const r of t.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new ko(We.create(bt))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const r=[];for(;t.parent;){const i=t.element.getCreatedAt(),s=t.parent.subPathOf(i);if(s===void 0)throw new k(S.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(s),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof Wr&&e.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(e){let t=0;const r=i=>{const s=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),t++};return r(e),e instanceof Wr&&e.getDescendants(i=>(r(i),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const r=this.elementPairMapByCreatedAt.get(t);r.element instanceof Wr&&r.element.getDescendants(i=>(e.add(i.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new ko(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r),s=i.element.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(i.parent.purge(i.element),t+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i&&(e!=null&&e.afterOrEqual(i))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function Ny(n,e){const t=new To(n);return new Proxy(e,t.getHandlers())}class To{constructor(e){u(this,"context");u(this,"handlers");this.context=e,this.handlers={set:(t,r,i)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]=${JSON.stringify(i)}`),To.setInternal(e,t,r,i),!0),get:(t,r)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]`),r==="getID"?()=>t.getCreatedAt():r==="toJSON"||r==="toString"?()=>t.toJSON():r==="toJS"?()=>t.toJS():r==="toJSForTest"?()=>t.toJSForTest():ai(e,t.get(r))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]`),To.deleteInternal(e,t,r),!0)}}static setInternal(e,t,r,i){if(r.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=pl(e,i,s),a=t.set(r,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Ii.create(r,o.deepcopy(),t.getCreatedAt(),s))}static buildObjectMembers(e,t){const r={};for(const[i,s]of Object.entries(t)){if(i.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=pl(e,s,o);r[i]=a}return r}static deleteInternal(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByKey(r,i);s&&(e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function zS(n,e){const t=new ae(n,e);return new Proxy(e,t.getHandlers())}function US(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function jS(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class ae{constructor(e,t){u(this,"context");u(this,"handlers");u(this,"array");this.context=e,this.array=t,this.handlers={get:(r,i,s)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return Cr(e,a)}:i==="getElementByIndex"?o=>{const a=r.get(o);return Cr(e,a)}:i==="getLast"?()=>Cr(e,r.getLast()):i==="deleteByID"?o=>{const a=ae.deleteInternalByID(e,r,o);return Cr(e,a)}:i==="insertAfter"?(o,a)=>{const l=ae.insertAfterInternal(e,r,o,a);return Cr(e,l)}:i==="insertBefore"?(o,a)=>{const l=ae.insertBeforeInternal(e,r,o,a);return Cr(e,l)}:i==="moveBefore"?(o,a)=>{ae.moveBeforeInternal(e,r,o,a)}:i==="moveAfter"?(o,a)=>{ae.moveAfterInternal(e,r,o,a)}:i==="moveFront"?o=>{ae.moveFrontInternal(e,r,o)}:i==="moveLast"?o=>{ae.moveLastInternal(e,r,o)}:US(i)?ai(e,r.get(Number(i))):i==="push"?o=>ae.pushInternal(e,r,o):i==="splice"?(o,a,...l)=>ae.splice(e,r,o,a,...l):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?ae.iteratorInternal.bind(this,e,r):i==="includes"?(o,a)=>ae.includes(e,r,o,a):i==="indexOf"?(o,a)=>ae.indexOf(e,r,o,a):i==="lastIndexOf"?(o,a)=>ae.lastIndexOf(e,r,o,a):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>ae.toTestString(r):typeof i=="string"&&jS(i)?(...o)=>{const a=Array.from(r).map(l=>ai(e,l));return Array.prototype[i].apply(a,o)}:Reflect.get(r,i,s),deleteProperty:(r,i)=>(J.isEnabled(be.Trivial)&&J.trivial(`array[${i}]`),ae.deleteInternalByIndex(e,r,Number.parseInt(i)),!0)}}static*iteratorInternal(e,t){for(const r of t)yield Cr(e,r)}static buildArrayElements(e,t){const r=[];for(const i of t){const s=e.issueTimeTicket(),o=pl(e,i,s);r.push(o)}return r}static pushInternal(e,t,r){return ae.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,i){const s=e.issueTimeTicket(),o=t.getPrevCreatedAt(r);t.moveAfter(o,i,s),e.push(br.create(t.getCreatedAt(),o,i,s))}static moveAfterInternal(e,t,r,i){const s=e.issueTimeTicket();t.moveAfter(r,i,s),e.push(br.create(t.getCreatedAt(),r,i,s))}static moveFrontInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getHead();t.moveAfter(s.getCreatedAt(),r,i),e.push(br.create(t.getCreatedAt(),s.getCreatedAt(),r,i))}static moveLastInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getLastCreatedAt();t.moveAfter(s,r,i),e.push(br.create(t.getCreatedAt(),s,r,i))}static insertAfterInternal(e,t,r,i){const s=e.issueTimeTicket(),o=pl(e,i,s);return t.insertAfter(r,o),e.registerElement(o,t),e.push(Po.create(t.getCreatedAt(),r,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,r,i){return ae.insertAfterInternal(e,t,t.getPrevCreatedAt(r),i)}static deleteInternalByIndex(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByIndex(r,i);if(s)return e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static deleteInternalByID(e,t,r){const i=e.issueTimeTicket(),s=t.delete(r,i);return e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static splice(e,t,r,i,...s){const o=t.length,a=r>=0?Math.min(r,o):Math.max(o+r,0),l=i===void 0?o:i<0?a:Math.min(a+i,o),c=[];for(let d=a;d=s)return!1;if(ie.isSupport(r))return Array.from(t).map(c=>ai(e,c)).includes(r,o);for(let l=o;l=s)return-1;if(ie.isSupport(r))return Array.from(t).map(c=>ai(e,c)).indexOf(r,o);for(let l=o;l=s?s-1:i<0?i+s:i;if(o<0)return-1;if(ie.isSupport(r))return Array.from(t).map(c=>ai(e,c)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((a=t.get(l))==null?void 0:a.getID())===r.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class Jl{constructor(e,t){u(this,"context");u(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,i){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);J.isEnabled(be.Debug)&&J.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${r}`);const o=i?fs(i):void 0,a=this.context.issueTimeTicket(),[l,,c,d]=this.text.edit(s,r,a,o);for(const h of c)this.context.registerGCPair(h);return this.context.push(new Do(this.text.getCreatedAt(),s[0],s[1],l,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(d)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,r){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);J.isEnabled(be.Debug)&&J.debug(`STYL: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const s=fs(r),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(i,s,o);for(const c of l)this.context.registerGCPair(c);return this.context.push(new Oo(this.text.getCreatedAt(),i[0],i[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Ft.fromStruct(e[0]),Ft.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class $l{constructor(e,t){u(this,"valueType");u(this,"value");u(this,"context");u(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),r=ie.of(e,t);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ms.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function ad(n,e,t){const{type:r}=n,i=t.issueTimeTicket();if(r===mr){Py(n);const{value:s}=n,o=Xe.create(Ee.of(i,0),r,s);e.append(o)}else{const{children:s=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!Xp(o)){const c=fs(o);a=new Tr;for(const[d,h]of Object.entries(c))a.set(d,h,i)}const l=Xe.create(Ee.of(i,0),r,void 0,a);e.append(l);for(const c of s)ad(c,l,t)}}function VS(n,e){const{type:t}=e,r=n.issueTimeTicket();let i;if(e.type===mr){const{value:s}=e;i=Xe.create(Ee.of(r,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!Xp(o)){const l=fs(o);a=new Tr;for(const[c,d]of Object.entries(l))a.set(c,d,r)}i=Xe.create(Ee.of(n.issueTimeTicket(),0),t,void 0,a);for(const l of s)ad(l,i,n)}return i}function Py(n){if(!n.value.length)throw new k(S.ErrInvalidArgument,"text node cannot have empty value");return!0}function ig(n){if(!n.length)return!0;if(n[0].type===mr)for(const t of n){const{type:r}=t;if(r!==mr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together");Py(t)}else for(const t of n){const{type:r}=t;if(r===mr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class zl{constructor(e){u(this,"initialRoot");u(this,"context");u(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return Xe.create(Ee.of(e.issueTimeTicket(),0),U1);const t=Xe.create(Ee.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)ad(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=t?fs(t):void 0,[a]=this.tree.style([r,i],o,s);this.context.push(pr.create(this.tree.getCreatedAt(),r,i,a,o?new Map(Object.entries(o)):new Map,s))}style(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=r?fs(r):void 0,[l,c]=this.tree.style([i,s],a,o);for(const d of c)this.context.registerGCPair(d);this.context.push(pr.create(this.tree.getCreatedAt(),i,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([i,s],r,o);for(const c of l)this.context.registerGCPair(c);this.context.push(pr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,s,a,r,o))}editInternal(e,t,r,i=0){var c;if(r.length!==0&&r[0]&&(ig(r),r[0].type!==mr))for(const d of r){const{children:h=[]}=d;ig(h)}const s=this.context.getLastTimeTicket();let o=new Array;if(((c=r[0])==null?void 0:c.type)===mr){let d="";for(const h of r){const{value:p}=h;d+=p}o.push(Xe.create(Ee.of(this.context.issueTimeTicket(),0),mr,d))}else o=r.map(d=>d&&VS(this.context,d)).filter(d=>d);const[,a,l]=this.tree.edit([e,t],o.length?o.map(d=>d==null?void 0:d.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(const d of a)this.context.registerGCPair(d);return this.context.push(Ro.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,i,l,s)),!0}editByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r?[r]:[],i)}editBulkByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r,i)}edit(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,r?[r]:[],i)}editBulk(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,r,i)}toXML(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(t);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Rt.fromStruct(e[0]),Rt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Rt.fromStruct(e[0]),Rt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function sg(n,e){return Ny(n,e)}function Cr(n,e){if(e){if(e instanceof ie)return e;if(e instanceof We)return Ny(n,e);if(e instanceof tt)return zS(n,e);if(e instanceof It)return new Jl(n,e);if(e instanceof nt){const t=new $l(sn.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof Et){const t=new zl;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function ai(n,e){const t=Cr(n,e);return t instanceof ie?t.getValue():t}function pl(n,e,t){let r;if(ie.isSupport(e))r=ie.of(e,t);else if(Array.isArray(e))r=tt.create(t,ae.buildArrayElements(n,e));else if(typeof e=="object")e instanceof Jl?(r=It.create(gs.create(),t),e.initialize(n,r)):e instanceof $l?(r=nt.create(e.getValueType(),e.getValue(),t),e.initialize(n,r)):e instanceof zl?(r=Et.create(e.buildRoot(n),t),e.initialize(n,r)):r=We.create(t,To.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const og=50;class qS{constructor(){u(this,"undoStack",[]);u(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=og&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=og&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const KS="yorkie-devtools-panel",WS="yorkie-devtools-sdk";let Oi="disconnected";const ag=new Map,ka=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=ka);function na(n,e){(e!=null&&e.force||Oi!=="disconnected")&&window.postMessage({source:WS,...n},"*")}function HS(n){if(!n.isEnableDevtools()||typeof window>"u"||ag.has(n.getKey()))return;ka.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(r=>r.type!==$e.StatusChanged&&r.type!==$e.Snapshot&&r.type!==$e.LocalChange&&r.type!==$e.RemoteChange&&r.type!==$e.Initialized&&r.type!==$e.Watched&&r.type!==$e.Unwatched&&r.type!==$e.PresenceChanged)||(ka.get(n.getKey()).push(t),Oi==="synced"&&na({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});ag.set(n.getKey(),[e]),na({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var i;if(((i=t.data)==null?void 0:i.source)!==KS)return;switch(t.data.msg){case"devtools::connect":if(Oi!=="disconnected")break;Oi="connected",na({msg:"doc::available",docKey:n.getKey()}),J.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Oi="disconnected",J.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Oi="synced",na({msg:"doc::sync::full",docKey:n.getKey(),events:ka.get(n.getKey())}),J.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Nr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Nr||{}),$e=(n=>(n.StatusChanged="status-changed",n.ConnectionChanged="connection-changed",n.SyncStatusChanged="sync-status-changed",n.Snapshot="snapshot",n.LocalChange="local-change",n.RemoteChange="remote-change",n.Initialized="initialized",n.Watched="watched",n.Unwatched="unwatched",n.PresenceChanged="presence-changed",n.Broadcast="broadcast",n.LocalBroadcast="local-broadcast",n))($e||{}),Kc=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(Kc||{}),Wc=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Wc||{});class Dy{constructor(e,t){u(this,"key");u(this,"status");u(this,"opts");u(this,"changeID");u(this,"checkpoint");u(this,"localChanges");u(this,"root");u(this,"clone");u(this,"eventStream");u(this,"eventStreamObserver");u(this,"onlineClients");u(this,"presences");u(this,"history");u(this,"internalHistory");u(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=ko.create(),this.changeID=Y1,this.checkpoint=Q1,this.localChanges=[],this.eventStream=$S(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new qS,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},HS(this)}update(e,t){if(this.getStatus()==="removed")throw new k(S.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{const s=sg(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(s,new Su(i,this.clone.presences.get(r)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(i.hasChange()){J.isEnabled(be.Trivial)&&J.trivial(`trying to update a local change: ${this.toJSON()}`);const s=i.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,Y.Local),l=i.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const c=[];o.length>0&&c.push({type:"local-change",source:Y.Local,value:{message:s.getMessage()||"",operations:o,actor:r,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&c.push({type:"presence-changed",source:Y.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(c),J.isEnabled(be.Trivial)&&J.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,r,i){if(typeof e=="string"){if(typeof t!="function")throw new k(S.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="initialized"&&c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||a(c)},r,i)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="initialized"&&c.type!=="presence-changed"||c.type==="presence-changed"&&c.value.clientID!==this.changeID.getActorID()||a(c)},r,i)}if(e==="others"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||c.value.clientID!==this.changeID.getActorID()&&a(c)},r,i)}if(e==="connection"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="connection-changed"&&a(c)},r,i)}if(e==="status"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="status-changed"&&a(c)},r,i)}if(e==="sync"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="sync-status-changed"&&a(c)},r,i)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="local-broadcast"&&a(c)},r)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="broadcast"&&a(c)},r)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,r,i)}const s=e,o=t;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const c=[];for(const d of l.value.operations)this.isSameElementOrChildOf(d.path,s)&&c.push(d);c.length&&o({...l,value:{...l.value,operations:c}})}},r,i)}if(typeof e=="function"){const s=e,o=t,a=r;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="snapshot"&&c.type!=="local-change"&&c.type!=="remote-change"||s(c)},o,a)}throw new k(S.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const r=e.split(".");return t.split(".").every((s,o)=>s===r[o])}applyChangePack(e){const t=e.hasSnapshot();for(t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),Y.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();t&&this.applyChanges(this.localChanges,Y.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),J.isEnabled(be.Trivial)&&J.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Nt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return Ml.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return sg(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r){const{root:i,presences:s}=fe.bytesToSnapshot(r);this.root=new ko(i),this.presences=s,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.publish([{type:"snapshot",source:Y.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?fe.bytesToHex(r):void 0,snapshotVector:fe.versionVectorToHex(t)}}])}applyChanges(e,t){J.isEnabled(be.Debug)&&J.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),J.isEnabled(be.Trivial)&&J.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` -`));for(const r of e)this.applyChange(r,t);J.isEnabled(be.Debug)&&J.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const r=[],i=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(i)){const o=e.getPresenceChange();switch(o.type){case Qr.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:t,value:{clientID:i,presence:o.presence}}:{type:"watched",source:Y.Remote,value:{clientID:i,presence:o.presence}});break;case Qr.Clear:r.push({type:"unwatched",source:Y.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:s}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===Y.Remote?{type:"remote-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,r=new Set;for(const i of t)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:Y.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,i=[];if(t===pi.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:Y.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(t===pi.DOCUMENT_UNWATCHED){const s=this.getPresence(r);this.removeOnlineClient(r),s&&i.push({type:"unwatched",source:Y.Remote,value:{clientID:r,presence:s}})}else if(t===pi.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:s,payload:o}=e.body.value.body,a=new TextDecoder;i.push({type:"broadcast",value:{clientID:r,topic:s,payload:JSON.parse(a.decode(o))}})}i.length>0&&this.publish(i)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(Wf),this.publish([{source:e==="removed"?Y.Remote:Y.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:r,snapshotVector:i}=e.value;if(!t)return;this.applySnapshot(BigInt(r),fe.hexToVersionVector(i),fe.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=hs.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:r,presence:i}of e.value)t.add(r),this.presences.set(r,i);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:r}=e.value;this.addOnlineClient(t),this.presences.set(t,r);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:r}=e.value;this.presences.set(t,r)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new k(S.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let r=this.getRoot();for(const i of t)if(r=r[i],r===void 0)return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?Nt(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?Nt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Nt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Nt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Nt(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,r)=>t.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){const r=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new k(S.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Jt)){new Su(t,Nt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:Y.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new k(S.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Jt)){new Su(t,Nt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:Y.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){const i={type:"local-broadcast",value:{topic:e,payload:t},options:r};this.publish([i])}getVersionVector(){return this.changeID.getVersionVector()}}function _S(n,e){return t=>async r=>(n&&r.header.set("x-api-key",n),e&&r.header.set("authorization",e),await t(r))}const GS="yorkie-js-sdk",YS="0.5.4",QS="Yorkie JS SDK",XS="./src/yorkie.ts",ZS={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},ek=["dist"],tk={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},nk={node:">=18.0.0",npm:">=7.1.0"},rk={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},ik={name:"hackerwins",email:"susukang98@gmail.com"},sk="Apache-2.0",ok={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},ak="https://github.com/yorkie-team/yorkie-js-sdk#readme",lk={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},uk={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},lg={name:GS,version:YS,description:QS,main:XS,publishConfig:ZS,files:ek,scripts:tk,engines:nk,repository:rk,author:ik,license:sk,bugs:ok,homepage:ak,devDependencies:lk,dependencies:uk};function ck(){return n=>async e=>(e.header.set("x-yorkie-user-agent",lg.name+"/"+lg.version),await n(e))}const fk=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Ta=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Ta||{});const ra={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Iu={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Oy{constructor(e,t){u(this,"id");u(this,"key");u(this,"status");u(this,"attachmentMap");u(this,"apiKey");u(this,"conditions");u(this,"syncLoopDuration");u(this,"reconnectStreamDelay");u(this,"retrySyncLoopDelay");u(this,"rpcClient");u(this,"taskQueue");u(this,"processing",!1);t=t||ra,this.key=t.key?t.key:Cy(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||ra.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||ra.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||ra.retrySyncLoopDelay,this.rpcClient=a1(D1,P1({baseUrl:e,interceptors:[_S(t.apiKey,t.token),ck()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),J.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw J.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),J.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw J.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Nr.Detached)throw new k(S.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const r=e.subscribe("local-broadcast",async s=>{var d;const{topic:o,payload:a}=s.value,l=(d=s.options)==null?void 0:d.error,c=s.options;try{await this.broadcast(e.getKey(),o,a,c)}catch(h){h instanceof Error&&(l==null||l(h))}}),i=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:fe.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=fe.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Nr.Removed)return e;e.applyStatus(Nr.Attached),this.attachmentMap.set(e.getKey(),new MS(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),J.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const l=t.initialRoot;e.update(c=>{for(const[d,h]of Object.entries(l))if(!a.has(d)){const p=d;c[p]=h}})}return e}).catch(s=>{throw J.error(`[AD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((i,s)=>s.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:fe.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=fe.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==Nr.Removed&&e.applyStatus(Nr.Detached),this.detachInternal(e.getKey()),J.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(i=>{throw J.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(e,t){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const i=r.syncMode;return i===t?e:(r.changeSyncMode(t),t==="manual"?(r.cancelWatchStream(),e):(t==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const t=[];for(const[,r]of this.attachmentMap)t.push(this.syncInternal(r,r.syncMode));return Promise.all(t).catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=fe.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=fe.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),J.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(i=>{throw J.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,i){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);if(!fk(r))throw new k(S.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??Iu.maxRetries,a=Iu.maxBackoff;let l=0;const c=h=>Math.min(Iu.initialRetryInterval*2**h,a),d=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{J.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(h=>{if(J.error(`[BC] c:"${this.getKey()}" err:`,h),this.handleConnectError(h))if(ld(),c(l-1)),J.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw J.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),h;else throw h}));return d()}runSyncLoop(){const e=()=>{if(!this.isActive()){J.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,t.push(this.syncInternal(r,r.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{J.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};J.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new k(S.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:i.signal});return t.doc.publish([{type:$e.ConnectionChanged,value:Kc.Connected}]),J.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const c of s)this.handleWatchDocumentsResponse(t,c),c.body.case==="initialization"&&o([s,i])}catch(c){t.doc.resetOnlineClients(),t.doc.publish([{type:$e.Initialized,source:Y.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:$e.ConnectionChanged,value:Kc.Disconnected}]),J.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(c)?r():this.conditions.WatchLoop=!1,a(c)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===pi.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(Nr.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:r,docID:i}=e,s=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:fe.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=fe.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:$e.SyncStatusChanged,value:Wc.Synced}]),r.getStatus()===Nr.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),c=a.getChangeSize();return J.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${c} cp:${a.getCheckpoint().toTestString()}`),r}).catch(o=>{throw r.publish([{type:$e.SyncStatusChanged,value:Wc.SyncFailed}]),J.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof pe?e.code===_.Canceled||e.code===_.Unknown||e.code===_.ResourceExhausted||e.code===_.Unavailable?!0:((rg(e)===S.ErrClientNotActivated||rg(e)===S.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{J.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const ug={Client:Oy,Document:Dy,Primitive:ie,Text:Jl,Counter:$l,Tree:zl,LogLevel:be,setLogLevel:xy,IntType:sn.IntegerCnt,LongType:sn.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Oy,Document:Dy,Primitive:ie,Text:Jl,Counter:$l,Tree:zl,LogLevel:be,setLogLevel:xy,IntType:sn.IntegerCnt,LongType:sn.LongCnt});var Ry={exports:{}};/*! +`));for(const r of e)this.applyChange(r,t);J.isEnabled(be.Debug)&&J.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const r=[],i=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(i)){const o=e.getPresenceChange();switch(o.type){case Qr.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:t,value:{clientID:i,presence:o.presence}}:{type:"watched",source:Y.Remote,value:{clientID:i,presence:o.presence}});break;case Qr.Clear:r.push({type:"unwatched",source:Y.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:s}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===Y.Remote?{type:"remote-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,r=new Set;for(const i of t)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:Y.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,i=[];if(t===pi.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:Y.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===pi.DOCUMENT_UNWATCHED){const s=this.getPresence(r);this.removeOnlineClient(r),s&&i.push({type:"unwatched",source:Y.Remote,value:{clientID:r,presence:s}})}else if(t===pi.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:s,payload:o}=e.body.value.body,a=new TextDecoder;i.push({type:"broadcast",value:{clientID:r,topic:s,payload:JSON.parse(a.decode(o))}})}i.length>0&&this.publish(i)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(Wf),this.publish([{source:e==="removed"?Y.Remote:Y.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:r,snapshotVector:i}=e.value;if(!t)return;this.applySnapshot(BigInt(r),fe.hexToVersionVector(i),fe.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=hs.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:r,presence:i}of e.value)t.add(r),this.presences.set(r,i);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:r}=e.value;this.addOnlineClient(t),this.presences.set(t,r);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:r}=e.value;this.presences.set(t,r)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new k(S.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let r=this.getRoot();for(const i of t)if(r=r[i],r===void 0)return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?Nt(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?Nt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Nt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Nt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Nt(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,r)=>t.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){const r=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new k(S.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Jt)){new Su(t,Nt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:Y.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new k(S.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Jt)){new Su(t,Nt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:Y.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){const i={type:"local-broadcast",value:{topic:e,payload:t},options:r};this.publish([i])}getVersionVector(){return this.changeID.getVersionVector()}}function _S(n,e){return t=>async r=>(n&&r.header.set("x-api-key",n),e&&r.header.set("authorization",e),await t(r))}const GS="yorkie-js-sdk",YS="0.5.4",QS="Yorkie JS SDK",XS="./src/yorkie.ts",ZS={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},ek=["dist"],tk={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},nk={node:">=18.0.0",npm:">=7.1.0"},rk={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},ik={name:"hackerwins",email:"susukang98@gmail.com"},sk="Apache-2.0",ok={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},ak="https://github.com/yorkie-team/yorkie-js-sdk#readme",lk={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},uk={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},lg={name:GS,version:YS,description:QS,main:XS,publishConfig:ZS,files:ek,scripts:tk,engines:nk,repository:rk,author:ik,license:sk,bugs:ok,homepage:ak,devDependencies:lk,dependencies:uk};function ck(){return n=>async e=>(e.header.set("x-yorkie-user-agent",lg.name+"/"+lg.version),await n(e))}const fk=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Ta=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Ta||{});const ra={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Iu={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Oy{constructor(e,t){u(this,"id");u(this,"key");u(this,"status");u(this,"attachmentMap");u(this,"apiKey");u(this,"conditions");u(this,"syncLoopDuration");u(this,"reconnectStreamDelay");u(this,"retrySyncLoopDelay");u(this,"rpcClient");u(this,"taskQueue");u(this,"processing",!1);t=t||ra,this.key=t.key?t.key:Cy(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||ra.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||ra.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||ra.retrySyncLoopDelay,this.rpcClient=a1(D1,P1({baseUrl:e,interceptors:[_S(t.apiKey,t.token),ck()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),J.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw J.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),J.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw J.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Nr.Detached)throw new k(S.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const r=e.subscribe("local-broadcast",async s=>{var d;const{topic:o,payload:a}=s.value,l=(d=s.options)==null?void 0:d.error,c=s.options;try{await this.broadcast(e.getKey(),o,a,c)}catch(h){h instanceof Error&&(l==null||l(h))}}),i=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:fe.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=fe.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Nr.Removed)return e;e.applyStatus(Nr.Attached),this.attachmentMap.set(e.getKey(),new MS(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),J.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const l=t.initialRoot;e.update(c=>{for(const[d,h]of Object.entries(l))if(!a.has(d)){const p=d;c[p]=h}})}return e}).catch(s=>{throw J.error(`[AD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((i,s)=>s.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:fe.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=fe.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==Nr.Removed&&e.applyStatus(Nr.Detached),this.detachInternal(e.getKey()),J.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(i=>{throw J.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(e,t){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const i=r.syncMode;return i===t?e:(r.changeSyncMode(t),t==="manual"?(r.cancelWatchStream(),e):(t==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const t=[];for(const[,r]of this.attachmentMap)t.push(this.syncInternal(r,r.syncMode));return Promise.all(t).catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=fe.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=fe.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),J.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(i=>{throw J.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,i){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);if(!fk(r))throw new k(S.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??Iu.maxRetries,a=Iu.maxBackoff;let l=0;const c=h=>Math.min(Iu.initialRetryInterval*2**h,a),d=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{J.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(h=>{if(J.error(`[BC] c:"${this.getKey()}" err:`,h),this.handleConnectError(h))if(ld(),c(l-1)),J.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw J.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),h;else throw h}));return d()}runSyncLoop(){const e=()=>{if(!this.isActive()){J.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,t.push(this.syncInternal(r,r.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{J.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};J.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new k(S.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:i.signal});return t.doc.publish([{type:$e.ConnectionChanged,value:Kc.Connected}]),J.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const c of s)this.handleWatchDocumentsResponse(t,c),c.body.case==="initialization"&&o([s,i])}catch(c){t.doc.resetOnlineClients(),t.doc.publish([{type:$e.Initialized,source:Y.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:$e.ConnectionChanged,value:Kc.Disconnected}]),J.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(c)?r():this.conditions.WatchLoop=!1,a(c)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===pi.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(Nr.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:r,docID:i}=e,s=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:fe.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=fe.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:$e.SyncStatusChanged,value:Wc.Synced}]),r.getStatus()===Nr.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),c=a.getChangeSize();return J.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${c} cp:${a.getCheckpoint().toTestString()}`),r}).catch(o=>{throw r.publish([{type:$e.SyncStatusChanged,value:Wc.SyncFailed}]),J.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof pe?e.code===_.Canceled||e.code===_.Unknown||e.code===_.ResourceExhausted||e.code===_.Unavailable?!0:((rg(e)===S.ErrClientNotActivated||rg(e)===S.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{J.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const ug={Client:Oy,Document:Dy,Primitive:ie,Text:Jl,Counter:$l,Tree:zl,LogLevel:be,setLogLevel:xy,IntType:sn.IntegerCnt,LongType:sn.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Oy,Document:Dy,Primitive:ie,Text:Jl,Counter:$l,Tree:zl,LogLevel:be,setLogLevel:xy,IntType:sn.IntegerCnt,LongType:sn.LongCnt});var Ry={exports:{}};/*! Copyright (c) 2018 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames diff --git a/examples/react-todomvc/index.html b/examples/react-todomvc/index.html index 5187b0bf5..0a4678246 100644 --- a/examples/react-todomvc/index.html +++ b/examples/react-todomvc/index.html @@ -5,7 +5,7 @@ Vite + React + TS - + diff --git a/examples/simultaneous-cursors/assets/index-BJv2R0i-.js b/examples/simultaneous-cursors/assets/index-BSvZl1Rn.js similarity index 94% rename from examples/simultaneous-cursors/assets/index-BJv2R0i-.js rename to examples/simultaneous-cursors/assets/index-BSvZl1Rn.js index e14e1a584..a6a26cfe3 100644 --- a/examples/simultaneous-cursors/assets/index-BJv2R0i-.js +++ b/examples/simultaneous-cursors/assets/index-BSvZl1Rn.js @@ -59,4 +59,4 @@ Error generating stack: `+s.message+` * * SPDX-License-Identifier: Apache-2.0 */var St=null;try{St=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function q(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}q.prototype.__isLong__;Object.defineProperty(q.prototype,"__isLong__",{value:!0});function Re(n){return(n&&n.__isLong__)===!0}function Xh(n){var e=Math.clz32(n&-n);return n?31-e:e}q.isLong=Re;var Zh={},eg={};function Ni(n,e){var t,r,i;return e?(n>>>=0,(i=0<=n&&n<256)&&(r=eg[n],r)?r:(t=W(n,0,!0),i&&(eg[n]=t),t)):(n|=0,(i=-128<=n&&n<128)&&(r=Zh[n],r)?r:(t=W(n,n<0?-1:0,!1),i&&(Zh[n]=t),t))}q.fromInt=Ni;function kt(n,e){if(isNaN(n))return e?gr:Rt;if(e){if(n<0)return gr;if(n>=ry)return oy}else{if(n<=-ng)return je;if(n+1>=ng)return sy}return n<0?kt(-n,e).neg():W(n%hs|0,n/hs|0,e)}q.fromNumber=kt;function W(n,e,t){return new q(n,e,t)}q.fromBits=W;var gl=Math.pow;function Qf(n,e,t){if(n.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return e?gr:Rt;if(t=t||10,t<2||360)throw Error("interior hyphen");if(r===0)return Qf(n.substring(1),e,t).neg();for(var i=kt(gl(t,8)),s=Rt,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*hs+(this.low>>>0):this.high*hs+(this.low>>>0)};C.toString=function(e){if(e=e||10,e<2||36>>0,d=c.toString(e);if(o=l,o.isZero())return d+a;for(;d.length<6;)d="0"+d;a=""+d+a}};C.getHighBits=function(){return this.high};C.getHighBitsUnsigned=function(){return this.high>>>0};C.getLowBits=function(){return this.low};C.getLowBitsUnsigned=function(){return this.low>>>0};C.getNumBitsAbs=function(){if(this.isNegative())return this.eq(je)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};C.isOdd=function(){return(this.low&1)===1};C.isEven=function(){return(this.low&1)===0};C.equals=function(e){return Re(e)||(e=zt(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};C.eq=C.equals;C.notEquals=function(e){return!this.eq(e)};C.neq=C.notEquals;C.ne=C.notEquals;C.lessThan=function(e){return this.comp(e)<0};C.lt=C.lessThan;C.lessThanOrEqual=function(e){return this.comp(e)<=0};C.lte=C.lessThanOrEqual;C.le=C.lessThanOrEqual;C.greaterThan=function(e){return this.comp(e)>0};C.gt=C.greaterThan;C.greaterThanOrEqual=function(e){return this.comp(e)>=0};C.gte=C.greaterThanOrEqual;C.ge=C.greaterThanOrEqual;C.compare=function(e){if(Re(e)||(e=zt(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};C.comp=C.compare;C.negate=function(){return!this.unsigned&&this.eq(je)?je:this.not().add(Ki)};C.neg=C.negate;C.add=function(e){Re(e)||(e=zt(e));var t=this.high>>>16,r=this.high&65535,i=this.low>>>16,s=this.low&65535,o=e.high>>>16,a=e.high&65535,l=e.low>>>16,c=e.low&65535,d=0,h=0,p=0,m=0;return m+=s+c,p+=m>>>16,m&=65535,p+=i+l,h+=p>>>16,p&=65535,h+=r+a,d+=h>>>16,h&=65535,d+=t+o,d&=65535,W(p<<16|m,d<<16|h,this.unsigned)};C.subtract=function(e){return Re(e)||(e=zt(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(Re(e)||(e=zt(e)),St){var t=St.mul(this.low,this.high,e.low,e.high);return W(t,St.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?gr:Rt;if(this.eq(je))return e.isOdd()?je:Rt;if(e.eq(je))return this.isOdd()?je:Rt;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(rg)&&e.lt(rg))return kt(this.toNumber()*e.toNumber(),this.unsigned);var r=this.high>>>16,i=this.high&65535,s=this.low>>>16,o=this.low&65535,a=e.high>>>16,l=e.high&65535,c=e.low>>>16,d=e.low&65535,h=0,p=0,m=0,w=0;return w+=o*d,m+=w>>>16,w&=65535,m+=s*d,p+=m>>>16,m&=65535,m+=o*c,p+=m>>>16,m&=65535,p+=i*d,h+=p>>>16,p&=65535,p+=s*c,h+=p>>>16,p&=65535,p+=o*l,h+=p>>>16,p&=65535,h+=r*d+i*c+s*l+o*a,h&=65535,W(m<<16|w,h<<16|p,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(Re(e)||(e=zt(e)),e.isZero())throw Error("division by zero");if(St){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?St.div_u:St.div_s)(this.low,this.high,e.low,e.high);return W(t,St.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?gr:Rt;var r,i,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return gr;if(e.gt(this.shru(1)))return iy;s=gr}else{if(this.eq(je)){if(e.eq(Ki)||e.eq(Kc))return je;if(e.eq(je))return Ki;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(Rt)?e.isNegative()?Ki:Kc:(i=this.sub(e.mul(r)),s=r.add(i.div(e)),s)}else if(e.eq(je))return this.unsigned?gr:Rt;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Rt}for(i=this;i.gte(e);){r=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(r)/Math.LN2),l=a<=48?1:gl(2,a-48),c=kt(r),d=c.mul(e);d.isNegative()||d.gt(i);)r-=l,c=kt(r,this.unsigned),d=c.mul(e);c.isZero()&&(c=Ki),s=s.add(c),i=i.sub(d)}return s};C.div=C.divide;C.modulo=function(e){if(Re(e)||(e=zt(e)),St){var t=(this.unsigned?St.rem_u:St.rem_s)(this.low,this.high,e.low,e.high);return W(t,St.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};C.mod=C.modulo;C.rem=C.modulo;C.not=function(){return W(~this.low,~this.high,this.unsigned)};C.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};C.clz=C.countLeadingZeros;C.countTrailingZeros=function(){return this.low?Xh(this.low):Xh(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return Re(e)||(e=zt(e)),W(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return Re(e)||(e=zt(e)),W(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return Re(e)||(e=zt(e)),W(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low<>>32-e,this.unsigned):W(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):W(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?W(this.high,0,this.unsigned):W(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var t;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(t=32-e,W(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,W(this.high<>>t,this.low<>>t,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var t;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(t=32-e,W(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,W(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?W(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:W(this.low,this.high,!0)};C.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};C.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};C.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};q.fromBytes=function(e,t,r){return r?q.fromBytesLE(e,t):q.fromBytesBE(e,t)};q.fromBytesLE=function(e,t){return new q(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};q.fromBytesBE=function(e,t){return new q(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var ve=(n=>(n[n.Null=0]="Null",n[n.Boolean=1]="Boolean",n[n.Integer=2]="Integer",n[n.Long=3]="Long",n[n.Double=4]="Double",n[n.String=5]="String",n[n.Bytes=6]="Bytes",n[n.Date=7]="Date",n))(ve||{});class re extends Po{constructor(t,r){super(r);u(this,"valueType");u(this,"value");this.valueType=re.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,r){return new re(t,r)}static valueFromBytes(t,r){switch(t){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(s,o){i.setUint8(o,s)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return q.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(q.fromBytesLE(Array.from(r),!0).toNumber());default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${tn(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=re.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof q)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return re.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,t,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const t=this.value,r=q.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class ml extends ny{constructor(t){super(t);u(this,"prev");u(this,"next");this.value=t}static createAfter(t,r){const i=new ml(r),s=t.next;return t.next=i,i.prev=t,i.next=s,s&&(s.prev=i),i}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class So{constructor(){u(this,"dummyHead");u(this,"last");u(this,"nodeMapByIndex");u(this,"nodeMapByCreatedAt");const e=re.of(0,Ft);e.setRemovedAt(Ft),this.dummyHead=new ml(e),this.last=this.dummyHead,this.nodeMapByIndex=new wo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new So}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(t);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,r=t.getCreatedAt()){const i=this.findNextBeforeExecutedAt(e,r),s=ml.createAfter(i,t);i===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(i,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,t,r){const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new k(S.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);i!==s&&(!s.getValue().getMovedAt()||r.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(i.getCreatedAt(),s.getValue(),r),s.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new k(S.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,r]=this.nodeMapByIndex.find(e);let i=t;if(e===0&&t===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const r=this.nodeMapByCreatedAt.get(e.toIDString()),i=r.isRemoved();return r.remove(t)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,t){const r=this.getByIndex(e);if(r)return r.remove(t)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const r=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${r}}`):e.push(`[${r}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class nt extends Wr{constructor(t,r){super(t);u(this,"elements");this.elements=r}static create(t,r){if(!r)return new nt(t,So.create());const i=So.create();for(const s of r)i.insertAfter(i.getLastCreatedAt(),s.deepcopy());return new nt(t,i)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,r){this.elements.insertAfter(t,r)}moveAfter(t,r,i){this.elements.moveAfter(t,r,i)}get(t){const r=this.elements.getByIndex(t);return r==null?void 0:r.getValue()}getByID(t){const r=this.elements.getByID(t);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,r){return this.elements.delete(t,r)}deleteByIndex(t,r){return this.elements.deleteByIndex(t,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const r of this.elements){const i=r.getValue();if(t(i,this))return;i instanceof Wr&&i.getDescendants(t)}}toJSON(){const t=[];for(const r of this)t.push(r.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let r=0;r({...m,value:m.value?{attributes:Zi(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[c,p,d,[l,l]]}setStyle(t,r,i,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],i),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],i),l=[],c=this.rgaTreeSplit.findBetween(a,o),d=new Map,h=[];for(const m of c){const w=m.getCreatedAt().getActorID(),I=s!=null&&s.size?s.has(w)?s.get(w):Ft:Hs;if(m.canStyle(i,I)){const O=d.get(w),y=m.getCreatedAt();(!O||y.after(O))&&d.set(w,y),h.push(m)}}const p=[];for(const m of h){if(m.isRemoved())continue;const[w,I]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());l.push({type:"style",actor:i.getActorID(),from:w,to:I,value:{attributes:Zi(r)}});for(const[O,y]of Object.entries(r)){const[g]=m.getValue().setAttr(O,y,i);g!==void 0&&p.push({parent:m.getValue(),child:g})}}return[d,p,l]}indexRangeToPosRange(t,r){const i=this.rgaTreeSplit.indexToPos(t);return t===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const r of this.rgaTreeSplit)r.isRemoved()||t.push(r.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();t.push({attributes:Zi(i.getAttributes()),content:i.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new Et(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())t.push(i)}return t}}class Oo extends $t{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"content");u(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(t,r,i,s,o,a,l){return new Oo(t,r,i,s,o,a,l)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c})=>({type:"edit",from:a,to:l,value:c,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.content;return`${t}.EDIT(${r},${i},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Ro extends $t{constructor(t,r,i,s,o,a){super(t,a);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(t,r,i,s,o,a){return new Ro(t,r,i,s,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:c})=>({type:"style",from:a,to:l,value:c,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.attributes;return`${t}.STYL(${r},${i},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const z1=2,U1="root",pr="text";function Os(n,e){let t=0;const r=n.children;for(let i=0;i0)throw new k(S.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const r=t.updateDescendantsSize();t.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===pr}get paddedSize(){return this.size+(this.isText?0:z1)}isAncestorOf(e){return j1(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const r=this.value.slice(0,e),i=this.value.slice(e);if(!i.length)return;this.value=r;const s=this.cloneText(e+t);return s.value=i,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new k(S.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const r=this.cloneElement(t);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,e),s=this.children.slice(e);this._children=i,r._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),r.size=r._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(i=>!i.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const r=this._children.indexOf(t);if(r!==-1)return r;t=t.parent}return-1}}function j1(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var ge=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(ge||{});function ay(n,e,t,r){if(e>t)throw new k(S.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new k(S.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new k(S.ErrInvalidArgument,`to is out of range: ${t} > ${n.size}`);if(e===t)return;let i=0;for(const s of n.children){if(e-s.paddedSizes.size;(s.isText||l)&&r([s,s.isText?"Text":"Start"],c),ay(s,Math.max(0,o),Math.min(a,s.size),r),c&&r([s,"End"],c)}i+=s.paddedSize}}function ly(n,e,t=0){for(const r of n.children)ly(r,e,t+1);e(n,t)}function Ml(n,e,t=0){for(const r of n._children)Ml(r,e,t+1);e(n,t)}function Wc(n,e,t=!0){if(e>n.size)throw new k(S.ErrInvalidArgument,`index is out of range: ${e} > ${n.size}`);if(n.isText)return{node:n,offset:e};let r=0,i=0;for(const s of n.children){if(t&&s.isText&&s.size>=e-i)return Wc(s,e-i,t);if(e===i)return{node:n,offset:r};if(!t&&s.paddedSize===e-i)return{node:n,offset:r+1};if(s.paddedSize>e-i)return Wc(s,e-i-1,t);i+=s.paddedSize,r+=1}return{node:n,offset:r}}function uy(n){return n.isText||n.children.length===0?n:uy(n.children[0])}function q1(n,e){if(n.sizen===e?0:n0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(r<0)if(t.left)t.left.parent=t,t=t.left;else{let i=t.parent,s=t;for(;i&&s===i.left;)s=i,i=i.parent;return i}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const r=this.comparator(e,t.key);if(r===0)return t;r<0?t=t.left:r>0&&(t=t.right)}}putInternal(e,t,r){if(!r)return this.counter+=1,new H1(e,t,!0);const i=this.comparator(e,r.key);return i<0?r.left=this.putInternal(e,t,r.left):i>0?r.right=this.putInternal(e,t,r.right):r.value=t,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const r=this.min(e.right);e.value=r.value,e.key=r.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class Lt{constructor(e,t){u(this,"parentID");u(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new Lt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:r}=e,i;return r.isText?(r.parent.children[0]===r&&t===0?i=r.parent:i=r,r=r.parent):t===0?i=r:i=r.children[t-1],Lt.of(r.id,Ee.of(i.getCreatedAt(),i.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return Lt.of(Ee.of(tt.fromStruct(e.parentID.createdAt),e.parentID.offset),Ee.of(tt.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),r=this.getLeftSiblingID(),i=e.findFloorNode(t);let s=e.findFloorNode(r);if(!i||!s)throw new k(S.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${r.toTestString()})`);return!r.equals(t)&&r.getOffset()>0&&r.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[i,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Ee{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ee(e,t)}static fromStruct(e){return Ee.of(tt.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const r=e.getCreatedAt().compare(t.getCreatedAt());return r!==0?r:e.getOffset()>t.getOffset()?1:e.getOffset(){const s=i.deepcopy();return s.parent=t,s}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new k(S.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new k(S.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),r&&this.updateAncestorsSize()}cloneText(t){return new Ze(Ee.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new Ze(Ee.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,r,i){const s=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(s){if(s.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,t.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,r){this.attrs||(this.attrs=new Ar);const i=new Array;for(const[s,o]of Object.entries(t))i.push(this.attrs.set(s,o,r));return i}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const r of this.attrs)r.getRemovedAt()&&t.push({parent:this,child:r});return t}}function Hc(n){var t;if(n.isText){const r=n;return{type:r.type,value:r.value}}const e={type:n.type,children:n.children.map(Hc)};return n.attrs&&(e.attributes=Zi((t=n.attrs)==null?void 0:t.toObject())),e}function Xf(n){if(n.isText)return n.value;let e="";return n.attrs&&n.attrs.size()&&(e=" "+Array.from(n.attrs).filter(t=>!t.isRemoved()).sort((t,r)=>t.getKey().localeCompare(r.getKey())).map(t=>{const r=JSON.parse(t.getValue());return typeof r=="string"?`${t.getKey()}="${r}"`:`${t.getKey()}="${tn(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>Xf(t)).join("")}`}function fy(n){if(n.isText){const e=n;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:n.type,children:n.children.map(fy),size:n.size,isRemoved:n.isRemoved}}class xt extends Po{constructor(t,r){super(r);u(this,"indexTree");u(this,"nodeMapByID");this.indexTree=new K1(t),this.nodeMapByID=new cy(Ee.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(t,r){return new xt(t,r)}findFloorNode(t){const r=this.nodeMapByID.floorEntry(t);if(!(!r||!r.key.getCreatedAt().equals(t.getCreatedAt())))return r.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,r){const[i,s]=t.toTreeNodePair(this);let o=s;const a=i===o,l=o.parent&&!a?o.parent:i;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const c=l.allChildren,d=a?0:c.indexOf(o)+1;for(let h=d;h{const I=w.getCreatedAt().getActorID(),O=s?s.has(I)?s.get(I):Ft:Hs;if(w.canStyle(i,O)&&r){const y=p.get(I),g=w.getCreatedAt();(!y||g.after(y))&&p.set(I,g);const v=w.setAttrs(r,i),T=v.reduce((P,[,B])=>(B&&(P[B.getKey()]=h[B.getKey()]),P),{}),x=w.parent,N=w.prevSibling||w.parent;Object.keys(T).length>0&&d.push({type:"style",from:this.toIndex(x,N),to:this.toIndex(w,w),fromPath:this.toPath(x,N),toPath:this.toPath(w,w),actor:i.getActorID(),value:T});for(const[P]of v)P&&m.push({parent:w,child:P})}}),[p,m,d]}removeStyle(t,r,i,s){const[o,a]=this.findNodesAndSplitText(t[0],i),[l,c]=this.findNodesAndSplitText(t[1],i),d=[],h=new Map,p=[];return this.traverseInPosRange(o,a,l,c,([m])=>{const w=m.getCreatedAt().getActorID(),I=s?s.has(w)?s.get(w):Ft:Hs;if(m.canStyle(i,I)&&r){const O=h.get(w),y=m.getCreatedAt();(!O||y.after(O))&&h.set(w,y),m.attrs||(m.attrs=new Ar);for(const T of r){const x=m.attrs.remove(T,i);for(const N of x)p.push({parent:m,child:N})}const g=m.parent,v=m.prevSibling||m.parent;d.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(g,v),to:this.toIndex(m,m),fromPath:this.toPath(g,v),toPath:this.toPath(m,m),value:r})}}),[h,p,d]}edit(t,r,i,s,o,a){const[l,c]=this.findNodesAndSplitText(t[0],s),[d,h]=this.findNodesAndSplitText(t[1],s),p=this.toIndex(l,c),m=this.toPath(l,c),w=[],I=[],O=[],y=new Map;this.traverseInPosRange(l,c,d,h,([T,x],N)=>{if(x===ge.Start&&!N)for(const H of T.children)O.push(H);const P=T.getCreatedAt().getActorID(),B=a?a.has(P)?a.get(P):Ft:Hs;if(T.canDelete(s,B)||w.includes(T.parent)){const H=y.get(P),U=T.getCreatedAt();(!H||U.after(H))&&y.set(P,U),(x===ge.Text||x===ge.Start)&&w.push(T),I.push([T,x])}});const g=this.makeDeletionChanges(I,s),v=[];for(const T of w)T.remove(s),T.isRemoved&&v.push({parent:this,child:T});for(const T of O)T.removedAt||l.append(T);if(i>0){let T=0,x=l,N=c;for(;T{l.isRemoved&&(P.remove(s),v.push({parent:this,child:P})),this.nodeMapByID.put(P.id,P)}),N.isRemoved||T.push(N);if(T.length){const N=T.map(P=>Hc(P));g.length&&g[g.length-1].from===p?g[g.length-1].value=N:g.push({type:"content",from:p,to:p,fromPath:m,toPath:m,actor:s.getActorID(),value:N})}}return[g,v,y]}editT(t,r,i,s,o){const a=this.findPos(t[0]),l=this.findPos(t[1]);this.edit([a,l],r,i,s,o)}move(t,r,i){throw new k(S.ErrUnimplemented,`not implemented: ${t}, ${r}, ${i}`)}purge(t){var s;(s=t.parent)==null||s.removeChild(t),this.nodeMapByID.remove(t.id);const r=t.insPrevID,i=t.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=i}if(i){const o=this.findFloorNode(i);o.insPrevID=r}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&t.push({parent:this,child:r});for(const i of r.getGCPairs())t.push(i)}),t}findPos(t,r=!0){const i=this.indexTree.findTreePos(t,r);return Lt.fromTreePos(i)}pathToPosRange(t){const r=this.pathToIndex(t);return[this.findPos(r),this.findPos(r+1)]}pathToPos(t){const r=this.indexTree.pathToIndex(t);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Xf(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),r=(i,s=void 0,o=void 0,a=0)=>{var m,w,I,O;let l,c,d;const h=i.isText?{node:i,offset:0}:s&&o?this.toTreePos(s,o):null;h&&(l=this.indexTree.indexOf(h),c=this.indexTree.treePosToPath(h),d=Lt.fromTreePos(h).toStruct());const p={type:i.type,parent:s==null?void 0:s.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(m=i.removedAt)==null?void 0:m.toTestString(),insPrev:(w=i.insPrevID)==null?void 0:w.toTestString(),insNext:(I=i.insNextID)==null?void 0:I.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:a,attributes:i.attrs?Zi((O=i.attrs)==null?void 0:O.toObject()):void 0,index:l,path:c,pos:d};for(let y=0;y0&&y===i[i.length-1].to?(i[i.length-1].to=g,i[i.length-1].toPath=this.toPath(O,m)):i.push({type:"content",from:y,to:g,fromPath:this.toPath(I,h),toPath:this.toPath(O,m),actor:r.getActorID()}))}return i.reverse()}findRightToken([t,r]){if(r===ge.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?ge.Text:ge.Start]:[t,ge.End]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===s.length-1)return[i,ge.End];const a=s[o+1];return[a,a.isText?ge.Text:ge.Start]}findLeftToken([t,r]){if(r===ge.End){const l=t.allChildren;if(l.length>0){const c=l[l.length-1];return[c,c.isText?ge.Text:ge.End]}return[t,ge.Start]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===0)return[i,ge.Start];const a=s[o-1];return[a,a.isText?ge.Text:ge.End]}}class Lo extends $t{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"contents");u(this,"splitLevel");u(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,r,i,s,o,a,l){return new Lo(t,r,i,s,o,a,l)}execute(t){var l;const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof xt))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),s=r,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(c=>c.deepcopy()),this.splitLevel,i,(()=>{let c=i.getDelimiter();return this.contents!==void 0&&(c+=this.contents.length),()=>tt.of(i.getLamport(),++c,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const c of a)t.registerGCPair(c);return{opInfos:o.map(({from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${t}.EDIT(${r},${i},${s.map(o=>Xf(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class es{constructor(e){u(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[r,i]of e){const s=this.vector.get(r),o=s&&s>i?s:i;t.set(r,o)}for(const[r,i]of this){const s=e.get(r),o=s&&s>i?s:i;t.set(r,o)}return new es(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,r]of this.vector)e.set(t,r);return new es(e)}filter(e){const t=new Map;for(const[r]of e){const i=this.vector.get(r);i!==void 0&&t.set(r,i)}return new es(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const G1=new es(new Map);class lr{constructor(e,t,r,i,s){u(this,"clientSeq");u(this,"serverSeq");u(this,"lamport");u(this,"actor");u(this,"versionVector");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.versionVector=i,this.actor=r}static of(e,t,r,i,s){return new lr(e,t,r,i,s)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new lr(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,r=this.versionVector.max(e.versionVector),i=new lr(this.clientSeq,t,this.actor,r);return i.versionVector.set(this.actor,t),i}setClocks(e,t){const r=e>this.lamport?e:this.lamport+1n,i=this.versionVector.max(t);return i.set(this.actor,r),lr.of(this.clientSeq,r,this.actor,i)}createTimeTicket(e){return tt.of(this.lamport,e,this.actor)}setActor(e){return new lr(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new lr(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Y1=new lr(0,0n,Gf,G1);class gs{constructor({id:e,operations:t,presenceChange:r,message:i}){u(this,"id");u(this,"operations");u(this,"presenceChange");u(this,"message");this.id=e,this.operations=t||[],this.presenceChange=r,this.message=i}static create({id:e,operations:t,presenceChange:r,message:i}){return new gs({id:e,operations:t,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,r){const i=[],s=[];for(const o of this.operations){const a=o.execute(e,r);if(!a)continue;const{opInfos:l,reverseOp:c}=a;i.push(...l),c&&s.unshift(c)}return this.presenceChange&&(this.presenceChange.type===Qr.Put?t.set(this.id.getActorID(),Pt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:i,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:fe.bytesToHex(fe.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>fe.bytesToHex(fe.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:r,presenceChange:i,message:s}=e;return gs.create({id:fe.bytesToChangeID(fe.hexToBytes(t)),operations:r==null?void 0:r.map(o=>fe.bytesToOperation(fe.hexToBytes(o))),presenceChange:i,message:s})}}class Jl{constructor(e,t,r,i,s,o,a){u(this,"documentKey");u(this,"checkpoint");u(this,"isRemoved");u(this,"changes");u(this,"snapshot");u(this,"minSyncedTicket");u(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=i,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=s}static create(e,t,r,i,s,o,a){return new Jl(e,t,r,i,s,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class ts{constructor(e,t){u(this,"serverSeq");u(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new ts(e,t)}increaseClientSeq(e){return e===0?this:new ts(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return ts.of(t,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Q1=new ts(0n,0);class sn{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new sn(e,t)}static fromStruct(e){return sn.of(tt.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new sn(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const X1=sn.of(Ft,0);class Mt{constructor(e,t){u(this,"id");u(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Mt(e,t)}static fromStruct(e){const t=sn.fromStruct(e.id);return Mt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return sn.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class Hr extends ny{constructor(t,r,i){super(r);u(this,"id");u(this,"removedAt");u(this,"prev");u(this,"next");u(this,"insPrev");u(this,"insNext");this.id=t,this.removedAt=i}static create(t,r){return new Hr(t,r)}static createComparator(){return(t,r)=>{const i=t.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:t.getOffset()>r.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const r=[];let i=e;for(;i&&i!==t;)r.push(i),i=i.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new k(S.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const r=e.split(t);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);const i=e.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r){if(!e.length)return[[],new Map,new Map];const[i,s]=this.filterNodes(e,t,r),o=new Map,a=new Map,l=this.makeChanges(s,t);for(const c of i){const d=c.getCreatedAt().getActorID();(!o.has(d)||c.getID().getCreatedAt().after(o.get(d)))&&o.set(d,c.getID().getCreatedAt()),a.set(c.getID().toIDString(),c),c.remove(t)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,t,r){const i=!!r,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const c of e){const d=c.getCreatedAt().getActorID(),h=i?r.has(d)?r.get(d):Ft:Hs;c.canDelete(t,h)?s.push(c):o.push(c)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const r=[];let i,s;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var on=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(on||{});class rt extends Po{constructor(t,r,i){super(i);u(this,"valueType");u(this,"value");switch(this.valueType=t,t){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=q.fromNumber(r).toInt():this.value=ig(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=q.fromNumber(r):this.value=r;break;default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,r,i){return new rt(t,r,i)}static valueFromBytes(t,r){switch(t){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return q.fromBytesLE(Array.from(r));default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=rt.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof q?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!rt.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===ve.Long?this.value=this.value+t.getValue().toInt():this.value=q.fromNumber(this.value+ig(t.getValue())).toInt(),this}}class ps extends $t{constructor(t,r,i){super(t,i);u(this,"value");this.value=r}static create(t,r,i){return new ps(t,r,i)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof rt))throw new k(S.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,s=this.value.deepcopy();return i.increase(s),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),i=t.getType()===ve.Long?t.getValue().multiply(-1):t.getValue()*-1;return ps.create(this.getParentCreatedAt(),re.of(i,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class yr extends $t{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"attributes");u(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(t,r,i,s,o,a){return new yr(t,r,i,s,o,new Array,a)}static createTreeRemoveStyleOperation(t,r,i,s,o,a){return new yr(t,r,i,s,new Map,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof xt))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,c])=>a[l]=c),[,o,s]=i.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=i.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c,fromPath:d,toPath:h})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:c}:{attributesToRemove:c},fromPath:d,toPath:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function Z1(n){const e=new _f,t=e.data;for(const[r,i]of Object.entries(n))t[r]=JSON.stringify(i);return e}function eS(n){if(n.type===Qr.Put)return new yo({type:Ii.PUT,presence:Z1(n.presence)});if(n.type===Qr.Clear)return new yo({type:Ii.CLEAR});throw new k(S.ErrUnimplemented,"unimplemented type")}function tS(n){return new Zp({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function dy(n){return new bl({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:ud(n.getActorID()),versionVector:Zf(n.getVersionVector())})}function F(n){if(n)return new b({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:ud(n.getActorID())})}function Zf(n){if(!n)return;const e=new Fl;for(const[t,r]of n)e.vector[t]=BigInt(r.toString());return e}function hy(n){switch(n){case ve.Null:return $.NULL;case ve.Boolean:return $.BOOLEAN;case ve.Integer:return $.INTEGER;case ve.Long:return $.LONG;case ve.Double:return $.DOUBLE;case ve.String:return $.STRING;case ve.Bytes:return $.BYTES;case ve.Date:return $.DATE;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function gy(n){switch(n){case on.IntegerCnt:return $.INTEGER_CNT;case on.LongCnt:return $.LONG_CNT;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function Tu(n){if(n instanceof He)return new ut({type:$.JSON_OBJECT,createdAt:F(n.getCreatedAt()),value:Cy(n)});if(n instanceof nt)return new ut({type:$.JSON_ARRAY,createdAt:F(n.getCreatedAt()),value:RS(n)});if(n instanceof Et)return new ut({type:$.TEXT,createdAt:F(n.getCreatedAt())});if(n instanceof re)return new ut({type:hy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof rt)return new ut({type:gy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof xt)return new ut({type:$.TREE,createdAt:F(n.getCreatedAt()),value:BS(n)});throw new k(S.ErrUnimplemented,"unimplemented element")}function nS(n){return new mo({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function ea(n){return new Tr({createdAt:F(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function ta(n){return new Ai({parentId:_s(n.getParentID()),leftSiblingId:_s(n.getLeftSiblingID())})}function _s(n){return new Kr({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function my(n){const e=new Hf;if(n instanceof Ei){const t=n,r=new Ya;r.parentCreatedAt=F(t.getParentCreatedAt()),r.key=t.getKey(),r.value=Tu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="set",e.body.value=r}else if(n instanceof Do){const t=n,r=new Qa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.value=Tu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="add",e.body.value=r}else if(n instanceof Fr){const t=n,r=new Xa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="move",e.body.value=r}else if(n instanceof Xr){const t=n,r=new Za;r.parentCreatedAt=F(t.getParentCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(n instanceof Oo){const t=n,r=new el;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ea(t.getFromPos()),r.to=ea(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);r.content=t.getContent();const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(n instanceof Ro){const t=n,r=new tl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ea(t.getFromPos()),r.to=ea(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="style",e.body.value=r}else if(n instanceof ps){const t=n,r=new nl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.value=Tu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(n instanceof Lo){const t=n,r=new rl,i=r.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())i[s]=F(o);r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ta(t.getFromPos()),r.to=ta(t.getToPos()),r.contents=uS(t.getContents()),r.splitLevel=t.getSplitLevel(),r.executedAt=F(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(n instanceof yr){const t=n,r=new il;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ta(t.getFromPos()),r.to=ta(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=t.getAttributesToRemove();if(s.length>0)r.attributesToRemove=s;else{const o=r.attributes;for(const[a,l]of t.getAttributes())o[a]=l}r.executedAt=F(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new k(S.ErrUnimplemented,"unimplemented operation");return e}function rS(n){const e=[];for(const t of n)e.push(my(t));return e}function iS(n){const e=new Qp({id:dy(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=rS(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=eS(n.getPresenceChange())),e}function sS(n){const e=[];for(const t of n)e.push(iS(t));return e}function oS(n){const e=[];for(const t of n)e.push(new Xp({key:t.getStrKey(),element:td(t.getValue())}));return e}function aS(n){const e=[];for(const t of n)e.push(new fl({element:td(t.getValue())}));return e}function lS(n){const e=[];for(const t of n){const r=new dl;r.id=nS(t.getID()),r.value=t.getValue().getContent(),r.removedAt=F(t.getRemovedAt());const i=r.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new fs;a.value=o.getValue(),a.updatedAt=F(o.getUpdatedAt()),i[o.getKey()]=a}e.push(r)}return e}function uS(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new hl({content:ed(t)}));return e}function cS(n){const e={};for(const t of n)e[t.getKey()]=new fs({value:t.getValue(),updatedAt:F(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function ed(n){if(!n)return[];const e=[];return Ml(n,(t,r)=>{const i=new po({id:_s(t.id),type:t.type,removedAt:F(t.removedAt),depth:r});t.isText&&(i.value=t.value),t.insPrevID&&(i.insPrevId=_s(t.insPrevID)),t.insNextID&&(i.insNextId=_s(t.insNextID)),t.attrs&&(i.attributes=cS(t.attrs)),e.push(i)}),e}function fS(n){const e=new _e;return e.body.case="jsonObject",e.body.value=new sl({nodes:oS(n.getRHT()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function py(n){const e=new _e;return e.body.case="jsonArray",e.body.value=new ol({nodes:aS(n.getElements()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function dS(n){const e=new _e;return e.body.case="primitive",e.body.value=new al({type:hy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function hS(n){const e=new _e;return e.body.case="text",e.body.value=new ll({nodes:lS(n.getRGATreeSplit()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function gS(n){const e=new _e;return e.body.case="counter",e.body.value=new ul({type:gy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function yy(n){const e=new _e;return e.body.case="tree",e.body.value=new cl({nodes:ed(n.getRoot()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function td(n){if(n instanceof He)return fS(n);if(n instanceof nt)return py(n);if(n instanceof re)return dS(n);if(n instanceof Et)return hS(n);if(n instanceof rt)return gS(n);if(n instanceof xt)return yy(n);throw new k(S.ErrUnimplemented,"unimplemented element")}function mS(n){return new Er({documentKey:n.getDocumentKey(),checkpoint:tS(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:sS(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Zf(n.getVersionVector()),minSyncedTicket:F(n.getMinSyncedTicket())})}function sg(n){const e=n.findDetails(O1);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function vy(n){return lr.of(n.clientSeq,BigInt(n.lamport),ad(n.actorId),nd(n.versionVector),BigInt(n.serverSeq))}function nd(n){if(!n)return;const e=new es;return Object.entries(n.vector).forEach(([t,r])=>{e.set(t,BigInt(r.toString()))}),e}function M(n){if(n)return tt.of(BigInt(n.lamport),n.delimiter,ad(n.actorId))}function rd(n){const e={};return Object.entries(n.data).forEach(([t,r])=>{e[t]=JSON.parse(r)}),e}function pS(n){const e=n.type;if(e===Ii.PUT){const t=rd(n.presence);return{type:Qr.Put,presence:t}}if(e===Ii.CLEAR)return{type:Qr.Clear};throw new k(S.ErrInvalidType,`unsupported type: ${e}`)}function yS(n){const e=new Map;return Object.entries(n).forEach(([t,r])=>{e.set(t,rd(r))}),e}function wy(n){switch(n){case $.NULL:return ve.Null;case $.BOOLEAN:return ve.Boolean;case $.INTEGER:return ve.Integer;case $.LONG:return ve.Long;case $.DOUBLE:return ve.Double;case $.STRING:return ve.String;case $.BYTES:return ve.Bytes;case $.DATE:return ve.Date}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function pl(n){switch(n){case $.INTEGER_CNT:return on.IntegerCnt;case $.LONG_CNT:return on.LongCnt}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function Au(n){switch(n.type){case $.JSON_OBJECT:return n.value?xy(n.value):He.create(M(n.createdAt));case $.JSON_ARRAY:return n.value?OS(n.value):nt.create(M(n.createdAt));case $.TEXT:return Et.create(ms.create(),M(n.createdAt));case $.TREE:return LS(n.value);case $.NULL:case $.BOOLEAN:case $.INTEGER:case $.LONG:case $.DOUBLE:case $.STRING:case $.BYTES:case $.DATE:return re.of(re.valueFromBytes(wy(n.type),n.value),M(n.createdAt));case $.INTEGER_CNT:case $.LONG_CNT:return rt.create(pl(n.type),rt.valueFromBytes(pl(n.type),n.value),M(n.createdAt))}}function na(n){return Mt.of(sn.of(M(n.createdAt),n.offset),n.relativeOffset)}function Sy(n){return sn.of(M(n.createdAt),n.offset)}function vS(n){const e=ko.create(n.value);Object.entries(n.attributes).forEach(([r,i])=>{e.setAttr(r,i.value,M(i.updatedAt))});const t=Hr.create(Sy(n.id),e);return t.remove(M(n.removedAt)),t}function Oi(n){return Lt.of(Gs(n.parentId),Gs(n.leftSiblingId))}function Gs(n){return Ee.of(M(n.createdAt),n.offset)}function wS(n){if(!n.length)return;const e=[];return n.forEach(t=>{const r=id(t.content);e.push(r)}),e}function id(n){if(n.length===0)return;const e=[];for(const i of n)e.push(kS(i));const t=e[e.length-1],r=new Map;r.set(n[e.length-1].depth,e[e.length-1]);for(let i=e.length-2;i>=0;i--)r.get(n[i].depth-1).prepend(e[i]),r.set(n[i].depth,e[i]);return t.updateDescendantsSize(),xt.create(t,Ft).getRoot()}function SS(n){const e=Ar.create();for(const[t,r]of Object.entries(n))e.setInternal(t,r.value,M(r.updatedAt),r.isRemoved);return e}function kS(n){const e=Gs(n.id),t=Ze.create(e,n.type),r=Object.entries(n.attributes);return t.isText?t.value=n.value:r.length&&(t.attrs=SS(n.attributes)),n.insPrevId&&(t.insPrevID=Gs(n.insPrevId)),n.insNextId&&(t.insNextID=Gs(n.insNextId)),t.removedAt=M(n.removedAt),t}function ky(n){if(n.body.case==="set"){const e=n.body.value;return Ei.create(e.key,Au(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Do.create(M(e.parentCreatedAt),M(e.prevCreatedAt),Au(e.value),M(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return Fr.create(M(e.parentCreatedAt),M(e.prevCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="remove"){const e=n.body.value;return Xr.create(M(e.parentCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="edit"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Oo.create(M(e.parentCreatedAt),na(e.from),na(e.to),t,e.content,r,M(e.executedAt))}else if(n.body.case==="style"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Ro.create(M(e.parentCreatedAt),na(e.from),na(e.to),t,r,M(e.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const e=n.body.value;return ps.create(M(e.parentCreatedAt),Au(e.value),M(e.executedAt))}else if(n.body.case==="treeEdit"){const e=n.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([r,i])=>{t.set(r,M(i))}),Lo.create(M(e.parentCreatedAt),Oi(e.from),Oi(e.to),wS(e.contents),e.splitLevel,t,M(e.executedAt))}else if(n.body.case==="treeStyle"){const e=n.body.value,t=new Map,r=e.attributesToRemove,i=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{i.set(s,M(o))}),(r==null?void 0:r.length)>0?yr.createTreeRemoveStyleOperation(M(e.parentCreatedAt),Oi(e.from),Oi(e.to),i,r,M(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),yr.create(M(e.parentCreatedAt),Oi(e.from),Oi(e.to),i,t,M(e.executedAt)))}else throw new k(S.ErrUnimplemented,"unimplemented operation")}}function TS(n){const e=[];for(const t of n){const r=ky(t);r&&e.push(r)}return e}function Ty(n){const e=[];for(const t of n)e.push(gs.create({id:vy(t.id),operations:TS(t.operations),presenceChange:t.presenceChange?pS(t.presenceChange):void 0,message:t.message}));return e}function AS(n){return ts.of(BigInt(n.serverSeq),n.clientSeq)}function IS(n){return Jl.create(n.documentKey,AS(n.checkpoint),n.isRemoved,Ty(n.changes),nd(n.versionVector),n.snapshot,M(n.minSyncedTicket))}function Ay(n){const e=new vo;for(const r of n.nodes){const i=sd(r.element);e.set(r.key,i,i.getPositionedAt())}const t=new He(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Iy(n){const e=new So;for(const r of n.nodes)e.insert(sd(r.element));const t=new nt(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function ES(n){const e=re.of(re.valueFromBytes(wy(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function xS(n){const e=new ms;let t=e.getHead();for(const i of n.nodes){const s=e.insertAfter(t,vS(i));i.insPrevId&&s.setInsPrev(e.findNode(Sy(i.insPrevId))),t=s}const r=new Et(e,M(n.createdAt));return r.setMovedAt(M(n.movedAt)),r.setRemovedAt(M(n.removedAt)),r}function CS(n){const e=rt.create(pl(n.type),rt.valueFromBytes(pl(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function Ey(n){const e=id(n.nodes);return xt.create(e,M(n.createdAt))}function sd(n){if(n.body.case==="jsonObject")return Ay(n.body.value);if(n.body.case==="jsonArray")return Iy(n.body.value);if(n.body.case==="primitive")return ES(n.body.value);if(n.body.case==="text")return xS(n.body.value);if(n.body.case==="counter")return CS(n.body.value);if(n.body.case==="tree")return Ey(n.body.value);throw new k(S.ErrUnimplemented,"unimplemented element")}function NS(n){if(!n)return{root:He.create(Ft),presences:new Map};const e=Tc.fromBinary(n);return{root:sd(e.root),presences:yS(e.presences)}}function PS(n){const e=Zf(n);return od(e.toBinary())}function DS(n){const e=ld(n),t=Fl.fromBinary(e);return nd(t)}function xy(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=_e.fromBinary(n);return Ay(e.body.value)}function Cy(n){return td(n).toBinary()}function OS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=_e.fromBinary(n);return Iy(e.body.value)}function RS(n){return py(n).toBinary()}function LS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=_e.fromBinary(n);return Ey(e.body.value)}function BS(n){return yy(n).toBinary()}function od(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function ad(n){return od(n)}function ld(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function ud(n){return ld(n)}function bS(n){const e=bl.fromBinary(n);return vy(e)}function FS(n){const e=Hf.fromBinary(n);return ky(e)}const fe={fromPresence:rd,toChangePack:mS,fromChangePack:IS,fromChanges:Ty,toTreeNodes:ed,fromTreeNodes:id,objectToBytes:Cy,bytesToObject:xy,bytesToSnapshot:NS,bytesToHex:od,hexToBytes:ld,toHexString:ad,toUint8Array:ud,toOperation:my,toChangeID:dy,PbChangeID:bl,bytesToChangeID:bS,bytesToOperation:FS,versionVectorToHex:PS,hexToVersionVector:DS};var be=(n=>(n[n.Trivial=0]="Trivial",n[n.Debug=1]="Debug",n[n.Info=2]="Info",n[n.Warn=3]="Warn",n[n.Error=4]="Error",n[n.Fatal=5]="Fatal",n))(be||{});let ai=3;function Ny(n){ai=n}const J={trivial:(...n)=>{ai>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{ai>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{ai>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{ai>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{ai>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...n):console.log("YORKIE E:",...n))},fatal:(...n)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...n):console.log("YORKIE F:",...n))},isEnabled:n=>ai<=n};function Py(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}class MS{constructor(e,t,r,i,s){u(this,"reconnectStreamDelay");u(this,"doc");u(this,"docID");u(this,"syncMode");u(this,"remoteChangeEventReceived");u(this,"watchStream");u(this,"watchLoopTimerID");u(this,"watchAbortController");u(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Aa.RealtimeSyncOff?!1:this.syncMode===Aa.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Aa.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Iu=()=>{};class JS{constructor(e){u(this,"finalized",!1);u(this,"observers",[]);u(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let i;if(!e)throw new k(S.ErrInvalidArgument,"missing observer");if(this.finalized)throw new k(S.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?i=e:i={next:e,error:t,complete:r},i.next===void 0&&(i.next=Iu),i.error===void 0&&(i.error=Iu),i.complete===void 0&&(i.complete=Iu);const s=Py(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(a){J.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(r=>r.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Wi{constructor(e,t,r,i){u(this,"id");u(this,"delimiter");u(this,"message");u(this,"root");u(this,"operations");u(this,"presenceChange");u(this,"previousPresence");u(this,"reversePresenceKeys");this.id=e,this.delimiter=ty,this.root=t,this.operations=[],this.previousPresence=Pt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(e,t,r,i){return new Wi(e,t,r,i)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return gs.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const r of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class To{constructor(e){u(this,"rootObject");u(this,"elementPairMapByCreatedAt");u(this,"gcElementSetByCreatedAt");u(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof Et||t instanceof xt)for(const r of t.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new To(He.create(Ft))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const r=[];for(;t.parent;){const i=t.element.getCreatedAt(),s=t.parent.subPathOf(i);if(s===void 0)throw new k(S.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(s),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof Wr&&e.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(e){let t=0;const r=i=>{const s=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),t++};return r(e),e instanceof Wr&&e.getDescendants(i=>(r(i),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const r=this.elementPairMapByCreatedAt.get(t);r.element instanceof Wr&&r.element.getDescendants(i=>(e.add(i.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new To(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r),s=i.element.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(i.parent.purge(i.element),t+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i&&(e!=null&&e.afterOrEqual(i))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function Dy(n,e){const t=new Ao(n);return new Proxy(e,t.getHandlers())}class Ao{constructor(e){u(this,"context");u(this,"handlers");this.context=e,this.handlers={set:(t,r,i)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]=${JSON.stringify(i)}`),Ao.setInternal(e,t,r,i),!0),get:(t,r)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]`),r==="getID"?()=>t.getCreatedAt():r==="toJSON"||r==="toString"?()=>t.toJSON():r==="toJS"?()=>t.toJS():r==="toJSForTest"?()=>t.toJSForTest():li(e,t.get(r))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]`),Ao.deleteInternal(e,t,r),!0)}}static setInternal(e,t,r,i){if(r.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=yl(e,i,s),a=t.set(r,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Ei.create(r,o.deepcopy(),t.getCreatedAt(),s))}static buildObjectMembers(e,t){const r={};for(const[i,s]of Object.entries(t)){if(i.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=yl(e,s,o);r[i]=a}return r}static deleteInternal(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByKey(r,i);s&&(e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function zS(n,e){const t=new oe(n,e);return new Proxy(e,t.getHandlers())}function US(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function VS(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class oe{constructor(e,t){u(this,"context");u(this,"handlers");u(this,"array");this.context=e,this.array=t,this.handlers={get:(r,i,s)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return Nr(e,a)}:i==="getElementByIndex"?o=>{const a=r.get(o);return Nr(e,a)}:i==="getLast"?()=>Nr(e,r.getLast()):i==="deleteByID"?o=>{const a=oe.deleteInternalByID(e,r,o);return Nr(e,a)}:i==="insertAfter"?(o,a)=>{const l=oe.insertAfterInternal(e,r,o,a);return Nr(e,l)}:i==="insertBefore"?(o,a)=>{const l=oe.insertBeforeInternal(e,r,o,a);return Nr(e,l)}:i==="moveBefore"?(o,a)=>{oe.moveBeforeInternal(e,r,o,a)}:i==="moveAfter"?(o,a)=>{oe.moveAfterInternal(e,r,o,a)}:i==="moveFront"?o=>{oe.moveFrontInternal(e,r,o)}:i==="moveLast"?o=>{oe.moveLastInternal(e,r,o)}:US(i)?li(e,r.get(Number(i))):i==="push"?o=>oe.pushInternal(e,r,o):i==="splice"?(o,a,...l)=>oe.splice(e,r,o,a,...l):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?oe.iteratorInternal.bind(this,e,r):i==="includes"?(o,a)=>oe.includes(e,r,o,a):i==="indexOf"?(o,a)=>oe.indexOf(e,r,o,a):i==="lastIndexOf"?(o,a)=>oe.lastIndexOf(e,r,o,a):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>oe.toTestString(r):typeof i=="string"&&VS(i)?(...o)=>{const a=Array.from(r).map(l=>li(e,l));return Array.prototype[i].apply(a,o)}:Reflect.get(r,i,s),deleteProperty:(r,i)=>(J.isEnabled(be.Trivial)&&J.trivial(`array[${i}]`),oe.deleteInternalByIndex(e,r,Number.parseInt(i)),!0)}}static*iteratorInternal(e,t){for(const r of t)yield Nr(e,r)}static buildArrayElements(e,t){const r=[];for(const i of t){const s=e.issueTimeTicket(),o=yl(e,i,s);r.push(o)}return r}static pushInternal(e,t,r){return oe.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,i){const s=e.issueTimeTicket(),o=t.getPrevCreatedAt(r);t.moveAfter(o,i,s),e.push(Fr.create(t.getCreatedAt(),o,i,s))}static moveAfterInternal(e,t,r,i){const s=e.issueTimeTicket();t.moveAfter(r,i,s),e.push(Fr.create(t.getCreatedAt(),r,i,s))}static moveFrontInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getHead();t.moveAfter(s.getCreatedAt(),r,i),e.push(Fr.create(t.getCreatedAt(),s.getCreatedAt(),r,i))}static moveLastInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getLastCreatedAt();t.moveAfter(s,r,i),e.push(Fr.create(t.getCreatedAt(),s,r,i))}static insertAfterInternal(e,t,r,i){const s=e.issueTimeTicket(),o=yl(e,i,s);return t.insertAfter(r,o),e.registerElement(o,t),e.push(Do.create(t.getCreatedAt(),r,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,r,i){return oe.insertAfterInternal(e,t,t.getPrevCreatedAt(r),i)}static deleteInternalByIndex(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByIndex(r,i);if(s)return e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static deleteInternalByID(e,t,r){const i=e.issueTimeTicket(),s=t.delete(r,i);return e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static splice(e,t,r,i,...s){const o=t.length,a=r>=0?Math.min(r,o):Math.max(o+r,0),l=i===void 0?o:i<0?a:Math.min(a+i,o),c=[];for(let d=a;d=s)return!1;if(re.isSupport(r))return Array.from(t).map(c=>li(e,c)).includes(r,o);for(let l=o;l=s)return-1;if(re.isSupport(r))return Array.from(t).map(c=>li(e,c)).indexOf(r,o);for(let l=o;l=s?s-1:i<0?i+s:i;if(o<0)return-1;if(re.isSupport(r))return Array.from(t).map(c=>li(e,c)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((a=t.get(l))==null?void 0:a.getID())===r.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class $l{constructor(e,t){u(this,"context");u(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,i){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);J.isEnabled(be.Debug)&&J.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${r}`);const o=i?ds(i):void 0,a=this.context.issueTimeTicket(),[l,,c,d]=this.text.edit(s,r,a,o);for(const h of c)this.context.registerGCPair(h);return this.context.push(new Oo(this.text.getCreatedAt(),s[0],s[1],l,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(d)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,r){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);J.isEnabled(be.Debug)&&J.debug(`STYL: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const s=ds(r),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(i,s,o);for(const c of l)this.context.registerGCPair(c);return this.context.push(new Ro(this.text.getCreatedAt(),i[0],i[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Mt.fromStruct(e[0]),Mt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class zl{constructor(e,t){u(this,"valueType");u(this,"value");u(this,"context");u(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),r=re.of(e,t);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ps.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function cd(n,e,t){const{type:r}=n,i=t.issueTimeTicket();if(r===pr){Oy(n);const{value:s}=n,o=Ze.create(Ee.of(i,0),r,s);e.append(o)}else{const{children:s=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!ey(o)){const c=ds(o);a=new Ar;for(const[d,h]of Object.entries(c))a.set(d,h,i)}const l=Ze.create(Ee.of(i,0),r,void 0,a);e.append(l);for(const c of s)cd(c,l,t)}}function jS(n,e){const{type:t}=e,r=n.issueTimeTicket();let i;if(e.type===pr){const{value:s}=e;i=Ze.create(Ee.of(r,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!ey(o)){const l=ds(o);a=new Ar;for(const[c,d]of Object.entries(l))a.set(c,d,r)}i=Ze.create(Ee.of(n.issueTimeTicket(),0),t,void 0,a);for(const l of s)cd(l,i,n)}return i}function Oy(n){if(!n.value.length)throw new k(S.ErrInvalidArgument,"text node cannot have empty value");return!0}function og(n){if(!n.length)return!0;if(n[0].type===pr)for(const t of n){const{type:r}=t;if(r!==pr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together");Oy(t)}else for(const t of n){const{type:r}=t;if(r===pr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Ul{constructor(e){u(this,"initialRoot");u(this,"context");u(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return Ze.create(Ee.of(e.issueTimeTicket(),0),U1);const t=Ze.create(Ee.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)cd(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=t?ds(t):void 0,[a]=this.tree.style([r,i],o,s);this.context.push(yr.create(this.tree.getCreatedAt(),r,i,a,o?new Map(Object.entries(o)):new Map,s))}style(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=r?ds(r):void 0,[l,c]=this.tree.style([i,s],a,o);for(const d of c)this.context.registerGCPair(d);this.context.push(yr.create(this.tree.getCreatedAt(),i,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([i,s],r,o);for(const c of l)this.context.registerGCPair(c);this.context.push(yr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,s,a,r,o))}editInternal(e,t,r,i=0){var c;if(r.length!==0&&r[0]&&(og(r),r[0].type!==pr))for(const d of r){const{children:h=[]}=d;og(h)}const s=this.context.getLastTimeTicket();let o=new Array;if(((c=r[0])==null?void 0:c.type)===pr){let d="";for(const h of r){const{value:p}=h;d+=p}o.push(Ze.create(Ee.of(this.context.issueTimeTicket(),0),pr,d))}else o=r.map(d=>d&&jS(this.context,d)).filter(d=>d);const[,a,l]=this.tree.edit([e,t],o.length?o.map(d=>d==null?void 0:d.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(const d of a)this.context.registerGCPair(d);return this.context.push(Lo.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,i,l,s)),!0}editByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r?[r]:[],i)}editBulkByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r,i)}edit(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,r?[r]:[],i)}editBulk(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,r,i)}toXML(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(t);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Lt.fromStruct(e[0]),Lt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Lt.fromStruct(e[0]),Lt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function ag(n,e){return Dy(n,e)}function Nr(n,e){if(e){if(e instanceof re)return e;if(e instanceof He)return Dy(n,e);if(e instanceof nt)return zS(n,e);if(e instanceof Et)return new $l(n,e);if(e instanceof rt){const t=new zl(on.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof xt){const t=new Ul;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function li(n,e){const t=Nr(n,e);return t instanceof re?t.getValue():t}function yl(n,e,t){let r;if(re.isSupport(e))r=re.of(e,t);else if(Array.isArray(e))r=nt.create(t,oe.buildArrayElements(n,e));else if(typeof e=="object")e instanceof $l?(r=Et.create(ms.create(),t),e.initialize(n,r)):e instanceof zl?(r=rt.create(e.getValueType(),e.getValue(),t),e.initialize(n,r)):e instanceof Ul?(r=xt.create(e.buildRoot(n),t),e.initialize(n,r)):r=He.create(t,Ao.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const lg=50;class qS{constructor(){u(this,"undoStack",[]);u(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=lg&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=lg&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const KS="yorkie-devtools-panel",WS="yorkie-devtools-sdk";let Ri="disconnected";const ug=new Map,Ta=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Ta);function ra(n,e){(e!=null&&e.force||Ri!=="disconnected")&&window.postMessage({source:WS,...n},"*")}function HS(n){if(!n.isEnableDevtools()||typeof window>"u"||ug.has(n.getKey()))return;Ta.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(r=>r.type!==$e.StatusChanged&&r.type!==$e.Snapshot&&r.type!==$e.LocalChange&&r.type!==$e.RemoteChange&&r.type!==$e.Initialized&&r.type!==$e.Watched&&r.type!==$e.Unwatched&&r.type!==$e.PresenceChanged)||(Ta.get(n.getKey()).push(t),Ri==="synced"&&ra({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});ug.set(n.getKey(),[e]),ra({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var i;if(((i=t.data)==null?void 0:i.source)!==KS)return;switch(t.data.msg){case"devtools::connect":if(Ri!=="disconnected")break;Ri="connected",ra({msg:"doc::available",docKey:n.getKey()}),J.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Ri="disconnected",J.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Ri="synced",ra({msg:"doc::sync::full",docKey:n.getKey(),events:Ta.get(n.getKey())}),J.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Pr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Pr||{}),$e=(n=>(n.StatusChanged="status-changed",n.ConnectionChanged="connection-changed",n.SyncStatusChanged="sync-status-changed",n.Snapshot="snapshot",n.LocalChange="local-change",n.RemoteChange="remote-change",n.Initialized="initialized",n.Watched="watched",n.Unwatched="unwatched",n.PresenceChanged="presence-changed",n.Broadcast="broadcast",n.LocalBroadcast="local-broadcast",n))($e||{}),_c=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(_c||{}),Gc=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Gc||{});class Ry{constructor(e,t){u(this,"key");u(this,"status");u(this,"opts");u(this,"changeID");u(this,"checkpoint");u(this,"localChanges");u(this,"root");u(this,"clone");u(this,"eventStream");u(this,"eventStreamObserver");u(this,"onlineClients");u(this,"presences");u(this,"history");u(this,"internalHistory");u(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=To.create(),this.changeID=Y1,this.checkpoint=Q1,this.localChanges=[],this.eventStream=$S(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new qS,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},HS(this)}update(e,t){if(this.getStatus()==="removed")throw new k(S.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Wi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{const s=ag(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(s,new ku(i,this.clone.presences.get(r)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(i.hasChange()){J.isEnabled(be.Trivial)&&J.trivial(`trying to update a local change: ${this.toJSON()}`);const s=i.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,Y.Local),l=i.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const c=[];o.length>0&&c.push({type:"local-change",source:Y.Local,value:{message:s.getMessage()||"",operations:o,actor:r,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&c.push({type:"presence-changed",source:Y.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(c),J.isEnabled(be.Trivial)&&J.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,r,i){if(typeof e=="string"){if(typeof t!="function")throw new k(S.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="initialized"&&c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||a(c)},r,i)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="initialized"&&c.type!=="presence-changed"||c.type==="presence-changed"&&c.value.clientID!==this.changeID.getActorID()||a(c)},r,i)}if(e==="others"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||c.value.clientID!==this.changeID.getActorID()&&a(c)},r,i)}if(e==="connection"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="connection-changed"&&a(c)},r,i)}if(e==="status"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="status-changed"&&a(c)},r,i)}if(e==="sync"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="sync-status-changed"&&a(c)},r,i)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="local-broadcast"&&a(c)},r)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="broadcast"&&a(c)},r)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,r,i)}const s=e,o=t;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const c=[];for(const d of l.value.operations)this.isSameElementOrChildOf(d.path,s)&&c.push(d);c.length&&o({...l,value:{...l.value,operations:c}})}},r,i)}if(typeof e=="function"){const s=e,o=t,a=r;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="snapshot"&&c.type!=="local-change"&&c.type!=="remote-change"||s(c)},o,a)}throw new k(S.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const r=e.split(".");return t.split(".").every((s,o)=>s===r[o])}applyChangePack(e){const t=e.hasSnapshot();for(t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),Y.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();t&&this.applyChanges(this.localChanges,Y.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),J.isEnabled(be.Trivial)&&J.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Pt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return Jl.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Wi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return ag(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r){const{root:i,presences:s}=fe.bytesToSnapshot(r);this.root=new To(i),this.presences=s,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.publish([{type:"snapshot",source:Y.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?fe.bytesToHex(r):void 0,snapshotVector:fe.versionVectorToHex(t)}}])}applyChanges(e,t){J.isEnabled(be.Debug)&&J.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),J.isEnabled(be.Trivial)&&J.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` -`));for(const r of e)this.applyChange(r,t);J.isEnabled(be.Debug)&&J.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const r=[],i=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(i)){const o=e.getPresenceChange();switch(o.type){case Qr.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:t,value:{clientID:i,presence:o.presence}}:{type:"watched",source:Y.Remote,value:{clientID:i,presence:o.presence}});break;case Qr.Clear:r.push({type:"unwatched",source:Y.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:s}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===Y.Remote?{type:"remote-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,r=new Set;for(const i of t)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:Y.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,i=[];if(t===yi.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:Y.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(t===yi.DOCUMENT_UNWATCHED){const s=this.getPresence(r);this.removeOnlineClient(r),s&&i.push({type:"unwatched",source:Y.Remote,value:{clientID:r,presence:s}})}else if(t===yi.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:s,payload:o}=e.body.value.body,a=new TextDecoder;i.push({type:"broadcast",value:{clientID:r,topic:s,payload:JSON.parse(a.decode(o))}})}i.length>0&&this.publish(i)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(Gf),this.publish([{source:e==="removed"?Y.Remote:Y.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:r,snapshotVector:i}=e.value;if(!t)return;this.applySnapshot(BigInt(r),fe.hexToVersionVector(i),fe.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=gs.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:r,presence:i}of e.value)t.add(r),this.presences.set(r,i);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:r}=e.value;this.addOnlineClient(t),this.presences.set(t,r);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:r}=e.value;this.presences.set(t,r)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new k(S.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let r=this.getRoot();for(const i of t)if(r=r[i],r===void 0)return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?Pt(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?Pt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Pt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Pt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Pt(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,r)=>t.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){const r=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new k(S.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Wi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof $t)){new ku(t,Pt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:Y.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new k(S.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Wi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof $t)){new ku(t,Pt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:Y.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){const i={type:"local-broadcast",value:{topic:e,payload:t},options:r};this.publish([i])}getVersionVector(){return this.changeID.getVersionVector()}}function _S(n,e){return t=>async r=>(n&&r.header.set("x-api-key",n),e&&r.header.set("authorization",e),await t(r))}const GS="yorkie-js-sdk",YS="0.5.4",QS="Yorkie JS SDK",XS="./src/yorkie.ts",ZS={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},ek=["dist"],tk={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},nk={node:">=18.0.0",npm:">=7.1.0"},rk={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},ik={name:"hackerwins",email:"susukang98@gmail.com"},sk="Apache-2.0",ok={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},ak="https://github.com/yorkie-team/yorkie-js-sdk#readme",lk={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},uk={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},cg={name:GS,version:YS,description:QS,main:XS,publishConfig:ZS,files:ek,scripts:tk,engines:nk,repository:rk,author:ik,license:sk,bugs:ok,homepage:ak,devDependencies:lk,dependencies:uk};function ck(){return n=>async e=>(e.header.set("x-yorkie-user-agent",cg.name+"/"+cg.version),await n(e))}const fk=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Aa=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Aa||{});const ia={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Eu={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Ly{constructor(e,t){u(this,"id");u(this,"key");u(this,"status");u(this,"attachmentMap");u(this,"apiKey");u(this,"conditions");u(this,"syncLoopDuration");u(this,"reconnectStreamDelay");u(this,"retrySyncLoopDelay");u(this,"rpcClient");u(this,"taskQueue");u(this,"processing",!1);t=t||ia,this.key=t.key?t.key:Py(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||ia.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||ia.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||ia.retrySyncLoopDelay,this.rpcClient=a1(D1,P1({baseUrl:e,interceptors:[_S(t.apiKey,t.token),ck()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),J.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw J.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),J.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw J.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Pr.Detached)throw new k(S.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const r=e.subscribe("local-broadcast",async s=>{var d;const{topic:o,payload:a}=s.value,l=(d=s.options)==null?void 0:d.error,c=s.options;try{await this.broadcast(e.getKey(),o,a,c)}catch(h){h instanceof Error&&(l==null||l(h))}}),i=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:fe.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=fe.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Pr.Removed)return e;e.applyStatus(Pr.Attached),this.attachmentMap.set(e.getKey(),new MS(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),J.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const l=t.initialRoot;e.update(c=>{for(const[d,h]of Object.entries(l))if(!a.has(d)){const p=d;c[p]=h}})}return e}).catch(s=>{throw J.error(`[AD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((i,s)=>s.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:fe.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=fe.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==Pr.Removed&&e.applyStatus(Pr.Detached),this.detachInternal(e.getKey()),J.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(i=>{throw J.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(e,t){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const i=r.syncMode;return i===t?e:(r.changeSyncMode(t),t==="manual"?(r.cancelWatchStream(),e):(t==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const t=[];for(const[,r]of this.attachmentMap)t.push(this.syncInternal(r,r.syncMode));return Promise.all(t).catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=fe.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=fe.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),J.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(i=>{throw J.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,i){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);if(!fk(r))throw new k(S.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??Eu.maxRetries,a=Eu.maxBackoff;let l=0;const c=h=>Math.min(Eu.initialRetryInterval*2**h,a),d=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{J.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(h=>{if(J.error(`[BC] c:"${this.getKey()}" err:`,h),this.handleConnectError(h))if(ld(),c(l-1)),J.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw J.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),h;else throw h}));return d()}runSyncLoop(){const e=()=>{if(!this.isActive()){J.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,t.push(this.syncInternal(r,r.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{J.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};J.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new k(S.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:i.signal});return t.doc.publish([{type:$e.ConnectionChanged,value:_c.Connected}]),J.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const c of s)this.handleWatchDocumentsResponse(t,c),c.body.case==="initialization"&&o([s,i])}catch(c){t.doc.resetOnlineClients(),t.doc.publish([{type:$e.Initialized,source:Y.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:$e.ConnectionChanged,value:_c.Disconnected}]),J.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(c)?r():this.conditions.WatchLoop=!1,a(c)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===yi.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(Pr.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:r,docID:i}=e,s=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:fe.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=fe.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:$e.SyncStatusChanged,value:Gc.Synced}]),r.getStatus()===Pr.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),c=a.getChangeSize();return J.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${c} cp:${a.getCheckpoint().toTestString()}`),r}).catch(o=>{throw r.publish([{type:$e.SyncStatusChanged,value:Gc.SyncFailed}]),J.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof pe?e.code===_.Canceled||e.code===_.Unknown||e.code===_.ResourceExhausted||e.code===_.Unavailable?!0:((sg(e)===S.ErrClientNotActivated||sg(e)===S.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{J.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const By={Client:Ly,Document:Ry,Primitive:re,Text:$l,Counter:zl,Tree:Ul,LogLevel:be,setLogLevel:Ny,IntType:on.IntegerCnt,LongType:on.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Ly,Document:Ry,Primitive:re,Text:$l,Counter:zl,Tree:Ul,LogLevel:be,setLogLevel:Ny,IntType:on.IntegerCnt,LongType:on.LongCnt});class dk{constructor(e,t){this.x=e,this.y=t,this.lifetime=0}}const hk=({xPos:n,yPos:e})=>{const[t,r]=Ue.useState([]),i=Ue.useRef(null),[s,o]=Ue.useState([]),a=(l,c)=>{const d=new dk(l,c);s.push(d),o(s),t.push(d),r(t)};return Ue.useEffect(()=>{const c=i.current.getContext("2d"),d=()=>{c.clearRect(0,0,c.canvas.width,c.canvas.height);const h=.7*(1*4e3)/60;for(let p=0;ph)s.shift();else{c.lineWidth=5,c.lineJoin="round";const I=0,O=0,y=0;c.strokeStyle=`rgb(${I},${O},${y})`,c.beginPath(),c.moveTo(w.x,w.y),c.lineTo(m.x,m.y),c.stroke(),c.closePath()}}requestAnimationFrame(d)};d()},[s]),Ue.useEffect(()=>{a(n,e)},[n,e]),ue.jsx("canvas",{className:"pen-cursor-canvas",ref:i,width:document.body.clientWidth,height:document.body.clientHeight})},gk="_goUp0_1lnal_1",mk="_goUpAnimation0_1lnal_1",pk="_fadeOut_1lnal_1",yk="_goUp1_1lnal_16",vk="_goUpAnimation1_1lnal_1",wk="_goUp2_1lnal_31",Sk="_goUpAnimation2_1lnal_1",kk="_leftRight0_1lnal_46",Tk="_leftRightAnimation0_1lnal_1",Ak="_leftRight1_1lnal_60",Ik="_leftRightAnimation1_1lnal_1",Ek="_leftRight2_1lnal_74",xk="_leftRightAnimation2_1lnal_1",xu={goUp0:gk,goUpAnimation0:mk,fadeOut:pk,goUp1:yk,goUpAnimation1:vk,goUp2:wk,goUpAnimation2:Sk,leftRight0:kk,leftRightAnimation0:Tk,leftRight1:Ak,leftRightAnimation1:Ik,leftRight2:Ek,leftRightAnimation2:xk};function Ck({x:n,y:e,timestamp:t,selectedCursorShape:r}){return ue.jsx("div",{className:"single-animation-container",children:ue.jsx("div",{className:`absolute select-none pointer-events-none ${xu.disappear} text-${t%5+2}xl ${xu["goUp"+t%3]}`,style:{left:n,top:e},children:ue.jsx("div",{className:xu["leftRight"+t%3],children:ue.jsx("div",{className:"transform -translate-x-1/2 -translate-y-1/2",children:ue.jsx("img",{src:`./icons/icon_${r}.svg`})})})})})}function fg(n,e){const t=Ue.useRef(n);Ue.useEffect(()=>{t.current=n},[n]),Ue.useEffect(()=>{function r(){t.current()}if(e!==null){let i=setInterval(r,e);return()=>clearInterval(i)}},[e])}const Nk=({pointerDown:n,xPos:e,yPos:t,selectedCursorShape:r})=>{const[i,s]=Ue.useState([]),o=100;return fg(()=>{s(a=>a.filter(l=>l.timestamp>Date.now()-4e3))},1e3),fg(()=>{n&&s(a=>a.concat([{point:{x:e,y:t},timestamp:Date.now()}]))},o),ue.jsx("div",{style:{transform:`translateX(${e}px) translateY(${t}px)`},children:i.map(a=>ue.jsx(Ck,{x:a.point.x,y:a.point.y,timestamp:a.timestamp,selectedCursorShape:r},a.timestamp.toString()))})},Pk=({selectedCursorShape:n,x:e,y:t,pointerDown:r})=>ue.jsxs(ue.Fragment,{children:[ue.jsx("img",{src:`./icons/icon_${n}.svg`,className:`${n}-cursor`,style:{transform:`translate3d(${e}px, ${t}px, 0)`}}),(n==="heart"||n==="thumbs")&&ue.jsx(Nk,{pointerDown:r,xPos:e,yPos:t,selectedCursorShape:n}),n==="pen"&&r&&ue.jsx(hk,{xPos:e,yPos:t})]}),Dk=({handleCursorShapeSelect:n,clientsLength:e})=>{const[t,r]=Ue.useState("cursor"),i=["heart","thumbs","pen","cursor"];return ue.jsxs("div",{className:"cursor-selector-container",children:[ue.jsx("div",{className:"cursor-selections-container",children:i.map(s=>ue.jsx("img",{onClick:()=>{n(s),r(s)},className:`${t===s?"cursor-shape-selected":"cursor-shape-not-selected"}`,src:`./icons/icon_${s}.svg`},s))}),ue.jsx("div",{className:"num-users-container",children:ue.jsx("p",{children:e!==1?`${e} users are here`:"1 user here"})})]})},Cu=new By.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),ii=new By.Document("simultaneous-cursors",{enableDevtools:!0}),Ok=()=>{const[n,e]=Ue.useState([]),t=r=>{ii.update((i,s)=>{s.set({cursorShape:r})})};return Ue.useEffect(()=>{(async()=>{await Cu.activate(),ii.subscribe("presence",a=>{e(ii.getPresences())}),await Cu.attach(ii,{initialPresence:{cursorShape:"cursor",cursor:{xPos:0,yPos:0},pointerDown:!1}}),window.addEventListener("beforeunload",()=>{Cu.deactivate()})})();const i=()=>{ii.update((a,l)=>{l.set({pointerDown:!1})})},s=()=>{ii.update((a,l)=>{l.set({pointerDown:!0})})},o=a=>{ii.update((l,c)=>{c.set({cursor:{xPos:a.clientX,yPos:a.clientY}})})};return window.addEventListener("mousedown",s),window.addEventListener("mouseup",i),window.addEventListener("mousemove",o),()=>{window.removeEventListener("mousedown",s),window.removeEventListener("mouseup",i),window.removeEventListener("mousemove",o)}},[]),ue.jsxs("div",{className:"general-container",children:[n.map(({clientID:r,presence:{cursorShape:i,cursor:s,pointerDown:o}})=>s?ue.jsx(Pk,{selectedCursorShape:i,x:s.xPos,y:s.yPos,pointerDown:o},r):null),ue.jsx(Dk,{handleCursorShapeSelect:t,clientsLength:n.length})]})};Nu.createRoot(document.getElementById("root")).render(ue.jsx(Ok,{})); +`));for(const r of e)this.applyChange(r,t);J.isEnabled(be.Debug)&&J.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const r=[],i=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(i)){const o=e.getPresenceChange();switch(o.type){case Qr.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:t,value:{clientID:i,presence:o.presence}}:{type:"watched",source:Y.Remote,value:{clientID:i,presence:o.presence}});break;case Qr.Clear:r.push({type:"unwatched",source:Y.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:s}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===Y.Remote?{type:"remote-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,r=new Set;for(const i of t)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:Y.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,i=[];if(t===yi.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:Y.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===yi.DOCUMENT_UNWATCHED){const s=this.getPresence(r);this.removeOnlineClient(r),s&&i.push({type:"unwatched",source:Y.Remote,value:{clientID:r,presence:s}})}else if(t===yi.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:s,payload:o}=e.body.value.body,a=new TextDecoder;i.push({type:"broadcast",value:{clientID:r,topic:s,payload:JSON.parse(a.decode(o))}})}i.length>0&&this.publish(i)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(Gf),this.publish([{source:e==="removed"?Y.Remote:Y.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:r,snapshotVector:i}=e.value;if(!t)return;this.applySnapshot(BigInt(r),fe.hexToVersionVector(i),fe.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=gs.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:r,presence:i}of e.value)t.add(r),this.presences.set(r,i);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:r}=e.value;this.addOnlineClient(t),this.presences.set(t,r);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:r}=e.value;this.presences.set(t,r)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new k(S.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let r=this.getRoot();for(const i of t)if(r=r[i],r===void 0)return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?Pt(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?Pt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Pt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Pt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Pt(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,r)=>t.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){const r=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new k(S.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Wi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof $t)){new ku(t,Pt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:Y.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new k(S.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Wi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof $t)){new ku(t,Pt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:Y.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){const i={type:"local-broadcast",value:{topic:e,payload:t},options:r};this.publish([i])}getVersionVector(){return this.changeID.getVersionVector()}}function _S(n,e){return t=>async r=>(n&&r.header.set("x-api-key",n),e&&r.header.set("authorization",e),await t(r))}const GS="yorkie-js-sdk",YS="0.5.4",QS="Yorkie JS SDK",XS="./src/yorkie.ts",ZS={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},ek=["dist"],tk={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},nk={node:">=18.0.0",npm:">=7.1.0"},rk={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},ik={name:"hackerwins",email:"susukang98@gmail.com"},sk="Apache-2.0",ok={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},ak="https://github.com/yorkie-team/yorkie-js-sdk#readme",lk={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},uk={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},cg={name:GS,version:YS,description:QS,main:XS,publishConfig:ZS,files:ek,scripts:tk,engines:nk,repository:rk,author:ik,license:sk,bugs:ok,homepage:ak,devDependencies:lk,dependencies:uk};function ck(){return n=>async e=>(e.header.set("x-yorkie-user-agent",cg.name+"/"+cg.version),await n(e))}const fk=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Aa=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Aa||{});const ia={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Eu={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Ly{constructor(e,t){u(this,"id");u(this,"key");u(this,"status");u(this,"attachmentMap");u(this,"apiKey");u(this,"conditions");u(this,"syncLoopDuration");u(this,"reconnectStreamDelay");u(this,"retrySyncLoopDelay");u(this,"rpcClient");u(this,"taskQueue");u(this,"processing",!1);t=t||ia,this.key=t.key?t.key:Py(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||ia.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||ia.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||ia.retrySyncLoopDelay,this.rpcClient=a1(D1,P1({baseUrl:e,interceptors:[_S(t.apiKey,t.token),ck()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),J.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw J.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),J.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw J.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Pr.Detached)throw new k(S.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const r=e.subscribe("local-broadcast",async s=>{var d;const{topic:o,payload:a}=s.value,l=(d=s.options)==null?void 0:d.error,c=s.options;try{await this.broadcast(e.getKey(),o,a,c)}catch(h){h instanceof Error&&(l==null||l(h))}}),i=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:fe.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=fe.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Pr.Removed)return e;e.applyStatus(Pr.Attached),this.attachmentMap.set(e.getKey(),new MS(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),J.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const l=t.initialRoot;e.update(c=>{for(const[d,h]of Object.entries(l))if(!a.has(d)){const p=d;c[p]=h}})}return e}).catch(s=>{throw J.error(`[AD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((i,s)=>s.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:fe.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=fe.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==Pr.Removed&&e.applyStatus(Pr.Detached),this.detachInternal(e.getKey()),J.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(i=>{throw J.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(e,t){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const i=r.syncMode;return i===t?e:(r.changeSyncMode(t),t==="manual"?(r.cancelWatchStream(),e):(t==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const t=[];for(const[,r]of this.attachmentMap)t.push(this.syncInternal(r,r.syncMode));return Promise.all(t).catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=fe.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=fe.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),J.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(i=>{throw J.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,i){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);if(!fk(r))throw new k(S.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??Eu.maxRetries,a=Eu.maxBackoff;let l=0;const c=h=>Math.min(Eu.initialRetryInterval*2**h,a),d=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{J.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(h=>{if(J.error(`[BC] c:"${this.getKey()}" err:`,h),this.handleConnectError(h))if(ld(),c(l-1)),J.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw J.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),h;else throw h}));return d()}runSyncLoop(){const e=()=>{if(!this.isActive()){J.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,t.push(this.syncInternal(r,r.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{J.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};J.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new k(S.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:i.signal});return t.doc.publish([{type:$e.ConnectionChanged,value:_c.Connected}]),J.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const c of s)this.handleWatchDocumentsResponse(t,c),c.body.case==="initialization"&&o([s,i])}catch(c){t.doc.resetOnlineClients(),t.doc.publish([{type:$e.Initialized,source:Y.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:$e.ConnectionChanged,value:_c.Disconnected}]),J.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(c)?r():this.conditions.WatchLoop=!1,a(c)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===yi.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(Pr.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:r,docID:i}=e,s=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:fe.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=fe.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:$e.SyncStatusChanged,value:Gc.Synced}]),r.getStatus()===Pr.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),c=a.getChangeSize();return J.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${c} cp:${a.getCheckpoint().toTestString()}`),r}).catch(o=>{throw r.publish([{type:$e.SyncStatusChanged,value:Gc.SyncFailed}]),J.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof pe?e.code===_.Canceled||e.code===_.Unknown||e.code===_.ResourceExhausted||e.code===_.Unavailable?!0:((sg(e)===S.ErrClientNotActivated||sg(e)===S.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{J.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const By={Client:Ly,Document:Ry,Primitive:re,Text:$l,Counter:zl,Tree:Ul,LogLevel:be,setLogLevel:Ny,IntType:on.IntegerCnt,LongType:on.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Ly,Document:Ry,Primitive:re,Text:$l,Counter:zl,Tree:Ul,LogLevel:be,setLogLevel:Ny,IntType:on.IntegerCnt,LongType:on.LongCnt});class dk{constructor(e,t){this.x=e,this.y=t,this.lifetime=0}}const hk=({xPos:n,yPos:e})=>{const[t,r]=Ue.useState([]),i=Ue.useRef(null),[s,o]=Ue.useState([]),a=(l,c)=>{const d=new dk(l,c);s.push(d),o(s),t.push(d),r(t)};return Ue.useEffect(()=>{const c=i.current.getContext("2d"),d=()=>{c.clearRect(0,0,c.canvas.width,c.canvas.height);const h=.7*(1*4e3)/60;for(let p=0;ph)s.shift();else{c.lineWidth=5,c.lineJoin="round";const I=0,O=0,y=0;c.strokeStyle=`rgb(${I},${O},${y})`,c.beginPath(),c.moveTo(w.x,w.y),c.lineTo(m.x,m.y),c.stroke(),c.closePath()}}requestAnimationFrame(d)};d()},[s]),Ue.useEffect(()=>{a(n,e)},[n,e]),ue.jsx("canvas",{className:"pen-cursor-canvas",ref:i,width:document.body.clientWidth,height:document.body.clientHeight})},gk="_goUp0_1lnal_1",mk="_goUpAnimation0_1lnal_1",pk="_fadeOut_1lnal_1",yk="_goUp1_1lnal_16",vk="_goUpAnimation1_1lnal_1",wk="_goUp2_1lnal_31",Sk="_goUpAnimation2_1lnal_1",kk="_leftRight0_1lnal_46",Tk="_leftRightAnimation0_1lnal_1",Ak="_leftRight1_1lnal_60",Ik="_leftRightAnimation1_1lnal_1",Ek="_leftRight2_1lnal_74",xk="_leftRightAnimation2_1lnal_1",xu={goUp0:gk,goUpAnimation0:mk,fadeOut:pk,goUp1:yk,goUpAnimation1:vk,goUp2:wk,goUpAnimation2:Sk,leftRight0:kk,leftRightAnimation0:Tk,leftRight1:Ak,leftRightAnimation1:Ik,leftRight2:Ek,leftRightAnimation2:xk};function Ck({x:n,y:e,timestamp:t,selectedCursorShape:r}){return ue.jsx("div",{className:"single-animation-container",children:ue.jsx("div",{className:`absolute select-none pointer-events-none ${xu.disappear} text-${t%5+2}xl ${xu["goUp"+t%3]}`,style:{left:n,top:e},children:ue.jsx("div",{className:xu["leftRight"+t%3],children:ue.jsx("div",{className:"transform -translate-x-1/2 -translate-y-1/2",children:ue.jsx("img",{src:`./icons/icon_${r}.svg`})})})})})}function fg(n,e){const t=Ue.useRef(n);Ue.useEffect(()=>{t.current=n},[n]),Ue.useEffect(()=>{function r(){t.current()}if(e!==null){let i=setInterval(r,e);return()=>clearInterval(i)}},[e])}const Nk=({pointerDown:n,xPos:e,yPos:t,selectedCursorShape:r})=>{const[i,s]=Ue.useState([]),o=100;return fg(()=>{s(a=>a.filter(l=>l.timestamp>Date.now()-4e3))},1e3),fg(()=>{n&&s(a=>a.concat([{point:{x:e,y:t},timestamp:Date.now()}]))},o),ue.jsx("div",{style:{transform:`translateX(${e}px) translateY(${t}px)`},children:i.map(a=>ue.jsx(Ck,{x:a.point.x,y:a.point.y,timestamp:a.timestamp,selectedCursorShape:r},a.timestamp.toString()))})},Pk=({selectedCursorShape:n,x:e,y:t,pointerDown:r})=>ue.jsxs(ue.Fragment,{children:[ue.jsx("img",{src:`./icons/icon_${n}.svg`,className:`${n}-cursor`,style:{transform:`translate3d(${e}px, ${t}px, 0)`}}),(n==="heart"||n==="thumbs")&&ue.jsx(Nk,{pointerDown:r,xPos:e,yPos:t,selectedCursorShape:n}),n==="pen"&&r&&ue.jsx(hk,{xPos:e,yPos:t})]}),Dk=({handleCursorShapeSelect:n,clientsLength:e})=>{const[t,r]=Ue.useState("cursor"),i=["heart","thumbs","pen","cursor"];return ue.jsxs("div",{className:"cursor-selector-container",children:[ue.jsx("div",{className:"cursor-selections-container",children:i.map(s=>ue.jsx("img",{onClick:()=>{n(s),r(s)},className:`${t===s?"cursor-shape-selected":"cursor-shape-not-selected"}`,src:`./icons/icon_${s}.svg`},s))}),ue.jsx("div",{className:"num-users-container",children:ue.jsx("p",{children:e!==1?`${e} users are here`:"1 user here"})})]})},Cu=new By.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),ii=new By.Document("simultaneous-cursors",{enableDevtools:!0}),Ok=()=>{const[n,e]=Ue.useState([]),t=r=>{ii.update((i,s)=>{s.set({cursorShape:r})})};return Ue.useEffect(()=>{(async()=>{await Cu.activate(),ii.subscribe("presence",a=>{e(ii.getPresences())}),await Cu.attach(ii,{initialPresence:{cursorShape:"cursor",cursor:{xPos:0,yPos:0},pointerDown:!1}}),window.addEventListener("beforeunload",()=>{Cu.deactivate()})})();const i=()=>{ii.update((a,l)=>{l.set({pointerDown:!1})})},s=()=>{ii.update((a,l)=>{l.set({pointerDown:!0})})},o=a=>{ii.update((l,c)=>{c.set({cursor:{xPos:a.clientX,yPos:a.clientY}})})};return window.addEventListener("mousedown",s),window.addEventListener("mouseup",i),window.addEventListener("mousemove",o),()=>{window.removeEventListener("mousedown",s),window.removeEventListener("mouseup",i),window.removeEventListener("mousemove",o)}},[]),ue.jsxs("div",{className:"general-container",children:[n.map(({clientID:r,presence:{cursorShape:i,cursor:s,pointerDown:o}})=>s?ue.jsx(Pk,{selectedCursorShape:i,x:s.xPos,y:s.yPos,pointerDown:o},r):null),ue.jsx(Dk,{handleCursorShapeSelect:t,clientsLength:n.length})]})};Nu.createRoot(document.getElementById("root")).render(ue.jsx(Ok,{})); diff --git a/examples/simultaneous-cursors/index.html b/examples/simultaneous-cursors/index.html index 780c7c14e..3345c2ae1 100644 --- a/examples/simultaneous-cursors/index.html +++ b/examples/simultaneous-cursors/index.html @@ -5,7 +5,7 @@ Simultaneous Cursors - Yorkie Example - + diff --git a/examples/vanilla-codemirror6/assets/index-CkLurkOj.js b/examples/vanilla-codemirror6/assets/index-BKhO_6dR.js similarity index 97% rename from examples/vanilla-codemirror6/assets/index-CkLurkOj.js rename to examples/vanilla-codemirror6/assets/index-BKhO_6dR.js index 16a2b53b1..f2c17ed4d 100644 --- a/examples/vanilla-codemirror6/assets/index-CkLurkOj.js +++ b/examples/vanilla-codemirror6/assets/index-BKhO_6dR.js @@ -20,7 +20,7 @@ var yS=Object.defineProperty;var bS=(n,e,t)=>e in n?yS(n,e,{enumerable:!0,config * * SPDX-License-Identifier: Apache-2.0 */var Ct=null;try{Ct=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Y(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}Y.prototype.__isLong__;Object.defineProperty(Y.prototype,"__isLong__",{value:!0});function je(n){return(n&&n.__isLong__)===!0}function Cd(n){var e=Math.clz32(n&-n);return n?31-e:e}Y.isLong=je;var Id={},Rd={};function Xr(n,e){var t,i,r;return e?(n>>>=0,(r=0<=n&&n<256)&&(i=Rd[n],i)?i:(t=ee(n,0,!0),r&&(Rd[n]=t),t)):(n|=0,(r=-128<=n&&n<128)&&(i=Id[n],i)?i:(t=ee(n,n<0?-1:0,!1),r&&(Id[n]=t),t))}Y.fromInt=Xr;function It(n,e){if(isNaN(n))return e?En:zt;if(e){if(n<0)return En;if(n>=eO)return nO}else{if(n<=-Dd)return tt;if(n+1>=Dd)return iO}return n<0?It(-n,e).neg():ee(n%fs|0,n/fs|0,e)}Y.fromNumber=It;function ee(n,e,t){return new Y(n,e,t)}Y.fromBits=ee;var yl=Math.pow;function Gu(n,e,t){if(n.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return e?En:zt;if(t=t||10,t<2||360)throw Error("interior hyphen");if(i===0)return Gu(n.substring(1),e,t).neg();for(var r=It(yl(t,8)),s=zt,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*fs+(this.low>>>0):this.high*fs+(this.low>>>0)};C.toString=function(e){if(e=e||10,e<2||36>>0,c=h.toString(e);if(o=l,o.isZero())return c+a;for(;c.length<6;)c="0"+c;a=""+c+a}};C.getHighBits=function(){return this.high};C.getHighBitsUnsigned=function(){return this.high>>>0};C.getLowBits=function(){return this.low};C.getLowBitsUnsigned=function(){return this.low>>>0};C.getNumBitsAbs=function(){if(this.isNegative())return this.eq(tt)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};C.isOdd=function(){return(this.low&1)===1};C.isEven=function(){return(this.low&1)===0};C.equals=function(e){return je(e)||(e=ei(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};C.eq=C.equals;C.notEquals=function(e){return!this.eq(e)};C.neq=C.notEquals;C.ne=C.notEquals;C.lessThan=function(e){return this.comp(e)<0};C.lt=C.lessThan;C.lessThanOrEqual=function(e){return this.comp(e)<=0};C.lte=C.lessThanOrEqual;C.le=C.lessThanOrEqual;C.greaterThan=function(e){return this.comp(e)>0};C.gt=C.greaterThan;C.greaterThanOrEqual=function(e){return this.comp(e)>=0};C.gte=C.greaterThanOrEqual;C.ge=C.greaterThanOrEqual;C.compare=function(e){if(je(e)||(e=ei(e)),this.eq(e))return 0;var t=this.isNegative(),i=e.isNegative();return t&&!i?-1:!t&&i?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};C.comp=C.compare;C.negate=function(){return!this.unsigned&&this.eq(tt)?tt:this.not().add(Gr)};C.neg=C.negate;C.add=function(e){je(e)||(e=ei(e));var t=this.high>>>16,i=this.high&65535,r=this.low>>>16,s=this.low&65535,o=e.high>>>16,a=e.high&65535,l=e.low>>>16,h=e.low&65535,c=0,u=0,f=0,p=0;return p+=s+h,f+=p>>>16,p&=65535,f+=r+l,u+=f>>>16,f&=65535,u+=i+a,c+=u>>>16,u&=65535,c+=t+o,c&=65535,ee(f<<16|p,c<<16|u,this.unsigned)};C.subtract=function(e){return je(e)||(e=ei(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(je(e)||(e=ei(e)),Ct){var t=Ct.mul(this.low,this.high,e.low,e.high);return ee(t,Ct.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?En:zt;if(this.eq(tt))return e.isOdd()?tt:zt;if(e.eq(tt))return this.isOdd()?tt:zt;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Nd)&&e.lt(Nd))return It(this.toNumber()*e.toNumber(),this.unsigned);var i=this.high>>>16,r=this.high&65535,s=this.low>>>16,o=this.low&65535,a=e.high>>>16,l=e.high&65535,h=e.low>>>16,c=e.low&65535,u=0,f=0,p=0,g=0;return g+=o*c,p+=g>>>16,g&=65535,p+=s*c,f+=p>>>16,p&=65535,p+=o*h,f+=p>>>16,p&=65535,f+=r*c,u+=f>>>16,f&=65535,f+=s*h,u+=f>>>16,f&=65535,f+=o*l,u+=f>>>16,f&=65535,u+=i*c+r*h+s*l+o*a,u&=65535,ee(p<<16|g,u<<16|f,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(je(e)||(e=ei(e)),e.isZero())throw Error("division by zero");if(Ct){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?Ct.div_u:Ct.div_s)(this.low,this.high,e.low,e.high);return ee(t,Ct.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?En:zt;var i,r,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return En;if(e.gt(this.shru(1)))return tO;s=En}else{if(this.eq(tt)){if(e.eq(Gr)||e.eq(Mc))return tt;if(e.eq(tt))return Gr;var o=this.shr(1);return i=o.div(e).shl(1),i.eq(zt)?e.isNegative()?Gr:Mc:(r=this.sub(e.mul(i)),s=i.add(r.div(e)),s)}else if(e.eq(tt))return this.unsigned?En:zt;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=zt}for(r=this;r.gte(e);){i=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(i)/Math.LN2),l=a<=48?1:yl(2,a-48),h=It(i),c=h.mul(e);c.isNegative()||c.gt(r);)i-=l,h=It(i,this.unsigned),c=h.mul(e);h.isZero()&&(h=Gr),s=s.add(h),r=r.sub(c)}return s};C.div=C.divide;C.modulo=function(e){if(je(e)||(e=ei(e)),Ct){var t=(this.unsigned?Ct.rem_u:Ct.rem_s)(this.low,this.high,e.low,e.high);return ee(t,Ct.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};C.mod=C.modulo;C.rem=C.modulo;C.not=function(){return ee(~this.low,~this.high,this.unsigned)};C.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};C.clz=C.countLeadingZeros;C.countTrailingZeros=function(){return this.low?Cd(this.low):Cd(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return je(e)||(e=ei(e)),ee(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return je(e)||(e=ei(e)),ee(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return je(e)||(e=ei(e)),ee(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return je(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?ee(this.low<>>32-e,this.unsigned):ee(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):ee(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return je(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?ee(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?ee(this.high,0,this.unsigned):ee(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var t;return je(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?ee(this.high,this.low,this.unsigned):e<32?(t=32-e,ee(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,ee(this.high<>>t,this.low<>>t,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var t;return je(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?ee(this.high,this.low,this.unsigned):e<32?(t=32-e,ee(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,ee(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?ee(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:ee(this.low,this.high,!0)};C.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};C.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};C.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};Y.fromBytes=function(e,t,i){return i?Y.fromBytesLE(e,t):Y.fromBytesBE(e,t)};Y.fromBytesLE=function(e,t){return new Y(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};Y.fromBytesBE=function(e,t){return new Y(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var $e=(n=>(n[n.Null=0]="Null",n[n.Boolean=1]="Boolean",n[n.Integer=2]="Integer",n[n.Long=3]="Long",n[n.Double=4]="Double",n[n.String=5]="String",n[n.Bytes=6]="Bytes",n[n.Date=7]="Date",n))($e||{});class pe extends qo{constructor(t,i){super(i);d(this,"valueType");d(this,"value");this.valueType=pe.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,i){return new pe(t,i)}static valueFromBytes(t,i){switch(t){case 0:return null;case 1:return!!i[0];case 2:return i[0]|i[1]<<8|i[2]<<16|i[3]<<24;case 4:{const r=new DataView(i.buffer);return i.forEach(function(s,o){r.setUint8(o,s)}),r.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(i);case 3:return Y.fromBytesLE(Array.from(i));case 6:return i;case 7:return new Date(Y.fromBytesLE(Array.from(i),!0).toNumber());default:throw new v(w.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${wi(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=pe.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof Y)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return pe.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,i=new Uint8Array(8);return new DataView(i.buffer).setFloat64(0,t,!0),i}case 5:return new TextEncoder().encode(this.value);case 3:{const i=this.value.toBytesLE();return Uint8Array.from(i)}case 6:return this.value;case 7:{const t=this.value,i=Y.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(i)}default:throw new v(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class bl extends Km{constructor(t){super(t);d(this,"prev");d(this,"next");this.value=t}static createAfter(t,i){const r=new bl(i),s=t.next;return t.next=r,r.prev=t,r.next=s,s&&(s.prev=r),r}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class po{constructor(){d(this,"dummyHead");d(this,"last");d(this,"nodeMapByIndex");d(this,"nodeMapByCreatedAt");const e=pe.of(0,Gt);e.setRemovedAt(Gt),this.dummyHead=new bl(e),this.last=this.dummyHead,this.nodeMapByIndex=new fo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new po}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new v(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;i.getNext()&&i.getNext().getPositionedAt().after(t);)i=i.getNext();return i}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,i=t.getCreatedAt()){const r=this.findNextBeforeExecutedAt(e,i),s=bl.createAfter(r,t);r===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(r,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,t,i){const r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new v(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new v(w.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);r!==s&&(!s.getValue().getMovedAt()||i.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(r.getCreatedAt(),s.getValue(),i),s.getValue().setMovedAt(i))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new v(w.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,i]=this.nodeMapByIndex.find(e);let r=t;if(e===0&&t===this.dummyHead||i>0)do r&&(r=r.getNext());while(r&&r.isRemoved());return r}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const i=this.nodeMapByCreatedAt.get(e.toIDString()),r=i.isRemoved();return i.remove(t)&&!r&&this.nodeMapByIndex.splayNode(i),i.getValue()}deleteByIndex(e,t){const i=this.getByIndex(e);if(i)return i.remove(t)&&this.nodeMapByIndex.splayNode(i),i.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const i=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${i}}`):e.push(`[${i}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class pt extends rr{constructor(t,i){super(t);d(this,"elements");this.elements=i}static create(t,i){if(!i)return new pt(t,po.create());const r=po.create();for(const s of i)r.insertAfter(r.getLastCreatedAt(),s.deepcopy());return new pt(t,r)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,i){this.elements.insertAfter(t,i)}moveAfter(t,i,r){this.elements.moveAfter(t,i,r)}get(t){const i=this.elements.getByIndex(t);return i==null?void 0:i.getValue()}getByID(t){const i=this.elements.getByID(t);return i==null?void 0:i.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,i){return this.elements.delete(t,i)}deleteByIndex(t,i){return this.elements.deleteByIndex(t,i)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const i of this.elements){const r=i.getValue();if(t(r,this))return;r instanceof rr&&r.getDescendants(t)}}toJSON(){const t=[];for(const i of this)t.push(i.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let i=0;i({...p,value:p.value?{attributes:es(p.value.getAttributes()),content:p.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[h,f,c,[l,l]]}setStyle(t,i,r,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],r),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],r),l=[],h=this.rgaTreeSplit.findBetween(a,o),c=new Map,u=[];for(const p of h){const g=p.getCreatedAt().getActorID(),y=s!=null&&s.size?s.has(g)?s.get(g):Gt:Ys;if(p.canStyle(r,y)){const O=c.get(g),S=p.getCreatedAt();(!O||S.after(O))&&c.set(g,S),u.push(p)}}const f=[];for(const p of u){if(p.isRemoved())continue;const[g,y]=this.rgaTreeSplit.findIndexesFromRange(p.createPosRange());l.push({type:"style",actor:r.getActorID(),from:g,to:y,value:{attributes:es(i)}});for(const[O,S]of Object.entries(i)){const[k]=p.getValue().setAttr(O,S,r);k!==void 0&&f.push({parent:p.getValue(),child:k})}}return[c,f,l]}indexRangeToPosRange(t,i){const r=this.rgaTreeSplit.indexToPos(t);return t===i?[r,r]:[r,this.rgaTreeSplit.indexToPos(i)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const i of this.rgaTreeSplit)i.isRemoved()||t.push(i.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const i of this.rgaTreeSplit)if(!i.isRemoved()){const r=i.getValue();t.push({attributes:es(r.getAttributes()),content:r.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new qt(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const i of this.rgaTreeSplit){i.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:i});for(const r of i.getValue().getGCPairs())t.push(r)}return t}}class Vo extends Yt{constructor(t,i,r,s,o,a,l){super(t,l);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"content");d(this,"attributes");this.fromPos=i,this.toPos=r,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(t,i,r,s,o,a,l){return new Vo(t,i,r,s,o,a,l)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof qt))throw new v(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=i,[,s,o]=r.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:h})=>({type:"edit",from:a,to:l,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=this.fromPos.toTestString(),r=this.toPos.toTestString(),s=this.content;return`${t}.EDIT(${i},${r},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Xo extends Yt{constructor(t,i,r,s,o,a){super(t,a);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"attributes");this.fromPos=i,this.toPos=r,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(t,i,r,s,o,a){return new Xo(t,i,r,s,o,a)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof qt))throw new v(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=i,[,s,o]=r.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:h})=>({type:"style",from:a,to:l,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=this.fromPos.toTestString(),r=this.toPos.toTestString(),s=this.attributes;return`${t}.STYL(${i},${r},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const Y1=2,H1="root",Dn="text";function Es(n,e){let t=0;const i=n.children;for(let r=0;r0)throw new v(w.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const i=t.updateDescendantsSize();t.isRemoved||(e+=i)}return this.size+=e,this.paddedSize}get isText(){return this.type===Dn}get paddedSize(){return this.size+(this.isText?0:Y1)}isAncestorOf(e){return ew(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const i=this.value.slice(0,e),r=this.value.slice(e);if(!r.length)return;this.value=i;const s=this.cloneText(e+t);return s.value=r,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const i=this._children.indexOf(t);if(i===-1)throw new v(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,i),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const i=this._children.indexOf(t);if(i===-1)throw new v(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,i+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new v(w.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const i=this.cloneElement(t);this.parent.insertAfterInternal(i,this),i.updateAncestorsSize();const r=this.children.slice(0,e),s=this.children.slice(e);this._children=r,i._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),i.size=i._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of i._children)o.parent=i;return i}insertAfterInternal(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const i=this._children.indexOf(t);if(i===-1)throw new v(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,i+1)}insertAtInternal(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(r=>!r.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const i=this._children.indexOf(t);if(i!==-1)return i;t=t.parent}return-1}}function ew(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var xe=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(xe||{});function rO(n,e,t,i){if(e>t)throw new v(w.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new v(w.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new v(w.ErrInvalidArgument,`to is out of range: ${t} > ${n.size}`);if(e===t)return;let r=0;for(const s of n.children){if(e-s.paddedSizes.size;(s.isText||l)&&i([s,s.isText?"Text":"Start"],h),rO(s,Math.max(0,o),Math.min(a,s.size),i),h&&i([s,"End"],h)}r+=s.paddedSize}}function sO(n,e,t=0){for(const i of n.children)sO(i,e,t+1);e(n,t)}function th(n,e,t=0){for(const i of n._children)th(i,e,t+1);e(n,t)}function Vc(n,e,t=!0){if(e>n.size)throw new v(w.ErrInvalidArgument,`index is out of range: ${e} > ${n.size}`);if(n.isText)return{node:n,offset:e};let i=0,r=0;for(const s of n.children){if(t&&s.isText&&s.size>=e-r)return Vc(s,e-r,t);if(e===r)return{node:n,offset:i};if(!t&&s.paddedSize===e-r)return{node:n,offset:i+1};if(s.paddedSize>e-r)return Vc(s,e-r-1,t);r+=s.paddedSize,i+=1}return{node:n,offset:i}}function oO(n){return n.isText||n.children.length===0?n:oO(n.children[0])}function tw(n,e){if(n.sizen===e?0:n0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(i<0)if(t.left)t.left.parent=t,t=t.left;else{let r=t.parent,s=t;for(;r&&s===r.left;)s=r,r=r.parent;return r}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const i=this.comparator(e,t.key);if(i===0)return t;i<0?t=t.left:i>0&&(t=t.right)}}putInternal(e,t,i){if(!i)return this.counter+=1,new rw(e,t,!0);const r=this.comparator(e,i.key);return r<0?i.left=this.putInternal(e,t,i.left):r>0?i.right=this.putInternal(e,t,i.right):i.value=t,this.isRed(i.right)&&!this.isRed(i.left)&&(i=this.rotateLeft(i)),this.isRed(i.left)&&this.isRed(i.left.left)&&(i=this.rotateRight(i)),this.isRed(i.left)&&this.isRed(i.right)&&this.flipColors(i),i}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const i=this.min(e.right);e.value=i.value,e.key=i.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class _t{constructor(e,t){d(this,"parentID");d(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new _t(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:i}=e,r;return i.isText?(i.parent.children[0]===i&&t===0?r=i.parent:r=i,i=i.parent):t===0?r=i:r=i.children[t-1],_t.of(i.id,Me.of(r.getCreatedAt(),r.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return _t.of(Me.of(dt.fromStruct(e.parentID.createdAt),e.parentID.offset),Me.of(dt.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),i=this.getLeftSiblingID(),r=e.findFloorNode(t);let s=e.findFloorNode(i);if(!r||!s)throw new v(w.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${i.toTestString()})`);return!i.equals(t)&&i.getOffset()>0&&i.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[r,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Me{constructor(e,t){d(this,"createdAt");d(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Me(e,t)}static fromStruct(e){return Me.of(dt.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const i=e.getCreatedAt().compare(t.getCreatedAt());return i!==0?i:e.getOffset()>t.getOffset()?1:e.getOffset(){const s=r.deepcopy();return s.parent=t,s}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new v(w.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new v(w.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const i=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),i&&this.updateAncestorsSize()}cloneText(t){return new ut(Me.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new ut(Me.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,i,r){const s=this.isText?this.splitText(i,this.id.getOffset()):this.splitElement(i,r);if(s){if(s.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,t.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,i){return!this.getCreatedAt().after(i)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,i){return this.isText?!1:!this.getCreatedAt().after(i)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,i){this.attrs||(this.attrs=new Vn);const r=new Array;for(const[s,o]of Object.entries(t))r.push(this.attrs.set(s,o,i));return r}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const i of this.attrs)i.getRemovedAt()&&t.push({parent:this,child:i});return t}}function Xc(n){var t;if(n.isText){const i=n;return{type:i.type,value:i.value}}const e={type:n.type,children:n.children.map(Xc)};return n.attrs&&(e.attributes=es((t=n.attrs)==null?void 0:t.toObject())),e}function Ju(n){if(n.isText)return n.value;let e="";return n.attrs&&n.attrs.size()&&(e=" "+Array.from(n.attrs).filter(t=>!t.isRemoved()).sort((t,i)=>t.getKey().localeCompare(i.getKey())).map(t=>{const i=JSON.parse(t.getValue());return typeof i=="string"?`${t.getKey()}="${i}"`:`${t.getKey()}="${wi(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>Ju(t)).join("")}`}function lO(n){if(n.isText){const e=n;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:n.type,children:n.children.map(lO),size:n.size,isRemoved:n.isRemoved}}class Mt extends qo{constructor(t,i){super(i);d(this,"indexTree");d(this,"nodeMapByID");this.indexTree=new iw(t),this.nodeMapByID=new aO(Me.createComparator()),this.indexTree.traverseAll(r=>{this.nodeMapByID.put(r.id,r)})}static create(t,i){return new Mt(t,i)}findFloorNode(t){const i=this.nodeMapByID.floorEntry(t);if(!(!i||!i.key.getCreatedAt().equals(t.getCreatedAt())))return i.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,i){const[r,s]=t.toTreeNodePair(this);let o=s;const a=r===o,l=o.parent&&!a?o.parent:r;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),i){const h=l.allChildren,c=a?0:h.indexOf(o)+1;for(let u=c;u{const y=g.getCreatedAt().getActorID(),O=s?s.has(y)?s.get(y):Gt:Ys;if(g.canStyle(r,O)&&i){const S=f.get(y),k=g.getCreatedAt();(!S||k.after(S))&&f.set(y,k);const $=g.setAttrs(i,r),x=$.reduce((R,[,j])=>(j&&(R[j.getKey()]=u[j.getKey()]),R),{}),Q=g.parent,A=g.prevSibling||g.parent;Object.keys(x).length>0&&c.push({type:"style",from:this.toIndex(Q,A),to:this.toIndex(g,g),fromPath:this.toPath(Q,A),toPath:this.toPath(g,g),actor:r.getActorID(),value:x});for(const[R]of $)R&&p.push({parent:g,child:R})}}),[f,p,c]}removeStyle(t,i,r,s){const[o,a]=this.findNodesAndSplitText(t[0],r),[l,h]=this.findNodesAndSplitText(t[1],r),c=[],u=new Map,f=[];return this.traverseInPosRange(o,a,l,h,([p])=>{const g=p.getCreatedAt().getActorID(),y=s?s.has(g)?s.get(g):Gt:Ys;if(p.canStyle(r,y)&&i){const O=u.get(g),S=p.getCreatedAt();(!O||S.after(O))&&u.set(g,S),p.attrs||(p.attrs=new Vn);for(const x of i){const Q=p.attrs.remove(x,r);for(const A of Q)f.push({parent:p,child:A})}const k=p.parent,$=p.prevSibling||p.parent;c.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(k,$),to:this.toIndex(p,p),fromPath:this.toPath(k,$),toPath:this.toPath(p,p),value:i})}}),[u,f,c]}edit(t,i,r,s,o,a){const[l,h]=this.findNodesAndSplitText(t[0],s),[c,u]=this.findNodesAndSplitText(t[1],s),f=this.toIndex(l,h),p=this.toPath(l,h),g=[],y=[],O=[],S=new Map;this.traverseInPosRange(l,h,c,u,([x,Q],A)=>{if(Q===xe.Start&&!A)for(const W of x.children)O.push(W);const R=x.getCreatedAt().getActorID(),j=a?a.has(R)?a.get(R):Gt:Ys;if(x.canDelete(s,j)||g.includes(x.parent)){const W=S.get(R),G=x.getCreatedAt();(!W||G.after(W))&&S.set(R,G),(Q===xe.Text||Q===xe.Start)&&g.push(x),y.push([x,Q])}});const k=this.makeDeletionChanges(y,s),$=[];for(const x of g)x.remove(s),x.isRemoved&&$.push({parent:this,child:x});for(const x of O)x.removedAt||l.append(x);if(r>0){let x=0,Q=l,A=h;for(;x{l.isRemoved&&(R.remove(s),$.push({parent:this,child:R})),this.nodeMapByID.put(R.id,R)}),A.isRemoved||x.push(A);if(x.length){const A=x.map(R=>Xc(R));k.length&&k[k.length-1].from===f?k[k.length-1].value=A:k.push({type:"content",from:f,to:f,fromPath:p,toPath:p,actor:s.getActorID(),value:A})}}return[k,$,S]}editT(t,i,r,s,o){const a=this.findPos(t[0]),l=this.findPos(t[1]);this.edit([a,l],i,r,s,o)}move(t,i,r){throw new v(w.ErrUnimplemented,`not implemented: ${t}, ${i}, ${r}`)}purge(t){var s;(s=t.parent)==null||s.removeChild(t),this.nodeMapByID.remove(t.id);const i=t.insPrevID,r=t.insNextID;if(i){const o=this.findFloorNode(i);o.insNextID=r}if(r){const o=this.findFloorNode(r);o.insPrevID=i}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(i=>{i.getRemovedAt()&&t.push({parent:this,child:i});for(const r of i.getGCPairs())t.push(r)}),t}findPos(t,i=!0){const r=this.indexTree.findTreePos(t,i);return _t.fromTreePos(r)}pathToPosRange(t){const i=this.pathToIndex(t);return[this.findPos(i),this.findPos(i+1)]}pathToPos(t){const i=this.indexTree.pathToIndex(t);return this.findPos(i)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Ju(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),i=(r,s=void 0,o=void 0,a=0)=>{var p,g,y,O;let l,h,c;const u=r.isText?{node:r,offset:0}:s&&o?this.toTreePos(s,o):null;u&&(l=this.indexTree.indexOf(u),h=this.indexTree.treePosToPath(u),c=_t.fromTreePos(u).toStruct());const f={type:r.type,parent:s==null?void 0:s.id.toTestString(),size:r.size,id:r.id.toTestString(),removedAt:(p=r.removedAt)==null?void 0:p.toTestString(),insPrev:(g=r.insPrevID)==null?void 0:g.toTestString(),insNext:(y=r.insNextID)==null?void 0:y.toTestString(),value:r.isText?r.value:void 0,isRemoved:r.isRemoved,children:[],depth:a,attributes:r.attrs?es((O=r.attrs)==null?void 0:O.toObject()):void 0,index:l,path:h,pos:c};for(let S=0;S0&&S===r[r.length-1].to?(r[r.length-1].to=k,r[r.length-1].toPath=this.toPath(O,p)):r.push({type:"content",from:S,to:k,fromPath:this.toPath(y,u),toPath:this.toPath(O,p),actor:i.getActorID()}))}return r.reverse()}findRightToken([t,i]){if(i===xe.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?xe.Text:xe.Start]:[t,xe.End]}const r=t.parent,s=r.allChildren,o=s.indexOf(t);if(r&&o===s.length-1)return[r,xe.End];const a=s[o+1];return[a,a.isText?xe.Text:xe.Start]}findLeftToken([t,i]){if(i===xe.End){const l=t.allChildren;if(l.length>0){const h=l[l.length-1];return[h,h.isText?xe.Text:xe.End]}return[t,xe.Start]}const r=t.parent,s=r.allChildren,o=s.indexOf(t);if(r&&o===0)return[r,xe.Start];const a=s[o-1];return[a,a.isText?xe.Text:xe.End]}}class Lo extends Yt{constructor(t,i,r,s,o,a,l){super(t,l);d(this,"fromPos");d(this,"toPos");d(this,"contents");d(this,"splitLevel");d(this,"maxCreatedAtMapByActor");this.fromPos=i,this.toPos=r,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,i,r,s,o,a,l){return new Lo(t,i,r,s,o,a,l)}execute(t){var l;const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof Mt))throw new v(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=this.getExecutedAt(),s=i,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(h=>h.deepcopy()),this.splitLevel,r,(()=>{let h=r.getDelimiter();return this.contents!==void 0&&(h+=this.contents.length),()=>dt.of(r.getLamport(),++h,r.getActorID())})(),this.maxCreatedAtMapByActor);for(const h of a)t.registerGCPair(h);return{opInfos:o.map(({from:h,to:c,value:u,splitLevel:f,fromPath:p,toPath:g})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:h,to:c,value:u,splitLevel:f,fromPath:p,toPath:g}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${t}.EDIT(${i},${r},${s.map(o=>Ju(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class ts{constructor(e){d(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[i,r]of e){const s=this.vector.get(i),o=s&&s>r?s:r;t.set(i,o)}for(const[i,r]of this){const s=e.get(i),o=s&&s>r?s:r;t.set(i,o)}return new ts(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,i]of this.vector)e.set(t,i);return new ts(e)}filter(e){const t=new Map;for(const[i]of e){const r=this.vector.get(i);r!==void 0&&t.set(i,r)}return new ts(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const ow=new ts(new Map);class An{constructor(e,t,i,r,s){d(this,"clientSeq");d(this,"serverSeq");d(this,"lamport");d(this,"actor");d(this,"versionVector");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.versionVector=r,this.actor=i}static of(e,t,i,r,s){return new An(e,t,i,r,s)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new An(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,i=this.versionVector.max(e.versionVector),r=new An(this.clientSeq,t,this.actor,i);return r.versionVector.set(this.actor,t),r}setClocks(e,t){const i=e>this.lamport?e:this.lamport+1n,r=this.versionVector.max(t);return r.set(this.actor,i),An.of(this.clientSeq,i,this.actor,r)}createTimeTicket(e){return dt.of(this.lamport,e,this.actor)}setActor(e){return new An(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new An(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const aw=new An(0,0n,zu,ow);class ds{constructor({id:e,operations:t,presenceChange:i,message:r}){d(this,"id");d(this,"operations");d(this,"presenceChange");d(this,"message");this.id=e,this.operations=t||[],this.presenceChange=i,this.message=r}static create({id:e,operations:t,presenceChange:i,message:r}){return new ds({id:e,operations:t,presenceChange:i,message:r})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,i){const r=[],s=[];for(const o of this.operations){const a=o.execute(e,i);if(!a)continue;const{opInfos:l,reverseOp:h}=a;r.push(...l),h&&s.unshift(h)}return this.presenceChange&&(this.presenceChange.type===cr.Put?t.set(this.id.getActorID(),Wt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:r,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:we.bytesToHex(we.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>we.bytesToHex(we.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:i,presenceChange:r,message:s}=e;return ds.create({id:we.bytesToChangeID(we.hexToBytes(t)),operations:i==null?void 0:i.map(o=>we.bytesToOperation(we.hexToBytes(o))),presenceChange:r,message:s})}}class ih{constructor(e,t,i,r,s,o,a){d(this,"documentKey");d(this,"checkpoint");d(this,"isRemoved");d(this,"changes");d(this,"snapshot");d(this,"minSyncedTicket");d(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=i,this.changes=r,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=s}static create(e,t,i,r,s,o,a){return new ih(e,t,i,r,s,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class is{constructor(e,t){d(this,"serverSeq");d(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new is(e,t)}increaseClientSeq(e){return e===0?this:new is(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,i=Math.max(this.clientSeq,e.clientSeq);return is.of(t,i)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const lw=new is(0n,0);class Ti{constructor(e,t){d(this,"createdAt");d(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ti(e,t)}static fromStruct(e){return Ti.of(dt.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new Ti(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const hw=Ti.of(Gt,0);class Jt{constructor(e,t){d(this,"id");d(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Jt(e,t)}static fromStruct(e){const t=Ti.fromStruct(e.id);return Jt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Ti.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class sr extends Km{constructor(t,i,r){super(i);d(this,"id");d(this,"removedAt");d(this,"prev");d(this,"next");d(this,"insPrev");d(this,"insNext");this.id=t,this.removedAt=r}static create(t,i){return new sr(t,i)}static createComparator(){return(t,i)=>{const r=t.getCreatedAt().compare(i.getCreatedAt());return r!==0?r:t.getOffset()>i.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const i=[];let r=e;for(;r&&r!==t;)i.push(r),r=r.getNext();return i}splitNode(e,t){if(t>e.getContentLength())throw new v(w.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const i=e.split(t);this.treeByIndex.updateWeight(i),this.insertAfter(e,i);const r=e.getInsNext();return r&&r.setInsPrev(i),i.setInsPrev(e),i}deleteNodes(e,t,i){if(!e.length)return[[],new Map,new Map];const[r,s]=this.filterNodes(e,t,i),o=new Map,a=new Map,l=this.makeChanges(s,t);for(const h of r){const c=h.getCreatedAt().getActorID();(!o.has(c)||h.getID().getCreatedAt().after(o.get(c)))&&o.set(c,h.getID().getCreatedAt()),a.set(h.getID().toIDString(),h),h.remove(t)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,t,i){const r=!!i,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const h of e){const c=h.getCreatedAt().getActorID(),u=r?i.has(c)?i.get(c):Gt:Ys;h.canDelete(t,u)?s.push(h):o.push(h)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const i=[];let r,s;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var Pi=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(Pi||{});class gt extends qo{constructor(t,i,r){super(r);d(this,"valueType");d(this,"value");switch(this.valueType=t,t){case 0:typeof i=="number"?i>Math.pow(2,31)-1||i<-Math.pow(2,31)?this.value=Y.fromNumber(i).toInt():this.value=Bd(i):this.value=i.toInt();break;case 1:typeof i=="number"?this.value=Y.fromNumber(i):this.value=i;break;default:throw new v(w.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,i,r){return new gt(t,i,r)}static valueFromBytes(t,i){switch(t){case 0:return i[0]|i[1]<<8|i[2]<<16|i[3]<<24;case 1:return Y.fromBytesLE(Array.from(i));default:throw new v(w.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=gt.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof Y?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!gt.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const i=this.value.toBytesLE();return Uint8Array.from(i)}default:throw new v(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function i(r){if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`)}return i(this),i(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===$e.Long?this.value=this.value+t.getValue().toInt():this.value=Y.fromNumber(this.value+Bd(t.getValue())).toInt(),this}}class gs extends Yt{constructor(t,i,r){super(t,r);d(this,"value");this.value=i}static create(t,i,r){return new gs(t,i,r)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof gt))throw new v(w.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const r=i,s=this.value.deepcopy();return r.increase(s),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),r=t.getType()===$e.Long?t.getValue().multiply(-1):t.getValue()*-1;return gs.create(this.getParentCreatedAt(),pe.of(r,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Nn extends Yt{constructor(t,i,r,s,o,a,l){super(t,l);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"attributes");d(this,"attributesToRemove");this.fromPos=i,this.toPos=r,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(t,i,r,s,o,a){return new Nn(t,i,r,s,o,new Array,a)}static createTreeRemoveStyleOperation(t,i,r,s,o,a){return new Nn(t,i,r,s,new Map,o,a)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof Mt))throw new v(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=i;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,h])=>a[l]=h),[,o,s]=r.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=r.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:h,fromPath:c,toPath:u})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:h}:{attributesToRemove:h},fromPath:c,toPath:u,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${i},${r},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function cw(n){const e=new Fu,t=e.data;for(const[i,r]of Object.entries(n))t[i]=JSON.stringify(r);return e}function uw(n){if(n.type===cr.Put)return new co({type:Dr.PUT,presence:cw(n.presence)});if(n.type===cr.Clear)return new co({type:Dr.CLEAR});throw new v(w.ErrUnimplemented,"unimplemented type")}function fw(n){return new Jm({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function hO(n){return new Kl({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:lf(n.getActorID()),versionVector:Yu(n.getVersionVector())})}function X(n){if(n)return new M({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:lf(n.getActorID())})}function Yu(n){if(!n)return;const e=new eh;for(const[t,i]of n)e.vector[t]=BigInt(i.toString());return e}function cO(n){switch(n){case $e.Null:return F.NULL;case $e.Boolean:return F.BOOLEAN;case $e.Integer:return F.INTEGER;case $e.Long:return F.LONG;case $e.Double:return F.DOUBLE;case $e.String:return F.STRING;case $e.Bytes:return F.BYTES;case $e.Date:return F.DATE;default:throw new v(w.ErrInvalidType,`unsupported type: ${n}`)}}function uO(n){switch(n){case Pi.IntegerCnt:return F.INTEGER_CNT;case Pi.LongCnt:return F.LONG_CNT;default:throw new v(w.ErrInvalidType,`unsupported type: ${n}`)}}function Ah(n){if(n instanceof nt)return new Ot({type:F.JSON_OBJECT,createdAt:X(n.getCreatedAt()),value:xO(n)});if(n instanceof pt)return new Ot({type:F.JSON_ARRAY,createdAt:X(n.getCreatedAt()),value:Zw(n)});if(n instanceof qt)return new Ot({type:F.TEXT,createdAt:X(n.getCreatedAt())});if(n instanceof pe)return new Ot({type:cO(n.getType()),createdAt:X(n.getCreatedAt()),value:n.toBytes()});if(n instanceof gt)return new Ot({type:uO(n.getType()),createdAt:X(n.getCreatedAt()),value:n.toBytes()});if(n instanceof Mt)return new Ot({type:F.TREE,createdAt:X(n.getCreatedAt()),value:jw(n)});throw new v(w.ErrUnimplemented,"unimplemented element")}function dw(n){return new ho({createdAt:X(n.getCreatedAt()),offset:n.getOffset()})}function ea(n){return new Mn({createdAt:X(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function ta(n){return new Er({parentId:Hs(n.getParentID()),leftSiblingId:Hs(n.getLeftSiblingID())})}function Hs(n){return new nr({createdAt:X(n.getCreatedAt()),offset:n.getOffset()})}function fO(n){const e=new Wu;if(n instanceof Nr){const t=n,i=new tl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.key=t.getKey(),i.value=Ah(t.getValue()),i.executedAt=X(t.getExecutedAt()),e.body.case="set",e.body.value=i}else if(n instanceof Mo){const t=n,i=new il;i.parentCreatedAt=X(t.getParentCreatedAt()),i.prevCreatedAt=X(t.getPrevCreatedAt()),i.value=Ah(t.getValue()),i.executedAt=X(t.getExecutedAt()),e.body.case="add",e.body.value=i}else if(n instanceof Kn){const t=n,i=new nl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.prevCreatedAt=X(t.getPrevCreatedAt()),i.createdAt=X(t.getCreatedAt()),i.executedAt=X(t.getExecutedAt()),e.body.case="move",e.body.value=i}else if(n instanceof ur){const t=n,i=new rl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.createdAt=X(t.getCreatedAt()),i.executedAt=X(t.getExecutedAt()),e.body.case="remove",e.body.value=i}else if(n instanceof Vo){const t=n,i=new sl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.from=ea(t.getFromPos()),i.to=ea(t.getToPos());const r=i.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=X(a);i.content=t.getContent();const s=i.attributes;for(const[o,a]of t.getAttributes())s[o]=a;i.executedAt=X(t.getExecutedAt()),e.body.case="edit",e.body.value=i}else if(n instanceof Xo){const t=n,i=new ol;i.parentCreatedAt=X(t.getParentCreatedAt()),i.from=ea(t.getFromPos()),i.to=ea(t.getToPos());const r=i.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=X(a);const s=i.attributes;for(const[o,a]of t.getAttributes())s[o]=a;i.executedAt=X(t.getExecutedAt()),e.body.case="style",e.body.value=i}else if(n instanceof gs){const t=n,i=new al;i.parentCreatedAt=X(t.getParentCreatedAt()),i.value=Ah(t.getValue()),i.executedAt=X(t.getExecutedAt()),e.body.case="increase",e.body.value=i}else if(n instanceof Lo){const t=n,i=new ll,r=i.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())r[s]=X(o);i.parentCreatedAt=X(t.getParentCreatedAt()),i.from=ta(t.getFromPos()),i.to=ta(t.getToPos()),i.contents=Sw(t.getContents()),i.splitLevel=t.getSplitLevel(),i.executedAt=X(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=i}else if(n instanceof Nn){const t=n,i=new hl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.from=ta(t.getFromPos()),i.to=ta(t.getToPos());const r=i.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=X(a);const s=t.getAttributesToRemove();if(s.length>0)i.attributesToRemove=s;else{const o=i.attributes;for(const[a,l]of t.getAttributes())o[a]=l}i.executedAt=X(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=i}else throw new v(w.ErrUnimplemented,"unimplemented operation");return e}function pw(n){const e=[];for(const t of n)e.push(fO(t));return e}function gw(n){const e=new zm({id:hO(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=pw(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=uw(n.getPresenceChange())),e}function mw(n){const e=[];for(const t of n)e.push(gw(t));return e}function Ow(n){const e=[];for(const t of n)e.push(new _m({key:t.getStrKey(),element:Ku(t.getValue())}));return e}function yw(n){const e=[];for(const t of n)e.push(new ml({element:Ku(t.getValue())}));return e}function bw(n){const e=[];for(const t of n){const i=new Gm;i.id=dw(t.getID()),i.value=t.getValue().getContent(),i.removedAt=X(t.getRemovedAt());const r=i.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new cs;a.value=o.getValue(),a.updatedAt=X(o.getUpdatedAt()),r[o.getKey()]=a}e.push(i)}return e}function Sw(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new Ol({content:Hu(t)}));return e}function ww(n){const e={};for(const t of n)e[t.getKey()]=new cs({value:t.getValue(),updatedAt:X(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function Hu(n){if(!n)return[];const e=[];return th(n,(t,i)=>{const r=new ju({id:Hs(t.id),type:t.type,removedAt:X(t.removedAt),depth:i});t.isText&&(r.value=t.value),t.insPrevID&&(r.insPrevId=Hs(t.insPrevID)),t.insNextID&&(r.insNextId=Hs(t.insNextID)),t.attrs&&(r.attributes=ww(t.attrs)),e.push(r)}),e}function vw(n){const e=new rt;return e.body.case="jsonObject",e.body.value=new cl({nodes:Ow(n.getRHT()),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function dO(n){const e=new rt;return e.body.case="jsonArray",e.body.value=new ul({nodes:yw(n.getElements()),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function kw(n){const e=new rt;return e.body.case="primitive",e.body.value=new fl({type:cO(n.getType()),value:n.toBytes(),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function xw(n){const e=new rt;return e.body.case="text",e.body.value=new dl({nodes:bw(n.getRGATreeSplit()),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function Tw(n){const e=new rt;return e.body.case="counter",e.body.value=new pl({type:uO(n.getType()),value:n.toBytes(),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function pO(n){const e=new rt;return e.body.case="tree",e.body.value=new gl({nodes:Hu(n.getRoot()),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function Ku(n){if(n instanceof nt)return vw(n);if(n instanceof pt)return dO(n);if(n instanceof pe)return kw(n);if(n instanceof qt)return xw(n);if(n instanceof gt)return Tw(n);if(n instanceof Mt)return pO(n);throw new v(w.ErrUnimplemented,"unimplemented element")}function Qw(n){return new Wn({documentKey:n.getDocumentKey(),checkpoint:fw(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:mw(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Yu(n.getVersionVector()),minSyncedTicket:X(n.getMinSyncedTicket())})}function qd(n){const e=n.findDetails(U1);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function gO(n){return An.of(n.clientSeq,BigInt(n.lamport),of(n.actorId),ef(n.versionVector),BigInt(n.serverSeq))}function ef(n){if(!n)return;const e=new ts;return Object.entries(n.vector).forEach(([t,i])=>{e.set(t,BigInt(i.toString()))}),e}function L(n){if(n)return dt.of(BigInt(n.lamport),n.delimiter,of(n.actorId))}function tf(n){const e={};return Object.entries(n.data).forEach(([t,i])=>{e[t]=JSON.parse(i)}),e}function Pw(n){const e=n.type;if(e===Dr.PUT){const t=tf(n.presence);return{type:cr.Put,presence:t}}if(e===Dr.CLEAR)return{type:cr.Clear};throw new v(w.ErrInvalidType,`unsupported type: ${e}`)}function Aw(n){const e=new Map;return Object.entries(n).forEach(([t,i])=>{e.set(t,tf(i))}),e}function mO(n){switch(n){case F.NULL:return $e.Null;case F.BOOLEAN:return $e.Boolean;case F.INTEGER:return $e.Integer;case F.LONG:return $e.Long;case F.DOUBLE:return $e.Double;case F.STRING:return $e.String;case F.BYTES:return $e.Bytes;case F.DATE:return $e.Date}throw new v(w.ErrUnimplemented,`unimplemented value type: ${n}`)}function Sl(n){switch(n){case F.INTEGER_CNT:return Pi.IntegerCnt;case F.LONG_CNT:return Pi.LongCnt}throw new v(w.ErrUnimplemented,`unimplemented value type: ${n}`)}function $h(n){switch(n.type){case F.JSON_OBJECT:return n.value?kO(n.value):nt.create(L(n.createdAt));case F.JSON_ARRAY:return n.value?Uw(n.value):pt.create(L(n.createdAt));case F.TEXT:return qt.create(ps.create(),L(n.createdAt));case F.TREE:return Ww(n.value);case F.NULL:case F.BOOLEAN:case F.INTEGER:case F.LONG:case F.DOUBLE:case F.STRING:case F.BYTES:case F.DATE:return pe.of(pe.valueFromBytes(mO(n.type),n.value),L(n.createdAt));case F.INTEGER_CNT:case F.LONG_CNT:return gt.create(Sl(n.type),gt.valueFromBytes(Sl(n.type),n.value),L(n.createdAt))}}function ia(n){return Jt.of(Ti.of(L(n.createdAt),n.offset),n.relativeOffset)}function OO(n){return Ti.of(L(n.createdAt),n.offset)}function $w(n){const e=go.create(n.value);Object.entries(n.attributes).forEach(([i,r])=>{e.setAttr(i,r.value,L(r.updatedAt))});const t=sr.create(OO(n.id),e);return t.remove(L(n.removedAt)),t}function Wr(n){return _t.of(Ks(n.parentId),Ks(n.leftSiblingId))}function Ks(n){return Me.of(L(n.createdAt),n.offset)}function Cw(n){if(!n.length)return;const e=[];return n.forEach(t=>{const i=nf(t.content);e.push(i)}),e}function nf(n){if(n.length===0)return;const e=[];for(const r of n)e.push(Rw(r));const t=e[e.length-1],i=new Map;i.set(n[e.length-1].depth,e[e.length-1]);for(let r=e.length-2;r>=0;r--)i.get(n[r].depth-1).prepend(e[r]),i.set(n[r].depth,e[r]);return t.updateDescendantsSize(),Mt.create(t,Gt).getRoot()}function Iw(n){const e=Vn.create();for(const[t,i]of Object.entries(n))e.setInternal(t,i.value,L(i.updatedAt),i.isRemoved);return e}function Rw(n){const e=Ks(n.id),t=ut.create(e,n.type),i=Object.entries(n.attributes);return t.isText?t.value=n.value:i.length&&(t.attrs=Iw(n.attributes)),n.insPrevId&&(t.insPrevID=Ks(n.insPrevId)),n.insNextId&&(t.insNextID=Ks(n.insNextId)),t.removedAt=L(n.removedAt),t}function yO(n){if(n.body.case==="set"){const e=n.body.value;return Nr.create(e.key,$h(e.value),L(e.parentCreatedAt),L(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Mo.create(L(e.parentCreatedAt),L(e.prevCreatedAt),$h(e.value),L(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return Kn.create(L(e.parentCreatedAt),L(e.prevCreatedAt),L(e.createdAt),L(e.executedAt))}else if(n.body.case==="remove"){const e=n.body.value;return ur.create(L(e.parentCreatedAt),L(e.createdAt),L(e.executedAt))}else if(n.body.case==="edit"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,s])=>{t.set(r,L(s))});const i=new Map;return Object.entries(e.attributes).forEach(([r,s])=>{i.set(r,s)}),Vo.create(L(e.parentCreatedAt),ia(e.from),ia(e.to),t,e.content,i,L(e.executedAt))}else if(n.body.case==="style"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,s])=>{t.set(r,L(s))});const i=new Map;return Object.entries(e.attributes).forEach(([r,s])=>{i.set(r,s)}),Xo.create(L(e.parentCreatedAt),ia(e.from),ia(e.to),t,i,L(e.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const e=n.body.value;return gs.create(L(e.parentCreatedAt),$h(e.value),L(e.executedAt))}else if(n.body.case==="treeEdit"){const e=n.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([i,r])=>{t.set(i,L(r))}),Lo.create(L(e.parentCreatedAt),Wr(e.from),Wr(e.to),Cw(e.contents),e.splitLevel,t,L(e.executedAt))}else if(n.body.case==="treeStyle"){const e=n.body.value,t=new Map,i=e.attributesToRemove,r=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{r.set(s,L(o))}),(i==null?void 0:i.length)>0?Nn.createTreeRemoveStyleOperation(L(e.parentCreatedAt),Wr(e.from),Wr(e.to),r,i,L(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),Nn.create(L(e.parentCreatedAt),Wr(e.from),Wr(e.to),r,t,L(e.executedAt)))}else throw new v(w.ErrUnimplemented,"unimplemented operation")}}function Ew(n){const e=[];for(const t of n){const i=yO(t);i&&e.push(i)}return e}function bO(n){const e=[];for(const t of n)e.push(ds.create({id:gO(t.id),operations:Ew(t.operations),presenceChange:t.presenceChange?Pw(t.presenceChange):void 0,message:t.message}));return e}function Dw(n){return is.of(BigInt(n.serverSeq),n.clientSeq)}function Nw(n){return ih.create(n.documentKey,Dw(n.checkpoint),n.isRemoved,bO(n.changes),ef(n.versionVector),n.snapshot,L(n.minSyncedTicket))}function SO(n){const e=new uo;for(const i of n.nodes){const r=rf(i.element);e.set(i.key,r,r.getPositionedAt())}const t=new nt(L(n.createdAt),e);return t.setMovedAt(L(n.movedAt)),t.setRemovedAt(L(n.removedAt)),t}function wO(n){const e=new po;for(const i of n.nodes)e.insert(rf(i.element));const t=new pt(L(n.createdAt),e);return t.setMovedAt(L(n.movedAt)),t.setRemovedAt(L(n.removedAt)),t}function Bw(n){const e=pe.of(pe.valueFromBytes(mO(n.type),n.value),L(n.createdAt));return e.setMovedAt(L(n.movedAt)),e.setRemovedAt(L(n.removedAt)),e}function qw(n){const e=new ps;let t=e.getHead();for(const r of n.nodes){const s=e.insertAfter(t,$w(r));r.insPrevId&&s.setInsPrev(e.findNode(OO(r.insPrevId))),t=s}const i=new qt(e,L(n.createdAt));return i.setMovedAt(L(n.movedAt)),i.setRemovedAt(L(n.removedAt)),i}function Mw(n){const e=gt.create(Sl(n.type),gt.valueFromBytes(Sl(n.type),n.value),L(n.createdAt));return e.setMovedAt(L(n.movedAt)),e.setRemovedAt(L(n.removedAt)),e}function vO(n){const e=nf(n.nodes);return Mt.create(e,L(n.createdAt))}function rf(n){if(n.body.case==="jsonObject")return SO(n.body.value);if(n.body.case==="jsonArray")return wO(n.body.value);if(n.body.case==="primitive")return Bw(n.body.value);if(n.body.case==="text")return qw(n.body.value);if(n.body.case==="counter")return Mw(n.body.value);if(n.body.case==="tree")return vO(n.body.value);throw new v(w.ErrUnimplemented,"unimplemented element")}function Vw(n){if(!n)return{root:nt.create(Gt),presences:new Map};const e=gc.fromBinary(n);return{root:rf(e.root),presences:Aw(e.presences)}}function Xw(n){const e=Yu(n);return sf(e.toBinary())}function Lw(n){const e=af(n),t=eh.fromBinary(e);return ef(t)}function kO(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return SO(e.body.value)}function xO(n){return Ku(n).toBinary()}function Uw(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return wO(e.body.value)}function Zw(n){return dO(n).toBinary()}function Ww(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return vO(e.body.value)}function jw(n){return pO(n).toBinary()}function sf(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function of(n){return sf(n)}function af(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function lf(n){return af(n)}function Fw(n){const e=Kl.fromBinary(n);return gO(e)}function zw(n){const e=Wu.fromBinary(n);return yO(e)}const we={fromPresence:tf,toChangePack:Qw,fromChangePack:Nw,fromChanges:bO,toTreeNodes:Hu,fromTreeNodes:nf,objectToBytes:xO,bytesToObject:kO,bytesToSnapshot:Vw,bytesToHex:sf,hexToBytes:af,toHexString:of,toUint8Array:lf,toOperation:fO,toChangeID:hO,PbChangeID:Kl,bytesToChangeID:Fw,bytesToOperation:zw,versionVectorToHex:Xw,hexToVersionVector:Lw};var Ge=(n=>(n[n.Trivial=0]="Trivial",n[n.Debug=1]="Debug",n[n.Info=2]="Info",n[n.Warn=3]="Warn",n[n.Error=4]="Error",n[n.Fatal=5]="Fatal",n))(Ge||{});let vr=3;function TO(n){vr=n}const U={trivial:(...n)=>{vr>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{vr>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{vr>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{vr>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{vr>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...n):console.log("YORKIE E:",...n))},fatal:(...n)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...n):console.log("YORKIE F:",...n))},isEnabled:n=>vr<=n};function QO(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}class _w{constructor(e,t,i,r,s){d(this,"reconnectStreamDelay");d(this,"doc");d(this,"docID");d(this,"syncMode");d(this,"remoteChangeEventReceived");d(this,"watchStream");d(this,"watchLoopTimerID");d(this,"watchAbortController");d(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=i,this.syncMode=r,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Ma.RealtimeSyncOff?!1:this.syncMode===Ma.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Ma.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Ch=()=>{};class Gw{constructor(e){d(this,"finalized",!1);d(this,"observers",[]);d(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,i){let r;if(!e)throw new v(w.ErrInvalidArgument,"missing observer");if(this.finalized)throw new v(w.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?r=e:r={next:e,error:t,complete:i},r.next===void 0&&(r.next=Ch),r.error===void 0&&(r.error=Ch),r.complete===void 0&&(r.complete=Ch);const s=QO(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:r}),this.finalized)try{this.finalError?r.error(this.finalError):r.complete()}catch(a){U.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(i=>i.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Jr{constructor(e,t,i,r){d(this,"id");d(this,"delimiter");d(this,"message");d(this,"root");d(this,"operations");d(this,"presenceChange");d(this,"previousPresence");d(this,"reversePresenceKeys");this.id=e,this.delimiter=Hm,this.root=t,this.operations=[],this.previousPresence=Wt(i),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=r}static create(e,t,i,r){return new Jr(e,t,i,r)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return ds.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const i of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(i):this.reversePresenceKeys.delete(i)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class mo{constructor(e){d(this,"rootObject");d(this,"elementPairMapByCreatedAt");d(this,"gcElementSetByCreatedAt");d(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof qt||t instanceof Mt)for(const i of t.getGCPairs())this.registerGCPair(i);return!1})}static create(){return new mo(nt.create(Gt))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const i=[];for(;t.parent;){const r=t.element.getCreatedAt(),s=t.parent.subPathOf(r);if(s===void 0)throw new v(w.ErrInvalidArgument,`cant find the given element: ${r.toIDString()}`);i.unshift(s),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return i.unshift("$"),i}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof rr&&e.getDescendants((i,r)=>(this.registerElement(i,r),!1))}deregisterElement(e){let t=0;const i=r=>{const s=r.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),t++};return i(e),e instanceof rr&&e.getDescendants(r=>(i(r),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const i=this.elementPairMapByCreatedAt.get(t);i.element instanceof rr&&i.element.getDescendants(r=>(e.add(r.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new mo(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const i of this.gcElementSetByCreatedAt){const r=this.elementPairMapByCreatedAt.get(i),s=r.element.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(r.parent.purge(r.element),t+=this.deregisterElement(r.element))}for(const[,i]of this.gcPairMap){const r=i.child.getRemovedAt();r&&(e!=null&&e.afterOrEqual(r))&&(i.parent.purge(i.child),this.gcPairMap.delete(i.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function PO(n,e){const t=new Oo(n);return new Proxy(e,t.getHandlers())}class Oo{constructor(e){d(this,"context");d(this,"handlers");this.context=e,this.handlers={set:(t,i,r)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`obj[${i}]=${JSON.stringify(r)}`),Oo.setInternal(e,t,i,r),!0),get:(t,i)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`obj[${i}]`),i==="getID"?()=>t.getCreatedAt():i==="toJSON"||i==="toString"?()=>t.toJSON():i==="toJS"?()=>t.toJS():i==="toJSForTest"?()=>t.toJSForTest():kr(e,t.get(i))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,i)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`obj[${i}]`),Oo.deleteInternal(e,t,i),!0)}}static setInternal(e,t,i,r){if(i.includes("."))throw new v(w.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=wl(e,r,s),a=t.set(i,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Nr.create(i,o.deepcopy(),t.getCreatedAt(),s))}static buildObjectMembers(e,t){const i={};for(const[r,s]of Object.entries(t)){if(r.includes("."))throw new v(w.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=wl(e,s,o);i[r]=a}return i}static deleteInternal(e,t,i){const r=e.issueTimeTicket(),s=t.deleteByKey(i,r);s&&(e.push(ur.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function Yw(n,e){const t=new me(n,e);return new Proxy(e,t.getHandlers())}function Hw(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function Kw(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class me{constructor(e,t){d(this,"context");d(this,"handlers");d(this,"array");this.context=e,this.array=t,this.handlers={get:(i,r,s)=>r==="getID"?()=>i.getCreatedAt():r==="getElementByID"?o=>{const a=i.getByID(o);if(!(!a||a.isRemoved()))return _n(e,a)}:r==="getElementByIndex"?o=>{const a=i.get(o);return _n(e,a)}:r==="getLast"?()=>_n(e,i.getLast()):r==="deleteByID"?o=>{const a=me.deleteInternalByID(e,i,o);return _n(e,a)}:r==="insertAfter"?(o,a)=>{const l=me.insertAfterInternal(e,i,o,a);return _n(e,l)}:r==="insertBefore"?(o,a)=>{const l=me.insertBeforeInternal(e,i,o,a);return _n(e,l)}:r==="moveBefore"?(o,a)=>{me.moveBeforeInternal(e,i,o,a)}:r==="moveAfter"?(o,a)=>{me.moveAfterInternal(e,i,o,a)}:r==="moveFront"?o=>{me.moveFrontInternal(e,i,o)}:r==="moveLast"?o=>{me.moveLastInternal(e,i,o)}:Hw(r)?kr(e,i.get(Number(r))):r==="push"?o=>me.pushInternal(e,i,o):r==="splice"?(o,a,...l)=>me.splice(e,i,o,a,...l):r==="length"?i.length:typeof r=="symbol"&&r===Symbol.iterator?me.iteratorInternal.bind(this,e,i):r==="includes"?(o,a)=>me.includes(e,i,o,a):r==="indexOf"?(o,a)=>me.indexOf(e,i,o,a):r==="lastIndexOf"?(o,a)=>me.lastIndexOf(e,i,o,a):r==="toJSForTest"?()=>i.toJSForTest():r==="toTestString"?()=>me.toTestString(i):typeof r=="string"&&Kw(r)?(...o)=>{const a=Array.from(i).map(l=>kr(e,l));return Array.prototype[r].apply(a,o)}:Reflect.get(i,r,s),deleteProperty:(i,r)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`array[${r}]`),me.deleteInternalByIndex(e,i,Number.parseInt(r)),!0)}}static*iteratorInternal(e,t){for(const i of t)yield _n(e,i)}static buildArrayElements(e,t){const i=[];for(const r of t){const s=e.issueTimeTicket(),o=wl(e,r,s);i.push(o)}return i}static pushInternal(e,t,i){return me.insertAfterInternal(e,t,t.getLastCreatedAt(),i),t.length}static moveBeforeInternal(e,t,i,r){const s=e.issueTimeTicket(),o=t.getPrevCreatedAt(i);t.moveAfter(o,r,s),e.push(Kn.create(t.getCreatedAt(),o,r,s))}static moveAfterInternal(e,t,i,r){const s=e.issueTimeTicket();t.moveAfter(i,r,s),e.push(Kn.create(t.getCreatedAt(),i,r,s))}static moveFrontInternal(e,t,i){const r=e.issueTimeTicket(),s=t.getHead();t.moveAfter(s.getCreatedAt(),i,r),e.push(Kn.create(t.getCreatedAt(),s.getCreatedAt(),i,r))}static moveLastInternal(e,t,i){const r=e.issueTimeTicket(),s=t.getLastCreatedAt();t.moveAfter(s,i,r),e.push(Kn.create(t.getCreatedAt(),s,i,r))}static insertAfterInternal(e,t,i,r){const s=e.issueTimeTicket(),o=wl(e,r,s);return t.insertAfter(i,o),e.registerElement(o,t),e.push(Mo.create(t.getCreatedAt(),i,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,i,r){return me.insertAfterInternal(e,t,t.getPrevCreatedAt(i),r)}static deleteInternalByIndex(e,t,i){const r=e.issueTimeTicket(),s=t.deleteByIndex(i,r);if(s)return e.push(ur.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s),s}static deleteInternalByID(e,t,i){const r=e.issueTimeTicket(),s=t.delete(i,r);return e.push(ur.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s),s}static splice(e,t,i,r,...s){const o=t.length,a=i>=0?Math.min(i,o):Math.max(o+i,0),l=r===void 0?o:r<0?a:Math.min(a+r,o),h=[];for(let c=a;c=s)return!1;if(pe.isSupport(i))return Array.from(t).map(h=>kr(e,h)).includes(i,o);for(let l=o;l=s)return-1;if(pe.isSupport(i))return Array.from(t).map(h=>kr(e,h)).indexOf(i,o);for(let l=o;l=s?s-1:r<0?r+s:r;if(o<0)return-1;if(pe.isSupport(i))return Array.from(t).map(h=>kr(e,h)).lastIndexOf(i,o);for(let l=o;l>0;l--)if(((a=t.get(l))==null?void 0:a.getID())===i.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}let nh=class{constructor(e,t){d(this,"context");d(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,i,r){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);U.isEnabled(Ge.Debug)&&U.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${i}`);const o=r?us(r):void 0,a=this.context.issueTimeTicket(),[l,,h,c]=this.text.edit(s,i,a,o);for(const u of h)this.context.registerGCPair(u);return this.context.push(new Vo(this.text.getCreatedAt(),s[0],s[1],l,i,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(c)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,i){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const r=this.text.indexRangeToPosRange(e,t);U.isEnabled(Ge.Debug)&&U.debug(`STYL: f:${e}->${r[0].toTestString()}, t:${t}->${r[1].toTestString()} a:${JSON.stringify(i)}`);const s=us(i),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(r,s,o);for(const h of l)this.context.registerGCPair(h);return this.context.push(new Xo(this.text.getCreatedAt(),r[0],r[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Jt.fromStruct(e[0]),Jt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}};class rh{constructor(e,t){d(this,"valueType");d(this,"value");d(this,"context");d(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new v(w.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),i=pe.of(e,t);if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`);return this.counter.increase(i),this.context.push(gs.create(this.counter.getCreatedAt(),i,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new v(w.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function hf(n,e,t){const{type:i}=n,r=t.issueTimeTicket();if(i===Dn){AO(n);const{value:s}=n,o=ut.create(Me.of(r,0),i,s);e.append(o)}else{const{children:s=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!Ym(o)){const h=us(o);a=new Vn;for(const[c,u]of Object.entries(h))a.set(c,u,r)}const l=ut.create(Me.of(r,0),i,void 0,a);e.append(l);for(const h of s)hf(h,l,t)}}function ev(n,e){const{type:t}=e,i=n.issueTimeTicket();let r;if(e.type===Dn){const{value:s}=e;r=ut.create(Me.of(i,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!Ym(o)){const l=us(o);a=new Vn;for(const[h,c]of Object.entries(l))a.set(h,c,i)}r=ut.create(Me.of(n.issueTimeTicket(),0),t,void 0,a);for(const l of s)hf(l,r,n)}return r}function AO(n){if(!n.value.length)throw new v(w.ErrInvalidArgument,"text node cannot have empty value");return!0}function Md(n){if(!n.length)return!0;if(n[0].type===Dn)for(const t of n){const{type:i}=t;if(i!==Dn)throw new v(w.ErrInvalidArgument,"element node and text node cannot be passed together");AO(t)}else for(const t of n){const{type:i}=t;if(i===Dn)throw new v(w.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}let sh=class{constructor(e){d(this,"initialRoot");d(this,"context");d(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return ut.create(Me.of(e.issueTimeTicket(),0),H1);const t=ut.create(Me.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const i of this.initialRoot.children)hf(i,t,e);return t}getSize(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new v(w.ErrInvalidArgument,"path should not be empty");const[i,r]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=t?us(t):void 0,[a]=this.tree.style([i,r],o,s);this.context.push(Nn.create(this.tree.getCreatedAt(),i,r,a,o?new Map(Object.entries(o)):new Map,s))}style(e,t,i){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=i?us(i):void 0,[l,h]=this.tree.style([r,s],a,o);for(const c of h)this.context.registerGCPair(c);this.context.push(Nn.create(this.tree.getCreatedAt(),r,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,i){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([r,s],i,o);for(const h of l)this.context.registerGCPair(h);this.context.push(Nn.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),r,s,a,i,o))}editInternal(e,t,i,r=0){var h;if(i.length!==0&&i[0]&&(Md(i),i[0].type!==Dn))for(const c of i){const{children:u=[]}=c;Md(u)}const s=this.context.getLastTimeTicket();let o=new Array;if(((h=i[0])==null?void 0:h.type)===Dn){let c="";for(const u of i){const{value:f}=u;c+=f}o.push(ut.create(Me.of(this.context.issueTimeTicket(),0),Dn,c))}else o=i.map(c=>c&&ev(this.context,c)).filter(c=>c);const[,a,l]=this.tree.edit([e,t],o.length?o.map(c=>c==null?void 0:c.deepcopy()):void 0,r,s,()=>this.context.issueTimeTicket());for(const c of a)this.context.registerGCPair(c);return this.context.push(Lo.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,r,l,s)),!0}editByPath(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new v(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new v(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,i?[i]:[],r)}editBulkByPath(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new v(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new v(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,i,r)}edit(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,i?[i]:[],r)}editBulk(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,i,r)}toXML(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],i=this.tree.indexRangeToPosRange(t);return[i[0].toStruct(),i[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");const t=[_t.fromStruct(e[0]),_t.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");const t=[_t.fromStruct(e[0]),_t.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}};function Vd(n,e){return PO(n,e)}function _n(n,e){if(e){if(e instanceof pe)return e;if(e instanceof nt)return PO(n,e);if(e instanceof pt)return Yw(n,e);if(e instanceof qt)return new nh(n,e);if(e instanceof gt){const t=new rh(Pi.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof Mt){const t=new sh;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function kr(n,e){const t=_n(n,e);return t instanceof pe?t.getValue():t}function wl(n,e,t){let i;if(pe.isSupport(e))i=pe.of(e,t);else if(Array.isArray(e))i=pt.create(t,me.buildArrayElements(n,e));else if(typeof e=="object")e instanceof nh?(i=qt.create(ps.create(),t),e.initialize(n,i)):e instanceof rh?(i=gt.create(e.getValueType(),e.getValue(),t),e.initialize(n,i)):e instanceof sh?(i=Mt.create(e.buildRoot(n),t),e.initialize(n,i)):i=nt.create(t,Oo.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return i}const Xd=50;class tv{constructor(){d(this,"undoStack",[]);d(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Xd&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Xd&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const iv="yorkie-devtools-panel",nv="yorkie-devtools-sdk";let Fr="disconnected";const Ld=new Map,qa=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=qa);function na(n,e){(e!=null&&e.force||Fr!=="disconnected")&&window.postMessage({source:nv,...n},"*")}function rv(n){if(!n.isEnableDevtools()||typeof window>"u"||Ld.has(n.getKey()))return;qa.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(i=>i.type!==_e.StatusChanged&&i.type!==_e.Snapshot&&i.type!==_e.LocalChange&&i.type!==_e.RemoteChange&&i.type!==_e.Initialized&&i.type!==_e.Watched&&i.type!==_e.Unwatched&&i.type!==_e.PresenceChanged)||(qa.get(n.getKey()).push(t),Fr==="synced"&&na({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});Ld.set(n.getKey(),[e]),na({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if(((r=t.data)==null?void 0:r.source)!==iv)return;switch(t.data.msg){case"devtools::connect":if(Fr!=="disconnected")break;Fr="connected",na({msg:"doc::available",docKey:n.getKey()}),U.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Fr="disconnected",U.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Fr="synced",na({msg:"doc::sync::full",docKey:n.getKey(),events:qa.get(n.getKey())}),U.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Gn=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Gn||{}),_e=(n=>(n.StatusChanged="status-changed",n.ConnectionChanged="connection-changed",n.SyncStatusChanged="sync-status-changed",n.Snapshot="snapshot",n.LocalChange="local-change",n.RemoteChange="remote-change",n.Initialized="initialized",n.Watched="watched",n.Unwatched="unwatched",n.PresenceChanged="presence-changed",n.Broadcast="broadcast",n.LocalBroadcast="local-broadcast",n))(_e||{}),yo=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(yo||{}),Lc=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Lc||{});class $O{constructor(e,t){d(this,"key");d(this,"status");d(this,"opts");d(this,"changeID");d(this,"checkpoint");d(this,"localChanges");d(this,"root");d(this,"clone");d(this,"eventStream");d(this,"eventStreamObserver");d(this,"onlineClients");d(this,"presences");d(this,"history");d(this,"internalHistory");d(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=mo.create(),this.changeID=aw,this.checkpoint=lw,this.localChanges=[],this.eventStream=Jw(i=>{this.eventStreamObserver=i}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new tv,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},rv(this)}update(e,t){if(this.getStatus()==="removed")throw new v(w.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const i=this.changeID.getActorID(),r=Jr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(i)||{},t);try{const s=Vd(r,this.clone.root.getObject());this.presences.has(i)||this.clone.presences.set(i,{}),this.isUpdating=!0,e(s,new Ph(r,this.clone.presences.get(i)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(r.hasChange()){U.isEnabled(Ge.Trivial)&&U.trivial(`trying to update a local change: ${this.toJSON()}`);const s=r.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,se.Local),l=r.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const h=[];o.length>0&&h.push({type:"local-change",source:se.Local,value:{message:s.getMessage()||"",operations:o,actor:i,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&h.push({type:"presence-changed",source:se.Local,value:{clientID:i,presence:this.getPresence(i)}}),this.publish(h),U.isEnabled(Ge.Trivial)&&U.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,i,r){if(typeof e=="string"){if(typeof t!="function")throw new v(w.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||a(h)},i,r)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="presence-changed"||h.type==="presence-changed"&&h.value.clientID!==this.changeID.getActorID()||a(h)},i,r)}if(e==="others"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||h.value.clientID!==this.changeID.getActorID()&&a(h)},i,r)}if(e==="connection"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="connection-changed"&&a(h)},i,r)}if(e==="status"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="status-changed"&&a(h)},i,r)}if(e==="sync"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="sync-status-changed"&&a(h)},i,r)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="local-broadcast"&&a(h)},i)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="broadcast"&&a(h)},i)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,i,r)}const s=e,o=t;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const h=[];for(const c of l.value.operations)this.isSameElementOrChildOf(c.path,s)&&h.push(c);h.length&&o({...l,value:{...l.value,operations:h}})}},i,r)}if(typeof e=="function"){const s=e,o=t,a=i;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="snapshot"&&h.type!=="local-change"&&h.type!=="remote-change"||s(h)},o,a)}throw new v(w.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const i=e.split(".");return t.split(".").every((s,o)=>s===i[o])}applyChangePack(e){const t=e.hasSnapshot();for(t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),se.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();t&&this.applyChanges(this.localChanges,se.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),U.isEnabled(Ge.Trivial)&&U.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Wt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return ih.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Jr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Vd(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,i){const{root:r,presences:s}=we.bytesToSnapshot(i);this.root=new mo(r),this.presences=s,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.publish([{type:"snapshot",source:se.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?we.bytesToHex(i):void 0,snapshotVector:we.versionVectorToHex(t)}}])}applyChanges(e,t){U.isEnabled(Ge.Debug)&&U.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),U.isEnabled(Ge.Trivial)&&U.trivial(e.map(i=>`${i.getID().toTestString()} ${i.toTestString()}`).join(` -`));for(const i of e)this.applyChange(i,t);U.isEnabled(Ge.Debug)&&U.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const i=[],r=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(r)){const o=e.getPresenceChange();switch(o.type){case cr.Put:i.push(this.presences.has(r)?{type:"presence-changed",source:t,value:{clientID:r,presence:o.presence}}:{type:"watched",source:se.Remote,value:{clientID:r,presence:o.presence}});break;case cr.Clear:i.push({type:"unwatched",source:se.Remote,value:{clientID:r,presence:this.getPresence(r)}}),this.removeOnlineClient(r);break}}const{opInfos:s}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;i.push(t===se.Remote?{type:"remote-change",source:t,value:{actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:t,value:{actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o})}i.length>0&&this.publish(i)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,i=new Set;for(const r of t)r!==this.changeID.getActorID()&&i.add(r);this.setOnlineClients(i),this.publish([{type:"initialized",source:se.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:i}=e.body.value,r=[];if(t===Rr.DOCUMENT_WATCHED)this.addOnlineClient(i),this.hasPresence(i)&&r.push({type:"watched",source:se.Remote,value:{clientID:i,presence:this.getPresence(i)}});else if(t===Rr.DOCUMENT_UNWATCHED){const s=this.getPresence(i);this.removeOnlineClient(i),s&&r.push({type:"unwatched",source:se.Remote,value:{clientID:i,presence:s}})}else if(t===Rr.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:s,payload:o}=e.body.value.body,a=new TextDecoder;r.push({type:"broadcast",value:{clientID:i,topic:s,payload:JSON.parse(a.decode(o))}})}r.length>0&&this.publish(r)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(zu),this.publish([{source:e==="removed"?se.Remote:se.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:i,snapshotVector:r}=e.value;if(!t)return;this.applySnapshot(BigInt(i),we.hexToVersionVector(r),we.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ds.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:i,presence:r}of e.value)t.add(i),this.presences.set(i,r);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:i}=e.value;this.addOnlineClient(t),this.presences.set(t,i);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:i}=e.value;this.presences.set(t,i)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new v(w.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let i=this.getRoot();for(const r of t)if(i=i[r],i===void 0)return;return i}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?Wt(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?Wt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Wt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Wt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Wt(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,i)=>t.clientID>i.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){const i=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(i)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new v(w.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new v(w.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Jr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof Yt)){new Ph(t,Wt(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const c=t.issueTimeTicket();h.setExecutedAt(c),t.push(h)}const i=t.getChange();i.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:r,reverseOps:s}=i.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!i.hasPresenceChange()&&r.length===0)return;this.localChanges.push(i),this.changeID=i.getID();const a=this.changeID.getActorID(),l=[];r.length>0&&l.push({type:"local-change",source:se.UndoRedo,value:{message:i.getMessage()||"",operations:r,actor:a,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new v(w.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new v(w.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Jr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof Yt)){new Ph(t,Wt(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const c=t.issueTimeTicket();h.setExecutedAt(c),t.push(h)}const i=t.getChange();i.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:r,reverseOps:s}=i.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!i.hasPresenceChange()&&r.length===0)return;this.localChanges.push(i),this.changeID=i.getID();const a=this.changeID.getActorID(),l=[];r.length>0&&l.push({type:"local-change",source:se.UndoRedo,value:{message:i.getMessage()||"",operations:r,actor:a,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,i){const r={type:"local-broadcast",value:{topic:e,payload:t},options:i};this.publish([r])}getVersionVector(){return this.changeID.getVersionVector()}}function sv(n,e){return t=>async i=>(n&&i.header.set("x-api-key",n),e&&i.header.set("authorization",e),await t(i))}const ov="yorkie-js-sdk",av="0.5.4",lv="Yorkie JS SDK",hv="./src/yorkie.ts",cv={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},uv=["dist"],fv={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},dv={node:">=18.0.0",npm:">=7.1.0"},pv={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},gv={name:"hackerwins",email:"susukang98@gmail.com"},mv="Apache-2.0",Ov={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},yv="https://github.com/yorkie-team/yorkie-js-sdk#readme",bv={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},Sv={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Ud={name:ov,version:av,description:lv,main:hv,publishConfig:cv,files:uv,scripts:fv,engines:dv,repository:pv,author:gv,license:mv,bugs:Ov,homepage:yv,devDependencies:bv,dependencies:Sv};function wv(){return n=>async e=>(e.header.set("x-yorkie-user-agent",Ud.name+"/"+Ud.version),await n(e))}const vv=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Ma=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Ma||{});const ra={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Ih={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class CO{constructor(e,t){d(this,"id");d(this,"key");d(this,"status");d(this,"attachmentMap");d(this,"apiKey");d(this,"conditions");d(this,"syncLoopDuration");d(this,"reconnectStreamDelay");d(this,"retrySyncLoopDelay");d(this,"rpcClient");d(this,"taskQueue");d(this,"processing",!1);t=t||ra,this.key=t.key?t.key:QO(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||ra.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||ra.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||ra.retrySyncLoopDelay,this.rpcClient=y1(L1,X1({baseUrl:e,interceptors:[sv(t.apiKey,t.token),wv()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),U.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw U.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),U.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw U.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Gn.Detached)throw new v(w.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const i=e.subscribe("local-broadcast",async s=>{var c;const{topic:o,payload:a}=s.value,l=(c=s.options)==null?void 0:c.error,h=s.options;try{await this.broadcast(e.getKey(),o,a,h)}catch(u){u instanceof Error&&(l==null||l(u))}}),r=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:we.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=we.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Gn.Removed)return e;e.applyStatus(Gn.Attached),this.attachmentMap.set(e.getKey(),new _w(this.reconnectStreamDelay,e,s.documentId,r,i)),r!=="manual"&&await this.runWatchLoop(e.getKey()),U.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const l=t.initialRoot;e.update(h=>{for(const[c,u]of Object.entries(l))if(!a.has(c)){const f=c;h[f]=u}})}return e}).catch(s=>{throw U.error(`[AD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e.getKey());if(!i)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((r,s)=>s.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:i.docID,changePack:we.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const s=we.fromChangePack(r.changePack);return e.applyChangePack(s),e.getStatus()!==Gn.Removed&&e.applyStatus(Gn.Detached),this.detachInternal(e.getKey()),U.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(r=>{throw U.error(`[DD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}async changeSyncMode(e,t){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e.getKey());if(!i)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const r=i.syncMode;return r===t?e:(i.changeSyncMode(t),t==="manual"?(i.cancelWatchStream(),e):(t==="realtime"&&(i.remoteChangeEventReceived=!0),r==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(i=>{throw U.error(`[SY] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}return this.enqueueTask(async()=>{const t=[];for(const[,i]of this.attachmentMap)t.push(this.syncInternal(i,i.syncMode));return Promise.all(t).catch(i=>{throw U.error(`[SY] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i})})}remove(e){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const i=we.toChangePack(e.createChangePack());return i.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:i},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const s=we.fromChangePack(r.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),U.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(r=>{throw U.error(`[RD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,i,r){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new v(w.ErrDocumentNotAttached,`${e} is not attached`);if(!vv(i))throw new v(w.ErrInvalidArgument,"payload is not serializable");const o=(r==null?void 0:r.maxRetries)??Ih.maxRetries,a=Ih.maxBackoff;let l=0;const h=u=>Math.min(Ih.initialRetryInterval*2**u,a),c=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(i))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{U.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(u=>{if(U.error(`[BC] c:"${this.getKey()}" err:`,u),this.handleConnectError(u))if(lc(),h(l-1)),U.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw U.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),u;else throw u}));return c()}runSyncLoop(){const e=()=>{if(!this.isActive()){U.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,i]of this.attachmentMap)i.needRealtimeSync()&&(i.remoteChangeEventReceived=!1,t.push(this.syncInternal(i,i.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(i=>{U.error(`[SL] c:"${this.getKey()}" sync failed:`,i),this.handleConnectError(i)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};U.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new v(w.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(i=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new v(w.ErrClientNotActivated,`${this.key} is not active`));const r=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:r.signal});return t.doc.publish([{type:_e.ConnectionChanged,value:yo.Connected}]),U.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const h of s)this.handleWatchDocumentsResponse(t,h),h.body.case==="initialization"&&o([s,r])}catch(h){t.doc.resetOnlineClients(),t.doc.publish([{type:_e.Initialized,source:se.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:_e.ConnectionChanged,value:yo.Disconnected}]),U.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(h)?i():this.conditions.WatchLoop=!1,a(h)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===Rr.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(Gn.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:i,docID:r}=e,s=i.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:r,changePack:we.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${i.getKey()}`}}).then(o=>{const a=we.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return i;i.applyChangePack(a),e.doc.publish([{type:_e.SyncStatusChanged,value:Lc.Synced}]),i.getStatus()===Gn.Removed&&this.detachInternal(i.getKey());const l=i.getKey(),h=a.getChangeSize();return U.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${h} cp:${a.getCheckpoint().toTestString()}`),i}).catch(o=>{throw i.publish([{type:_e.SyncStatusChanged,value:Lc.SyncFailed}]),U.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof Te?e.code===ie.Canceled||e.code===ie.Unknown||e.code===ie.ResourceExhausted||e.code===ie.Unavailable?!0:((qd(e)===w.ErrClientNotActivated||qd(e)===w.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,i)=>{this.taskQueue.push(()=>e().then(t).catch(i)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{U.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Rh={Client:CO,Document:$O,Primitive:pe,Text:nh,Counter:rh,Tree:sh,LogLevel:Ge,setLogLevel:TO,IntType:Pi.IntegerCnt,LongType:Pi.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:CO,Document:$O,Primitive:pe,Text:nh,Counter:rh,Tree:sh,LogLevel:Ge,setLogLevel:TO,IntType:Pi.IntegerCnt,LongType:Pi.LongCnt});class K{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ms(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),ui.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ms(this,e,t);let i=[];return this.decompose(e,t,i,0),ui.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new eo(this),s=new eo(e);for(let o=t,a=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(a+=r.value.length,r.done||a>=i)return!0}}iter(e=1){return new eo(this,e)}iterRange(e,t=this.length){return new IO(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new RO(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?K.empty:e.length<=32?new Se(e):ui.from(Se.split(e,[]))}}class Se extends K{constructor(e,t=kv(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],a=r+o.length;if((t?i:a)>=e)return new xv(r,a,i,o);r=a+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new Se(Zd(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),a=Va(s.text,o.text.slice(),0,s.length);if(a.length<=32)i.push(new Se(a,o.length+s.length));else{let l=a.length>>1;i.push(new Se(a.slice(0,l)),new Se(a.slice(l)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof Se))return super.replace(e,t,i);[e,t]=ms(this,e,t);let r=Va(this.text,Va(i.text,Zd(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new Se(r,s):ui.from(Se.split(r,[]),s)}sliceString(e,t=this.length,i=` +`));for(const i of e)this.applyChange(i,t);U.isEnabled(Ge.Debug)&&U.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const i=[],r=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(r)){const o=e.getPresenceChange();switch(o.type){case cr.Put:i.push(this.presences.has(r)?{type:"presence-changed",source:t,value:{clientID:r,presence:o.presence}}:{type:"watched",source:se.Remote,value:{clientID:r,presence:o.presence}});break;case cr.Clear:i.push({type:"unwatched",source:se.Remote,value:{clientID:r,presence:this.getPresence(r)}}),this.removeOnlineClient(r);break}}const{opInfos:s}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;i.push(t===se.Remote?{type:"remote-change",source:t,value:{actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:t,value:{actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o})}i.length>0&&this.publish(i)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,i=new Set;for(const r of t)r!==this.changeID.getActorID()&&i.add(r);this.setOnlineClients(i),this.publish([{type:"initialized",source:se.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:i}=e.body.value,r=[];if(t===Rr.DOCUMENT_WATCHED){if(this.onlineClients.has(i)&&this.hasPresence(i))return;this.addOnlineClient(i),this.hasPresence(i)&&r.push({type:"watched",source:se.Remote,value:{clientID:i,presence:this.getPresence(i)}})}else if(t===Rr.DOCUMENT_UNWATCHED){const s=this.getPresence(i);this.removeOnlineClient(i),s&&r.push({type:"unwatched",source:se.Remote,value:{clientID:i,presence:s}})}else if(t===Rr.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:s,payload:o}=e.body.value.body,a=new TextDecoder;r.push({type:"broadcast",value:{clientID:i,topic:s,payload:JSON.parse(a.decode(o))}})}r.length>0&&this.publish(r)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(zu),this.publish([{source:e==="removed"?se.Remote:se.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:i,snapshotVector:r}=e.value;if(!t)return;this.applySnapshot(BigInt(i),we.hexToVersionVector(r),we.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ds.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:i,presence:r}of e.value)t.add(i),this.presences.set(i,r);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:i}=e.value;this.addOnlineClient(t),this.presences.set(t,i);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:i}=e.value;this.presences.set(t,i)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new v(w.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let i=this.getRoot();for(const r of t)if(i=i[r],i===void 0)return;return i}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?Wt(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?Wt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Wt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Wt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Wt(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,i)=>t.clientID>i.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){const i=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(i)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new v(w.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new v(w.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Jr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof Yt)){new Ph(t,Wt(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const c=t.issueTimeTicket();h.setExecutedAt(c),t.push(h)}const i=t.getChange();i.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:r,reverseOps:s}=i.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!i.hasPresenceChange()&&r.length===0)return;this.localChanges.push(i),this.changeID=i.getID();const a=this.changeID.getActorID(),l=[];r.length>0&&l.push({type:"local-change",source:se.UndoRedo,value:{message:i.getMessage()||"",operations:r,actor:a,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new v(w.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new v(w.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Jr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof Yt)){new Ph(t,Wt(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const c=t.issueTimeTicket();h.setExecutedAt(c),t.push(h)}const i=t.getChange();i.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:r,reverseOps:s}=i.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!i.hasPresenceChange()&&r.length===0)return;this.localChanges.push(i),this.changeID=i.getID();const a=this.changeID.getActorID(),l=[];r.length>0&&l.push({type:"local-change",source:se.UndoRedo,value:{message:i.getMessage()||"",operations:r,actor:a,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,i){const r={type:"local-broadcast",value:{topic:e,payload:t},options:i};this.publish([r])}getVersionVector(){return this.changeID.getVersionVector()}}function sv(n,e){return t=>async i=>(n&&i.header.set("x-api-key",n),e&&i.header.set("authorization",e),await t(i))}const ov="yorkie-js-sdk",av="0.5.4",lv="Yorkie JS SDK",hv="./src/yorkie.ts",cv={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},uv=["dist"],fv={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},dv={node:">=18.0.0",npm:">=7.1.0"},pv={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},gv={name:"hackerwins",email:"susukang98@gmail.com"},mv="Apache-2.0",Ov={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},yv="https://github.com/yorkie-team/yorkie-js-sdk#readme",bv={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},Sv={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Ud={name:ov,version:av,description:lv,main:hv,publishConfig:cv,files:uv,scripts:fv,engines:dv,repository:pv,author:gv,license:mv,bugs:Ov,homepage:yv,devDependencies:bv,dependencies:Sv};function wv(){return n=>async e=>(e.header.set("x-yorkie-user-agent",Ud.name+"/"+Ud.version),await n(e))}const vv=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Ma=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Ma||{});const ra={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Ih={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class CO{constructor(e,t){d(this,"id");d(this,"key");d(this,"status");d(this,"attachmentMap");d(this,"apiKey");d(this,"conditions");d(this,"syncLoopDuration");d(this,"reconnectStreamDelay");d(this,"retrySyncLoopDelay");d(this,"rpcClient");d(this,"taskQueue");d(this,"processing",!1);t=t||ra,this.key=t.key?t.key:QO(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||ra.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||ra.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||ra.retrySyncLoopDelay,this.rpcClient=y1(L1,X1({baseUrl:e,interceptors:[sv(t.apiKey,t.token),wv()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),U.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw U.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),U.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw U.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Gn.Detached)throw new v(w.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const i=e.subscribe("local-broadcast",async s=>{var c;const{topic:o,payload:a}=s.value,l=(c=s.options)==null?void 0:c.error,h=s.options;try{await this.broadcast(e.getKey(),o,a,h)}catch(u){u instanceof Error&&(l==null||l(u))}}),r=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:we.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=we.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Gn.Removed)return e;e.applyStatus(Gn.Attached),this.attachmentMap.set(e.getKey(),new _w(this.reconnectStreamDelay,e,s.documentId,r,i)),r!=="manual"&&await this.runWatchLoop(e.getKey()),U.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const l=t.initialRoot;e.update(h=>{for(const[c,u]of Object.entries(l))if(!a.has(c)){const f=c;h[f]=u}})}return e}).catch(s=>{throw U.error(`[AD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e.getKey());if(!i)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((r,s)=>s.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:i.docID,changePack:we.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const s=we.fromChangePack(r.changePack);return e.applyChangePack(s),e.getStatus()!==Gn.Removed&&e.applyStatus(Gn.Detached),this.detachInternal(e.getKey()),U.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(r=>{throw U.error(`[DD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}async changeSyncMode(e,t){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e.getKey());if(!i)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const r=i.syncMode;return r===t?e:(i.changeSyncMode(t),t==="manual"?(i.cancelWatchStream(),e):(t==="realtime"&&(i.remoteChangeEventReceived=!0),r==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(i=>{throw U.error(`[SY] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}return this.enqueueTask(async()=>{const t=[];for(const[,i]of this.attachmentMap)t.push(this.syncInternal(i,i.syncMode));return Promise.all(t).catch(i=>{throw U.error(`[SY] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i})})}remove(e){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const i=we.toChangePack(e.createChangePack());return i.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:i},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const s=we.fromChangePack(r.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),U.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(r=>{throw U.error(`[RD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,i,r){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new v(w.ErrDocumentNotAttached,`${e} is not attached`);if(!vv(i))throw new v(w.ErrInvalidArgument,"payload is not serializable");const o=(r==null?void 0:r.maxRetries)??Ih.maxRetries,a=Ih.maxBackoff;let l=0;const h=u=>Math.min(Ih.initialRetryInterval*2**u,a),c=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(i))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{U.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(u=>{if(U.error(`[BC] c:"${this.getKey()}" err:`,u),this.handleConnectError(u))if(lc(),h(l-1)),U.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw U.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),u;else throw u}));return c()}runSyncLoop(){const e=()=>{if(!this.isActive()){U.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,i]of this.attachmentMap)i.needRealtimeSync()&&(i.remoteChangeEventReceived=!1,t.push(this.syncInternal(i,i.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(i=>{U.error(`[SL] c:"${this.getKey()}" sync failed:`,i),this.handleConnectError(i)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};U.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new v(w.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(i=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new v(w.ErrClientNotActivated,`${this.key} is not active`));const r=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:r.signal});return t.doc.publish([{type:_e.ConnectionChanged,value:yo.Connected}]),U.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const h of s)this.handleWatchDocumentsResponse(t,h),h.body.case==="initialization"&&o([s,r])}catch(h){t.doc.resetOnlineClients(),t.doc.publish([{type:_e.Initialized,source:se.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:_e.ConnectionChanged,value:yo.Disconnected}]),U.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(h)?i():this.conditions.WatchLoop=!1,a(h)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===Rr.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(Gn.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:i,docID:r}=e,s=i.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:r,changePack:we.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${i.getKey()}`}}).then(o=>{const a=we.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return i;i.applyChangePack(a),e.doc.publish([{type:_e.SyncStatusChanged,value:Lc.Synced}]),i.getStatus()===Gn.Removed&&this.detachInternal(i.getKey());const l=i.getKey(),h=a.getChangeSize();return U.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${h} cp:${a.getCheckpoint().toTestString()}`),i}).catch(o=>{throw i.publish([{type:_e.SyncStatusChanged,value:Lc.SyncFailed}]),U.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof Te?e.code===ie.Canceled||e.code===ie.Unknown||e.code===ie.ResourceExhausted||e.code===ie.Unavailable?!0:((qd(e)===w.ErrClientNotActivated||qd(e)===w.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,i)=>{this.taskQueue.push(()=>e().then(t).catch(i)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{U.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Rh={Client:CO,Document:$O,Primitive:pe,Text:nh,Counter:rh,Tree:sh,LogLevel:Ge,setLogLevel:TO,IntType:Pi.IntegerCnt,LongType:Pi.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:CO,Document:$O,Primitive:pe,Text:nh,Counter:rh,Tree:sh,LogLevel:Ge,setLogLevel:TO,IntType:Pi.IntegerCnt,LongType:Pi.LongCnt});class K{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ms(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),ui.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ms(this,e,t);let i=[];return this.decompose(e,t,i,0),ui.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new eo(this),s=new eo(e);for(let o=t,a=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(a+=r.value.length,r.done||a>=i)return!0}}iter(e=1){return new eo(this,e)}iterRange(e,t=this.length){return new IO(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new RO(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?K.empty:e.length<=32?new Se(e):ui.from(Se.split(e,[]))}}class Se extends K{constructor(e,t=kv(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],a=r+o.length;if((t?i:a)>=e)return new xv(r,a,i,o);r=a+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new Se(Zd(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),a=Va(s.text,o.text.slice(),0,s.length);if(a.length<=32)i.push(new Se(a,o.length+s.length));else{let l=a.length>>1;i.push(new Se(a.slice(0,l)),new Se(a.slice(l)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof Se))return super.replace(e,t,i);[e,t]=ms(this,e,t);let r=Va(this.text,Va(i.text,Zd(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new Se(r,s):ui.from(Se.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ms(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=a.slice(Math.max(0,e-s),t-s)),s=l+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new Se(i,r)),i=[],r=-1);return r>-1&&t.push(new Se(i,r)),t}}class ui extends K{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],a=r+o.length,l=i+o.lines-1;if((t?l:a)>=e)return o.lineInner(e,t,i,r);r=a+1,i=l+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(l>=t?2:0));o>=e&&l<=t&&!h?i.push(a):a.decompose(e-o,t-o,i,h)}o=l+1}}replace(e,t,i){if([e,t]=ms(this,e,t),i.lines=s&&t<=a){let l=o.replace(e-s,t-s,i),h=this.lines-o.lines+l.lines;if(l.lines>4&&l.lines>h>>6){let c=this.children.slice();return c[r]=l,new ui(c,this.length-(t-e)+i.length)}return super.replace(s,a,l)}s=a+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` `){[e,t]=ms(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=a.sliceString(e-o,t-o,i)),o=l+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof ui))return 0;let i=0,[r,s,o,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==a)return i;let l=this.children[r],h=e.children[s];if(l!=h)return i+l.scanIdentical(h,t);i+=l.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let p of e)i+=p.lines;if(i<32){let p=[];for(let g of e)g.flatten(p);return new Se(p,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,a=[],l=0,h=-1,c=[];function u(p){let g;if(p.lines>s&&p instanceof ui)for(let y of p.children)u(y);else p.lines>o&&(l>o||!l)?(f(),a.push(p)):p instanceof Se&&l&&(g=c[c.length-1])instanceof Se&&p.lines+g.lines<=32?(l+=p.lines,h+=p.length+1,c[c.length-1]=new Se(g.text.concat(p.text),g.length+1+p.length)):(l+p.lines>r&&f(),l+=p.lines,h+=p.length+1,c.push(p))}function f(){l!=0&&(a.push(c.length==1?c[0]:ui.from(c,h)),h=-1,l=c.length=0)}for(let p of e)u(p);return f(),a.length==1?a[0]:new ui(a,t)}}K.empty=new Se([""],0);function kv(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Va(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(l>i&&(a=a.slice(0,i-r)),r0?1:(e instanceof Se?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,a=r instanceof Se?r.text.length:r.children.length;if(o==(t>0?a:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` `,this;e--}else if(r instanceof Se){let l=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,l.length>Math.max(0,e))return this.value=e==0?l:t>0?l.slice(e):l.slice(0,l.length-e),this;e-=l.length}else{let l=r.children[o+(t<0?-1:0)];e>l.length?(e-=l.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(l),this.offsets.push(t>0?1:(l instanceof Se?l.text.length:l.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class IO{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new eo(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class RO{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(K.prototype[Symbol.iterator]=function(){return this.iter()},eo.prototype[Symbol.iterator]=IO.prototype[Symbol.iterator]=RO.prototype[Symbol.iterator]=function(){return this});let xv=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ms(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}let ns="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(n=>n?parseInt(n,36):1);for(let n=1;nn)return ns[e-1]<=n;return!1}function Wd(n){return n>=127462&&n<=127487}const jd=8205;function We(n,e,t=!0,i=!0){return(t?EO:Qv)(n,e,i)}function EO(n,e,t){if(e==n.length)return e;e&&DO(n.charCodeAt(e))&&NO(n.charCodeAt(e-1))&&e--;let i=Ne(n,e);for(e+=lt(i);e=0&&Wd(Ne(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function Qv(n,e,t){for(;e>0;){let i=EO(n,e-2,t);if(i=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function Ne(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return DO(i)?(t-55296<<10)+(i-56320)+65536:t}function cf(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function lt(n){return n<65536?1:2}const Uc=/\r\n?|\n/;var qe=function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n}(qe||(qe={}));class Qi{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=a}else{if(i!=qe.Simple&&h>=e&&(i==qe.TrackDel&&re||i==qe.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!a)return e==r||t<0?s:s+l;s+=l}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&a>=e)return rt?"cover":!0;r=a}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new Qi(e)}static create(e){return new Qi(e)}}class Ce extends Qi{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Zc(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Wc(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=a,t[r+1]=o;let l=r>>1;for(;i.length0&&er(i,t,s.text),s.forward(c),a+=c}let h=e[o++];for(;a>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,a=null;function l(c=!1){if(!c&&!r.length)return;of||u<0||f>t)throw new RangeError(`Invalid change range ${u} to ${f} (in doc of length ${t})`);let g=p?typeof p=="string"?K.of(p.split(i||Uc)):p:K.empty,y=g.length;if(u==f&&y==0)return;uo&&Le(r,u-o,-1),Le(r,f-u,y),er(s,r,g),o=f}}return h(e),l(!a),a}static empty(e){return new Ce(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;ra&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function er(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)a=n.sections[o++],l=n.sections[o++];e(r,h,s,c,u),r=h,s=c}}}function Wc(n,e,t,i=!1){let r=[],s=i?[]:null,o=new bo(n),a=new bo(e);for(let l=-1;;)if(o.ins==-1&&a.ins==-1){let h=Math.min(o.len,a.len);Le(r,h,-1),o.forward(h),a.forward(h)}else if(a.ins>=0&&(o.ins<0||l==o.i||o.off==0&&(a.len=0&&l=0){let h=0,c=o.len;for(;c;)if(a.ins==-1){let u=Math.min(c,a.len);h+=u,c-=u,a.forward(u)}else if(a.ins==0&&a.lenl||o.ins>=0&&o.len>l)&&(a||i.length>h),s.forward2(l),o.forward(l)}}}}class bo{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?K.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?K.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class $r{constructor(e,t,i){this.from=e,this.to=t,this.flags=i}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}get goalColumn(){let e=this.flags>>6;return e==16777215?void 0:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new $r(i,r,this.flags)}extend(e,t=e){if(e<=this.anchor&&t>=this.anchor)return P.range(e,t);let i=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return P.range(this.anchor,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return P.range(e.anchor,e.head)}static create(e,t,i){return new $r(e,t,i)}}class P{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:P.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new P(e.ranges.map(t=>$r.fromJSON(t)),e.main)}static single(e,t=e){return new P([P.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;re?8:0)|s)}static normalized(e,t=0){let i=e[t];e.sort((r,s)=>r.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?P.range(l,a):P.range(a,l))}}return new P(e,t)}}function qO(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let uf=0;class B{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=uf++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new B(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:ff),!!e.static,e.enables)}of(e){return new Xa([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Xa(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Xa(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function ff(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Xa{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=uf++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,a=this.type==2,l=!1,h=!1,c=[];for(let u of this.dependencies)u=="doc"?l=!0:u=="selection"?h=!0:((t=e[u.id])!==null&&t!==void 0?t:1)&1||c.push(e[u.id]);return{create(u){return u.values[o]=i(u),1},update(u,f){if(l&&f.docChanged||h&&(f.docChanged||f.selection)||jc(u,c)){let p=i(u);if(a?!Fd(p,u.values[o],r):!r(p,u.values[o]))return u.values[o]=p,1}return 0},reconfigure:(u,f)=>{let p,g=f.config.address[s];if(g!=null){let y=kl(f,g);if(this.dependencies.every(O=>O instanceof B?f.facet(O)===u.facet(O):O instanceof Re?f.field(O,!1)==u.field(O,!1):!0)||(a?Fd(p=i(u),y,r):r(p=i(u),y)))return u.values[o]=y,0}else p=i(u);return u.values[o]=p,1}}}}function Fd(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[l.id]),r=t.map(l=>l.type),s=i.filter(l=>!(l&1)),o=n[e.id]>>1;function a(l){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(zd).find(i=>i.field==this);return((t==null?void 0:t.create)||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}init(e){return[this,zd.of({field:this,create:e})]}get extension(){return this}}const Tr={lowest:4,low:3,default:2,high:1,highest:0};function Ds(n){return e=>new MO(e,n)}const mr={highest:Ds(Tr.highest),high:Ds(Tr.high),default:Ds(Tr.default),low:Ds(Tr.low),lowest:Ds(Tr.lowest)};class MO{constructor(e,t){this.inner=e,this.prec=t}}class oh{of(e){return new Fc(this,e)}reconfigure(e){return oh.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class Fc{constructor(e,t){this.compartment=e,this.inner=t}}class vl{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let f of Av(e,t,o))f instanceof Re?r.push(f):(s[f.facet.id]||(s[f.facet.id]=[])).push(f);let a=Object.create(null),l=[],h=[];for(let f of r)a[f.id]=h.length<<1,h.push(p=>f.slot(p));let c=i==null?void 0:i.config.facets;for(let f in s){let p=s[f],g=p[0].facet,y=c&&c[f]||[];if(p.every(O=>O.type==0))if(a[g.id]=l.length<<1|1,ff(y,p))l.push(i.facet(g));else{let O=g.combine(p.map(S=>S.value));l.push(i&&g.compare(O,i.facet(g))?i.facet(g):O)}else{for(let O of p)O.type==0?(a[O.id]=l.length<<1|1,l.push(O.value)):(a[O.id]=h.length<<1,h.push(S=>O.dynamicSlot(S)));a[g.id]=h.length<<1,h.push(O=>Pv(O,g,p))}}let u=h.map(f=>f(a));return new vl(e,o,u,a,l,s)}}function Av(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,a){let l=r.get(o);if(l!=null){if(l<=a)return;let h=i[l].indexOf(o);h>-1&&i[l].splice(h,1),o instanceof Fc&&t.delete(o.compartment)}if(r.set(o,a),Array.isArray(o))for(let h of o)s(h,a);else if(o instanceof Fc){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,a)}else if(o instanceof MO)s(o.inner,o.prec);else if(o instanceof Re)i[a].push(o),o.provides&&s(o.provides,a);else if(o instanceof Xa)i[a].push(o),o.facet.extensions&&s(o.facet.extensions,Tr.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,a)}}return s(n,Tr.default),i.reduce((o,a)=>o.concat(a))}function to(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function kl(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const VO=B.define(),zc=B.define({combine:n=>n.some(e=>e),static:!0}),XO=B.define({combine:n=>n.length?n[0]:void 0,static:!0}),LO=B.define(),UO=B.define(),ZO=B.define(),WO=B.define({combine:n=>n.length?n[0]:!1});class jn{constructor(e,t){this.type=e,this.value=t}static define(){return new $v}}class $v{of(e){return new jn(this,e)}}class Cv{constructor(e){this.map=e}of(e){return new z(this,e)}}class z{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new z(this.type,t)}is(e){return this.type==e}static define(e={}){return new Cv(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}z.reconfigure=z.define();z.appendConfig=z.define();class ye{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&qO(i,t.newLength),s.some(a=>a.type==ye.time)||(this.annotations=s.concat(ye.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ye(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ye.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ye.time=jn.define();ye.userEvent=jn.define();ye.addToHistory=jn.define();ye.remote=jn.define();function Iv(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ye?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ye?n=s[0]:n=FO(e,rs(s),!1)}return n}function Ev(n){let e=n.startState,t=e.facet(ZO),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=jO(i,_c(e,s,n.changes.newLength),!0))}return i==n?n:ye.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const Dv=[];function rs(n){return n==null?Dv:Array.isArray(n)?n:[n]}var fe=function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n}(fe||(fe={}));const Nv=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Gc;try{Gc=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function Bv(n){if(Gc)return Gc.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||Nv.test(t)))return!0}return!1}function qv(n){return e=>{if(!/\S/.test(e))return fe.Space;if(Bv(e))return fe.Word;for(let t=0;t-1)return fe.Word;return fe.Other}}class H{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let a=0;ar.set(h,l)),t=null),r.set(a.value.compartment,a.value.extension)):a.is(z.reconfigure)?(t=null,i=a.value):a.is(z.appendConfig)&&(t=null,i=rs(i).concat(a.value));let s;t?s=e.startState.values.slice():(t=vl.resolve(i,r,this),s=new H(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,h)=>h.reconfigure(l,this),null).values);let o=e.startState.facet(zc)?e.newSelection:e.newSelection.asSingle();new H(t,e.newDoc,o,s,(a,l)=>l.update(a,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:P.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=rs(i.effects);for(let a=1;ao.spec.fromJSON(a,l)))}}return H.create({doc:e.doc,selection:P.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=vl.resolve(e.extensions||[],new Map),i=e.doc instanceof K?e.doc:K.of((e.doc||"").split(t.staticFacet(H.lineSeparator)||Uc)),r=e.selection?e.selection instanceof P?e.selection:P.single(e.selection.anchor,e.selection.head):P.single(0);return qO(r,i.length),t.staticFacet(zc)||(r=r.asSingle()),new H(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(H.tabSize)}get lineBreak(){return this.facet(H.lineSeparator)||` diff --git a/examples/vanilla-codemirror6/index.html b/examples/vanilla-codemirror6/index.html index b9bf2b0b5..cad1fe515 100644 --- a/examples/vanilla-codemirror6/index.html +++ b/examples/vanilla-codemirror6/index.html @@ -4,7 +4,7 @@ Yorkie + CodeMirror 6 Example - + diff --git a/examples/vanilla-quill/assets/index-YVtFiz5i.js b/examples/vanilla-quill/assets/index-CXKQfVgS.js similarity index 96% rename from examples/vanilla-quill/assets/index-YVtFiz5i.js rename to examples/vanilla-quill/assets/index-CXKQfVgS.js index 52eb18c49..da36550c8 100644 --- a/examples/vanilla-quill/assets/index-YVtFiz5i.js +++ b/examples/vanilla-quill/assets/index-CXKQfVgS.js @@ -20,7 +20,7 @@ var Vu=Object.defineProperty;var Ku=(i,t,e)=>t in i?Vu(i,t,{enumerable:!0,config * * SPDX-License-Identifier: Apache-2.0 */var Ht=null;try{Ht=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Ve(i,t,e){this.low=i|0,this.high=t|0,this.unsigned=!!e}Ve.prototype.__isLong__;Object.defineProperty(Ve.prototype,"__isLong__",{value:!0});function yt(i){return(i&&i.__isLong__)===!0}function ml(i){var t=Math.clz32(i&-i);return i?31-t:t}Ve.isLong=yt;var yl={},vl={};function Pi(i,t){var e,n,r;return t?(i>>>=0,(r=0<=i&&i<256)&&(n=vl[i],n)?n:(e=Ke(i,0,!0),r&&(vl[i]=e),e)):(i|=0,(r=-128<=i&&i<128)&&(n=yl[i],n)?n:(e=Ke(i,i<0?-1:0,!1),r&&(yl[i]=e),e))}Ve.fromInt=Pi;function Wt(i,t){if(isNaN(i))return t?Wr:an;if(t){if(i<0)return Wr;if(i>=fu)return gu}else{if(i<=-wl)return Et;if(i+1>=wl)return du}return i<0?Wt(-i,t).neg():Ke(i%Yi|0,i/Yi|0,t)}Ve.fromNumber=Wt;function Ke(i,t,e){return new Ve(i,t,e)}Ve.fromBits=Ke;var bs=Math.pow;function Sa(i,t,e){if(i.length===0)throw Error("empty string");if(typeof t=="number"?(e=t,t=!1):t=!!t,i==="NaN"||i==="Infinity"||i==="+Infinity"||i==="-Infinity")return t?Wr:an;if(e=e||10,e<2||360)throw Error("interior hyphen");if(n===0)return Sa(i.substring(1),t,e).neg();for(var r=Wt(bs(e,8)),o=an,s=0;s>>0:this.low};he.toNumber=function(){return this.unsigned?(this.high>>>0)*Yi+(this.low>>>0):this.high*Yi+(this.low>>>0)};he.toString=function(t){if(t=t||10,t<2||36>>0,y=m.toString(t);if(s=c,s.isZero())return y+u;for(;y.length<6;)y="0"+y;u=""+y+u}};he.getHighBits=function(){return this.high};he.getHighBitsUnsigned=function(){return this.high>>>0};he.getLowBits=function(){return this.low};he.getLowBitsUnsigned=function(){return this.low>>>0};he.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Et)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,e=31;e>0&&!(t&1<=0};he.isOdd=function(){return(this.low&1)===1};he.isEven=function(){return(this.low&1)===0};he.equals=function(t){return yt(t)||(t=hn(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};he.eq=he.equals;he.notEquals=function(t){return!this.eq(t)};he.neq=he.notEquals;he.ne=he.notEquals;he.lessThan=function(t){return this.comp(t)<0};he.lt=he.lessThan;he.lessThanOrEqual=function(t){return this.comp(t)<=0};he.lte=he.lessThanOrEqual;he.le=he.lessThanOrEqual;he.greaterThan=function(t){return this.comp(t)>0};he.gt=he.greaterThan;he.greaterThanOrEqual=function(t){return this.comp(t)>=0};he.gte=he.greaterThanOrEqual;he.ge=he.greaterThanOrEqual;he.compare=function(t){if(yt(t)||(t=hn(t)),this.eq(t))return 0;var e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};he.comp=he.compare;he.negate=function(){return!this.unsigned&&this.eq(Et)?Et:this.not().add(Ui)};he.neg=he.negate;he.add=function(t){yt(t)||(t=hn(t));var e=this.high>>>16,n=this.high&65535,r=this.low>>>16,o=this.low&65535,s=t.high>>>16,u=t.high&65535,c=t.low>>>16,m=t.low&65535,y=0,d=0,l=0,a=0;return a+=o+m,l+=a>>>16,a&=65535,l+=r+c,d+=l>>>16,l&=65535,d+=n+u,y+=d>>>16,d&=65535,y+=e+s,y&=65535,Ke(l<<16|a,y<<16|d,this.unsigned)};he.subtract=function(t){return yt(t)||(t=hn(t)),this.add(t.neg())};he.sub=he.subtract;he.multiply=function(t){if(this.isZero())return this;if(yt(t)||(t=hn(t)),Ht){var e=Ht.mul(this.low,this.high,t.low,t.high);return Ke(e,Ht.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Wr:an;if(this.eq(Et))return t.isOdd()?Et:an;if(t.eq(Et))return this.isOdd()?Et:an;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Al)&&t.lt(Al))return Wt(this.toNumber()*t.toNumber(),this.unsigned);var n=this.high>>>16,r=this.high&65535,o=this.low>>>16,s=this.low&65535,u=t.high>>>16,c=t.high&65535,m=t.low>>>16,y=t.low&65535,d=0,l=0,a=0,p=0;return p+=s*y,a+=p>>>16,p&=65535,a+=o*y,l+=a>>>16,a&=65535,a+=s*m,l+=a>>>16,a&=65535,l+=r*y,d+=l>>>16,l&=65535,l+=o*m,d+=l>>>16,l&=65535,l+=s*c,d+=l>>>16,l&=65535,d+=n*y+r*m+o*c+s*u,d&=65535,Ke(a<<16|p,d<<16|l,this.unsigned)};he.mul=he.multiply;he.divide=function(t){if(yt(t)||(t=hn(t)),t.isZero())throw Error("division by zero");if(Ht){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?Ht.div_u:Ht.div_s)(this.low,this.high,t.low,t.high);return Ke(e,Ht.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Wr:an;var n,r,o;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Wr;if(t.gt(this.shru(1)))return hu;o=Wr}else{if(this.eq(Et)){if(t.eq(Ui)||t.eq(da))return Et;if(t.eq(Et))return Ui;var s=this.shr(1);return n=s.div(t).shl(1),n.eq(an)?t.isNegative()?Ui:da:(r=this.sub(t.mul(n)),o=n.add(r.div(t)),o)}else if(t.eq(Et))return this.unsigned?Wr:an;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();o=an}for(r=this;r.gte(t);){n=Math.max(1,Math.floor(r.toNumber()/t.toNumber()));for(var u=Math.ceil(Math.log(n)/Math.LN2),c=u<=48?1:bs(2,u-48),m=Wt(n),y=m.mul(t);y.isNegative()||y.gt(r);)n-=c,m=Wt(n,this.unsigned),y=m.mul(t);m.isZero()&&(m=Ui),o=o.add(m),r=r.sub(y)}return o};he.div=he.divide;he.modulo=function(t){if(yt(t)||(t=hn(t)),Ht){var e=(this.unsigned?Ht.rem_u:Ht.rem_s)(this.low,this.high,t.low,t.high);return Ke(e,Ht.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};he.mod=he.modulo;he.rem=he.modulo;he.not=function(){return Ke(~this.low,~this.high,this.unsigned)};he.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};he.clz=he.countLeadingZeros;he.countTrailingZeros=function(){return this.low?ml(this.low):ml(this.high)+32};he.ctz=he.countTrailingZeros;he.and=function(t){return yt(t)||(t=hn(t)),Ke(this.low&t.low,this.high&t.high,this.unsigned)};he.or=function(t){return yt(t)||(t=hn(t)),Ke(this.low|t.low,this.high|t.high,this.unsigned)};he.xor=function(t){return yt(t)||(t=hn(t)),Ke(this.low^t.low,this.high^t.high,this.unsigned)};he.shiftLeft=function(t){return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?Ke(this.low<>>32-t,this.unsigned):Ke(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):Ke(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};he.shr=he.shiftRight;he.shiftRightUnsigned=function(t){return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?Ke(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?Ke(this.high,0,this.unsigned):Ke(this.high>>>t-32,0,this.unsigned)};he.shru=he.shiftRightUnsigned;he.shr_u=he.shiftRightUnsigned;he.rotateLeft=function(t){var e;return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?Ke(this.high,this.low,this.unsigned):t<32?(e=32-t,Ke(this.low<>>e,this.high<>>e,this.unsigned)):(t-=32,e=32-t,Ke(this.high<>>e,this.low<>>e,this.unsigned))};he.rotl=he.rotateLeft;he.rotateRight=function(t){var e;return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?Ke(this.high,this.low,this.unsigned):t<32?(e=32-t,Ke(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,e=32-t,Ke(this.low<>>t,this.high<>>t,this.unsigned))};he.rotr=he.rotateRight;he.toSigned=function(){return this.unsigned?Ke(this.low,this.high,!1):this};he.toUnsigned=function(){return this.unsigned?this:Ke(this.low,this.high,!0)};he.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};he.toBytesLE=function(){var t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};he.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]};Ve.fromBytes=function(t,e,n){return n?Ve.fromBytesLE(t,e):Ve.fromBytesBE(t,e)};Ve.fromBytesLE=function(t,e){return new Ve(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)};Ve.fromBytesBE=function(t,e){return new Ve(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)};var ft=(i=>(i[i.Null=0]="Null",i[i.Boolean=1]="Boolean",i[i.Integer=2]="Integer",i[i.Long=3]="Long",i[i.Double=4]="Double",i[i.String=5]="String",i[i.Bytes=6]="Bytes",i[i.Date=7]="Date",i))(ft||{});class et extends Eo{constructor(e,n){super(n);T(this,"valueType");T(this,"value");this.valueType=et.getPrimitiveType(e),this.value=e===void 0?null:e}static of(e,n){return new et(e,n)}static valueFromBytes(e,n){switch(e){case 0:return null;case 1:return!!n[0];case 2:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 4:{const r=new DataView(n.buffer);return n.forEach(function(o,s){r.setUint8(s,o)}),r.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(n);case 3:return Ve.fromBytesLE(Array.from(n));case 6:return n;case 7:return new Date(Ve.fromBytesLE(Array.from(n),!0).toNumber());default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return this.valueType===5?`"${Fn(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const e=et.of(this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e.setRemovedAt(this.getRemovedAt()),e}getType(){return this.valueType}static getPrimitiveType(e){switch(typeof e){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(e)?2:4;case"string":return 5;case"object":if(e===null)return 0;if(e instanceof Ve)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return et.getPrimitiveType(e)!==void 0}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===2||e===3||e===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 4:{const e=this.value,n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,e,!0),n}case 5:return new TextEncoder().encode(this.value);case 3:{const n=this.value.toBytesLE();return Uint8Array.from(n)}case 6:return this.value;case 7:{const e=this.value,n=Ve.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(n)}default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class ws extends cu{constructor(e){super(e);T(this,"prev");T(this,"next");this.value=e}static createAfter(e,n){const r=new ws(n),o=e.next;return e.next=r,r.prev=e,r.next=o,o&&(o.prev=r),r}remove(e){return this.value.remove(e)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class bo{constructor(){T(this,"dummyHead");T(this,"last");T(this,"nodeMapByIndex");T(this,"nodeMapByCreatedAt");const t=et.of(0,un);t.setRemovedAt(un),this.dummyHead=new ws(t),this.last=this.dummyHead,this.nodeMapByIndex=new vo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new bo}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,e){let n=this.nodeMapByCreatedAt.get(t.toIDString());if(!n)throw new ne(te.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);for(;n.getNext()&&n.getNext().getPositionedAt().after(e);)n=n.getNext();return n}release(t){this.last===t&&(this.last=t.getPrev()),t.release(),this.nodeMapByIndex.delete(t),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}insertAfter(t,e,n=e.getCreatedAt()){const r=this.findNextBeforeExecutedAt(t,n),o=ws.createAfter(r,e);r===this.last&&(this.last=o),this.nodeMapByIndex.insertAfter(r,o),this.nodeMapByCreatedAt.set(o.getCreatedAt().toIDString(),o)}moveAfter(t,e,n){const r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new ne(te.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const o=this.nodeMapByCreatedAt.get(e.toIDString());if(!o)throw new ne(te.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);r!==o&&(!o.getValue().getMovedAt()||n.after(o.getValue().getMovedAt()))&&(this.release(o),this.insertAfter(r.getCreatedAt(),o.getValue(),n),o.getValue().setMovedAt(n))}insert(t){this.insertAfter(this.last.getCreatedAt(),t)}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}subPathOf(t){const e=this.nodeMapByCreatedAt.get(t.toIDString());if(e)return String(this.nodeMapByIndex.indexOf(e))}purge(t){const e=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!e)throw new ne(te.ErrInvalidArgument,`fail to find the given createdAt: ${t.getCreatedAt().toIDString()}`);this.release(e)}getByIndex(t){if(t>=this.length)return;const[e,n]=this.nodeMapByIndex.find(t);let r=e;if(t===0&&e===this.dummyHead||n>0)do r&&(r=r.getNext());while(r&&r.isRemoved());return r}getPrevCreatedAt(t){let e=this.nodeMapByCreatedAt.get(t.toIDString());do e=e.getPrev();while(this.dummyHead!==e&&e.isRemoved());return e.getValue().getCreatedAt()}delete(t,e){const n=this.nodeMapByCreatedAt.get(t.toIDString()),r=n.isRemoved();return n.remove(e)&&!r&&this.nodeMapByIndex.splayNode(n),n.getValue()}deleteByIndex(t,e){const n=this.getByIndex(t);if(n)return n.remove(e)&&this.nodeMapByIndex.splayNode(n),n.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const t=[];for(const e of this){const n=`${e.getCreatedAt().toIDString()}:${e.getValue().toJSON()}`;e.isRemoved()?t.push(`{${n}}`):t.push(`[${n}]`)}return t.join("")}*[Symbol.iterator](){let t=this.dummyHead.getNext();for(;t;)yield t,t=t.getNext()}}class Rt extends hi{constructor(e,n){super(e);T(this,"elements");this.elements=n}static create(e,n){if(!n)return new Rt(e,bo.create());const r=bo.create();for(const o of n)r.insertAfter(r.getLastCreatedAt(),o.deepcopy());return new Rt(e,r)}subPathOf(e){return this.elements.subPathOf(e)}purge(e){this.elements.purge(e)}insertAfter(e,n){this.elements.insertAfter(e,n)}moveAfter(e,n,r){this.elements.moveAfter(e,n,r)}get(e){const n=this.elements.getByIndex(e);return n==null?void 0:n.getValue()}getByID(e){const n=this.elements.getByID(e);return n==null?void 0:n.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(e){return this.elements.getPrevCreatedAt(e)}delete(e,n){return this.elements.delete(e,n)}deleteByIndex(e,n){return this.elements.deleteByIndex(e,n)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const e of this.elements)e.isRemoved()||(yield e.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(e){for(const n of this.elements){const r=n.getValue();if(e(r,this))return;r instanceof hi&&r.getDescendants(e)}}toJSON(){const e=[];for(const n of this)e.push(n.toJSON());return`[${e.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const e={};for(let n=0;n({...a,value:a.value?{attributes:$i(a.value.getAttributes()),content:a.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[m,l,y,[c,c]]}setStyle(e,n,r,o){const[,s]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,u]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),c=[],m=this.rgaTreeSplit.findBetween(u,s),y=new Map,d=[];for(const a of m){const p=a.getCreatedAt().getActorID(),b=o!=null&&o.size?o.has(p)?o.get(p):un:uo;if(a.canStyle(r,b)){const w=y.get(p),v=a.getCreatedAt();(!w||v.after(w))&&y.set(p,v),d.push(a)}}const l=[];for(const a of d){if(a.isRemoved())continue;const[p,b]=this.rgaTreeSplit.findIndexesFromRange(a.createPosRange());c.push({type:"style",actor:r.getActorID(),from:p,to:b,value:{attributes:$i(n)}});for(const[w,v]of Object.entries(n)){const[h]=a.getValue().setAttr(w,v,r);h!==void 0&&l.push({parent:a.getValue(),child:h})}}return[y,l,c]}indexRangeToPosRange(e,n){const r=this.rgaTreeSplit.indexToPos(e);return e===n?[r,r]:[r,this.rgaTreeSplit.indexToPos(n)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const e=[];for(const n of this.rgaTreeSplit)n.isRemoved()||e.push(n.getValue().toJSON());return`[${e.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const e=[];for(const n of this.rgaTreeSplit)if(!n.isRemoved()){const r=n.getValue();e.push({attributes:$i(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const e=new Gt(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return e.remove(this.getRemovedAt()),e}findIndexesFromRange(e){return this.rgaTreeSplit.findIndexesFromRange(e)}getGCPairs(){const e=[];for(const n of this.rgaTreeSplit){n.getRemovedAt()&&e.push({parent:this.rgaTreeSplit,child:n});for(const r of n.getValue().getGCPairs())e.push(r)}return e}}class ko extends fn{constructor(e,n,r,o,s,u,c){super(e,c);T(this,"fromPos");T(this,"toPos");T(this,"maxCreatedAtMapByActor");T(this,"content");T(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.content=s,this.attributes=u}static create(e,n,r,o,s,u,c){return new ko(e,n,r,o,s,u,c)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Gt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,o,s]=r.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const u of s)e.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:m})=>({type:"edit",from:u,to:c,value:m,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),o=this.content;return`${e}.EDIT(${n},${r},${o})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Oo extends fn{constructor(e,n,r,o,s,u){super(e,u);T(this,"fromPos");T(this,"toPos");T(this,"maxCreatedAtMapByActor");T(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.attributes=s}static create(e,n,r,o,s,u){return new Oo(e,n,r,o,s,u)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Gt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,o,s]=r.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const u of o)e.registerGCPair(u);return{opInfos:s.map(({from:u,to:c,value:m})=>({type:"style",from:u,to:c,value:m,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),o=this.attributes;return`${e}.STYL(${n},${r},${JSON.stringify(o)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const xf=2,kf="root",Gr="text";function oo(i,t){let e=0;const n=i.children;for(let r=0;r0)throw new ne(te.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let t=this.parent;const e=this.isRemoved?-1:1;for(;t&&(t.size+=this.paddedSize*e,!t.isRemoved);)t=t.parent}updateDescendantsSize(){let t=0;for(const e of this._children){const n=e.updateDescendantsSize();e.isRemoved||(t+=n)}return this.size+=t,this.paddedSize}get isText(){return this.type===Gr}get paddedSize(){return this.size+(this.isText?0:xf)}isAncestorOf(t){return If(this,t)}get nextSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t+1];if(e)return e}get prevSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t-1];if(e)return e}splitText(t,e){if(t===0||t===this.size)return;const n=this.value.slice(0,t),r=this.value.slice(t);if(!r.length)return;this.value=n;const o=this.cloneText(t+e);return o.value=r,this.parent.insertAfterInternal(o,this),o}get children(){return this._children.filter(t=>!t.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(t=>t.isText)}append(...t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this._children.push(...t);for(const e of t)e.parent=this,e.updateAncestorsSize()}prepend(...t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this._children.unshift(...t);for(const e of t)e.parent=this}insertBefore(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new ne(te.ErrInvalidArgument,"child not found");this.insertAtInternal(t,n),t.updateAncestorsSize()}insertAfter(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new ne(te.ErrInvalidArgument,"child not found");this.insertAtInternal(t,n+1),t.updateAncestorsSize()}insertAt(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,e),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const e=this._children.indexOf(t);if(e===-1)throw new ne(te.ErrInvalidArgument,"child not found");this._children.splice(e,1),t.parent=void 0}splitElement(t,e){const n=this.cloneElement(e);this.parent.insertAfterInternal(n,this),n.updateAncestorsSize();const r=this.children.slice(0,t),o=this.children.slice(t);this._children=r,n._children=o,this.size=this._children.reduce((s,u)=>s+u.paddedSize,0),n.size=n._children.reduce((s,u)=>s+u.paddedSize,0);for(const s of n._children)s.parent=n;return n}insertAfterInternal(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new ne(te.ErrInvalidArgument,"child not found");this.insertAtInternal(t,n+1)}insertAtInternal(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this._children.splice(e,0,t),t.parent=this}findOffset(t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");if(t.isRemoved){const e=this._children.indexOf(t);return this.allChildren.splice(0,e).filter(r=>!r.isRemoved).length}return this.children.indexOf(t)}findBranchOffset(t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");let e=t;for(;e;){const n=this._children.indexOf(e);if(n!==-1)return n;e=e.parent}return-1}}function If(i,t){if(i===t)return!1;for(;t.parent;){if(t.parent===i)return!0;t=t.parent}return!1}var ut=(i=>(i.Start="Start",i.End="End",i.Text="Text",i))(ut||{});function pu(i,t,e,n){if(t>e)throw new ne(te.ErrInvalidArgument,`from is greater than to: ${t} > ${e}`);if(t>i.size)throw new ne(te.ErrInvalidArgument,`from is out of range: ${t} > ${i.size}`);if(e>i.size)throw new ne(te.ErrInvalidArgument,`to is out of range: ${e} > ${i.size}`);if(t===e)return;let r=0;for(const o of i.children){if(t-o.paddedSizeo.size;(o.isText||c)&&n([o,o.isText?"Text":"Start"],m),pu(o,Math.max(0,s),Math.min(u,o.size),n),m&&n([o,"End"],m)}r+=o.paddedSize}}function mu(i,t,e=0){for(const n of i.children)mu(n,t,e+1);t(i,e)}function ks(i,t,e=0){for(const n of i._children)ks(n,t,e+1);t(i,e)}function ga(i,t,e=!0){if(t>i.size)throw new ne(te.ErrInvalidArgument,`index is out of range: ${t} > ${i.size}`);if(i.isText)return{node:i,offset:t};let n=0,r=0;for(const o of i.children){if(e&&o.isText&&o.size>=t-r)return ga(o,t-r,e);if(t===r)return{node:i,offset:n};if(!e&&o.paddedSize===t-r)return{node:i,offset:n+1};if(o.paddedSize>t-r)return ga(o,t-r-1,e);r+=o.paddedSize,n+=1}return{node:i,offset:n}}function yu(i){return i.isText||i.children.length===0?i:yu(i.children[0])}function Nf(i,t){if(i.sizei===t?0:i0)if(e.right)e.right.parent=e,e=e.right;else return e;else if(n<0)if(e.left)e.left.parent=e,e=e.left;else{let r=e.parent,o=e;for(;r&&o===r.left;)o=r,r=r.parent;return r}else return e}}lastEntry(){if(!this.root)return this.root;let t=this.root;for(;t.right;)t=t.right;return t}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(t,e){for(;e;){const n=this.comparator(t,e.key);if(n===0)return e;n<0?e=e.left:n>0&&(e=e.right)}}putInternal(t,e,n){if(!n)return this.counter+=1,new Cf(t,e,!0);const r=this.comparator(t,n.key);return r<0?n.left=this.putInternal(t,e,n.left):r>0?n.right=this.putInternal(t,e,n.right):n.value=e,this.isRed(n.right)&&!this.isRed(n.left)&&(n=this.rotateLeft(n)),this.isRed(n.left)&&this.isRed(n.left.left)&&(n=this.rotateRight(n)),this.isRed(n.left)&&this.isRed(n.right)&&this.flipColors(n),n}removeInternal(t,e){if(this.comparator(e,t.key)<0)!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeInternal(t.left,e);else{if(this.isRed(t.left)&&(t=this.rotateRight(t)),this.comparator(e,t.key)===0&&!t.right){this.counter-=1;return}if(!this.isRed(t.right)&&!this.isRed(t.right.left)&&(t=this.moveRedRight(t)),this.comparator(e,t.key)===0){this.counter-=1;const n=this.min(t.right);t.value=n.value,t.key=n.key,t.right=this.removeMin(t.right)}else t.right=this.removeInternal(t.right,e)}return this.fixUp(t)}min(t){return t.left?this.min(t.left):t}removeMin(t){if(t.left)return!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeMin(t.left),this.fixUp(t)}fixUp(t){return this.isRed(t.right)&&(t=this.rotateLeft(t)),this.isRed(t.left)&&this.isRed(t.left.left)&&(t=this.rotateRight(t)),this.isRed(t.left)&&this.isRed(t.right)&&this.flipColors(t),t}moveRedLeft(t){return this.flipColors(t),this.isRed(t.right.left)&&(t.right=this.rotateRight(t.right),t=this.rotateLeft(t),this.flipColors(t)),t}moveRedRight(t){return this.flipColors(t),this.isRed(t.left.left)&&(t=this.rotateRight(t),this.flipColors(t)),t}isRed(t){return t&&t.isRed}rotateLeft(t){const e=t.right;return t.right=e.left,e.left=t,e.isRed=e.left.isRed,e.left.isRed=!0,e}rotateRight(t){const e=t.left;return t.left=e.right,e.right=t,e.isRed=e.right.isRed,e.right.isRed=!0,e}flipColors(t){t.isRed=!t.isRed,t.left.isRed=!t.left.isRed,t.right.isRed=!t.right.isRed}}class ln{constructor(t,e){T(this,"parentID");T(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=e}static of(t,e){return new ln(t,e)}static fromTreePos(t){const{offset:e}=t;let{node:n}=t,r;return n.isText?(n.parent.children[0]===n&&e===0?r=n.parent:r=n,n=n.parent):e===0?r=n:r=n.children[e-1],ln.of(n.id,pt.of(r.getCreatedAt(),r.getOffset()+e))}getParentID(){return this.parentID}static fromStruct(t){return ln.of(pt.of(Lt.fromStruct(t.parentID.createdAt),t.parentID.offset),pt.of(Lt.fromStruct(t.leftSiblingID.createdAt),t.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(t){const e=this.getParentID(),n=this.getLeftSiblingID(),r=t.findFloorNode(e);let o=t.findFloorNode(n);if(!r||!o)throw new ne(te.ErrRefused,`cannot find node of CRDTTreePos(${e.toTestString()}, ${n.toTestString()})`);return!n.equals(e)&&n.getOffset()>0&&n.getOffset()===o.id.getOffset()&&o.insPrevID&&(o=t.findFloorNode(o.insPrevID)),[r,o]}getLeftSiblingID(){return this.leftSiblingID}equals(t){return this.getParentID().getCreatedAt().equals(t.getParentID().getCreatedAt())&&this.getParentID().getOffset()===t.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(t.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===t.getLeftSiblingID().getOffset()}}class pt{constructor(t,e){T(this,"createdAt");T(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new pt(t,e)}static fromStruct(t){return pt.of(Lt.fromStruct(t.createdAt),t.offset)}static createComparator(){return(t,e)=>{const n=t.getCreatedAt().compare(e.getCreatedAt());return n!==0?n:t.getOffset()>e.getOffset()?1:t.getOffset(){const o=r.deepcopy();return o.parent=e,o}),e.insPrevID=this.insPrevID,e.insNextID=this.insNextID,e}get value(){if(!this.isText)throw new ne(te.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(e){if(!this.isText)throw new ne(te.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=e,this.size=e.length}get isRemoved(){return!!this.removedAt}remove(e){const n=!this.removedAt;(!this.removedAt||this.removedAt.compare(e)>0)&&(this.removedAt=e),n&&this.updateAncestorsSize()}cloneText(e){return new Ct(pt.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new Ct(pt.of(e(),0),this.type,void 0,void 0,this.removedAt)}split(e,n,r){const o=this.isText?this.splitText(n,this.id.getOffset()):this.splitElement(n,r);if(o){if(o.insPrevID=this.id,this.insNextID){const s=e.findFloorNode(this.insNextID);s.insPrevID=o.id,o.insNextID=this.insNextID}this.insNextID=o.id,e.registerNode(o)}return o}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(e,n){return!this.getCreatedAt().after(n)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,n){return this.isText?!1:!this.getCreatedAt().after(n)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,n){this.attrs||(this.attrs=new Xr);const r=new Array;for(const[o,s]of Object.entries(e))r.push(this.attrs.set(o,s,n));return r}purge(e){this.attrs&&this.attrs.purge(e)}getGCPairs(){const e=[];if(!this.attrs)return e;for(const n of this.attrs)n.getRemovedAt()&&e.push({parent:this,child:n});return e}}function pa(i){var e;if(i.isText){const n=i;return{type:n.type,value:n.value}}const t={type:i.type,children:i.children.map(pa)};return i.attrs&&(t.attributes=$i((e=i.attrs)==null?void 0:e.toObject())),t}function Ea(i){if(i.isText)return i.value;let t="";return i.attrs&&i.attrs.size()&&(t=" "+Array.from(i.attrs).filter(e=>!e.isRemoved()).sort((e,n)=>e.getKey().localeCompare(n.getKey())).map(e=>{const n=JSON.parse(e.getValue());return typeof n=="string"?`${e.getKey()}="${n}"`:`${e.getKey()}="${Fn(e.getValue())}"`}).join(" ")),`<${i.type}${t}>${i.children.map(e=>Ea(e)).join("")}`}function bu(i){if(i.isText){const t=i;return{type:t.type,value:t.value,size:t.size,isRemoved:t.isRemoved}}return{type:i.type,children:i.children.map(bu),size:i.size,isRemoved:i.isRemoved}}class Yt extends Eo{constructor(e,n){super(n);T(this,"indexTree");T(this,"nodeMapByID");this.indexTree=new _f(e),this.nodeMapByID=new vu(pt.createComparator()),this.indexTree.traverseAll(r=>{this.nodeMapByID.put(r.id,r)})}static create(e,n){return new Yt(e,n)}findFloorNode(e){const n=this.nodeMapByID.floorEntry(e);if(!(!n||!n.key.getCreatedAt().equals(e.getCreatedAt())))return n.value}registerNode(e){this.nodeMapByID.put(e.id,e)}findNodesAndSplitText(e,n){const[r,o]=e.toTreeNodePair(this);let s=o;const u=r===s,c=s.parent&&!u?s.parent:r;if(s.isText&&s.split(this,e.getLeftSiblingID().getOffset()-s.id.getOffset()),n){const m=c.allChildren,y=u?0:m.indexOf(s)+1;for(let d=y;d{const b=p.getCreatedAt().getActorID(),w=o?o.has(b)?o.get(b):un:uo;if(p.canStyle(r,w)&&n){const v=l.get(b),h=p.getCreatedAt();(!v||h.after(v))&&l.set(b,h);const g=p.setAttrs(n,r),f=g.reduce((E,[,O])=>(O&&(E[O.getKey()]=d[O.getKey()]),E),{}),A=p.parent,S=p.prevSibling||p.parent;Object.keys(f).length>0&&y.push({type:"style",from:this.toIndex(A,S),to:this.toIndex(p,p),fromPath:this.toPath(A,S),toPath:this.toPath(p,p),actor:r.getActorID(),value:f});for(const[E]of g)E&&a.push({parent:p,child:E})}}),[l,a,y]}removeStyle(e,n,r,o){const[s,u]=this.findNodesAndSplitText(e[0],r),[c,m]=this.findNodesAndSplitText(e[1],r),y=[],d=new Map,l=[];return this.traverseInPosRange(s,u,c,m,([a])=>{const p=a.getCreatedAt().getActorID(),b=o?o.has(p)?o.get(p):un:uo;if(a.canStyle(r,b)&&n){const w=d.get(p),v=a.getCreatedAt();(!w||v.after(w))&&d.set(p,v),a.attrs||(a.attrs=new Xr);for(const f of n){const A=a.attrs.remove(f,r);for(const S of A)l.push({parent:a,child:S})}const h=a.parent,g=a.prevSibling||a.parent;y.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(h,g),to:this.toIndex(a,a),fromPath:this.toPath(h,g),toPath:this.toPath(a,a),value:n})}}),[d,l,y]}edit(e,n,r,o,s,u){const[c,m]=this.findNodesAndSplitText(e[0],o),[y,d]=this.findNodesAndSplitText(e[1],o),l=this.toIndex(c,m),a=this.toPath(c,m),p=[],b=[],w=[],v=new Map;this.traverseInPosRange(c,m,y,d,([f,A],S)=>{if(A===ut.Start&&!S)for(const P of f.children)w.push(P);const E=f.getCreatedAt().getActorID(),O=u?u.has(E)?u.get(E):un:uo;if(f.canDelete(o,O)||p.includes(f.parent)){const P=v.get(E),k=f.getCreatedAt();(!P||k.after(P))&&v.set(E,k),(A===ut.Text||A===ut.Start)&&p.push(f),b.push([f,A])}});const h=this.makeDeletionChanges(b,o),g=[];for(const f of p)f.remove(o),f.isRemoved&&g.push({parent:this,child:f});for(const f of w)f.removedAt||c.append(f);if(r>0){let f=0,A=c,S=m;for(;f{c.isRemoved&&(E.remove(o),g.push({parent:this,child:E})),this.nodeMapByID.put(E.id,E)}),S.isRemoved||f.push(S);if(f.length){const S=f.map(E=>pa(E));h.length&&h[h.length-1].from===l?h[h.length-1].value=S:h.push({type:"content",from:l,to:l,fromPath:a,toPath:a,actor:o.getActorID(),value:S})}}return[h,g,v]}editT(e,n,r,o,s){const u=this.findPos(e[0]),c=this.findPos(e[1]);this.edit([u,c],n,r,o,s)}move(e,n,r){throw new ne(te.ErrUnimplemented,`not implemented: ${e}, ${n}, ${r}`)}purge(e){var o;(o=e.parent)==null||o.removeChild(e),this.nodeMapByID.remove(e.id);const n=e.insPrevID,r=e.insNextID;if(n){const s=this.findFloorNode(n);s.insNextID=r}if(r){const s=this.findFloorNode(r);s.insPrevID=n}e.insPrevID=void 0,e.insNextID=void 0}getGCPairs(){const e=[];return this.indexTree.traverse(n=>{n.getRemovedAt()&&e.push({parent:this,child:n});for(const r of n.getGCPairs())e.push(r)}),e}findPos(e,n=!0){const r=this.indexTree.findTreePos(e,n);return ln.fromTreePos(r)}pathToPosRange(e){const n=this.pathToIndex(e);return[this.findPos(n),this.findPos(n+1)]}pathToPos(e){const n=this.indexTree.pathToIndex(e);return this.findPos(n)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Ea(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const e=this.indexTree.getRoot(),n=(r,o=void 0,s=void 0,u=0)=>{var a,p,b,w;let c,m,y;const d=r.isText?{node:r,offset:0}:o&&s?this.toTreePos(o,s):null;d&&(c=this.indexTree.indexOf(d),m=this.indexTree.treePosToPath(d),y=ln.fromTreePos(d).toStruct());const l={type:r.type,parent:o==null?void 0:o.id.toTestString(),size:r.size,id:r.id.toTestString(),removedAt:(a=r.removedAt)==null?void 0:a.toTestString(),insPrev:(p=r.insPrevID)==null?void 0:p.toTestString(),insNext:(b=r.insNextID)==null?void 0:b.toTestString(),value:r.isText?r.value:void 0,isRemoved:r.isRemoved,children:[],depth:u,attributes:r.attrs?$i((w=r.attrs)==null?void 0:w.toObject()):void 0,index:c,path:m,pos:y};for(let v=0;v0&&v===r[r.length-1].to?(r[r.length-1].to=h,r[r.length-1].toPath=this.toPath(w,a)):r.push({type:"content",from:v,to:h,fromPath:this.toPath(b,d),toPath:this.toPath(w,a),actor:n.getActorID()}))}return r.reverse()}findRightToken([e,n]){if(n===ut.Start){const c=e.allChildren;return c.length>0?[c[0],c[0].isText?ut.Text:ut.Start]:[e,ut.End]}const r=e.parent,o=r.allChildren,s=o.indexOf(e);if(r&&s===o.length-1)return[r,ut.End];const u=o[s+1];return[u,u.isText?ut.Text:ut.Start]}findLeftToken([e,n]){if(n===ut.End){const c=e.allChildren;if(c.length>0){const m=c[c.length-1];return[m,m.isText?ut.Text:ut.End]}return[e,ut.Start]}const r=e.parent,o=r.allChildren,s=o.indexOf(e);if(r&&s===0)return[r,ut.Start];const u=o[s-1];return[u,u.isText?ut.Text:ut.End]}}class Io extends fn{constructor(e,n,r,o,s,u,c){super(e,c);T(this,"fromPos");T(this,"toPos");T(this,"contents");T(this,"splitLevel");T(this,"maxCreatedAtMapByActor");this.fromPos=n,this.toPos=r,this.contents=o,this.splitLevel=s,this.maxCreatedAtMapByActor=u}static create(e,n,r,o,s,u,c){return new Io(e,n,r,o,s,u,c)}execute(e){var c;const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Yt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=this.getExecutedAt(),o=n,[s,u]=o.edit([this.fromPos,this.toPos],(c=this.contents)==null?void 0:c.map(m=>m.deepcopy()),this.splitLevel,r,(()=>{let m=r.getDelimiter();return this.contents!==void 0&&(m+=this.contents.length),()=>Lt.of(r.getLamport(),++m,r.getActorID())})(),this.maxCreatedAtMapByActor);for(const m of u)e.registerGCPair(m);return{opInfos:s.map(({from:m,to:y,value:d,splitLevel:l,fromPath:a,toPath:p})=>({type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:m,to:y,value:d,splitLevel:l,fromPath:a,toPath:p}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,o=this.contents||[];return`${e}.EDIT(${n},${r},${o.map(s=>Ea(s)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class zi{constructor(t){T(this,"vector");this.vector=t||new Map}set(t,e){this.vector.set(t,e)}get(t){return this.vector.get(t)}maxLamport(){let t=BigInt(0);for(const[,e]of this)e>t&&(t=e);return t}max(t){const e=new Map;for(const[n,r]of t){const o=this.vector.get(n),s=o&&o>r?o:r;e.set(n,s)}for(const[n,r]of this){const o=t.get(n),s=o&&o>r?o:r;e.set(n,s)}return new zi(e)}afterOrEqual(t){const e=this.vector.get(t.getActorID());return e===void 0?!1:e>=t.getLamport()}deepcopy(){const t=new Map;for(const[e,n]of this.vector)t.set(e,n);return new zi(t)}filter(t){const e=new Map;for(const[n]of t){const r=this.vector.get(n);r!==void 0&&e.set(n,r)}return new zi(e)}size(){return this.vector.size}*[Symbol.iterator](){for(const[t,e]of this.vector)yield[t,e]}}const Rf=new zi(new Map);class zr{constructor(t,e,n,r,o){T(this,"clientSeq");T(this,"serverSeq");T(this,"lamport");T(this,"actor");T(this,"versionVector");this.clientSeq=t,this.serverSeq=o,this.lamport=e,this.versionVector=r,this.actor=n}static of(t,e,n,r,o){return new zr(t,e,n,r,o)}next(){const t=this.versionVector.deepcopy();return t.set(this.actor,this.lamport+1n),new zr(this.clientSeq+1,this.lamport+1n,this.actor,t)}syncClocks(t){const e=t.lamport>this.lamport?t.lamport+1n:this.lamport+1n,n=this.versionVector.max(t.versionVector),r=new zr(this.clientSeq,e,this.actor,n);return r.versionVector.set(this.actor,e),r}setClocks(t,e){const n=t>this.lamport?t:this.lamport+1n,r=this.versionVector.max(e);return r.set(this.actor,n),zr.of(this.clientSeq,n,this.actor,r)}createTimeTicket(t){return Lt.of(this.lamport,t,this.actor)}setActor(t){return new zr(this.clientSeq,this.lamport,t,this.versionVector,this.serverSeq)}setVersionVector(t){return new zr(this.clientSeq,this.lamport,this.actor,t,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Df=new zr(0,0n,Aa,Rf);class Zi{constructor({id:t,operations:e,presenceChange:n,message:r}){T(this,"id");T(this,"operations");T(this,"presenceChange");T(this,"message");this.id=t,this.operations=e||[],this.presenceChange=n,this.message=r}static create({id:t,operations:e,presenceChange:n,message:r}){return new Zi({id:t,operations:e,presenceChange:n,message:r})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(t){for(const e of this.operations)e.setActor(t);this.id=this.id.setActor(t)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(t,e,n){const r=[],o=[];for(const s of this.operations){const u=s.execute(t,n);if(!u)continue;const{opInfos:c,reverseOp:m}=u;r.push(...c),m&&o.unshift(m)}return this.presenceChange&&(this.presenceChange.type===pi.Put?e.set(this.id.getActorID(),sn(this.presenceChange.presence)):e.delete(this.id.getActorID())),{opInfos:r,reverseOps:o}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:at.bytesToHex(at.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>at.bytesToHex(at.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:e,operations:n,presenceChange:r,message:o}=t;return Zi.create({id:at.bytesToChangeID(at.hexToBytes(e)),operations:n==null?void 0:n.map(s=>at.bytesToOperation(at.hexToBytes(s))),presenceChange:r,message:o})}}class Os{constructor(t,e,n,r,o,s,u){T(this,"documentKey");T(this,"checkpoint");T(this,"isRemoved");T(this,"changes");T(this,"snapshot");T(this,"minSyncedTicket");T(this,"versionVector");this.documentKey=t,this.checkpoint=e,this.isRemoved=n,this.changes=r,this.snapshot=s,this.minSyncedTicket=u,this.versionVector=o}static create(t,e,n,r,o,s,u){return new Os(t,e,n,r,o,s,u)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class Vi{constructor(t,e){T(this,"serverSeq");T(this,"clientSeq");this.serverSeq=t,this.clientSeq=e}static of(t,e){return new Vi(t,e)}increaseClientSeq(t){return t===0?this:new Vi(this.serverSeq,this.clientSeq+t)}forward(t){if(this.equals(t))return this;const e=this.serverSeq>t.serverSeq?this.serverSeq:t.serverSeq,n=Math.max(this.clientSeq,t.clientSeq);return Vi.of(e,n)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(t){return this.clientSeq===t.clientSeq&&this.serverSeq==t.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Bf=new Vi(0n,0);class jn{constructor(t,e){T(this,"createdAt");T(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new jn(t,e)}static fromStruct(t){return jn.of(Lt.fromStruct(t.createdAt),t.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(t){return this.createdAt.compare(t.createdAt)===0&&this.offset===t.offset}hasSameCreatedAt(t){return this.createdAt.compare(t.createdAt)===0}split(t){return new jn(this.createdAt,this.offset+t)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const Mf=jn.of(un,0);class cn{constructor(t,e){T(this,"id");T(this,"relativeOffset");this.id=t,this.relativeOffset=e}static of(t,e){return new cn(t,e)}static fromStruct(t){const e=jn.fromStruct(t.id);return cn.of(e,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return jn.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(t){return this.id.equals(t.id)?this.relativeOffset===t.relativeOffset:!1}}class di extends cu{constructor(e,n,r){super(n);T(this,"id");T(this,"removedAt");T(this,"prev");T(this,"next");T(this,"insPrev");T(this,"insNext");this.id=e,this.removedAt=r}static create(e,n){return new di(e,n)}static createComparator(){return(e,n)=>{const r=e.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:e.getOffset()>n.getOffset()?1:e.getOffset()0&&e.getID().getOffset()==t.getOffset()){if(!e.hasInsPrev())return e;e=e.getInsPrev()}return e}findFloorNode(t){const e=this.treeByID.floorEntry(t);if(e&&!(!e.key.equals(t)&&!e.key.hasSameCreatedAt(t)))return e.value}findBetween(t,e){const n=[];let r=t;for(;r&&r!==e;)n.push(r),r=r.getNext();return n}splitNode(t,e){if(e>t.getContentLength())throw new ne(te.ErrInvalidArgument,"offset should be less than or equal to length");if(e===0)return t;if(e===t.getContentLength())return t.getNext();const n=t.split(e);this.treeByIndex.updateWeight(n),this.insertAfter(t,n);const r=t.getInsNext();return r&&r.setInsPrev(n),n.setInsPrev(t),n}deleteNodes(t,e,n){if(!t.length)return[[],new Map,new Map];const[r,o]=this.filterNodes(t,e,n),s=new Map,u=new Map,c=this.makeChanges(o,e);for(const m of r){const y=m.getCreatedAt().getActorID();(!s.has(y)||m.getID().getCreatedAt().after(s.get(y)))&&s.set(y,m.getID().getCreatedAt()),u.set(m.getID().toIDString(),m),m.remove(e)}return this.deleteIndexNodes(o),[c,s,u]}filterNodes(t,e,n){const r=!!n,o=[],s=[],[u,c]=this.findEdgesOfCandidates(t);s.push(u);for(const m of t){const y=m.getCreatedAt().getActorID(),d=r?n.has(y)?n.get(y):un:uo;m.canDelete(e,d)?o.push(m):s.push(m)}return s.push(c),[o,s]}findEdgesOfCandidates(t){return[t[0].getPrev(),t[t.length-1].getNext()]}makeChanges(t,e){const n=[];let r,o;for(let s=0;si<0?Math.ceil(i):Math.floor(i);var Un=(i=>(i[i.IntegerCnt=0]="IntegerCnt",i[i.LongCnt=1]="LongCnt",i))(Un||{});class Dt extends Eo{constructor(e,n,r){super(r);T(this,"valueType");T(this,"value");switch(this.valueType=e,e){case 0:typeof n=="number"?n>Math.pow(2,31)-1||n<-Math.pow(2,31)?this.value=Ve.fromNumber(n).toInt():this.value=Tl(n):this.value=n.toInt();break;case 1:typeof n=="number"?this.value=Ve.fromNumber(n):this.value=n;break;default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${e}`)}}static create(e,n,r){return new Dt(e,n,r)}static valueFromBytes(e,n){switch(e){case 0:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 1:return Ve.fromBytesLE(Array.from(n));default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const e=Dt.create(this.valueType,this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e}getType(){return this.valueType}static getCounterType(e){switch(typeof e){case"object":return e instanceof Ve?1:void 0;case"number":return e>Math.pow(2,31)-1||e<-Math.pow(2,31)?1:0;default:return}}static isSupport(e){return!!Dt.getCounterType(e)}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===0||e===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 1:{const n=this.value.toBytesLE();return Uint8Array.from(n)}default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(e){function n(r){if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`)}return n(this),n(e),this.valueType===1?this.value=this.value.add(e.getValue()):e.getType()===ft.Long?this.value=this.value+e.getValue().toInt():this.value=Ve.fromNumber(this.value+Tl(e.getValue())).toInt(),this}}class Qi extends fn{constructor(e,n,r){super(e,r);T(this,"value");this.value=n}static create(e,n,r){return new Qi(e,n,r)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Dt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const r=n,o=this.value.deepcopy();return r.increase(o),{opInfos:[{type:"increase",path:e.createPath(this.getParentCreatedAt()),value:o.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const e=this.value.deepcopy(),r=e.getType()===ft.Long?e.getValue().multiply(-1):e.getValue()*-1;return Qi.create(this.getParentCreatedAt(),et.of(r,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Yr extends fn{constructor(e,n,r,o,s,u,c){super(e,c);T(this,"fromPos");T(this,"toPos");T(this,"maxCreatedAtMapByActor");T(this,"attributes");T(this,"attributesToRemove");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.attributes=s,this.attributesToRemove=u}static create(e,n,r,o,s,u){return new Yr(e,n,r,o,s,new Array,u)}static createTreeRemoveStyleOperation(e,n,r,o,s,u){return new Yr(e,n,r,o,new Map,s,u)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Yt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=n;let o,s;if(this.attributes.size){const u={};[...this.attributes].forEach(([c,m])=>u[c]=m),[,s,o]=r.style([this.fromPos,this.toPos],u,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const u=this.attributesToRemove;[,s,o]=r.removeStyle([this.fromPos,this.toPos],u,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const u of s)e.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:m,fromPath:y,toPath:d})=>({type:"tree-style",from:u,to:c,value:this.attributes.size?{attributes:m}:{attributesToRemove:m},fromPath:y,toPath:d,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${e}.STYLE(${n},${r},${Object.entries(this.attributes||{}).map(([o,s])=>`${o}:"${s}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function qf(i){const t=new wa,e=t.data;for(const[n,r]of Object.entries(i))e[n]=JSON.stringify(r);return t}function Ff(i){if(i.type===pi.Put)return new mo({type:Ni.PUT,presence:qf(i.presence)});if(i.type===pi.Clear)return new mo({type:Ni.CLEAR});throw new ne(te.ErrUnimplemented,"unimplemented type")}function jf(i){return new au({serverSeq:i.getServerSeq(),clientSeq:i.getClientSeq()})}function wu(i){return new Es({clientSeq:i.getClientSeq(),lamport:i.getLamport(),actorId:Da(i.getActorID()),versionVector:xa(i.getVersionVector())})}function ke(i){if(i)return new xe({lamport:i.getLamport(),delimiter:i.getDelimiter(),actorId:Da(i.getActorID())})}function xa(i){if(!i)return;const t=new xs;for(const[e,n]of i)t.vector[e]=BigInt(n.toString());return t}function Au(i){switch(i){case ft.Null:return Re.NULL;case ft.Boolean:return Re.BOOLEAN;case ft.Integer:return Re.INTEGER;case ft.Long:return Re.LONG;case ft.Double:return Re.DOUBLE;case ft.String:return Re.STRING;case ft.Bytes:return Re.BYTES;case ft.Date:return Re.DATE;default:throw new ne(te.ErrInvalidType,`unsupported type: ${i}`)}}function Tu(i){switch(i){case Un.IntegerCnt:return Re.INTEGER_CNT;case Un.LongCnt:return Re.LONG_CNT;default:throw new ne(te.ErrInvalidType,`unsupported type: ${i}`)}}function Ms(i){if(i instanceof xt)return new Mt({type:Re.JSON_OBJECT,createdAt:ke(i.getCreatedAt()),value:Du(i)});if(i instanceof Rt)return new Mt({type:Re.JSON_ARRAY,createdAt:ke(i.getCreatedAt()),value:yh(i)});if(i instanceof Gt)return new Mt({type:Re.TEXT,createdAt:ke(i.getCreatedAt())});if(i instanceof et)return new Mt({type:Au(i.getType()),createdAt:ke(i.getCreatedAt()),value:i.toBytes()});if(i instanceof Dt)return new Mt({type:Tu(i.getType()),createdAt:ke(i.getCreatedAt()),value:i.toBytes()});if(i instanceof Yt)return new Mt({type:Re.TREE,createdAt:ke(i.getCreatedAt()),value:bh(i)});throw new ne(te.ErrUnimplemented,"unimplemented element")}function Uf(i){return new go({createdAt:ke(i.getCreatedAt()),offset:i.getOffset()})}function Fo(i){return new Zr({createdAt:ke(i.getID().getCreatedAt()),offset:i.getID().getOffset(),relativeOffset:i.getRelativeOffset()})}function jo(i){return new Ii({parentId:co(i.getParentID()),leftSiblingId:co(i.getLeftSiblingID())})}function co(i){return new fi({createdAt:ke(i.getCreatedAt()),offset:i.getOffset()})}function Su(i){const t=new ba;if(i instanceof _i){const e=i,n=new ts;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.key=e.getKey(),n.value=Ms(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="set",t.body.value=n}else if(i instanceof xo){const e=i,n=new ns;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.prevCreatedAt=ke(e.getPrevCreatedAt()),n.value=Ms(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="add",t.body.value=n}else if(i instanceof ci){const e=i,n=new rs;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.prevCreatedAt=ke(e.getPrevCreatedAt()),n.createdAt=ke(e.getCreatedAt()),n.executedAt=ke(e.getExecutedAt()),t.body.case="move",t.body.value=n}else if(i instanceof mi){const e=i,n=new is;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.createdAt=ke(e.getCreatedAt()),n.executedAt=ke(e.getExecutedAt()),t.body.case="remove",t.body.value=n}else if(i instanceof ko){const e=i,n=new os;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=Fo(e.getFromPos()),n.to=Fo(e.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of e.getMaxCreatedAtMapByActor())r[s]=ke(u);n.content=e.getContent();const o=n.attributes;for(const[s,u]of e.getAttributes())o[s]=u;n.executedAt=ke(e.getExecutedAt()),t.body.case="edit",t.body.value=n}else if(i instanceof Oo){const e=i,n=new ss;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=Fo(e.getFromPos()),n.to=Fo(e.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of e.getMaxCreatedAtMapByActor())r[s]=ke(u);const o=n.attributes;for(const[s,u]of e.getAttributes())o[s]=u;n.executedAt=ke(e.getExecutedAt()),t.body.case="style",t.body.value=n}else if(i instanceof Qi){const e=i,n=new as;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.value=Ms(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="increase",t.body.value=n}else if(i instanceof Io){const e=i,n=new ls,r=n.createdAtMapByActor;for(const[o,s]of e.getMaxCreatedAtMapByActor())r[o]=ke(s);n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=jo(e.getFromPos()),n.to=jo(e.getToPos()),n.contents=Wf(e.getContents()),n.splitLevel=e.getSplitLevel(),n.executedAt=ke(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=n}else if(i instanceof Yr){const e=i,n=new us;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=jo(e.getFromPos()),n.to=jo(e.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of e.getMaxCreatedAtMapByActor())r[s]=ke(u);const o=e.getAttributesToRemove();if(o.length>0)n.attributesToRemove=o;else{const s=n.attributes;for(const[u,c]of e.getAttributes())s[u]=c}n.executedAt=ke(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=n}else throw new ne(te.ErrUnimplemented,"unimplemented operation");return t}function Jf(i){const t=[];for(const e of i)t.push(Su(e));return t}function $f(i){const t=new ou({id:wu(i.getID()),message:i.getMessage()});return i.hasOperations()&&(t.operations=Jf(i.getOperations())),i.hasPresenceChange()&&(t.presenceChange=Ff(i.getPresenceChange())),t}function zf(i){const t=[];for(const e of i)t.push($f(e));return t}function Vf(i){const t=[];for(const e of i)t.push(new su({key:e.getStrKey(),element:Oa(e.getValue())}));return t}function Kf(i){const t=[];for(const e of i)t.push(new ms({element:Oa(e.getValue())}));return t}function Hf(i){const t=[];for(const e of i){const n=new ys;n.id=Uf(e.getID()),n.value=e.getValue().getContent(),n.removedAt=ke(e.getRemovedAt());const r=n.attributes,o=e.getValue().getAttrs();for(const s of o){const u=new Wi;u.value=s.getValue(),u.updatedAt=ke(s.getUpdatedAt()),r[s.getKey()]=u}t.push(n)}return t}function Wf(i){const t=[];if(!i||!i.length)return t;for(const e of i)t.push(new vs({content:ka(e)}));return t}function Gf(i){const t={};for(const e of i)t[e.getKey()]=new Wi({value:e.getValue(),updatedAt:ke(e.getUpdatedAt()),isRemoved:e.isRemoved()});return t}function ka(i){if(!i)return[];const t=[];return ks(i,(e,n)=>{const r=new po({id:co(e.id),type:e.type,removedAt:ke(e.removedAt),depth:n});e.isText&&(r.value=e.value),e.insPrevID&&(r.insPrevId=co(e.insPrevID)),e.insNextID&&(r.insNextId=co(e.insNextID)),e.attrs&&(r.attributes=Gf(e.attrs)),t.push(r)}),t}function Yf(i){const t=new kt;return t.body.case="jsonObject",t.body.value=new cs({nodes:Vf(i.getRHT()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Eu(i){const t=new kt;return t.body.case="jsonArray",t.body.value=new fs({nodes:Kf(i.getElements()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Zf(i){const t=new kt;return t.body.case="primitive",t.body.value=new hs({type:Au(i.getType()),value:i.toBytes(),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Xf(i){const t=new kt;return t.body.case="text",t.body.value=new ds({nodes:Hf(i.getRGATreeSplit()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Qf(i){const t=new kt;return t.body.case="counter",t.body.value=new gs({type:Tu(i.getType()),value:i.toBytes(),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function xu(i){const t=new kt;return t.body.case="tree",t.body.value=new ps({nodes:ka(i.getRoot()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Oa(i){if(i instanceof xt)return Yf(i);if(i instanceof Rt)return Eu(i);if(i instanceof et)return Zf(i);if(i instanceof Gt)return Xf(i);if(i instanceof Dt)return Qf(i);if(i instanceof Yt)return xu(i);throw new ne(te.ErrUnimplemented,"unimplemented element")}function eh(i){return new Qr({documentKey:i.getDocumentKey(),checkpoint:jf(i.getCheckpoint()),isRemoved:i.getIsRemoved(),changes:zf(i.getChanges()),snapshot:i.getSnapshot(),versionVector:xa(i.getVersionVector()),minSyncedTicket:ke(i.getMinSyncedTicket())})}function Sl(i){const t=i.findDetails(mf);for(const e of t)if(e.metadata.code)return e.metadata.code;return""}function ku(i){return zr.of(i.clientSeq,BigInt(i.lamport),La(i.actorId),Ia(i.versionVector),BigInt(i.serverSeq))}function Ia(i){if(!i)return;const t=new zi;return Object.entries(i.vector).forEach(([e,n])=>{t.set(e,BigInt(n.toString()))}),t}function Ie(i){if(i)return Lt.of(BigInt(i.lamport),i.delimiter,La(i.actorId))}function Na(i){const t={};return Object.entries(i.data).forEach(([e,n])=>{t[e]=JSON.parse(n)}),t}function th(i){const t=i.type;if(t===Ni.PUT){const e=Na(i.presence);return{type:pi.Put,presence:e}}if(t===Ni.CLEAR)return{type:pi.Clear};throw new ne(te.ErrInvalidType,`unsupported type: ${t}`)}function nh(i){const t=new Map;return Object.entries(i).forEach(([e,n])=>{t.set(e,Na(n))}),t}function Ou(i){switch(i){case Re.NULL:return ft.Null;case Re.BOOLEAN:return ft.Boolean;case Re.INTEGER:return ft.Integer;case Re.LONG:return ft.Long;case Re.DOUBLE:return ft.Double;case Re.STRING:return ft.String;case Re.BYTES:return ft.Bytes;case Re.DATE:return ft.Date}throw new ne(te.ErrUnimplemented,`unimplemented value type: ${i}`)}function As(i){switch(i){case Re.INTEGER_CNT:return Un.IntegerCnt;case Re.LONG_CNT:return Un.LongCnt}throw new ne(te.ErrUnimplemented,`unimplemented value type: ${i}`)}function qs(i){switch(i.type){case Re.JSON_OBJECT:return i.value?Ru(i.value):xt.create(Ie(i.createdAt));case Re.JSON_ARRAY:return i.value?mh(i.value):Rt.create(Ie(i.createdAt));case Re.TEXT:return Gt.create(Xi.create(),Ie(i.createdAt));case Re.TREE:return vh(i.value);case Re.NULL:case Re.BOOLEAN:case Re.INTEGER:case Re.LONG:case Re.DOUBLE:case Re.STRING:case Re.BYTES:case Re.DATE:return et.of(et.valueFromBytes(Ou(i.type),i.value),Ie(i.createdAt));case Re.INTEGER_CNT:case Re.LONG_CNT:return Dt.create(As(i.type),Dt.valueFromBytes(As(i.type),i.value),Ie(i.createdAt))}}function Uo(i){return cn.of(jn.of(Ie(i.createdAt),i.offset),i.relativeOffset)}function Iu(i){return jn.of(Ie(i.createdAt),i.offset)}function rh(i){const t=wo.create(i.value);Object.entries(i.attributes).forEach(([n,r])=>{t.setAttr(n,r.value,Ie(r.updatedAt))});const e=di.create(Iu(i.id),t);return e.remove(Ie(i.removedAt)),e}function Mi(i){return ln.of(fo(i.parentId),fo(i.leftSiblingId))}function fo(i){return pt.of(Ie(i.createdAt),i.offset)}function ih(i){if(!i.length)return;const t=[];return i.forEach(e=>{const n=_a(e.content);t.push(n)}),t}function _a(i){if(i.length===0)return;const t=[];for(const r of i)t.push(sh(r));const e=t[t.length-1],n=new Map;n.set(i[t.length-1].depth,t[t.length-1]);for(let r=t.length-2;r>=0;r--)n.get(i[r].depth-1).prepend(t[r]),n.set(i[r].depth,t[r]);return e.updateDescendantsSize(),Yt.create(e,un).getRoot()}function oh(i){const t=Xr.create();for(const[e,n]of Object.entries(i))t.setInternal(e,n.value,Ie(n.updatedAt),n.isRemoved);return t}function sh(i){const t=fo(i.id),e=Ct.create(t,i.type),n=Object.entries(i.attributes);return e.isText?e.value=i.value:n.length&&(e.attrs=oh(i.attributes)),i.insPrevId&&(e.insPrevID=fo(i.insPrevId)),i.insNextId&&(e.insNextID=fo(i.insNextId)),e.removedAt=Ie(i.removedAt),e}function Nu(i){if(i.body.case==="set"){const t=i.body.value;return _i.create(t.key,qs(t.value),Ie(t.parentCreatedAt),Ie(t.executedAt))}else if(i.body.case==="add"){const t=i.body.value;return xo.create(Ie(t.parentCreatedAt),Ie(t.prevCreatedAt),qs(t.value),Ie(t.executedAt))}else if(i.body.case==="move"){const t=i.body.value;return ci.create(Ie(t.parentCreatedAt),Ie(t.prevCreatedAt),Ie(t.createdAt),Ie(t.executedAt))}else if(i.body.case==="remove"){const t=i.body.value;return mi.create(Ie(t.parentCreatedAt),Ie(t.createdAt),Ie(t.executedAt))}else if(i.body.case==="edit"){const t=i.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([r,o])=>{e.set(r,Ie(o))});const n=new Map;return Object.entries(t.attributes).forEach(([r,o])=>{n.set(r,o)}),ko.create(Ie(t.parentCreatedAt),Uo(t.from),Uo(t.to),e,t.content,n,Ie(t.executedAt))}else if(i.body.case==="style"){const t=i.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([r,o])=>{e.set(r,Ie(o))});const n=new Map;return Object.entries(t.attributes).forEach(([r,o])=>{n.set(r,o)}),Oo.create(Ie(t.parentCreatedAt),Uo(t.from),Uo(t.to),e,n,Ie(t.executedAt))}else{if(i.body.case==="select")return;if(i.body.case==="increase"){const t=i.body.value;return Qi.create(Ie(t.parentCreatedAt),qs(t.value),Ie(t.executedAt))}else if(i.body.case==="treeEdit"){const t=i.body.value,e=new Map;return Object.entries(t.createdAtMapByActor).forEach(([n,r])=>{e.set(n,Ie(r))}),Io.create(Ie(t.parentCreatedAt),Mi(t.from),Mi(t.to),ih(t.contents),t.splitLevel,e,Ie(t.executedAt))}else if(i.body.case==="treeStyle"){const t=i.body.value,e=new Map,n=t.attributesToRemove,r=new Map;return t!=null&&t.createdAtMapByActor&&Object.entries(t.createdAtMapByActor).forEach(([o,s])=>{r.set(o,Ie(s))}),(n==null?void 0:n.length)>0?Yr.createTreeRemoveStyleOperation(Ie(t.parentCreatedAt),Mi(t.from),Mi(t.to),r,n,Ie(t.executedAt)):(Object.entries(t.attributes).forEach(([o,s])=>{e.set(o,s)}),Yr.create(Ie(t.parentCreatedAt),Mi(t.from),Mi(t.to),r,e,Ie(t.executedAt)))}else throw new ne(te.ErrUnimplemented,"unimplemented operation")}}function ah(i){const t=[];for(const e of i){const n=Nu(e);n&&t.push(n)}return t}function _u(i){const t=[];for(const e of i)t.push(Zi.create({id:ku(e.id),operations:ah(e.operations),presenceChange:e.presenceChange?th(e.presenceChange):void 0,message:e.message}));return t}function lh(i){return Vi.of(BigInt(i.serverSeq),i.clientSeq)}function uh(i){return Os.create(i.documentKey,lh(i.checkpoint),i.isRemoved,_u(i.changes),Ia(i.versionVector),i.snapshot,Ie(i.minSyncedTicket))}function Pu(i){const t=new yo;for(const n of i.nodes){const r=Pa(n.element);t.set(n.key,r,r.getPositionedAt())}const e=new xt(Ie(i.createdAt),t);return e.setMovedAt(Ie(i.movedAt)),e.setRemovedAt(Ie(i.removedAt)),e}function Cu(i){const t=new bo;for(const n of i.nodes)t.insert(Pa(n.element));const e=new Rt(Ie(i.createdAt),t);return e.setMovedAt(Ie(i.movedAt)),e.setRemovedAt(Ie(i.removedAt)),e}function ch(i){const t=et.of(et.valueFromBytes(Ou(i.type),i.value),Ie(i.createdAt));return t.setMovedAt(Ie(i.movedAt)),t.setRemovedAt(Ie(i.removedAt)),t}function fh(i){const t=new Xi;let e=t.getHead();for(const r of i.nodes){const o=t.insertAfter(e,rh(r));r.insPrevId&&o.setInsPrev(t.findNode(Iu(r.insPrevId))),e=o}const n=new Gt(t,Ie(i.createdAt));return n.setMovedAt(Ie(i.movedAt)),n.setRemovedAt(Ie(i.removedAt)),n}function hh(i){const t=Dt.create(As(i.type),Dt.valueFromBytes(As(i.type),i.value),Ie(i.createdAt));return t.setMovedAt(Ie(i.movedAt)),t.setRemovedAt(Ie(i.removedAt)),t}function Lu(i){const t=_a(i.nodes);return Yt.create(t,Ie(i.createdAt))}function Pa(i){if(i.body.case==="jsonObject")return Pu(i.body.value);if(i.body.case==="jsonArray")return Cu(i.body.value);if(i.body.case==="primitive")return ch(i.body.value);if(i.body.case==="text")return fh(i.body.value);if(i.body.case==="counter")return hh(i.body.value);if(i.body.case==="tree")return Lu(i.body.value);throw new ne(te.ErrUnimplemented,"unimplemented element")}function dh(i){if(!i)return{root:xt.create(un),presences:new Map};const t=zs.fromBinary(i);return{root:Pa(t.root),presences:nh(t.presences)}}function gh(i){const t=xa(i);return Ca(t.toBinary())}function ph(i){const t=Ra(i),e=xs.fromBinary(t);return Ia(e)}function Ru(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return Pu(t.body.value)}function Du(i){return Oa(i).toBinary()}function mh(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return Cu(t.body.value)}function yh(i){return Eu(i).toBinary()}function vh(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return Lu(t.body.value)}function bh(i){return xu(i).toBinary()}function Ca(i){return i?Array.from(i).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function La(i){return Ca(i)}function Ra(i){return new Uint8Array(i.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function Da(i){return Ra(i)}function wh(i){const t=Es.fromBinary(i);return ku(t)}function Ah(i){const t=ba.fromBinary(i);return Nu(t)}const at={fromPresence:Na,toChangePack:eh,fromChangePack:uh,fromChanges:_u,toTreeNodes:ka,fromTreeNodes:_a,objectToBytes:Du,bytesToObject:Ru,bytesToSnapshot:dh,bytesToHex:Ca,hexToBytes:Ra,toHexString:La,toUint8Array:Da,toOperation:Su,toChangeID:wu,PbChangeID:Es,bytesToChangeID:wh,bytesToOperation:Ah,versionVectorToHex:gh,hexToVersionVector:ph};var wt=(i=>(i[i.Trivial=0]="Trivial",i[i.Debug=1]="Debug",i[i.Info=2]="Info",i[i.Warn=3]="Warn",i[i.Error=4]="Error",i[i.Fatal=5]="Fatal",i))(wt||{});let bi=3;function Bu(i){bi=i}const Ne={trivial:(...i)=>{bi>0||typeof console<"u"&&console.log("YORKIE T:",...i)},debug:(...i)=>{bi>1||typeof console<"u"&&console.log("YORKIE D:",...i)},info:(...i)=>{bi>2||typeof console<"u"&&console.log("YORKIE I:",...i)},warn:(...i)=>{bi>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...i):console.log("YORKIE W:",...i))},error:(...i)=>{bi>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...i):console.log("YORKIE E:",...i))},fatal:(...i)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...i):console.log("YORKIE F:",...i))},isEnabled:i=>bi<=i};function Mu(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,i=>{const t=Math.random()*16|0;return(i==="x"?t:t&3|8).toString(16)})}class Th{constructor(t,e,n,r,o){T(this,"reconnectStreamDelay");T(this,"doc");T(this,"docID");T(this,"syncMode");T(this,"remoteChangeEventReceived");T(this,"watchStream");T(this,"watchLoopTimerID");T(this,"watchAbortController");T(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=t,this.doc=e,this.docID=n,this.syncMode=r,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=o}changeSyncMode(t){this.syncMode=t}needRealtimeSync(){return this.syncMode===Zo.RealtimeSyncOff?!1:this.syncMode===Zo.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Zo.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(t){const e=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await t(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(e,this.reconnectStreamDelay)})}catch{}};await e()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Fs=()=>{};class Sh{constructor(t){T(this,"finalized",!1);T(this,"observers",[]);T(this,"finalError");try{t(this)}catch(e){this.error(e)}}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,e,n){let r;if(!t)throw new ne(te.ErrInvalidArgument,"missing observer");if(this.finalized)throw new ne(te.ErrRefused,"observable is finalized due to previous error");typeof t=="object"?r=t:r={next:t,error:e,complete:n},r.next===void 0&&(r.next=Fs),r.error===void 0&&(r.error=Fs),r.complete===void 0&&(r.complete=Fs);const o=Mu(),s=this.unsubscribeOne.bind(this,o);if(this.observers.push({subscriptionID:o,observer:r}),this.finalized)try{this.finalError?r.error(this.finalError):r.complete()}catch(u){Ne.warn(u)}return s}unsubscribeOne(t){var e;this.observers=(e=this.observers)==null?void 0:e.filter(n=>n.subscriptionID!==t)}forEachObserver(t){if(!this.finalized)for(let e=0;et}}class Ji{constructor(t,e,n,r){T(this,"id");T(this,"delimiter");T(this,"message");T(this,"root");T(this,"operations");T(this,"presenceChange");T(this,"previousPresence");T(this,"reversePresenceKeys");this.id=t,this.delimiter=uu,this.root=e,this.operations=[],this.previousPresence=sn(n),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=r}static create(t,e,n,r){return new Ji(t,e,n,r)}push(t){this.operations.push(t)}registerElement(t,e){this.root.registerElement(t,e)}registerRemovedElement(t){this.root.registerRemovedElement(t)}registerGCPair(t){this.root.registerGCPair(t)}getChange(){return Zi.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(t){this.presenceChange=t}setReversePresence(t,e){for(const n of Object.keys(t))e!=null&&e.addToHistory?this.reversePresenceKeys.add(n):this.reversePresenceKeys.delete(n)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const t={};for(const e of this.reversePresenceKeys)t[e]=this.previousPresence[e];return t}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class Ao{constructor(t){T(this,"rootObject");T(this,"elementPairMapByCreatedAt");T(this,"gcElementSetByCreatedAt");T(this,"gcPairMap");this.rootObject=t,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(t,void 0),t.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof Gt||e instanceof Yt)for(const n of e.getGCPairs())this.registerGCPair(n);return!1})}static create(){return new Ao(xt.create(un))}findByCreatedAt(t){const e=this.elementPairMapByCreatedAt.get(t.toIDString());if(e)return e.element}findElementPairByCreatedAt(t){return this.elementPairMapByCreatedAt.get(t.toIDString())}createSubPaths(t){let e=this.elementPairMapByCreatedAt.get(t.toIDString());if(!e)return[];const n=[];for(;e.parent;){const r=e.element.getCreatedAt(),o=e.parent.subPathOf(r);if(o===void 0)throw new ne(te.ErrInvalidArgument,`cant find the given element: ${r.toIDString()}`);n.unshift(o),e=this.elementPairMapByCreatedAt.get(e.parent.getCreatedAt().toIDString())}return n.unshift("$"),n}createPath(t){return this.createSubPaths(t).join(".")}registerElement(t,e){this.elementPairMapByCreatedAt.set(t.getCreatedAt().toIDString(),{parent:e,element:t}),t instanceof hi&&t.getDescendants((n,r)=>(this.registerElement(n,r),!1))}deregisterElement(t){let e=0;const n=r=>{const o=r.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(o),this.gcElementSetByCreatedAt.delete(o),e++};return n(t),t instanceof hi&&t.getDescendants(r=>(n(r),!1)),e}registerRemovedElement(t){this.gcElementSetByCreatedAt.add(t.getCreatedAt().toIDString())}registerGCPair(t){if(this.gcPairMap.get(t.child.toIDString())){this.gcPairMap.delete(t.child.toIDString());return}this.gcPairMap.set(t.child.toIDString(),t)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const t=new Set;for(const e of this.gcElementSetByCreatedAt){t.add(e);const n=this.elementPairMapByCreatedAt.get(e);n.element instanceof hi&&n.element.getDescendants(r=>(t.add(r.getCreatedAt().toIDString()),!1))}return t.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new Ao(this.rootObject.deepcopy())}garbageCollect(t){let e=0;for(const n of this.gcElementSetByCreatedAt){const r=this.elementPairMapByCreatedAt.get(n),o=r.element.getRemovedAt();o&&(t!=null&&t.afterOrEqual(o))&&(r.parent.purge(r.element),e+=this.deregisterElement(r.element))}for(const[,n]of this.gcPairMap){const r=n.child.getRemovedAt();r&&(t!=null&&t.afterOrEqual(r))&&(n.parent.purge(n.child),this.gcPairMap.delete(n.child.toIDString()),e+=1)}return e}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function qu(i,t){const e=new To(i);return new Proxy(t,e.getHandlers())}class To{constructor(t){T(this,"context");T(this,"handlers");this.context=t,this.handlers={set:(e,n,r)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`obj[${n}]=${JSON.stringify(r)}`),To.setInternal(t,e,n,r),!0),get:(e,n)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`obj[${n}]`),n==="getID"?()=>e.getCreatedAt():n==="toJSON"||n==="toString"?()=>e.toJSON():n==="toJS"?()=>e.toJS():n==="toJSForTest"?()=>e.toJSForTest():wi(t,e.get(n))),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(e,n)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`obj[${n}]`),To.deleteInternal(t,e,n),!0)}}static setInternal(t,e,n,r){if(n.includes("."))throw new ne(te.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),s=Ts(t,r,o),u=e.set(n,s,o);t.registerElement(s,e),u&&t.registerRemovedElement(u),t.push(_i.create(n,s.deepcopy(),e.getCreatedAt(),o))}static buildObjectMembers(t,e){const n={};for(const[r,o]of Object.entries(e)){if(r.includes("."))throw new ne(te.ErrInvalidObjectKey,"key must not contain the '.'.");const s=t.issueTimeTicket(),u=Ts(t,o,s);n[r]=u}return n}static deleteInternal(t,e,n){const r=t.issueTimeTicket(),o=e.deleteByKey(n,r);o&&(t.push(mi.create(e.getCreatedAt(),o.getCreatedAt(),r)),t.registerRemovedElement(o))}getHandlers(){return this.handlers}}function xh(i,t){const e=new nt(i,t);return new Proxy(t,e.getHandlers())}function kh(i){return typeof i=="string"||i instanceof String?!isNaN(i):!1}function Oh(i){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(i)}class nt{constructor(t,e){T(this,"context");T(this,"handlers");T(this,"array");this.context=t,this.array=e,this.handlers={get:(n,r,o)=>r==="getID"?()=>n.getCreatedAt():r==="getElementByID"?s=>{const u=n.getByID(s);if(!(!u||u.isRemoved()))return oi(t,u)}:r==="getElementByIndex"?s=>{const u=n.get(s);return oi(t,u)}:r==="getLast"?()=>oi(t,n.getLast()):r==="deleteByID"?s=>{const u=nt.deleteInternalByID(t,n,s);return oi(t,u)}:r==="insertAfter"?(s,u)=>{const c=nt.insertAfterInternal(t,n,s,u);return oi(t,c)}:r==="insertBefore"?(s,u)=>{const c=nt.insertBeforeInternal(t,n,s,u);return oi(t,c)}:r==="moveBefore"?(s,u)=>{nt.moveBeforeInternal(t,n,s,u)}:r==="moveAfter"?(s,u)=>{nt.moveAfterInternal(t,n,s,u)}:r==="moveFront"?s=>{nt.moveFrontInternal(t,n,s)}:r==="moveLast"?s=>{nt.moveLastInternal(t,n,s)}:kh(r)?wi(t,n.get(Number(r))):r==="push"?s=>nt.pushInternal(t,n,s):r==="splice"?(s,u,...c)=>nt.splice(t,n,s,u,...c):r==="length"?n.length:typeof r=="symbol"&&r===Symbol.iterator?nt.iteratorInternal.bind(this,t,n):r==="includes"?(s,u)=>nt.includes(t,n,s,u):r==="indexOf"?(s,u)=>nt.indexOf(t,n,s,u):r==="lastIndexOf"?(s,u)=>nt.lastIndexOf(t,n,s,u):r==="toJSForTest"?()=>n.toJSForTest():r==="toTestString"?()=>nt.toTestString(n):typeof r=="string"&&Oh(r)?(...s)=>{const u=Array.from(n).map(c=>wi(t,c));return Array.prototype[r].apply(u,s)}:Reflect.get(n,r,o),deleteProperty:(n,r)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`array[${r}]`),nt.deleteInternalByIndex(t,n,Number.parseInt(r)),!0)}}static*iteratorInternal(t,e){for(const n of e)yield oi(t,n)}static buildArrayElements(t,e){const n=[];for(const r of e){const o=t.issueTimeTicket(),s=Ts(t,r,o);n.push(s)}return n}static pushInternal(t,e,n){return nt.insertAfterInternal(t,e,e.getLastCreatedAt(),n),e.length}static moveBeforeInternal(t,e,n,r){const o=t.issueTimeTicket(),s=e.getPrevCreatedAt(n);e.moveAfter(s,r,o),t.push(ci.create(e.getCreatedAt(),s,r,o))}static moveAfterInternal(t,e,n,r){const o=t.issueTimeTicket();e.moveAfter(n,r,o),t.push(ci.create(e.getCreatedAt(),n,r,o))}static moveFrontInternal(t,e,n){const r=t.issueTimeTicket(),o=e.getHead();e.moveAfter(o.getCreatedAt(),n,r),t.push(ci.create(e.getCreatedAt(),o.getCreatedAt(),n,r))}static moveLastInternal(t,e,n){const r=t.issueTimeTicket(),o=e.getLastCreatedAt();e.moveAfter(o,n,r),t.push(ci.create(e.getCreatedAt(),o,n,r))}static insertAfterInternal(t,e,n,r){const o=t.issueTimeTicket(),s=Ts(t,r,o);return e.insertAfter(n,s),t.registerElement(s,e),t.push(xo.create(e.getCreatedAt(),n,s.deepcopy(),o)),s}static insertBeforeInternal(t,e,n,r){return nt.insertAfterInternal(t,e,e.getPrevCreatedAt(n),r)}static deleteInternalByIndex(t,e,n){const r=t.issueTimeTicket(),o=e.deleteByIndex(n,r);if(o)return t.push(mi.create(e.getCreatedAt(),o.getCreatedAt(),r)),t.registerRemovedElement(o),o}static deleteInternalByID(t,e,n){const r=t.issueTimeTicket(),o=e.delete(n,r);return t.push(mi.create(e.getCreatedAt(),o.getCreatedAt(),r)),t.registerRemovedElement(o),o}static splice(t,e,n,r,...o){const s=e.length,u=n>=0?Math.min(n,s):Math.max(s+n,0),c=r===void 0?s:r<0?u:Math.min(u+r,s),m=[];for(let y=u;y=o)return!1;if(et.isSupport(n))return Array.from(e).map(m=>wi(t,m)).includes(n,s);for(let c=s;c=o)return-1;if(et.isSupport(n))return Array.from(e).map(m=>wi(t,m)).indexOf(n,s);for(let c=s;c=o?o-1:r<0?r+o:r;if(s<0)return-1;if(et.isSupport(n))return Array.from(e).map(m=>wi(t,m)).lastIndexOf(n,s);for(let c=s;c>0;c--)if(((u=e.get(c))==null?void 0:u.getID())===n.getID())return c;return-1}static toTestString(t){return t.toTestString()}getHandlers(){return this.handlers}}let Is=class{constructor(t,e){T(this,"context");T(this,"text");this.context=t,this.text=e}initialize(t,e){this.context=t,this.text=e}getID(){return this.text.getID()}edit(t,e,n,r){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const o=this.text.indexRangeToPosRange(t,e);Ne.isEnabled(wt.Debug)&&Ne.debug(`EDIT: f:${t}->${o[0].toTestString()}, t:${e}->${o[1].toTestString()} c:${n}`);const s=r?Gi(r):void 0,u=this.context.issueTimeTicket(),[c,,m,y]=this.text.edit(o,n,u,s);for(const d of m)this.context.registerGCPair(d);return this.context.push(new ko(this.text.getCreatedAt(),o[0],o[1],c,n,s?new Map(Object.entries(s)):new Map,u)),this.text.findIndexesFromRange(y)}delete(t,e){return this.edit(t,e,"")}empty(){return this.edit(0,this.length,"")}setStyle(t,e,n){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const r=this.text.indexRangeToPosRange(t,e);Ne.isEnabled(wt.Debug)&&Ne.debug(`STYL: f:${t}->${r[0].toTestString()}, t:${e}->${r[1].toTestString()} a:${JSON.stringify(n)}`);const o=Gi(n),s=this.context.issueTimeTicket(),[u,c]=this.text.setStyle(r,o,s);for(const m of c)this.context.registerGCPair(m);return this.context.push(new Oo(this.text.getCreatedAt(),r[0],r[1],u,new Map(Object.entries(o)),s)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");const e=this.text.indexRangeToPosRange(t[0],t[1]);return[e[0].toStruct(),e[1].toStruct()]}posRangeToIndexRange(t){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");const e=this.text.findIndexesFromRange([cn.fromStruct(t[0]),cn.fromStruct(t[1])]);return[e[0],e[1]]}toTestString(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,e){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,e)}};class Ns{constructor(t,e){T(this,"valueType");T(this,"value");T(this,"context");T(this,"counter");this.valueType=t,this.value=e}initialize(t,e){this.valueType=e.getValueType(),this.context=t,this.counter=e,this.value=e.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(t){if(!this.context||!this.counter)throw new ne(te.ErrNotInitialized,"Counter is not initialized yet");const e=this.context.issueTimeTicket(),n=et.of(t,e);if(!n.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof n.getValue()}`);return this.counter.increase(n),this.context.push(Qi.create(this.counter.getCreatedAt(),n,e)),this}toJSForTest(){if(!this.context||!this.counter)throw new ne(te.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function Ba(i,t,e){const{type:n}=i,r=e.issueTimeTicket();if(n===Gr){Fu(i);const{value:o}=i,s=Ct.create(pt.of(r,0),n,o);t.append(s)}else{const{children:o=[]}=i,{attributes:s}=i;let u;if(typeof s=="object"&&!lu(s)){const m=Gi(s);u=new Xr;for(const[y,d]of Object.entries(m))u.set(y,d,r)}const c=Ct.create(pt.of(r,0),n,void 0,u);t.append(c);for(const m of o)Ba(m,c,e)}}function Ih(i,t){const{type:e}=t,n=i.issueTimeTicket();let r;if(t.type===Gr){const{value:o}=t;r=Ct.create(pt.of(n,0),e,o)}else if(t){const{children:o=[]}=t,{attributes:s}=t;let u;if(typeof s=="object"&&!lu(s)){const c=Gi(s);u=new Xr;for(const[m,y]of Object.entries(c))u.set(m,y,n)}r=Ct.create(pt.of(i.issueTimeTicket(),0),e,void 0,u);for(const c of o)Ba(c,r,i)}return r}function Fu(i){if(!i.value.length)throw new ne(te.ErrInvalidArgument,"text node cannot have empty value");return!0}function El(i){if(!i.length)return!0;if(i[0].type===Gr)for(const e of i){const{type:n}=e;if(n!==Gr)throw new ne(te.ErrInvalidArgument,"element node and text node cannot be passed together");Fu(e)}else for(const e of i){const{type:n}=e;if(n===Gr)throw new ne(te.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class _s{constructor(t){T(this,"initialRoot");T(this,"context");T(this,"tree");this.initialRoot=t}initialize(t,e){this.context=t,this.tree=e}getID(){return this.tree.getID()}buildRoot(t){if(!this.initialRoot)return Ct.create(pt.of(t.issueTimeTicket(),0),kf);const e=Ct.create(pt.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const n of this.initialRoot.children)Ba(n,e,t);return e}getSize(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,e){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new ne(te.ErrInvalidArgument,"path should not be empty");const[n,r]=this.tree.pathToPosRange(t),o=this.context.issueTimeTicket(),s=e?Gi(e):void 0,[u]=this.tree.style([n,r],s,o);this.context.push(Yr.create(this.tree.getCreatedAt(),n,r,u,s?new Map(Object.entries(s)):new Map,o))}style(t,e,n){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(t),o=this.tree.findPos(e),s=this.context.issueTimeTicket(),u=n?Gi(n):void 0,[c,m]=this.tree.style([r,o],u,s);for(const y of m)this.context.registerGCPair(y);this.context.push(Yr.create(this.tree.getCreatedAt(),r,o,c,u?new Map(Object.entries(u)):new Map,s))}removeStyle(t,e,n){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(t),o=this.tree.findPos(e),s=this.context.issueTimeTicket(),[u,c]=this.tree.removeStyle([r,o],n,s);for(const m of c)this.context.registerGCPair(m);this.context.push(Yr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),r,o,u,n,s))}editInternal(t,e,n,r=0){var m;if(n.length!==0&&n[0]&&(El(n),n[0].type!==Gr))for(const y of n){const{children:d=[]}=y;El(d)}const o=this.context.getLastTimeTicket();let s=new Array;if(((m=n[0])==null?void 0:m.type)===Gr){let y="";for(const d of n){const{value:l}=d;y+=l}s.push(Ct.create(pt.of(this.context.issueTimeTicket(),0),Gr,y))}else s=n.map(y=>y&&Ih(this.context,y)).filter(y=>y);const[,u,c]=this.tree.edit([t,e],s.length?s.map(y=>y==null?void 0:y.deepcopy()):void 0,r,o,()=>this.context.issueTimeTicket());for(const y of u)this.context.registerGCPair(y);return this.context.push(Io.create(this.tree.getCreatedAt(),t,e,s.length?s:void 0,r,c,o)),!0}editByPath(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new ne(te.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new ne(te.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),s=this.tree.pathToPos(e);return this.editInternal(o,s,n?[n]:[],r)}editBulkByPath(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new ne(te.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new ne(te.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),s=this.tree.pathToPos(e);return this.editInternal(o,s,n,r)}edit(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),s=this.tree.findPos(e);return this.editInternal(o,s,n?[n]:[],r)}editBulk(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),s=this.tree.findPos(e);return this.editInternal(o,s,n,r)}toXML(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");const e=[this.tree.pathToIndex(t[0]),this.tree.pathToIndex(t[1])],n=this.tree.indexRangeToPosRange(e);return[n[0].toStruct(),n[1].toStruct()]}indexRangeToPosRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");const e=[ln.fromStruct(t[0]),ln.fromStruct(t[1])];return this.tree.posRangeToIndexRange(e)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");const e=[ln.fromStruct(t[0]),ln.fromStruct(t[1])];return this.tree.posRangeToPathRange(e)}}function xl(i,t){return qu(i,t)}function oi(i,t){if(t){if(t instanceof et)return t;if(t instanceof xt)return qu(i,t);if(t instanceof Rt)return xh(i,t);if(t instanceof Gt)return new Is(i,t);if(t instanceof Dt){const e=new Ns(Un.IntegerCnt,0);return e.initialize(i,t),e}else if(t instanceof Yt){const e=new _s;return e.initialize(i,t),e}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function wi(i,t){const e=oi(i,t);return e instanceof et?e.getValue():e}function Ts(i,t,e){let n;if(et.isSupport(t))n=et.of(t,e);else if(Array.isArray(t))n=Rt.create(e,nt.buildArrayElements(i,t));else if(typeof t=="object")t instanceof Is?(n=Gt.create(Xi.create(),e),t.initialize(i,n)):t instanceof Ns?(n=Dt.create(t.getValueType(),t.getValue(),e),t.initialize(i,n)):t instanceof _s?(n=Yt.create(t.buildRoot(i),e),t.initialize(i,n)):n=xt.create(e,To.buildObjectMembers(i,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return n}const kl=50;class Nh{constructor(){T(this,"undoStack",[]);T(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=kl&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=kl&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const _h="yorkie-devtools-panel",Ph="yorkie-devtools-sdk";let qi="disconnected";const Ol=new Map,Yo=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Yo);function Jo(i,t){(t!=null&&t.force||qi!=="disconnected")&&window.postMessage({source:Ph,...i},"*")}function Ch(i){if(!i.isEnableDevtools()||typeof window>"u"||Ol.has(i.getKey()))return;Yo.set(i.getKey(),[]);const t=i.subscribe("all",e=>{e.some(n=>n.type!==gt.StatusChanged&&n.type!==gt.Snapshot&&n.type!==gt.LocalChange&&n.type!==gt.RemoteChange&&n.type!==gt.Initialized&&n.type!==gt.Watched&&n.type!==gt.Unwatched&&n.type!==gt.PresenceChanged)||(Yo.get(i.getKey()).push(e),qi==="synced"&&Jo({msg:"doc::sync::partial",docKey:i.getKey(),event:e}))});Ol.set(i.getKey(),[t]),Jo({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.source)!==_h)return;switch(e.data.msg){case"devtools::connect":if(qi!=="disconnected")break;qi="connected",Jo({msg:"doc::available",docKey:i.getKey()}),Ne.info(`[YD] Devtools connected. Doc: ${i.getKey()}`);break;case"devtools::disconnect":qi="disconnected",Ne.info(`[YD] Devtools disconnected. Doc: ${i.getKey()}`);break;case"devtools::subscribe":qi="synced",Jo({msg:"doc::sync::full",docKey:i.getKey(),events:Yo.get(i.getKey())}),Ne.info(`[YD] Devtools subscribed. Doc: ${i.getKey()}`);break}})}var si=(i=>(i.Detached="detached",i.Attached="attached",i.Removed="removed",i))(si||{}),gt=(i=>(i.StatusChanged="status-changed",i.ConnectionChanged="connection-changed",i.SyncStatusChanged="sync-status-changed",i.Snapshot="snapshot",i.LocalChange="local-change",i.RemoteChange="remote-change",i.Initialized="initialized",i.Watched="watched",i.Unwatched="unwatched",i.PresenceChanged="presence-changed",i.Broadcast="broadcast",i.LocalBroadcast="local-broadcast",i))(gt||{}),So=(i=>(i.Connected="connected",i.Disconnected="disconnected",i))(So||{}),ma=(i=>(i.Synced="synced",i.SyncFailed="sync-failed",i))(ma||{});class ju{constructor(t,e){T(this,"key");T(this,"status");T(this,"opts");T(this,"changeID");T(this,"checkpoint");T(this,"localChanges");T(this,"root");T(this,"clone");T(this,"eventStream");T(this,"eventStreamObserver");T(this,"onlineClients");T(this,"presences");T(this,"history");T(this,"internalHistory");T(this,"isUpdating");this.opts=e||{},this.key=t,this.status="detached",this.root=Ao.create(),this.changeID=Df,this.checkpoint=Bf,this.localChanges=[],this.eventStream=Eh(n=>{this.eventStreamObserver=n}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new Nh,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},Ch(this)}update(t,e){if(this.getStatus()==="removed")throw new ne(te.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const n=this.changeID.getActorID(),r=Ji.create(this.changeID.next(),this.clone.root,this.clone.presences.get(n)||{},e);try{const o=xl(r,this.clone.root.getObject());this.presences.has(n)||this.clone.presences.set(n,{}),this.isUpdating=!0,t(o,new Bs(r,this.clone.presences.get(n)))}catch(o){throw this.clone=void 0,o}finally{this.isUpdating=!1}if(r.hasChange()){Ne.isEnabled(wt.Trivial)&&Ne.trivial(`trying to update a local change: ${this.toJSON()}`);const o=r.getChange(),{opInfos:s,reverseOps:u}=o.execute(this.root,this.presences,Ye.Local),c=r.getReversePresence();c&&u.push({type:"presence",value:c}),this.localChanges.push(o),u.length>0&&this.internalHistory.pushUndo(u),s.length>0&&this.internalHistory.clearRedo(),this.changeID=o.getID();const m=[];s.length>0&&m.push({type:"local-change",source:Ye.Local,value:{message:o.getMessage()||"",operations:s,actor:n,clientSeq:o.getID().getClientSeq(),serverSeq:o.getID().getServerSeq()},rawChange:this.isEnableDevtools()?o.toStruct():void 0}),o.hasPresenceChange()&&m.push({type:"presence-changed",source:Ye.Local,value:{clientID:n,presence:this.getPresence(n)}}),this.publish(m),Ne.isEnabled(wt.Trivial)&&Ne.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,e,n,r){if(typeof t=="string"){if(typeof e!="function")throw new ne(te.ErrInvalidArgument,"Second argument must be a callback function");if(t==="presence"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="initialized"&&m.type!=="watched"&&m.type!=="unwatched"&&m.type!=="presence-changed"||u(m)},n,r)}if(t==="my-presence"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="initialized"&&m.type!=="presence-changed"||m.type==="presence-changed"&&m.value.clientID!==this.changeID.getActorID()||u(m)},n,r)}if(t==="others"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="watched"&&m.type!=="unwatched"&&m.type!=="presence-changed"||m.value.clientID!==this.changeID.getActorID()&&u(m)},n,r)}if(t==="connection"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="connection-changed"&&u(m)},n,r)}if(t==="status"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="status-changed"&&u(m)},n,r)}if(t==="sync"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="sync-status-changed"&&u(m)},n,r)}if(t==="local-broadcast"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="local-broadcast"&&u(m)},n)}if(t==="broadcast"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="broadcast"&&u(m)},n)}if(t==="all"){const u=e;return this.eventStream.subscribe(u,n,r)}const o=t,s=e;return this.eventStream.subscribe(u=>{for(const c of u){if(c.type!=="local-change"&&c.type!=="remote-change")continue;const m=[];for(const y of c.value.operations)this.isSameElementOrChildOf(y.path,o)&&m.push(y);m.length&&s({...c,value:{...c.value,operations:m}})}},n,r)}if(typeof t=="function"){const o=t,s=e,u=n;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="snapshot"&&m.type!=="local-change"&&m.type!=="remote-change"||o(m)},s,u)}throw new ne(te.ErrInvalidArgument,`"${t}" is not a valid`)}publish(t){this.eventStreamObserver&&this.eventStreamObserver.next(t)}isSameElementOrChildOf(t,e){if(e===t)return!0;const n=t.split(".");return e.split(".").every((o,s)=>o===n[s])}applyChangePack(t){const e=t.hasSnapshot();for(e?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getVersionVector(),t.getSnapshot()):t.hasChanges()&&this.applyChanges(t.getChanges(),Ye.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t.getCheckpoint().getClientSeq());)this.localChanges.shift();e&&this.applyChanges(this.localChanges,Ye.Remote),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),e||this.garbageCollect(t.getVersionVector()),e||this.filterVersionVector(t.getVersionVector()),t.getIsRemoved()&&this.applyStatus("removed"),Ne.isEnabled(wt.Trivial)&&Ne.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:sn(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),e=this.checkpoint.increaseClientSeq(t.length);return Os.create(this.key,e,!1,t,this.getVersionVector())}setActor(t){for(const e of this.localChanges)e.setActor(t);this.changeID=this.changeID.setActor(t)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const t=Ji.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return xl(t,this.clone.root.getObject())}garbageCollect(t){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(t),this.root.garbageCollect(t))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,e,n){const{root:r,presences:o}=at.bytesToSnapshot(n);this.root=new Ao(r),this.presences=o,this.changeID=this.changeID.setClocks(t,e),this.clone=void 0,this.publish([{type:"snapshot",source:Ye.Remote,value:{serverSeq:t.toString(),snapshot:this.isEnableDevtools()?at.bytesToHex(n):void 0,snapshotVector:at.versionVectorToHex(e)}}])}applyChanges(t,e){Ne.isEnabled(wt.Debug)&&Ne.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),Ne.isEnabled(wt.Trivial)&&Ne.trivial(t.map(n=>`${n.getID().toTestString()} ${n.toTestString()}`).join(` -`));for(const n of t)this.applyChange(n,e);Ne.isEnabled(wt.Debug)&&Ne.debug(`after appling ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(t,e){this.ensureClone(),t.execute(this.clone.root,this.clone.presences,e);const n=[],r=t.getID().getActorID();if(t.hasPresenceChange()&&this.onlineClients.has(r)){const s=t.getPresenceChange();switch(s.type){case pi.Put:n.push(this.presences.has(r)?{type:"presence-changed",source:e,value:{clientID:r,presence:s.presence}}:{type:"watched",source:Ye.Remote,value:{clientID:r,presence:s.presence}});break;case pi.Clear:n.push({type:"unwatched",source:Ye.Remote,value:{clientID:r,presence:this.getPresence(r)}}),this.removeOnlineClient(r);break}}const{opInfos:o}=t.execute(this.root,this.presences,e);if(this.changeID=this.changeID.syncClocks(t.getID()),o.length>0){const s=this.isEnableDevtools()?t.toStruct():void 0;n.push(e===Ye.Remote?{type:"remote-change",source:e,value:{actor:r,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:s}:{type:"local-change",source:e,value:{actor:r,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:s})}n.length>0&&this.publish(n)}applyWatchStream(t){if(t.body.case==="initialization"){const e=t.body.value.clientIds,n=new Set;for(const r of e)r!==this.changeID.getActorID()&&n.add(r);this.setOnlineClients(n),this.publish([{type:"initialized",source:Ye.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:e,publisher:n}=t.body.value,r=[];if(e===Oi.DOCUMENT_WATCHED)this.addOnlineClient(n),this.hasPresence(n)&&r.push({type:"watched",source:Ye.Remote,value:{clientID:n,presence:this.getPresence(n)}});else if(e===Oi.DOCUMENT_UNWATCHED){const o=this.getPresence(n);this.removeOnlineClient(n),o&&r.push({type:"unwatched",source:Ye.Remote,value:{clientID:n,presence:o}})}else if(e===Oi.DOCUMENT_BROADCAST&&t.body.value.body){const{topic:o,payload:s}=t.body.value.body,u=new TextDecoder;r.push({type:"broadcast",value:{clientID:n,topic:o,payload:JSON.parse(u.decode(s))}})}r.length>0&&this.publish(r)}}applyStatus(t){this.status=t,t==="detached"&&this.setActor(Aa),this.publish([{source:t==="removed"?Ye.Remote:Ye.Local,type:"status-changed",value:t==="attached"?{status:t,actorID:this.changeID.getActorID()}:{status:t}}])}applyDocEvent(t){if(t.type==="status-changed"){this.applyStatus(t.value.status),t.value.status==="attached"&&this.setActor(t.value.actorID);return}if(t.type==="snapshot"){const{snapshot:e,serverSeq:n,snapshotVector:r}=t.value;if(!e)return;this.applySnapshot(BigInt(n),at.hexToVersionVector(r),at.hexToBytes(e));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const e=Zi.fromStruct(t.rawChange);this.applyChange(e,t.source)}if(t.type==="initialized"){const e=new Set;for(const{clientID:n,presence:r}of t.value)e.add(n),this.presences.set(n,r);this.setOnlineClients(e);return}if(t.type==="watched"){const{clientID:e,presence:n}=t.value;this.addOnlineClient(e),this.presences.set(e,n);return}if(t.type==="unwatched"){const{clientID:e}=t.value;this.removeOnlineClient(e),this.presences.delete(e)}if(t.type==="presence-changed"){const{clientID:e,presence:n}=t.value;this.presences.set(e,n)}}applyTransactionEvent(t){for(const e of t)this.applyDocEvent(e)}getValueByPath(t){if(!t.startsWith("$"))throw new ne(te.ErrInvalidArgument,'path must start with "$"');const e=t.split(".");e.shift();let n=this.getRoot();for(const r of e)if(n=n[r],n===void 0)return;return n}setOnlineClients(t){this.onlineClients=t}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(t){this.onlineClients.add(t)}removeOnlineClient(t){this.onlineClients.delete(t)}hasPresence(t){return this.presences.has(t)}getMyPresence(){if(this.status!=="attached")return{};const t=this.presences.get(this.changeID.getActorID());return t?sn(t):{}}getPresence(t){if(t===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(t))return;const e=this.presences.get(t);return e?sn(e):void 0}getPresenceForTest(t){const e=this.presences.get(t);return e?sn(e):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:sn(this.getMyPresence())});for(const e of this.onlineClients)this.presences.has(e)&&t.push({clientID:e,presence:sn(this.presences.get(e))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(e=>e.clientID!==t).sort((e,n)=>e.clientID>n.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(t){const n=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(n)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new ne(te.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new ne(te.ErrRefused,"There is no operation to be undone");this.ensureClone();const e=Ji.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of t){if(!(m instanceof fn)){new Bs(e,sn(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const y=e.issueTimeTicket();m.setExecutedAt(y),e.push(m)}const n=e.getChange();n.execute(this.clone.root,this.clone.presences,Ye.UndoRedo);const{opInfos:r,reverseOps:o}=n.execute(this.root,this.presences,Ye.UndoRedo),s=e.getReversePresence();if(s&&o.push({type:"presence",value:s}),o.length>0&&this.internalHistory.pushRedo(o),!n.hasPresenceChange()&&r.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const u=this.changeID.getActorID(),c=[];r.length>0&&c.push({type:"local-change",source:Ye.UndoRedo,value:{message:n.getMessage()||"",operations:r,actor:u,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&c.push({type:"presence-changed",source:Ye.UndoRedo,value:{clientID:u,presence:this.getPresence(u)}}),this.publish(c)}redo(){if(this.isUpdating)throw new ne(te.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new ne(te.ErrRefused,"There is no operation to be redone");this.ensureClone();const e=Ji.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of t){if(!(m instanceof fn)){new Bs(e,sn(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const y=e.issueTimeTicket();m.setExecutedAt(y),e.push(m)}const n=e.getChange();n.execute(this.clone.root,this.clone.presences,Ye.UndoRedo);const{opInfos:r,reverseOps:o}=n.execute(this.root,this.presences,Ye.UndoRedo),s=e.getReversePresence();if(s&&o.push({type:"presence",value:s}),o.length>0&&this.internalHistory.pushUndo(o),!n.hasPresenceChange()&&r.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const u=this.changeID.getActorID(),c=[];r.length>0&&c.push({type:"local-change",source:Ye.UndoRedo,value:{message:n.getMessage()||"",operations:r,actor:u,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&c.push({type:"presence-changed",source:Ye.UndoRedo,value:{clientID:u,presence:this.getPresence(u)}}),this.publish(c)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(t,e,n){const r={type:"local-broadcast",value:{topic:t,payload:e},options:n};this.publish([r])}getVersionVector(){return this.changeID.getVersionVector()}}function Lh(i,t){return e=>async n=>(i&&n.header.set("x-api-key",i),t&&n.header.set("authorization",t),await e(n))}const Rh="yorkie-js-sdk",Dh="0.5.4",Bh="Yorkie JS SDK",Mh="./src/yorkie.ts",qh={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},Fh=["dist"],jh={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},Uh={node:">=18.0.0",npm:">=7.1.0"},Jh={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},$h={name:"hackerwins",email:"susukang98@gmail.com"},zh="Apache-2.0",Vh={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},Kh="https://github.com/yorkie-team/yorkie-js-sdk#readme",Hh={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},Wh={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Il={name:Rh,version:Dh,description:Bh,main:Mh,publishConfig:qh,files:Fh,scripts:jh,engines:Uh,repository:Jh,author:$h,license:zh,bugs:Vh,homepage:Kh,devDependencies:Hh,dependencies:Wh};function Gh(){return i=>async t=>(t.header.set("x-yorkie-user-agent",Il.name+"/"+Il.version),await i(t))}const Yh=i=>{try{if(JSON.stringify(i)===void 0)return!1}catch{return!1}return!0};var Zo=(i=>(i.Manual="manual",i.Realtime="realtime",i.RealtimePushOnly="realtime-pushonly",i.RealtimeSyncOff="realtime-syncoff",i))(Zo||{});const $o={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},js={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Uu{constructor(t,e){T(this,"id");T(this,"key");T(this,"status");T(this,"attachmentMap");T(this,"apiKey");T(this,"conditions");T(this,"syncLoopDuration");T(this,"reconnectStreamDelay");T(this,"retrySyncLoopDelay");T(this,"rpcClient");T(this,"taskQueue");T(this,"processing",!1);e=e||$o,this.key=e.key?e.key:Mu(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=e.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=e.syncLoopDuration||$o.syncLoopDuration,this.reconnectStreamDelay=e.reconnectStreamDelay||$o.reconnectStreamDelay,this.retrySyncLoopDelay=e.retrySyncLoopDelay||$o.retrySyncLoopDelay,this.rpcClient=Vc(pf,gf({baseUrl:t,interceptors:[Lh(e.apiKey,e.token),Gh()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),Ne.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw Ne.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),Ne.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw Ne.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,e={}){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==si.Detached)throw new ne(te.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((o,s)=>s.set(e.initialPresence||{}));const n=t.subscribe("local-broadcast",async o=>{var y;const{topic:s,payload:u}=o.value,c=(y=o.options)==null?void 0:y.error,m=o.options;try{await this.broadcast(t.getKey(),s,u,m)}catch(d){d instanceof Error&&(c==null||c(d))}}),r=e.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:at.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const s=at.fromChangePack(o.changePack);if(t.applyChangePack(s),t.getStatus()===si.Removed)return t;t.applyStatus(si.Attached),this.attachmentMap.set(t.getKey(),new Th(this.reconnectStreamDelay,t,o.documentId,r,n)),r!=="manual"&&await this.runWatchLoop(t.getKey()),Ne.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const u=t.getRootObject();if(e.initialRoot){const c=e.initialRoot;t.update(m=>{for(const[y,d]of Object.entries(c))if(!u.has(y)){const l=y;m[l]=d}})}return t}).catch(o=>{throw Ne.error(`[AD] c:"${this.getKey()}" err :`,o),this.handleConnectError(o),o}))}detach(t,e={}){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((r,o)=>o.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:n.docID,changePack:at.toChangePack(t.createChangePack()),removeIfNotAttached:e.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(r=>{const o=at.fromChangePack(r.changePack);return t.applyChangePack(o),t.getStatus()!==si.Removed&&t.applyStatus(si.Detached),this.detachInternal(t.getKey()),Ne.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(r=>{throw Ne.error(`[DD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}async changeSyncMode(t,e){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const r=n.syncMode;return r===e?t:(n.changeSyncMode(e),e==="manual"?(n.cancelWatchStream(),t):(e==="realtime"&&(n.remoteChangeEventReceived=!0),r==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);if(t){const e=this.attachmentMap.get(t.getKey());if(!e)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(e,"realtime").catch(n=>{throw Ne.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n}))}return this.enqueueTask(async()=>{const e=[];for(const[,n]of this.attachmentMap)e.push(this.syncInternal(n,n.syncMode));return Promise.all(e).catch(n=>{throw Ne.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n})})}remove(t){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const e=this.attachmentMap.get(t.getKey());if(!e)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const n=at.toChangePack(t.createChangePack());return n.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:e.docID,changePack:n},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(r=>{const o=at.fromChangePack(r.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),Ne.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(r=>{throw Ne.error(`[RD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(t){return this.conditions[t]}broadcast(t,e,n,r){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const o=this.attachmentMap.get(t);if(!o)throw new ne(te.ErrDocumentNotAttached,`${t} is not attached`);if(!Yh(n))throw new ne(te.ErrInvalidArgument,"payload is not serializable");const s=(r==null?void 0:r.maxRetries)??js.maxRetries,u=js.maxBackoff;let c=0;const m=d=>Math.min(js.initialRetryInterval*2**d,u),y=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:o.docID,topic:e,payload:new TextEncoder().encode(JSON.stringify(n))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{Ne.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${e}"`)}).catch(d=>{if(Ne.error(`[BC] c:"${this.getKey()}" err:`,d),this.handleConnectError(d))if(cy(),m(c-1)),Ne.info(`[BC] c:"${this.getKey()}" retry attempt ${c}/${s}`);else throw Ne.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),d;else throw d}));return y()}runSyncLoop(){const t=()=>{if(!this.isActive()){Ne.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const e=[];for(const[,n]of this.attachmentMap)n.needRealtimeSync()&&(n.remoteChangeEventReceived=!1,e.push(this.syncInternal(n,n.syncMode)));Promise.all(e).then(()=>setTimeout(t,this.syncLoopDuration)).catch(n=>{Ne.error(`[SL] c:"${this.getKey()}" sync failed:`,n),this.handleConnectError(n)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};Ne.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,t()}async runWatchLoop(t){const e=this.attachmentMap.get(t);if(!e)throw new ne(te.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,e.runWatchLoop(n=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new ne(te.ErrClientNotActivated,`${this.key} is not active`));const r=new AbortController,o=this.rpcClient.watchDocument({clientId:this.id,documentId:e.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:r.signal});return e.doc.publish([{type:gt.ConnectionChanged,value:So.Connected}]),Ne.info(`[WD] c:"${this.getKey()}" watches d:"${t}"`),new Promise((s,u)=>{(async()=>{try{for await(const m of o)this.handleWatchDocumentsResponse(e,m),m.body.case==="initialization"&&s([o,r])}catch(m){e.doc.resetOnlineClients(),e.doc.publish([{type:gt.Initialized,source:Ye.Local,value:e.doc.getPresences()}]),e.doc.publish([{type:gt.ConnectionChanged,value:So.Disconnected}]),Ne.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(m)?n():this.conditions.WatchLoop=!1,u(m)}})()})})}handleWatchDocumentsResponse(t,e){if(e.body.case==="event"&&e.body.value.type===Oi.DOCUMENT_CHANGED){t.remoteChangeEventReceived=!0;return}t.doc.applyWatchStream(e)}deactivateInternal(){this.status="deactivated";for(const[t,e]of this.attachmentMap)this.detachInternal(t),e.doc.applyStatus(si.Detached)}detachInternal(t){const e=this.attachmentMap.get(t);e&&(e.cancelWatchStream(),e.unsubscribeBroadcastEvent(),this.attachmentMap.delete(t))}syncInternal(t,e){const{doc:n,docID:r}=t,o=n.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:r,changePack:at.toChangePack(o),pushOnly:e==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${n.getKey()}`}}).then(s=>{const u=at.fromChangePack(s.changePack);if(u.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return n;n.applyChangePack(u),t.doc.publish([{type:gt.SyncStatusChanged,value:ma.Synced}]),n.getStatus()===si.Removed&&this.detachInternal(n.getKey());const c=n.getKey(),m=u.getChangeSize();return Ne.info(`[PP] c:"${this.getKey()}" sync d:"${c}", push:${o.getChangeSize()} pull:${m} cp:${u.getCheckpoint().toTestString()}`),n}).catch(s=>{throw n.publish([{type:gt.SyncStatusChanged,value:ma.SyncFailed}]),Ne.error(`[PP] c:"${this.getKey()}" err :`,s),s})}handleConnectError(t){return t instanceof ct?t.code===Ge.Canceled||t.code===Ge.Unknown||t.code===Ge.ResourceExhausted||t.code===Ge.Unavailable?!0:((Sl(t)===te.ErrClientNotActivated||Sl(t)===te.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(t){return new Promise((e,n)=>{this.taskQueue.push(()=>t().then(e).catch(n)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{Ne.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Us={Client:Uu,Document:ju,Primitive:et,Text:Is,Counter:Ns,Tree:_s,LogLevel:wt,setLogLevel:Bu,IntType:Un.IntegerCnt,LongType:Un.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Uu,Document:ju,Primitive:et,Text:Is,Counter:Ns,Tree:_s,LogLevel:wt,setLogLevel:Bu,IntType:Un.IntegerCnt,LongType:Un.LongCnt});var Zh=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ju(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var $u={exports:{}};/*! +`));for(const n of t)this.applyChange(n,e);Ne.isEnabled(wt.Debug)&&Ne.debug(`after appling ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(t,e){this.ensureClone(),t.execute(this.clone.root,this.clone.presences,e);const n=[],r=t.getID().getActorID();if(t.hasPresenceChange()&&this.onlineClients.has(r)){const s=t.getPresenceChange();switch(s.type){case pi.Put:n.push(this.presences.has(r)?{type:"presence-changed",source:e,value:{clientID:r,presence:s.presence}}:{type:"watched",source:Ye.Remote,value:{clientID:r,presence:s.presence}});break;case pi.Clear:n.push({type:"unwatched",source:Ye.Remote,value:{clientID:r,presence:this.getPresence(r)}}),this.removeOnlineClient(r);break}}const{opInfos:o}=t.execute(this.root,this.presences,e);if(this.changeID=this.changeID.syncClocks(t.getID()),o.length>0){const s=this.isEnableDevtools()?t.toStruct():void 0;n.push(e===Ye.Remote?{type:"remote-change",source:e,value:{actor:r,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:s}:{type:"local-change",source:e,value:{actor:r,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:s})}n.length>0&&this.publish(n)}applyWatchStream(t){if(t.body.case==="initialization"){const e=t.body.value.clientIds,n=new Set;for(const r of e)r!==this.changeID.getActorID()&&n.add(r);this.setOnlineClients(n),this.publish([{type:"initialized",source:Ye.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:e,publisher:n}=t.body.value,r=[];if(e===Oi.DOCUMENT_WATCHED){if(this.onlineClients.has(n)&&this.hasPresence(n))return;this.addOnlineClient(n),this.hasPresence(n)&&r.push({type:"watched",source:Ye.Remote,value:{clientID:n,presence:this.getPresence(n)}})}else if(e===Oi.DOCUMENT_UNWATCHED){const o=this.getPresence(n);this.removeOnlineClient(n),o&&r.push({type:"unwatched",source:Ye.Remote,value:{clientID:n,presence:o}})}else if(e===Oi.DOCUMENT_BROADCAST&&t.body.value.body){const{topic:o,payload:s}=t.body.value.body,u=new TextDecoder;r.push({type:"broadcast",value:{clientID:n,topic:o,payload:JSON.parse(u.decode(s))}})}r.length>0&&this.publish(r)}}applyStatus(t){this.status=t,t==="detached"&&this.setActor(Aa),this.publish([{source:t==="removed"?Ye.Remote:Ye.Local,type:"status-changed",value:t==="attached"?{status:t,actorID:this.changeID.getActorID()}:{status:t}}])}applyDocEvent(t){if(t.type==="status-changed"){this.applyStatus(t.value.status),t.value.status==="attached"&&this.setActor(t.value.actorID);return}if(t.type==="snapshot"){const{snapshot:e,serverSeq:n,snapshotVector:r}=t.value;if(!e)return;this.applySnapshot(BigInt(n),at.hexToVersionVector(r),at.hexToBytes(e));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const e=Zi.fromStruct(t.rawChange);this.applyChange(e,t.source)}if(t.type==="initialized"){const e=new Set;for(const{clientID:n,presence:r}of t.value)e.add(n),this.presences.set(n,r);this.setOnlineClients(e);return}if(t.type==="watched"){const{clientID:e,presence:n}=t.value;this.addOnlineClient(e),this.presences.set(e,n);return}if(t.type==="unwatched"){const{clientID:e}=t.value;this.removeOnlineClient(e),this.presences.delete(e)}if(t.type==="presence-changed"){const{clientID:e,presence:n}=t.value;this.presences.set(e,n)}}applyTransactionEvent(t){for(const e of t)this.applyDocEvent(e)}getValueByPath(t){if(!t.startsWith("$"))throw new ne(te.ErrInvalidArgument,'path must start with "$"');const e=t.split(".");e.shift();let n=this.getRoot();for(const r of e)if(n=n[r],n===void 0)return;return n}setOnlineClients(t){this.onlineClients=t}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(t){this.onlineClients.add(t)}removeOnlineClient(t){this.onlineClients.delete(t)}hasPresence(t){return this.presences.has(t)}getMyPresence(){if(this.status!=="attached")return{};const t=this.presences.get(this.changeID.getActorID());return t?sn(t):{}}getPresence(t){if(t===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(t))return;const e=this.presences.get(t);return e?sn(e):void 0}getPresenceForTest(t){const e=this.presences.get(t);return e?sn(e):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:sn(this.getMyPresence())});for(const e of this.onlineClients)this.presences.has(e)&&t.push({clientID:e,presence:sn(this.presences.get(e))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(e=>e.clientID!==t).sort((e,n)=>e.clientID>n.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(t){const n=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(n)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new ne(te.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new ne(te.ErrRefused,"There is no operation to be undone");this.ensureClone();const e=Ji.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of t){if(!(m instanceof fn)){new Bs(e,sn(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const y=e.issueTimeTicket();m.setExecutedAt(y),e.push(m)}const n=e.getChange();n.execute(this.clone.root,this.clone.presences,Ye.UndoRedo);const{opInfos:r,reverseOps:o}=n.execute(this.root,this.presences,Ye.UndoRedo),s=e.getReversePresence();if(s&&o.push({type:"presence",value:s}),o.length>0&&this.internalHistory.pushRedo(o),!n.hasPresenceChange()&&r.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const u=this.changeID.getActorID(),c=[];r.length>0&&c.push({type:"local-change",source:Ye.UndoRedo,value:{message:n.getMessage()||"",operations:r,actor:u,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&c.push({type:"presence-changed",source:Ye.UndoRedo,value:{clientID:u,presence:this.getPresence(u)}}),this.publish(c)}redo(){if(this.isUpdating)throw new ne(te.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new ne(te.ErrRefused,"There is no operation to be redone");this.ensureClone();const e=Ji.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of t){if(!(m instanceof fn)){new Bs(e,sn(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const y=e.issueTimeTicket();m.setExecutedAt(y),e.push(m)}const n=e.getChange();n.execute(this.clone.root,this.clone.presences,Ye.UndoRedo);const{opInfos:r,reverseOps:o}=n.execute(this.root,this.presences,Ye.UndoRedo),s=e.getReversePresence();if(s&&o.push({type:"presence",value:s}),o.length>0&&this.internalHistory.pushUndo(o),!n.hasPresenceChange()&&r.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const u=this.changeID.getActorID(),c=[];r.length>0&&c.push({type:"local-change",source:Ye.UndoRedo,value:{message:n.getMessage()||"",operations:r,actor:u,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&c.push({type:"presence-changed",source:Ye.UndoRedo,value:{clientID:u,presence:this.getPresence(u)}}),this.publish(c)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(t,e,n){const r={type:"local-broadcast",value:{topic:t,payload:e},options:n};this.publish([r])}getVersionVector(){return this.changeID.getVersionVector()}}function Lh(i,t){return e=>async n=>(i&&n.header.set("x-api-key",i),t&&n.header.set("authorization",t),await e(n))}const Rh="yorkie-js-sdk",Dh="0.5.4",Bh="Yorkie JS SDK",Mh="./src/yorkie.ts",qh={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},Fh=["dist"],jh={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},Uh={node:">=18.0.0",npm:">=7.1.0"},Jh={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},$h={name:"hackerwins",email:"susukang98@gmail.com"},zh="Apache-2.0",Vh={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},Kh="https://github.com/yorkie-team/yorkie-js-sdk#readme",Hh={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},Wh={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Il={name:Rh,version:Dh,description:Bh,main:Mh,publishConfig:qh,files:Fh,scripts:jh,engines:Uh,repository:Jh,author:$h,license:zh,bugs:Vh,homepage:Kh,devDependencies:Hh,dependencies:Wh};function Gh(){return i=>async t=>(t.header.set("x-yorkie-user-agent",Il.name+"/"+Il.version),await i(t))}const Yh=i=>{try{if(JSON.stringify(i)===void 0)return!1}catch{return!1}return!0};var Zo=(i=>(i.Manual="manual",i.Realtime="realtime",i.RealtimePushOnly="realtime-pushonly",i.RealtimeSyncOff="realtime-syncoff",i))(Zo||{});const $o={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},js={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Uu{constructor(t,e){T(this,"id");T(this,"key");T(this,"status");T(this,"attachmentMap");T(this,"apiKey");T(this,"conditions");T(this,"syncLoopDuration");T(this,"reconnectStreamDelay");T(this,"retrySyncLoopDelay");T(this,"rpcClient");T(this,"taskQueue");T(this,"processing",!1);e=e||$o,this.key=e.key?e.key:Mu(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=e.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=e.syncLoopDuration||$o.syncLoopDuration,this.reconnectStreamDelay=e.reconnectStreamDelay||$o.reconnectStreamDelay,this.retrySyncLoopDelay=e.retrySyncLoopDelay||$o.retrySyncLoopDelay,this.rpcClient=Vc(pf,gf({baseUrl:t,interceptors:[Lh(e.apiKey,e.token),Gh()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),Ne.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw Ne.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),Ne.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw Ne.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,e={}){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==si.Detached)throw new ne(te.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((o,s)=>s.set(e.initialPresence||{}));const n=t.subscribe("local-broadcast",async o=>{var y;const{topic:s,payload:u}=o.value,c=(y=o.options)==null?void 0:y.error,m=o.options;try{await this.broadcast(t.getKey(),s,u,m)}catch(d){d instanceof Error&&(c==null||c(d))}}),r=e.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:at.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const s=at.fromChangePack(o.changePack);if(t.applyChangePack(s),t.getStatus()===si.Removed)return t;t.applyStatus(si.Attached),this.attachmentMap.set(t.getKey(),new Th(this.reconnectStreamDelay,t,o.documentId,r,n)),r!=="manual"&&await this.runWatchLoop(t.getKey()),Ne.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const u=t.getRootObject();if(e.initialRoot){const c=e.initialRoot;t.update(m=>{for(const[y,d]of Object.entries(c))if(!u.has(y)){const l=y;m[l]=d}})}return t}).catch(o=>{throw Ne.error(`[AD] c:"${this.getKey()}" err :`,o),this.handleConnectError(o),o}))}detach(t,e={}){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((r,o)=>o.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:n.docID,changePack:at.toChangePack(t.createChangePack()),removeIfNotAttached:e.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(r=>{const o=at.fromChangePack(r.changePack);return t.applyChangePack(o),t.getStatus()!==si.Removed&&t.applyStatus(si.Detached),this.detachInternal(t.getKey()),Ne.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(r=>{throw Ne.error(`[DD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}async changeSyncMode(t,e){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const r=n.syncMode;return r===e?t:(n.changeSyncMode(e),e==="manual"?(n.cancelWatchStream(),t):(e==="realtime"&&(n.remoteChangeEventReceived=!0),r==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);if(t){const e=this.attachmentMap.get(t.getKey());if(!e)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(e,"realtime").catch(n=>{throw Ne.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n}))}return this.enqueueTask(async()=>{const e=[];for(const[,n]of this.attachmentMap)e.push(this.syncInternal(n,n.syncMode));return Promise.all(e).catch(n=>{throw Ne.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n})})}remove(t){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const e=this.attachmentMap.get(t.getKey());if(!e)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const n=at.toChangePack(t.createChangePack());return n.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:e.docID,changePack:n},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(r=>{const o=at.fromChangePack(r.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),Ne.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(r=>{throw Ne.error(`[RD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(t){return this.conditions[t]}broadcast(t,e,n,r){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const o=this.attachmentMap.get(t);if(!o)throw new ne(te.ErrDocumentNotAttached,`${t} is not attached`);if(!Yh(n))throw new ne(te.ErrInvalidArgument,"payload is not serializable");const s=(r==null?void 0:r.maxRetries)??js.maxRetries,u=js.maxBackoff;let c=0;const m=d=>Math.min(js.initialRetryInterval*2**d,u),y=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:o.docID,topic:e,payload:new TextEncoder().encode(JSON.stringify(n))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{Ne.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${e}"`)}).catch(d=>{if(Ne.error(`[BC] c:"${this.getKey()}" err:`,d),this.handleConnectError(d))if(cy(),m(c-1)),Ne.info(`[BC] c:"${this.getKey()}" retry attempt ${c}/${s}`);else throw Ne.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),d;else throw d}));return y()}runSyncLoop(){const t=()=>{if(!this.isActive()){Ne.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const e=[];for(const[,n]of this.attachmentMap)n.needRealtimeSync()&&(n.remoteChangeEventReceived=!1,e.push(this.syncInternal(n,n.syncMode)));Promise.all(e).then(()=>setTimeout(t,this.syncLoopDuration)).catch(n=>{Ne.error(`[SL] c:"${this.getKey()}" sync failed:`,n),this.handleConnectError(n)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};Ne.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,t()}async runWatchLoop(t){const e=this.attachmentMap.get(t);if(!e)throw new ne(te.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,e.runWatchLoop(n=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new ne(te.ErrClientNotActivated,`${this.key} is not active`));const r=new AbortController,o=this.rpcClient.watchDocument({clientId:this.id,documentId:e.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:r.signal});return e.doc.publish([{type:gt.ConnectionChanged,value:So.Connected}]),Ne.info(`[WD] c:"${this.getKey()}" watches d:"${t}"`),new Promise((s,u)=>{(async()=>{try{for await(const m of o)this.handleWatchDocumentsResponse(e,m),m.body.case==="initialization"&&s([o,r])}catch(m){e.doc.resetOnlineClients(),e.doc.publish([{type:gt.Initialized,source:Ye.Local,value:e.doc.getPresences()}]),e.doc.publish([{type:gt.ConnectionChanged,value:So.Disconnected}]),Ne.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(m)?n():this.conditions.WatchLoop=!1,u(m)}})()})})}handleWatchDocumentsResponse(t,e){if(e.body.case==="event"&&e.body.value.type===Oi.DOCUMENT_CHANGED){t.remoteChangeEventReceived=!0;return}t.doc.applyWatchStream(e)}deactivateInternal(){this.status="deactivated";for(const[t,e]of this.attachmentMap)this.detachInternal(t),e.doc.applyStatus(si.Detached)}detachInternal(t){const e=this.attachmentMap.get(t);e&&(e.cancelWatchStream(),e.unsubscribeBroadcastEvent(),this.attachmentMap.delete(t))}syncInternal(t,e){const{doc:n,docID:r}=t,o=n.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:r,changePack:at.toChangePack(o),pushOnly:e==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${n.getKey()}`}}).then(s=>{const u=at.fromChangePack(s.changePack);if(u.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return n;n.applyChangePack(u),t.doc.publish([{type:gt.SyncStatusChanged,value:ma.Synced}]),n.getStatus()===si.Removed&&this.detachInternal(n.getKey());const c=n.getKey(),m=u.getChangeSize();return Ne.info(`[PP] c:"${this.getKey()}" sync d:"${c}", push:${o.getChangeSize()} pull:${m} cp:${u.getCheckpoint().toTestString()}`),n}).catch(s=>{throw n.publish([{type:gt.SyncStatusChanged,value:ma.SyncFailed}]),Ne.error(`[PP] c:"${this.getKey()}" err :`,s),s})}handleConnectError(t){return t instanceof ct?t.code===Ge.Canceled||t.code===Ge.Unknown||t.code===Ge.ResourceExhausted||t.code===Ge.Unavailable?!0:((Sl(t)===te.ErrClientNotActivated||Sl(t)===te.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(t){return new Promise((e,n)=>{this.taskQueue.push(()=>t().then(e).catch(n)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{Ne.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Us={Client:Uu,Document:ju,Primitive:et,Text:Is,Counter:Ns,Tree:_s,LogLevel:wt,setLogLevel:Bu,IntType:Un.IntegerCnt,LongType:Un.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Uu,Document:ju,Primitive:et,Text:Is,Counter:Ns,Tree:_s,LogLevel:wt,setLogLevel:Bu,IntType:Un.IntegerCnt,LongType:Un.LongCnt});var Zh=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ju(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var $u={exports:{}};/*! * Quill Editor v1.3.7 * https://quilljs.com/ * Copyright (c) 2014, Jason Chen diff --git a/examples/vanilla-quill/index.html b/examples/vanilla-quill/index.html index 4d90b6aec..3da691b48 100644 --- a/examples/vanilla-quill/index.html +++ b/examples/vanilla-quill/index.html @@ -4,7 +4,7 @@ Yorkie + Quill Example - + diff --git a/examples/vuejs-kanban/assets/index-CkVy1gop.js b/examples/vuejs-kanban/assets/index-aMQmcurO.js similarity index 93% rename from examples/vuejs-kanban/assets/index-CkVy1gop.js rename to examples/vuejs-kanban/assets/index-aMQmcurO.js index 693cc7755..cc682066b 100644 --- a/examples/vuejs-kanban/assets/index-CkVy1gop.js +++ b/examples/vuejs-kanban/assets/index-aMQmcurO.js @@ -20,4 +20,4 @@ var Zf=Object.defineProperty;var Qf=(r,e,t)=>e in r?Zf(r,e,{enumerable:!0,config * * SPDX-License-Identifier: Apache-2.0 */var it=null;try{it=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function X(r,e,t){this.low=r|0,this.high=e|0,this.unsigned=!!t}X.prototype.__isLong__;Object.defineProperty(X.prototype,"__isLong__",{value:!0});function Ce(r){return(r&&r.__isLong__)===!0}function Lu(r){var e=Math.clz32(r&-r);return r?31-e:e}X.isLong=Ce;var Ju={},Mu={};function zn(r,e){var t,n,s;return e?(r>>>=0,(s=0<=r&&r<256)&&(n=Mu[r],n)?n:(t=Q(r,0,!0),s&&(Mu[r]=t),t)):(r|=0,(s=-128<=r&&r<128)&&(n=Ju[r],n)?n:(t=Q(r,r<0?-1:0,!1),s&&(Ju[r]=t),t))}X.fromInt=zn;function ot(r,e){if(isNaN(r))return e?Xr:pt;if(e){if(r<0)return Xr;if(r>=vf)return Tf}else{if(r<=-Uu)return Je;if(r+1>=Uu)return bf}return r<0?ot(-r,e).neg():Q(r%hs|0,r/hs|0,e)}X.fromNumber=ot;function Q(r,e,t){return new X(r,e,t)}X.fromBits=Q;var Qi=Math.pow;function rc(r,e,t){if(r.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,r==="NaN"||r==="Infinity"||r==="+Infinity"||r==="-Infinity")return e?Xr:pt;if(t=t||10,t<2||360)throw Error("interior hyphen");if(n===0)return rc(r.substring(1),e,t).neg();for(var s=ot(Qi(t,8)),i=pt,o=0;o>>0:this.low};k.toNumber=function(){return this.unsigned?(this.high>>>0)*hs+(this.low>>>0):this.high*hs+(this.low>>>0)};k.toString=function(e){if(e=e||10,e<2||36>>0,h=l.toString(e);if(o=u,o.isZero())return h+a;for(;h.length<6;)h="0"+h;a=""+h+a}};k.getHighBits=function(){return this.high};k.getHighBitsUnsigned=function(){return this.high>>>0};k.getLowBits=function(){return this.low};k.getLowBitsUnsigned=function(){return this.low>>>0};k.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Je)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};k.isOdd=function(){return(this.low&1)===1};k.isEven=function(){return(this.low&1)===0};k.equals=function(e){return Ce(e)||(e=At(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};k.eq=k.equals;k.notEquals=function(e){return!this.eq(e)};k.neq=k.notEquals;k.ne=k.notEquals;k.lessThan=function(e){return this.comp(e)<0};k.lt=k.lessThan;k.lessThanOrEqual=function(e){return this.comp(e)<=0};k.lte=k.lessThanOrEqual;k.le=k.lessThanOrEqual;k.greaterThan=function(e){return this.comp(e)>0};k.gt=k.greaterThan;k.greaterThanOrEqual=function(e){return this.comp(e)>=0};k.gte=k.greaterThanOrEqual;k.ge=k.greaterThanOrEqual;k.compare=function(e){if(Ce(e)||(e=At(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};k.comp=k.compare;k.negate=function(){return!this.unsigned&&this.eq(Je)?Je:this.not().add(_n)};k.neg=k.negate;k.add=function(e){Ce(e)||(e=At(e));var t=this.high>>>16,n=this.high&65535,s=this.low>>>16,i=this.low&65535,o=e.high>>>16,a=e.high&65535,u=e.low>>>16,l=e.low&65535,h=0,g=0,v=0,m=0;return m+=i+l,v+=m>>>16,m&=65535,v+=s+u,g+=v>>>16,v&=65535,g+=n+a,h+=g>>>16,g&=65535,h+=t+o,h&=65535,Q(v<<16|m,h<<16|g,this.unsigned)};k.subtract=function(e){return Ce(e)||(e=At(e)),this.add(e.neg())};k.sub=k.subtract;k.multiply=function(e){if(this.isZero())return this;if(Ce(e)||(e=At(e)),it){var t=it.mul(this.low,this.high,e.low,e.high);return Q(t,it.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?Xr:pt;if(this.eq(Je))return e.isOdd()?Je:pt;if(e.eq(Je))return this.isOdd()?Je:pt;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(qu)&&e.lt(qu))return ot(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,s=this.high&65535,i=this.low>>>16,o=this.low&65535,a=e.high>>>16,u=e.high&65535,l=e.low>>>16,h=e.low&65535,g=0,v=0,m=0,A=0;return A+=o*h,m+=A>>>16,A&=65535,m+=i*h,v+=m>>>16,m&=65535,m+=o*l,v+=m>>>16,m&=65535,v+=s*h,g+=v>>>16,v&=65535,v+=i*l,g+=v>>>16,v&=65535,v+=o*u,g+=v>>>16,v&=65535,g+=n*h+s*l+i*u+o*a,g&=65535,Q(m<<16|A,g<<16|v,this.unsigned)};k.mul=k.multiply;k.divide=function(e){if(Ce(e)||(e=At(e)),e.isZero())throw Error("division by zero");if(it){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?it.div_u:it.div_s)(this.low,this.high,e.low,e.high);return Q(t,it.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Xr:pt;var n,s,i;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Xr;if(e.gt(this.shru(1)))return wf;i=Xr}else{if(this.eq(Je)){if(e.eq(_n)||e.eq(Ia))return Je;if(e.eq(Je))return _n;var o=this.shr(1);return n=o.div(e).shl(1),n.eq(pt)?e.isNegative()?_n:Ia:(s=this.sub(e.mul(n)),i=n.add(s.div(e)),i)}else if(e.eq(Je))return this.unsigned?Xr:pt;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();i=pt}for(s=this;s.gte(e);){n=Math.max(1,Math.floor(s.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(n)/Math.LN2),u=a<=48?1:Qi(2,a-48),l=ot(n),h=l.mul(e);h.isNegative()||h.gt(s);)n-=u,l=ot(n,this.unsigned),h=l.mul(e);l.isZero()&&(l=_n),i=i.add(l),s=s.sub(h)}return i};k.div=k.divide;k.modulo=function(e){if(Ce(e)||(e=At(e)),it){var t=(this.unsigned?it.rem_u:it.rem_s)(this.low,this.high,e.low,e.high);return Q(t,it.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};k.mod=k.modulo;k.rem=k.modulo;k.not=function(){return Q(~this.low,~this.high,this.unsigned)};k.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};k.clz=k.countLeadingZeros;k.countTrailingZeros=function(){return this.low?Lu(this.low):Lu(this.high)+32};k.ctz=k.countTrailingZeros;k.and=function(e){return Ce(e)||(e=At(e)),Q(this.low&e.low,this.high&e.high,this.unsigned)};k.or=function(e){return Ce(e)||(e=At(e)),Q(this.low|e.low,this.high|e.high,this.unsigned)};k.xor=function(e){return Ce(e)||(e=At(e)),Q(this.low^e.low,this.high^e.high,this.unsigned)};k.shiftLeft=function(e){return Ce(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Q(this.low<>>32-e,this.unsigned):Q(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):Q(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};k.shr=k.shiftRight;k.shiftRightUnsigned=function(e){return Ce(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Q(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?Q(this.high,0,this.unsigned):Q(this.high>>>e-32,0,this.unsigned)};k.shru=k.shiftRightUnsigned;k.shr_u=k.shiftRightUnsigned;k.rotateLeft=function(e){var t;return Ce(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Q(this.high,this.low,this.unsigned):e<32?(t=32-e,Q(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,Q(this.high<>>t,this.low<>>t,this.unsigned))};k.rotl=k.rotateLeft;k.rotateRight=function(e){var t;return Ce(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Q(this.high,this.low,this.unsigned):e<32?(t=32-e,Q(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,Q(this.low<>>e,this.high<>>e,this.unsigned))};k.rotr=k.rotateRight;k.toSigned=function(){return this.unsigned?Q(this.low,this.high,!1):this};k.toUnsigned=function(){return this.unsigned?this:Q(this.low,this.high,!0)};k.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};k.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};k.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};X.fromBytes=function(e,t,n){return n?X.fromBytesLE(e,t):X.fromBytesBE(e,t)};X.fromBytesLE=function(e,t){return new X(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};X.fromBytesBE=function(e,t){return new X(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var be=(r=>(r[r.Null=0]="Null",r[r.Boolean=1]="Boolean",r[r.Integer=2]="Integer",r[r.Long=3]="Long",r[r.Double=4]="Double",r[r.String=5]="String",r[r.Bytes=6]="Bytes",r[r.Date=7]="Date",r))(be||{});class le extends Gs{constructor(t,n){super(n);c(this,"valueType");c(this,"value");this.valueType=le.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,n){return new le(t,n)}static valueFromBytes(t,n){switch(t){case 0:return null;case 1:return!!n[0];case 2:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 4:{const s=new DataView(n.buffer);return n.forEach(function(i,o){s.setUint8(o,i)}),s.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(n);case 3:return X.fromBytesLE(Array.from(n));case 6:return n;case 7:return new Date(X.fromBytesLE(Array.from(n),!0).toNumber());default:throw new w(y.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${$t(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=le.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof X)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return le.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!0),n}case 5:return new TextEncoder().encode(this.value);case 3:{const n=this.value.toBytesLE();return Uint8Array.from(n)}case 6:return this.value;case 7:{const t=this.value,n=X.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(n)}default:throw new w(y.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class eo extends yf{constructor(t){super(t);c(this,"prev");c(this,"next");this.value=t}static createAfter(t,n){const s=new eo(n),i=t.next;return t.next=s,s.prev=t,s.next=i,i&&(i.prev=s),s}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class Ks{constructor(){c(this,"dummyHead");c(this,"last");c(this,"nodeMapByIndex");c(this,"nodeMapByCreatedAt");const e=le.of(0,wt);e.setRemovedAt(wt),this.dummyHead=new eo(e),this.last=this.dummyHead,this.nodeMapByIndex=new zs,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Ks}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new w(y.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;n.getNext()&&n.getNext().getPositionedAt().after(t);)n=n.getNext();return n}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,n=t.getCreatedAt()){const s=this.findNextBeforeExecutedAt(e,n),i=eo.createAfter(s,t);s===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(s,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(e,t,n){const s=this.nodeMapByCreatedAt.get(e.toIDString());if(!s)throw new w(y.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new w(y.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);s!==i&&(!i.getValue().getMovedAt()||n.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(s.getCreatedAt(),i.getValue(),n),i.getValue().setMovedAt(n))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new w(y.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,n]=this.nodeMapByIndex.find(e);let s=t;if(e===0&&t===this.dummyHead||n>0)do s&&(s=s.getNext());while(s&&s.isRemoved());return s}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const n=this.nodeMapByCreatedAt.get(e.toIDString()),s=n.isRemoved();return n.remove(t)&&!s&&this.nodeMapByIndex.splayNode(n),n.getValue()}deleteByIndex(e,t){const n=this.getByIndex(e);if(n)return n.remove(t)&&this.nodeMapByIndex.splayNode(n),n.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const n=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${n}}`):e.push(`[${n}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class je extends pn{constructor(t,n){super(t);c(this,"elements");this.elements=n}static create(t,n){if(!n)return new je(t,Ks.create());const s=Ks.create();for(const i of n)s.insertAfter(s.getLastCreatedAt(),i.deepcopy());return new je(t,s)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,n){this.elements.insertAfter(t,n)}moveAfter(t,n,s){this.elements.moveAfter(t,n,s)}get(t){const n=this.elements.getByIndex(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.elements.getByID(t);return n==null?void 0:n.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,n){return this.elements.delete(t,n)}deleteByIndex(t,n){return this.elements.deleteByIndex(t,n)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const n of this.elements){const s=n.getValue();if(t(s,this))return;s instanceof pn&&s.getDescendants(t)}}toJSON(){const t=[];for(const n of this)t.push(n.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let n=0;n({...m,value:m.value?{attributes:rs(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[l,v,h,[u,u]]}setStyle(t,n,s,i){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],s),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],s),u=[],l=this.rgaTreeSplit.findBetween(a,o),h=new Map,g=[];for(const m of l){const A=m.getCreatedAt().getActorID(),E=i!=null&&i.size?i.has(A)?i.get(A):wt:Ns;if(m.canStyle(s,E)){const R=h.get(A),$=m.getCreatedAt();(!R||$.after(R))&&h.set(A,$),g.push(m)}}const v=[];for(const m of g){if(m.isRemoved())continue;const[A,E]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());u.push({type:"style",actor:s.getActorID(),from:A,to:E,value:{attributes:rs(n)}});for(const[R,$]of Object.entries(n)){const[U]=m.getValue().setAttr(R,$,s);U!==void 0&&v.push({parent:m.getValue(),child:U})}}return[h,v,u]}indexRangeToPosRange(t,n){const s=this.rgaTreeSplit.indexToPos(t);return t===n?[s,s]:[s,this.rgaTreeSplit.indexToPos(n)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const n of this.rgaTreeSplit)n.isRemoved()||t.push(n.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const n of this.rgaTreeSplit)if(!n.isRemoved()){const s=n.getValue();t.push({attributes:rs(s.getAttributes()),content:s.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new at(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const n of this.rgaTreeSplit){n.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:n});for(const s of n.getValue().getGCPairs())t.push(s)}return t}}class _s extends Tt{constructor(t,n,s,i,o,a,u){super(t,u);c(this,"fromPos");c(this,"toPos");c(this,"maxCreatedAtMapByActor");c(this,"content");c(this,"attributes");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.content=o,this.attributes=a}static create(t,n,s,i,o,a,u){return new _s(t,n,s,i,o,a,u)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof at))throw new w(y.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=n,[,i,o]=s.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:u,value:l})=>({type:"edit",from:a,to:u,value:l,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.content;return`${t}.EDIT(${n},${s},${i})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Xs extends Tt{constructor(t,n,s,i,o,a){super(t,a);c(this,"fromPos");c(this,"toPos");c(this,"maxCreatedAtMapByActor");c(this,"attributes");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o}static create(t,n,s,i,o,a){return new Xs(t,n,s,i,o,a)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof at))throw new w(y.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=n,[,i,o]=s.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of i)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:u,value:l})=>({type:"style",from:a,to:u,value:l,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.attributes;return`${t}.STYL(${n},${s},${JSON.stringify(i)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const np=2,sp="root",Zr="text";function As(r,e){let t=0;const n=r.children;for(let s=0;s0)throw new w(y.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const n=t.updateDescendantsSize();t.isRemoved||(e+=n)}return this.size+=e,this.paddedSize}get isText(){return this.type===Zr}get paddedSize(){return this.size+(this.isText?0:np)}isAncestorOf(e){return op(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const n=this.value.slice(0,e),s=this.value.slice(e);if(!s.length)return;this.value=n;const i=this.cloneText(e+t);return i.value=s,this.parent.insertAfterInternal(i,this),i}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new w(y.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new w(y.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new w(y.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const n=this.cloneElement(t);this.parent.insertAfterInternal(n,this),n.updateAncestorsSize();const s=this.children.slice(0,e),i=this.children.slice(e);this._children=s,n._children=i,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),n.size=n._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of n._children)o.parent=n;return n}insertAfterInternal(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new w(y.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1)}insertAtInternal(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(s=>!s.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const n=this._children.indexOf(t);if(n!==-1)return n;t=t.parent}return-1}}function op(r,e){if(r===e)return!1;for(;e.parent;){if(e.parent===r)return!0;e=e.parent}return!1}var ve=(r=>(r.Start="Start",r.End="End",r.Text="Text",r))(ve||{});function Af(r,e,t,n){if(e>t)throw new w(y.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>r.size)throw new w(y.ErrInvalidArgument,`from is out of range: ${e} > ${r.size}`);if(t>r.size)throw new w(y.ErrInvalidArgument,`to is out of range: ${t} > ${r.size}`);if(e===t)return;let s=0;for(const i of r.children){if(e-i.paddedSizei.size;(i.isText||u)&&n([i,i.isText?"Text":"Start"],l),Af(i,Math.max(0,o),Math.min(a,i.size),n),l&&n([i,"End"],l)}s+=i.paddedSize}}function If(r,e,t=0){for(const n of r.children)If(n,e,t+1);e(r,t)}function yo(r,e,t=0){for(const n of r._children)yo(n,e,t+1);e(r,t)}function Sa(r,e,t=!0){if(e>r.size)throw new w(y.ErrInvalidArgument,`index is out of range: ${e} > ${r.size}`);if(r.isText)return{node:r,offset:e};let n=0,s=0;for(const i of r.children){if(t&&i.isText&&i.size>=e-s)return Sa(i,e-s,t);if(e===s)return{node:r,offset:n};if(!t&&i.paddedSize===e-s)return{node:r,offset:n+1};if(i.paddedSize>e-s)return Sa(i,e-s-1,t);s+=i.paddedSize,n+=1}return{node:r,offset:n}}function Sf(r){return r.isText||r.children.length===0?r:Sf(r.children[0])}function ap(r,e){if(r.sizer===e?0:r0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(n<0)if(t.left)t.left.parent=t,t=t.left;else{let s=t.parent,i=t;for(;s&&i===s.left;)i=s,s=s.parent;return s}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const n=this.comparator(e,t.key);if(n===0)return t;n<0?t=t.left:n>0&&(t=t.right)}}putInternal(e,t,n){if(!n)return this.counter+=1,new lp(e,t,!0);const s=this.comparator(e,n.key);return s<0?n.left=this.putInternal(e,t,n.left):s>0?n.right=this.putInternal(e,t,n.right):n.value=t,this.isRed(n.right)&&!this.isRed(n.left)&&(n=this.rotateLeft(n)),this.isRed(n.left)&&this.isRed(n.left.left)&&(n=this.rotateRight(n)),this.isRed(n.left)&&this.isRed(n.right)&&this.flipColors(n),n}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const n=this.min(e.right);e.value=n.value,e.key=n.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class yt{constructor(e,t){c(this,"parentID");c(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new yt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:n}=e,s;return n.isText?(n.parent.children[0]===n&&t===0?s=n.parent:s=n,n=n.parent):t===0?s=n:s=n.children[t-1],yt.of(n.id,Ae.of(s.getCreatedAt(),s.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return yt.of(Ae.of(Ke.fromStruct(e.parentID.createdAt),e.parentID.offset),Ae.of(Ke.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),n=this.getLeftSiblingID(),s=e.findFloorNode(t);let i=e.findFloorNode(n);if(!s||!i)throw new w(y.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${n.toTestString()})`);return!n.equals(t)&&n.getOffset()>0&&n.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=e.findFloorNode(i.insPrevID)),[s,i]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Ae{constructor(e,t){c(this,"createdAt");c(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ae(e,t)}static fromStruct(e){return Ae.of(Ke.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const n=e.getCreatedAt().compare(t.getCreatedAt());return n!==0?n:e.getOffset()>t.getOffset()?1:e.getOffset(){const i=s.deepcopy();return i.parent=t,i}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new w(y.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new w(y.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const n=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),n&&this.updateAncestorsSize()}cloneText(t){return new ze(Ae.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new ze(Ae.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,n,s){const i=this.isText?this.splitText(n,this.id.getOffset()):this.splitElement(n,s);if(i){if(i.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=i.id,i.insNextID=this.insNextID}this.insNextID=i.id,t.registerNode(i)}return i}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,n){return!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,n){return this.isText?!1:!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,n){this.attrs||(this.attrs=new rn);const s=new Array;for(const[i,o]of Object.entries(t))s.push(this.attrs.set(i,o,n));return s}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const n of this.attrs)n.getRemovedAt()&&t.push({parent:this,child:n});return t}}function xa(r){var t;if(r.isText){const n=r;return{type:n.type,value:n.value}}const e={type:r.type,children:r.children.map(xa)};return r.attrs&&(e.attributes=rs((t=r.attrs)==null?void 0:t.toObject())),e}function nc(r){if(r.isText)return r.value;let e="";return r.attrs&&r.attrs.size()&&(e=" "+Array.from(r.attrs).filter(t=>!t.isRemoved()).sort((t,n)=>t.getKey().localeCompare(n.getKey())).map(t=>{const n=JSON.parse(t.getValue());return typeof n=="string"?`${t.getKey()}="${n}"`:`${t.getKey()}="${$t(t.getValue())}"`}).join(" ")),`<${r.type}${e}>${r.children.map(t=>nc(t)).join("")}`}function kf(r){if(r.isText){const e=r;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:r.type,children:r.children.map(kf),size:r.size,isRemoved:r.isRemoved}}class ct extends Gs{constructor(t,n){super(n);c(this,"indexTree");c(this,"nodeMapByID");this.indexTree=new cp(t),this.nodeMapByID=new xf(Ae.createComparator()),this.indexTree.traverseAll(s=>{this.nodeMapByID.put(s.id,s)})}static create(t,n){return new ct(t,n)}findFloorNode(t){const n=this.nodeMapByID.floorEntry(t);if(!(!n||!n.key.getCreatedAt().equals(t.getCreatedAt())))return n.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,n){const[s,i]=t.toTreeNodePair(this);let o=i;const a=s===o,u=o.parent&&!a?o.parent:s;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),n){const l=u.allChildren,h=a?0:l.indexOf(o)+1;for(let g=h;g{const E=A.getCreatedAt().getActorID(),R=i?i.has(E)?i.get(E):wt:Ns;if(A.canStyle(s,R)&&n){const $=v.get(E),U=A.getCreatedAt();(!$||U.after($))&&v.set(E,U);const _=A.setAttrs(n,s),D=_.reduce((ae,[,Se])=>(Se&&(ae[Se.getKey()]=g[Se.getKey()]),ae),{}),G=A.parent,ee=A.prevSibling||A.parent;Object.keys(D).length>0&&h.push({type:"style",from:this.toIndex(G,ee),to:this.toIndex(A,A),fromPath:this.toPath(G,ee),toPath:this.toPath(A,A),actor:s.getActorID(),value:D});for(const[ae]of _)ae&&m.push({parent:A,child:ae})}}),[v,m,h]}removeStyle(t,n,s,i){const[o,a]=this.findNodesAndSplitText(t[0],s),[u,l]=this.findNodesAndSplitText(t[1],s),h=[],g=new Map,v=[];return this.traverseInPosRange(o,a,u,l,([m])=>{const A=m.getCreatedAt().getActorID(),E=i?i.has(A)?i.get(A):wt:Ns;if(m.canStyle(s,E)&&n){const R=g.get(A),$=m.getCreatedAt();(!R||$.after(R))&&g.set(A,$),m.attrs||(m.attrs=new rn);for(const D of n){const G=m.attrs.remove(D,s);for(const ee of G)v.push({parent:m,child:ee})}const U=m.parent,_=m.prevSibling||m.parent;h.push({actor:s.getActorID(),type:"removeStyle",from:this.toIndex(U,_),to:this.toIndex(m,m),fromPath:this.toPath(U,_),toPath:this.toPath(m,m),value:n})}}),[g,v,h]}edit(t,n,s,i,o,a){const[u,l]=this.findNodesAndSplitText(t[0],i),[h,g]=this.findNodesAndSplitText(t[1],i),v=this.toIndex(u,l),m=this.toPath(u,l),A=[],E=[],R=[],$=new Map;this.traverseInPosRange(u,l,h,g,([D,G],ee)=>{if(G===ve.Start&&!ee)for(const ut of D.children)R.push(ut);const ae=D.getCreatedAt().getActorID(),Se=a?a.has(ae)?a.get(ae):wt:Ns;if(D.canDelete(i,Se)||A.includes(D.parent)){const ut=$.get(ae),He=D.getCreatedAt();(!ut||He.after(ut))&&$.set(ae,He),(G===ve.Text||G===ve.Start)&&A.push(D),E.push([D,G])}});const U=this.makeDeletionChanges(E,i),_=[];for(const D of A)D.remove(i),D.isRemoved&&_.push({parent:this,child:D});for(const D of R)D.removedAt||u.append(D);if(s>0){let D=0,G=u,ee=l;for(;D{u.isRemoved&&(ae.remove(i),_.push({parent:this,child:ae})),this.nodeMapByID.put(ae.id,ae)}),ee.isRemoved||D.push(ee);if(D.length){const ee=D.map(ae=>xa(ae));U.length&&U[U.length-1].from===v?U[U.length-1].value=ee:U.push({type:"content",from:v,to:v,fromPath:m,toPath:m,actor:i.getActorID(),value:ee})}}return[U,_,$]}editT(t,n,s,i,o){const a=this.findPos(t[0]),u=this.findPos(t[1]);this.edit([a,u],n,s,i,o)}move(t,n,s){throw new w(y.ErrUnimplemented,`not implemented: ${t}, ${n}, ${s}`)}purge(t){var i;(i=t.parent)==null||i.removeChild(t),this.nodeMapByID.remove(t.id);const n=t.insPrevID,s=t.insNextID;if(n){const o=this.findFloorNode(n);o.insNextID=s}if(s){const o=this.findFloorNode(s);o.insPrevID=n}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(n=>{n.getRemovedAt()&&t.push({parent:this,child:n});for(const s of n.getGCPairs())t.push(s)}),t}findPos(t,n=!0){const s=this.indexTree.findTreePos(t,n);return yt.fromTreePos(s)}pathToPosRange(t){const n=this.pathToIndex(t);return[this.findPos(n),this.findPos(n+1)]}pathToPos(t){const n=this.indexTree.pathToIndex(t);return this.findPos(n)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return nc(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),n=(s,i=void 0,o=void 0,a=0)=>{var m,A,E,R;let u,l,h;const g=s.isText?{node:s,offset:0}:i&&o?this.toTreePos(i,o):null;g&&(u=this.indexTree.indexOf(g),l=this.indexTree.treePosToPath(g),h=yt.fromTreePos(g).toStruct());const v={type:s.type,parent:i==null?void 0:i.id.toTestString(),size:s.size,id:s.id.toTestString(),removedAt:(m=s.removedAt)==null?void 0:m.toTestString(),insPrev:(A=s.insPrevID)==null?void 0:A.toTestString(),insNext:(E=s.insNextID)==null?void 0:E.toTestString(),value:s.isText?s.value:void 0,isRemoved:s.isRemoved,children:[],depth:a,attributes:s.attrs?rs((R=s.attrs)==null?void 0:R.toObject()):void 0,index:u,path:l,pos:h};for(let $=0;$0&&$===s[s.length-1].to?(s[s.length-1].to=U,s[s.length-1].toPath=this.toPath(R,m)):s.push({type:"content",from:$,to:U,fromPath:this.toPath(E,g),toPath:this.toPath(R,m),actor:n.getActorID()}))}return s.reverse()}findRightToken([t,n]){if(n===ve.Start){const u=t.allChildren;return u.length>0?[u[0],u[0].isText?ve.Text:ve.Start]:[t,ve.End]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===i.length-1)return[s,ve.End];const a=i[o+1];return[a,a.isText?ve.Text:ve.Start]}findLeftToken([t,n]){if(n===ve.End){const u=t.allChildren;if(u.length>0){const l=u[u.length-1];return[l,l.isText?ve.Text:ve.End]}return[t,ve.Start]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===0)return[s,ve.Start];const a=i[o-1];return[a,a.isText?ve.Text:ve.End]}}class Zs extends Tt{constructor(t,n,s,i,o,a,u){super(t,u);c(this,"fromPos");c(this,"toPos");c(this,"contents");c(this,"splitLevel");c(this,"maxCreatedAtMapByActor");this.fromPos=n,this.toPos=s,this.contents=i,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,n,s,i,o,a,u){return new Zs(t,n,s,i,o,a,u)}execute(t){var u;const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof ct))throw new w(y.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=this.getExecutedAt(),i=n,[o,a]=i.edit([this.fromPos,this.toPos],(u=this.contents)==null?void 0:u.map(l=>l.deepcopy()),this.splitLevel,s,(()=>{let l=s.getDelimiter();return this.contents!==void 0&&(l+=this.contents.length),()=>Ke.of(s.getLamport(),++l,s.getActorID())})(),this.maxCreatedAtMapByActor);for(const l of a)t.registerGCPair(l);return{opInfos:o.map(({from:l,to:h,value:g,splitLevel:v,fromPath:m,toPath:A})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:l,to:h,value:g,splitLevel:v,fromPath:m,toPath:A}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,i=this.contents||[];return`${t}.EDIT(${n},${s},${i.map(o=>nc(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class ns{constructor(e){c(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[n,s]of e){const i=this.vector.get(n),o=i&&i>s?i:s;t.set(n,o)}for(const[n,s]of this){const i=e.get(n),o=i&&i>s?i:s;t.set(n,o)}return new ns(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,n]of this.vector)e.set(t,n);return new ns(e)}filter(e){const t=new Map;for(const[n]of e){const s=this.vector.get(n);s!==void 0&&t.set(n,s)}return new ns(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const hp=new ns(new Map);class Hr{constructor(e,t,n,s,i){c(this,"clientSeq");c(this,"serverSeq");c(this,"lamport");c(this,"actor");c(this,"versionVector");this.clientSeq=e,this.serverSeq=i,this.lamport=t,this.versionVector=s,this.actor=n}static of(e,t,n,s,i){return new Hr(e,t,n,s,i)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new Hr(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,n=this.versionVector.max(e.versionVector),s=new Hr(this.clientSeq,t,this.actor,n);return s.versionVector.set(this.actor,t),s}setClocks(e,t){const n=e>this.lamport?e:this.lamport+1n,s=this.versionVector.max(t);return s.set(this.actor,n),Hr.of(this.clientSeq,n,this.actor,s)}createTimeTicket(e){return Ke.of(this.lamport,e,this.actor)}setActor(e){return new Hr(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new Hr(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const dp=new Hr(0,0n,ec,hp);class ds{constructor({id:e,operations:t,presenceChange:n,message:s}){c(this,"id");c(this,"operations");c(this,"presenceChange");c(this,"message");this.id=e,this.operations=t||[],this.presenceChange=n,this.message=s}static create({id:e,operations:t,presenceChange:n,message:s}){return new ds({id:e,operations:t,presenceChange:n,message:s})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,n){const s=[],i=[];for(const o of this.operations){const a=o.execute(e,n);if(!a)continue;const{opInfos:u,reverseOp:l}=a;s.push(...u),l&&i.unshift(l)}return this.presenceChange&&(this.presenceChange.type===bn.Put?t.set(this.id.getActorID(),ht(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:s,reverseOps:i}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:me.bytesToHex(me.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>me.bytesToHex(me.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:n,presenceChange:s,message:i}=e;return ds.create({id:me.bytesToChangeID(me.hexToBytes(t)),operations:n==null?void 0:n.map(o=>me.bytesToOperation(me.hexToBytes(o))),presenceChange:s,message:i})}}class vo{constructor(e,t,n,s,i,o,a){c(this,"documentKey");c(this,"checkpoint");c(this,"isRemoved");c(this,"changes");c(this,"snapshot");c(this,"minSyncedTicket");c(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=n,this.changes=s,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=i}static create(e,t,n,s,i,o,a){return new vo(e,t,n,s,i,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class ss{constructor(e,t){c(this,"serverSeq");c(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new ss(e,t)}increaseClientSeq(e){return e===0?this:new ss(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,n=Math.max(this.clientSeq,e.clientSeq);return ss.of(t,n)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const gp=new ss(0n,0);class qt{constructor(e,t){c(this,"createdAt");c(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new qt(e,t)}static fromStruct(e){return qt.of(Ke.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new qt(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const mp=qt.of(wt,0);class bt{constructor(e,t){c(this,"id");c(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new bt(e,t)}static fromStruct(e){const t=qt.fromStruct(e.id);return bt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return qt.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class yn extends yf{constructor(t,n,s){super(n);c(this,"id");c(this,"removedAt");c(this,"prev");c(this,"next");c(this,"insPrev");c(this,"insNext");this.id=t,this.removedAt=s}static create(t,n){return new yn(t,n)}static createComparator(){return(t,n)=>{const s=t.getCreatedAt().compare(n.getCreatedAt());return s!==0?s:t.getOffset()>n.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const n=[];let s=e;for(;s&&s!==t;)n.push(s),s=s.getNext();return n}splitNode(e,t){if(t>e.getContentLength())throw new w(y.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const n=e.split(t);this.treeByIndex.updateWeight(n),this.insertAfter(e,n);const s=e.getInsNext();return s&&s.setInsPrev(n),n.setInsPrev(e),n}deleteNodes(e,t,n){if(!e.length)return[[],new Map,new Map];const[s,i]=this.filterNodes(e,t,n),o=new Map,a=new Map,u=this.makeChanges(i,t);for(const l of s){const h=l.getCreatedAt().getActorID();(!o.has(h)||l.getID().getCreatedAt().after(o.get(h)))&&o.set(h,l.getID().getCreatedAt()),a.set(l.getID().toIDString(),l),l.remove(t)}return this.deleteIndexNodes(i),[u,o,a]}filterNodes(e,t,n){const s=!!n,i=[],o=[],[a,u]=this.findEdgesOfCandidates(e);o.push(a);for(const l of e){const h=l.getCreatedAt().getActorID(),g=s?n.has(h)?n.get(h):wt:Ns;l.canDelete(t,g)?i.push(l):o.push(l)}return o.push(u),[i,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const n=[];let s,i;for(let o=0;or<0?Math.ceil(r):Math.floor(r);var Vt=(r=>(r[r.IntegerCnt=0]="IntegerCnt",r[r.LongCnt=1]="LongCnt",r))(Vt||{});class We extends Gs{constructor(t,n,s){super(s);c(this,"valueType");c(this,"value");switch(this.valueType=t,t){case 0:typeof n=="number"?n>Math.pow(2,31)-1||n<-Math.pow(2,31)?this.value=X.fromNumber(n).toInt():this.value=Vu(n):this.value=n.toInt();break;case 1:typeof n=="number"?this.value=X.fromNumber(n):this.value=n;break;default:throw new w(y.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,n,s){return new We(t,n,s)}static valueFromBytes(t,n){switch(t){case 0:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 1:return X.fromBytesLE(Array.from(n));default:throw new w(y.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=We.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof X?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!We.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const n=this.value.toBytesLE();return Uint8Array.from(n)}default:throw new w(y.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function n(s){if(!s.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof s.getValue()}`)}return n(this),n(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===be.Long?this.value=this.value+t.getValue().toInt():this.value=X.fromNumber(this.value+Vu(t.getValue())).toInt(),this}}class ms extends Tt{constructor(t,n,s){super(t,s);c(this,"value");this.value=n}static create(t,n,s){return new ms(t,n,s)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof We))throw new w(y.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const s=n,i=this.value.deepcopy();return s.increase(i),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:i.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),s=t.getType()===be.Long?t.getValue().multiply(-1):t.getValue()*-1;return ms.create(this.getParentCreatedAt(),le.of(s,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Qr extends Tt{constructor(t,n,s,i,o,a,u){super(t,u);c(this,"fromPos");c(this,"toPos");c(this,"maxCreatedAtMapByActor");c(this,"attributes");c(this,"attributesToRemove");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o,this.attributesToRemove=a}static create(t,n,s,i,o,a){return new Qr(t,n,s,i,o,new Array,a)}static createTreeRemoveStyleOperation(t,n,s,i,o,a){return new Qr(t,n,s,i,new Map,o,a)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof ct))throw new w(y.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=n;let i,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([u,l])=>a[u]=l),[,o,i]=s.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,i]=s.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:u,value:l,fromPath:h,toPath:g})=>({type:"tree-style",from:a,to:u,value:this.attributes.size?{attributes:l}:{attributesToRemove:l},fromPath:h,toPath:g,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${n},${s},${Object.entries(this.attributes||{}).map(([i,o])=>`${i}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function pp(r){const e=new Qa,t=e.data;for(const[n,s]of Object.entries(r))t[n]=JSON.stringify(s);return e}function yp(r){if(r.type===bn.Put)return new qs({type:Un.PUT,presence:pp(r.presence)});if(r.type===bn.Clear)return new qs({type:Un.CLEAR});throw new w(y.ErrUnimplemented,"unimplemented type")}function vp(r){return new gf({serverSeq:r.getServerSeq(),clientSeq:r.getClientSeq()})}function Ef(r){return new mo({clientSeq:r.getClientSeq(),lamport:r.getLamport(),actorId:gc(r.getActorID()),versionVector:sc(r.getVersionVector())})}function J(r){if(r)return new L({lamport:r.getLamport(),delimiter:r.getDelimiter(),actorId:gc(r.getActorID())})}function sc(r){if(!r)return;const e=new po;for(const[t,n]of r)e.vector[t]=BigInt(n.toString());return e}function Cf(r){switch(r){case be.Null:return W.NULL;case be.Boolean:return W.BOOLEAN;case be.Integer:return W.INTEGER;case be.Long:return W.LONG;case be.Double:return W.DOUBLE;case be.String:return W.STRING;case be.Bytes:return W.BYTES;case be.Date:return W.DATE;default:throw new w(y.ErrInvalidType,`unsupported type: ${r}`)}}function Nf(r){switch(r){case Vt.IntegerCnt:return W.INTEGER_CNT;case Vt.LongCnt:return W.LONG_CNT;default:throw new w(y.ErrInvalidType,`unsupported type: ${r}`)}}function Fo(r){if(r instanceof Me)return new Ye({type:W.JSON_OBJECT,createdAt:J(r.getCreatedAt()),value:Vf(r)});if(r instanceof je)return new Ye({type:W.JSON_ARRAY,createdAt:J(r.getCreatedAt()),value:Yp(r)});if(r instanceof at)return new Ye({type:W.TEXT,createdAt:J(r.getCreatedAt())});if(r instanceof le)return new Ye({type:Cf(r.getType()),createdAt:J(r.getCreatedAt()),value:r.toBytes()});if(r instanceof We)return new Ye({type:Nf(r.getType()),createdAt:J(r.getCreatedAt()),value:r.toBytes()});if(r instanceof ct)return new Ye({type:W.TREE,createdAt:J(r.getCreatedAt()),value:Xp(r)});throw new w(y.ErrUnimplemented,"unimplemented element")}function wp(r){return new $s({createdAt:J(r.getCreatedAt()),offset:r.getOffset()})}function fi(r){return new tn({createdAt:J(r.getID().getCreatedAt()),offset:r.getID().getOffset(),relativeOffset:r.getRelativeOffset()})}function hi(r){return new $n({parentId:Ps(r.getParentID()),leftSiblingId:Ps(r.getLeftSiblingID())})}function Ps(r){return new mn({createdAt:J(r.getCreatedAt()),offset:r.getOffset()})}function Pf(r){const e=new Za;if(r instanceof qn){const t=r,n=new Fi;n.parentCreatedAt=J(t.getParentCreatedAt()),n.key=t.getKey(),n.value=Fo(t.getValue()),n.executedAt=J(t.getExecutedAt()),e.body.case="set",e.body.value=n}else if(r instanceof Ys){const t=r,n=new Li;n.parentCreatedAt=J(t.getParentCreatedAt()),n.prevCreatedAt=J(t.getPrevCreatedAt()),n.value=Fo(t.getValue()),n.executedAt=J(t.getExecutedAt()),e.body.case="add",e.body.value=n}else if(r instanceof hn){const t=r,n=new Ji;n.parentCreatedAt=J(t.getParentCreatedAt()),n.prevCreatedAt=J(t.getPrevCreatedAt()),n.createdAt=J(t.getCreatedAt()),n.executedAt=J(t.getExecutedAt()),e.body.case="move",e.body.value=n}else if(r instanceof Tn){const t=r,n=new Mi;n.parentCreatedAt=J(t.getParentCreatedAt()),n.createdAt=J(t.getCreatedAt()),n.executedAt=J(t.getExecutedAt()),e.body.case="remove",e.body.value=n}else if(r instanceof _s){const t=r,n=new $i;n.parentCreatedAt=J(t.getParentCreatedAt()),n.from=fi(t.getFromPos()),n.to=fi(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=J(a);n.content=t.getContent();const i=n.attributes;for(const[o,a]of t.getAttributes())i[o]=a;n.executedAt=J(t.getExecutedAt()),e.body.case="edit",e.body.value=n}else if(r instanceof Xs){const t=r,n=new Ui;n.parentCreatedAt=J(t.getParentCreatedAt()),n.from=fi(t.getFromPos()),n.to=fi(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=J(a);const i=n.attributes;for(const[o,a]of t.getAttributes())i[o]=a;n.executedAt=J(t.getExecutedAt()),e.body.case="style",e.body.value=n}else if(r instanceof ms){const t=r,n=new qi;n.parentCreatedAt=J(t.getParentCreatedAt()),n.value=Fo(t.getValue()),n.executedAt=J(t.getExecutedAt()),e.body.case="increase",e.body.value=n}else if(r instanceof Zs){const t=r,n=new Vi,s=n.createdAtMapByActor;for(const[i,o]of t.getMaxCreatedAtMapByActor())s[i]=J(o);n.parentCreatedAt=J(t.getParentCreatedAt()),n.from=hi(t.getFromPos()),n.to=hi(t.getToPos()),n.contents=kp(t.getContents()),n.splitLevel=t.getSplitLevel(),n.executedAt=J(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=n}else if(r instanceof Qr){const t=r,n=new zi;n.parentCreatedAt=J(t.getParentCreatedAt()),n.from=hi(t.getFromPos()),n.to=hi(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=J(a);const i=t.getAttributesToRemove();if(i.length>0)n.attributesToRemove=i;else{const o=n.attributes;for(const[a,u]of t.getAttributes())o[a]=u}n.executedAt=J(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=n}else throw new w(y.ErrUnimplemented,"unimplemented operation");return e}function bp(r){const e=[];for(const t of r)e.push(Pf(t));return e}function Tp(r){const e=new hf({id:Ef(r.getID()),message:r.getMessage()});return r.hasOperations()&&(e.operations=bp(r.getOperations())),r.hasPresenceChange()&&(e.presenceChange=yp(r.getPresenceChange())),e}function Ap(r){const e=[];for(const t of r)e.push(Tp(t));return e}function Ip(r){const e=[];for(const t of r)e.push(new df({key:t.getStrKey(),element:oc(t.getValue())}));return e}function Sp(r){const e=[];for(const t of r)e.push(new _i({element:oc(t.getValue())}));return e}function xp(r){const e=[];for(const t of r){const n=new Xi;n.id=wp(t.getID()),n.value=t.getValue().getContent(),n.removedAt=J(t.getRemovedAt());const s=n.attributes,i=t.getValue().getAttrs();for(const o of i){const a=new ls;a.value=o.getValue(),a.updatedAt=J(o.getUpdatedAt()),s[o.getKey()]=a}e.push(n)}return e}function kp(r){const e=[];if(!r||!r.length)return e;for(const t of r)e.push(new Zi({content:ic(t)}));return e}function Ep(r){const e={};for(const t of r)e[t.getKey()]=new ls({value:t.getValue(),updatedAt:J(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function ic(r){if(!r)return[];const e=[];return yo(r,(t,n)=>{const s=new Us({id:Ps(t.id),type:t.type,removedAt:J(t.removedAt),depth:n});t.isText&&(s.value=t.value),t.insPrevID&&(s.insPrevId=Ps(t.insPrevID)),t.insNextID&&(s.insNextId=Ps(t.insNextID)),t.attrs&&(s.attributes=Ep(t.attrs)),e.push(s)}),e}function Cp(r){const e=new Ue;return e.body.case="jsonObject",e.body.value=new Ki({nodes:Ip(r.getRHT()),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Of(r){const e=new Ue;return e.body.case="jsonArray",e.body.value=new ji({nodes:Sp(r.getElements()),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Np(r){const e=new Ue;return e.body.case="primitive",e.body.value=new Wi({type:Cf(r.getType()),value:r.toBytes(),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Pp(r){const e=new Ue;return e.body.case="text",e.body.value=new Hi({nodes:xp(r.getRGATreeSplit()),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Op(r){const e=new Ue;return e.body.case="counter",e.body.value=new Gi({type:Nf(r.getType()),value:r.toBytes(),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Df(r){const e=new Ue;return e.body.case="tree",e.body.value=new Yi({nodes:ic(r.getRoot()),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function oc(r){if(r instanceof Me)return Cp(r);if(r instanceof je)return Of(r);if(r instanceof le)return Np(r);if(r instanceof at)return Pp(r);if(r instanceof We)return Op(r);if(r instanceof ct)return Df(r);throw new w(y.ErrUnimplemented,"unimplemented element")}function Dp(r){return new sn({documentKey:r.getDocumentKey(),checkpoint:vp(r.getCheckpoint()),isRemoved:r.getIsRemoved(),changes:Ap(r.getChanges()),snapshot:r.getSnapshot(),versionVector:sc(r.getVersionVector()),minSyncedTicket:J(r.getMinSyncedTicket())})}function zu(r){const e=r.findDetails(Gm);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function Bf(r){return Hr.of(r.clientSeq,BigInt(r.lamport),hc(r.actorId),ac(r.versionVector),BigInt(r.serverSeq))}function ac(r){if(!r)return;const e=new ns;return Object.entries(r.vector).forEach(([t,n])=>{e.set(t,BigInt(n.toString()))}),e}function M(r){if(r)return Ke.of(BigInt(r.lamport),r.delimiter,hc(r.actorId))}function cc(r){const e={};return Object.entries(r.data).forEach(([t,n])=>{e[t]=JSON.parse(n)}),e}function Bp(r){const e=r.type;if(e===Un.PUT){const t=cc(r.presence);return{type:bn.Put,presence:t}}if(e===Un.CLEAR)return{type:bn.Clear};throw new w(y.ErrInvalidType,`unsupported type: ${e}`)}function Rp(r){const e=new Map;return Object.entries(r).forEach(([t,n])=>{e.set(t,cc(n))}),e}function Rf(r){switch(r){case W.NULL:return be.Null;case W.BOOLEAN:return be.Boolean;case W.INTEGER:return be.Integer;case W.LONG:return be.Long;case W.DOUBLE:return be.Double;case W.STRING:return be.String;case W.BYTES:return be.Bytes;case W.DATE:return be.Date}throw new w(y.ErrUnimplemented,`unimplemented value type: ${r}`)}function to(r){switch(r){case W.INTEGER_CNT:return Vt.IntegerCnt;case W.LONG_CNT:return Vt.LongCnt}throw new w(y.ErrUnimplemented,`unimplemented value type: ${r}`)}function Lo(r){switch(r.type){case W.JSON_OBJECT:return r.value?qf(r.value):Me.create(M(r.createdAt));case W.JSON_ARRAY:return r.value?Gp(r.value):je.create(M(r.createdAt));case W.TEXT:return at.create(gs.create(),M(r.createdAt));case W.TREE:return _p(r.value);case W.NULL:case W.BOOLEAN:case W.INTEGER:case W.LONG:case W.DOUBLE:case W.STRING:case W.BYTES:case W.DATE:return le.of(le.valueFromBytes(Rf(r.type),r.value),M(r.createdAt));case W.INTEGER_CNT:case W.LONG_CNT:return We.create(to(r.type),We.valueFromBytes(to(r.type),r.value),M(r.createdAt))}}function di(r){return bt.of(qt.of(M(r.createdAt),r.offset),r.relativeOffset)}function Ff(r){return qt.of(M(r.createdAt),r.offset)}function Fp(r){const e=js.create(r.value);Object.entries(r.attributes).forEach(([n,s])=>{e.setAttr(n,s.value,M(s.updatedAt))});const t=yn.create(Ff(r.id),e);return t.remove(M(r.removedAt)),t}function Hn(r){return yt.of(Os(r.parentId),Os(r.leftSiblingId))}function Os(r){return Ae.of(M(r.createdAt),r.offset)}function Lp(r){if(!r.length)return;const e=[];return r.forEach(t=>{const n=uc(t.content);e.push(n)}),e}function uc(r){if(r.length===0)return;const e=[];for(const s of r)e.push(Mp(s));const t=e[e.length-1],n=new Map;n.set(r[e.length-1].depth,e[e.length-1]);for(let s=e.length-2;s>=0;s--)n.get(r[s].depth-1).prepend(e[s]),n.set(r[s].depth,e[s]);return t.updateDescendantsSize(),ct.create(t,wt).getRoot()}function Jp(r){const e=rn.create();for(const[t,n]of Object.entries(r))e.setInternal(t,n.value,M(n.updatedAt),n.isRemoved);return e}function Mp(r){const e=Os(r.id),t=ze.create(e,r.type),n=Object.entries(r.attributes);return t.isText?t.value=r.value:n.length&&(t.attrs=Jp(r.attributes)),r.insPrevId&&(t.insPrevID=Os(r.insPrevId)),r.insNextId&&(t.insNextID=Os(r.insNextId)),t.removedAt=M(r.removedAt),t}function Lf(r){if(r.body.case==="set"){const e=r.body.value;return qn.create(e.key,Lo(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(r.body.case==="add"){const e=r.body.value;return Ys.create(M(e.parentCreatedAt),M(e.prevCreatedAt),Lo(e.value),M(e.executedAt))}else if(r.body.case==="move"){const e=r.body.value;return hn.create(M(e.parentCreatedAt),M(e.prevCreatedAt),M(e.createdAt),M(e.executedAt))}else if(r.body.case==="remove"){const e=r.body.value;return Tn.create(M(e.parentCreatedAt),M(e.createdAt),M(e.executedAt))}else if(r.body.case==="edit"){const e=r.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([s,i])=>{t.set(s,M(i))});const n=new Map;return Object.entries(e.attributes).forEach(([s,i])=>{n.set(s,i)}),_s.create(M(e.parentCreatedAt),di(e.from),di(e.to),t,e.content,n,M(e.executedAt))}else if(r.body.case==="style"){const e=r.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([s,i])=>{t.set(s,M(i))});const n=new Map;return Object.entries(e.attributes).forEach(([s,i])=>{n.set(s,i)}),Xs.create(M(e.parentCreatedAt),di(e.from),di(e.to),t,n,M(e.executedAt))}else{if(r.body.case==="select")return;if(r.body.case==="increase"){const e=r.body.value;return ms.create(M(e.parentCreatedAt),Lo(e.value),M(e.executedAt))}else if(r.body.case==="treeEdit"){const e=r.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([n,s])=>{t.set(n,M(s))}),Zs.create(M(e.parentCreatedAt),Hn(e.from),Hn(e.to),Lp(e.contents),e.splitLevel,t,M(e.executedAt))}else if(r.body.case==="treeStyle"){const e=r.body.value,t=new Map,n=e.attributesToRemove,s=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([i,o])=>{s.set(i,M(o))}),(n==null?void 0:n.length)>0?Qr.createTreeRemoveStyleOperation(M(e.parentCreatedAt),Hn(e.from),Hn(e.to),s,n,M(e.executedAt)):(Object.entries(e.attributes).forEach(([i,o])=>{t.set(i,o)}),Qr.create(M(e.parentCreatedAt),Hn(e.from),Hn(e.to),s,t,M(e.executedAt)))}else throw new w(y.ErrUnimplemented,"unimplemented operation")}}function $p(r){const e=[];for(const t of r){const n=Lf(t);n&&e.push(n)}return e}function Jf(r){const e=[];for(const t of r)e.push(ds.create({id:Bf(t.id),operations:$p(t.operations),presenceChange:t.presenceChange?Bp(t.presenceChange):void 0,message:t.message}));return e}function Up(r){return ss.of(BigInt(r.serverSeq),r.clientSeq)}function qp(r){return vo.create(r.documentKey,Up(r.checkpoint),r.isRemoved,Jf(r.changes),ac(r.versionVector),r.snapshot,M(r.minSyncedTicket))}function Mf(r){const e=new Vs;for(const n of r.nodes){const s=lc(n.element);e.set(n.key,s,s.getPositionedAt())}const t=new Me(M(r.createdAt),e);return t.setMovedAt(M(r.movedAt)),t.setRemovedAt(M(r.removedAt)),t}function $f(r){const e=new Ks;for(const n of r.nodes)e.insert(lc(n.element));const t=new je(M(r.createdAt),e);return t.setMovedAt(M(r.movedAt)),t.setRemovedAt(M(r.removedAt)),t}function Vp(r){const e=le.of(le.valueFromBytes(Rf(r.type),r.value),M(r.createdAt));return e.setMovedAt(M(r.movedAt)),e.setRemovedAt(M(r.removedAt)),e}function zp(r){const e=new gs;let t=e.getHead();for(const s of r.nodes){const i=e.insertAfter(t,Fp(s));s.insPrevId&&i.setInsPrev(e.findNode(Ff(s.insPrevId))),t=i}const n=new at(e,M(r.createdAt));return n.setMovedAt(M(r.movedAt)),n.setRemovedAt(M(r.removedAt)),n}function Kp(r){const e=We.create(to(r.type),We.valueFromBytes(to(r.type),r.value),M(r.createdAt));return e.setMovedAt(M(r.movedAt)),e.setRemovedAt(M(r.removedAt)),e}function Uf(r){const e=uc(r.nodes);return ct.create(e,M(r.createdAt))}function lc(r){if(r.body.case==="jsonObject")return Mf(r.body.value);if(r.body.case==="jsonArray")return $f(r.body.value);if(r.body.case==="primitive")return Vp(r.body.value);if(r.body.case==="text")return zp(r.body.value);if(r.body.case==="counter")return Kp(r.body.value);if(r.body.case==="tree")return Uf(r.body.value);throw new w(y.ErrUnimplemented,"unimplemented element")}function jp(r){if(!r)return{root:Me.create(wt),presences:new Map};const e=ea.fromBinary(r);return{root:lc(e.root),presences:Rp(e.presences)}}function Wp(r){const e=sc(r);return fc(e.toBinary())}function Hp(r){const e=dc(r),t=po.fromBinary(e);return ac(t)}function qf(r){if(!r)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=Ue.fromBinary(r);return Mf(e.body.value)}function Vf(r){return oc(r).toBinary()}function Gp(r){if(!r)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=Ue.fromBinary(r);return $f(e.body.value)}function Yp(r){return Of(r).toBinary()}function _p(r){if(!r)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=Ue.fromBinary(r);return Uf(e.body.value)}function Xp(r){return Df(r).toBinary()}function fc(r){return r?Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function hc(r){return fc(r)}function dc(r){return new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function gc(r){return dc(r)}function Zp(r){const e=mo.fromBinary(r);return Bf(e)}function Qp(r){const e=Za.fromBinary(r);return Lf(e)}const me={fromPresence:cc,toChangePack:Dp,fromChangePack:qp,fromChanges:Jf,toTreeNodes:ic,fromTreeNodes:uc,objectToBytes:Vf,bytesToObject:qf,bytesToSnapshot:jp,bytesToHex:fc,hexToBytes:dc,toHexString:hc,toUint8Array:gc,toOperation:Pf,toChangeID:Ef,PbChangeID:mo,bytesToChangeID:Zp,bytesToOperation:Qp,versionVectorToHex:Wp,hexToVersionVector:Hp};var Be=(r=>(r[r.Trivial=0]="Trivial",r[r.Debug=1]="Debug",r[r.Info=2]="Info",r[r.Warn=3]="Warn",r[r.Error=4]="Error",r[r.Fatal=5]="Fatal",r))(Be||{});let En=3;function zf(r){En=r}const z={trivial:(...r)=>{En>0||typeof console<"u"&&console.log("YORKIE T:",...r)},debug:(...r)=>{En>1||typeof console<"u"&&console.log("YORKIE D:",...r)},info:(...r)=>{En>2||typeof console<"u"&&console.log("YORKIE I:",...r)},warn:(...r)=>{En>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...r):console.log("YORKIE W:",...r))},error:(...r)=>{En>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...r):console.log("YORKIE E:",...r))},fatal:(...r)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...r):console.log("YORKIE F:",...r))},isEnabled:r=>En<=r};function Kf(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}class ey{constructor(e,t,n,s,i){c(this,"reconnectStreamDelay");c(this,"doc");c(this,"docID");c(this,"syncMode");c(this,"remoteChangeEventReceived");c(this,"watchStream");c(this,"watchLoopTimerID");c(this,"watchAbortController");c(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=n,this.syncMode=s,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Ei.RealtimeSyncOff?!1:this.syncMode===Ei.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Ei.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Jo=()=>{};class ty{constructor(e){c(this,"finalized",!1);c(this,"observers",[]);c(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let s;if(!e)throw new w(y.ErrInvalidArgument,"missing observer");if(this.finalized)throw new w(y.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?s=e:s={next:e,error:t,complete:n},s.next===void 0&&(s.next=Jo),s.error===void 0&&(s.error=Jo),s.complete===void 0&&(s.complete=Jo);const i=Kf(),o=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:s}),this.finalized)try{this.finalError?s.error(this.finalError):s.complete()}catch(a){z.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(n=>n.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Xn{constructor(e,t,n,s){c(this,"id");c(this,"delimiter");c(this,"message");c(this,"root");c(this,"operations");c(this,"presenceChange");c(this,"previousPresence");c(this,"reversePresenceKeys");this.id=e,this.delimiter=pf,this.root=t,this.operations=[],this.previousPresence=ht(n),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=s}static create(e,t,n,s){return new Xn(e,t,n,s)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return ds.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const n of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(n):this.reversePresenceKeys.delete(n)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class Ws{constructor(e){c(this,"rootObject");c(this,"elementPairMapByCreatedAt");c(this,"gcElementSetByCreatedAt");c(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof at||t instanceof ct)for(const n of t.getGCPairs())this.registerGCPair(n);return!1})}static create(){return new Ws(Me.create(wt))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const n=[];for(;t.parent;){const s=t.element.getCreatedAt(),i=t.parent.subPathOf(s);if(i===void 0)throw new w(y.ErrInvalidArgument,`cant find the given element: ${s.toIDString()}`);n.unshift(i),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return n.unshift("$"),n}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof pn&&e.getDescendants((n,s)=>(this.registerElement(n,s),!1))}deregisterElement(e){let t=0;const n=s=>{const i=s.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(i),this.gcElementSetByCreatedAt.delete(i),t++};return n(e),e instanceof pn&&e.getDescendants(s=>(n(s),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const n=this.elementPairMapByCreatedAt.get(t);n.element instanceof pn&&n.element.getDescendants(s=>(e.add(s.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new Ws(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const n of this.gcElementSetByCreatedAt){const s=this.elementPairMapByCreatedAt.get(n),i=s.element.getRemovedAt();i&&(e!=null&&e.afterOrEqual(i))&&(s.parent.purge(s.element),t+=this.deregisterElement(s.element))}for(const[,n]of this.gcPairMap){const s=n.child.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(n.parent.purge(n.child),this.gcPairMap.delete(n.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function jf(r,e){const t=new Hs(r);return new Proxy(e,t.getHandlers())}class Hs{constructor(e){c(this,"context");c(this,"handlers");this.context=e,this.handlers={set:(t,n,s)=>(z.isEnabled(Be.Trivial)&&z.trivial(`obj[${n}]=${JSON.stringify(s)}`),Hs.setInternal(e,t,n,s),!0),get:(t,n)=>(z.isEnabled(Be.Trivial)&&z.trivial(`obj[${n}]`),n==="getID"?()=>t.getCreatedAt():n==="toJSON"||n==="toString"?()=>t.toJSON():n==="toJS"?()=>t.toJS():n==="toJSForTest"?()=>t.toJSForTest():Cn(e,t.get(n))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,n)=>(z.isEnabled(Be.Trivial)&&z.trivial(`obj[${n}]`),Hs.deleteInternal(e,t,n),!0)}}static setInternal(e,t,n,s){if(n.includes("."))throw new w(y.ErrInvalidObjectKey,"key must not contain the '.'.");const i=e.issueTimeTicket(),o=ro(e,s,i),a=t.set(n,o,i);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(qn.create(n,o.deepcopy(),t.getCreatedAt(),i))}static buildObjectMembers(e,t){const n={};for(const[s,i]of Object.entries(t)){if(s.includes("."))throw new w(y.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=ro(e,i,o);n[s]=a}return n}static deleteInternal(e,t,n){const s=e.issueTimeTicket(),i=t.deleteByKey(n,s);i&&(e.push(Tn.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}}function ny(r,e){const t=new de(r,e);return new Proxy(e,t.getHandlers())}function sy(r){return typeof r=="string"||r instanceof String?!isNaN(r):!1}function iy(r){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(r)}class de{constructor(e,t){c(this,"context");c(this,"handlers");c(this,"array");this.context=e,this.array=t,this.handlers={get:(n,s,i)=>s==="getID"?()=>n.getCreatedAt():s==="getElementByID"?o=>{const a=n.getByID(o);if(!(!a||a.isRemoved()))return un(e,a)}:s==="getElementByIndex"?o=>{const a=n.get(o);return un(e,a)}:s==="getLast"?()=>un(e,n.getLast()):s==="deleteByID"?o=>{const a=de.deleteInternalByID(e,n,o);return un(e,a)}:s==="insertAfter"?(o,a)=>{const u=de.insertAfterInternal(e,n,o,a);return un(e,u)}:s==="insertBefore"?(o,a)=>{const u=de.insertBeforeInternal(e,n,o,a);return un(e,u)}:s==="moveBefore"?(o,a)=>{de.moveBeforeInternal(e,n,o,a)}:s==="moveAfter"?(o,a)=>{de.moveAfterInternal(e,n,o,a)}:s==="moveFront"?o=>{de.moveFrontInternal(e,n,o)}:s==="moveLast"?o=>{de.moveLastInternal(e,n,o)}:sy(s)?Cn(e,n.get(Number(s))):s==="push"?o=>de.pushInternal(e,n,o):s==="splice"?(o,a,...u)=>de.splice(e,n,o,a,...u):s==="length"?n.length:typeof s=="symbol"&&s===Symbol.iterator?de.iteratorInternal.bind(this,e,n):s==="includes"?(o,a)=>de.includes(e,n,o,a):s==="indexOf"?(o,a)=>de.indexOf(e,n,o,a):s==="lastIndexOf"?(o,a)=>de.lastIndexOf(e,n,o,a):s==="toJSForTest"?()=>n.toJSForTest():s==="toTestString"?()=>de.toTestString(n):typeof s=="string"&&iy(s)?(...o)=>{const a=Array.from(n).map(u=>Cn(e,u));return Array.prototype[s].apply(a,o)}:Reflect.get(n,s,i),deleteProperty:(n,s)=>(z.isEnabled(Be.Trivial)&&z.trivial(`array[${s}]`),de.deleteInternalByIndex(e,n,Number.parseInt(s)),!0)}}static*iteratorInternal(e,t){for(const n of t)yield un(e,n)}static buildArrayElements(e,t){const n=[];for(const s of t){const i=e.issueTimeTicket(),o=ro(e,s,i);n.push(o)}return n}static pushInternal(e,t,n){return de.insertAfterInternal(e,t,t.getLastCreatedAt(),n),t.length}static moveBeforeInternal(e,t,n,s){const i=e.issueTimeTicket(),o=t.getPrevCreatedAt(n);t.moveAfter(o,s,i),e.push(hn.create(t.getCreatedAt(),o,s,i))}static moveAfterInternal(e,t,n,s){const i=e.issueTimeTicket();t.moveAfter(n,s,i),e.push(hn.create(t.getCreatedAt(),n,s,i))}static moveFrontInternal(e,t,n){const s=e.issueTimeTicket(),i=t.getHead();t.moveAfter(i.getCreatedAt(),n,s),e.push(hn.create(t.getCreatedAt(),i.getCreatedAt(),n,s))}static moveLastInternal(e,t,n){const s=e.issueTimeTicket(),i=t.getLastCreatedAt();t.moveAfter(i,n,s),e.push(hn.create(t.getCreatedAt(),i,n,s))}static insertAfterInternal(e,t,n,s){const i=e.issueTimeTicket(),o=ro(e,s,i);return t.insertAfter(n,o),e.registerElement(o,t),e.push(Ys.create(t.getCreatedAt(),n,o.deepcopy(),i)),o}static insertBeforeInternal(e,t,n,s){return de.insertAfterInternal(e,t,t.getPrevCreatedAt(n),s)}static deleteInternalByIndex(e,t,n){const s=e.issueTimeTicket(),i=t.deleteByIndex(n,s);if(i)return e.push(Tn.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i),i}static deleteInternalByID(e,t,n){const s=e.issueTimeTicket(),i=t.delete(n,s);return e.push(Tn.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i),i}static splice(e,t,n,s,...i){const o=t.length,a=n>=0?Math.min(n,o):Math.max(o+n,0),u=s===void 0?o:s<0?a:Math.min(a+s,o),l=[];for(let h=a;h=i)return!1;if(le.isSupport(n))return Array.from(t).map(l=>Cn(e,l)).includes(n,o);for(let u=o;u=i)return-1;if(le.isSupport(n))return Array.from(t).map(l=>Cn(e,l)).indexOf(n,o);for(let u=o;u=i?i-1:s<0?s+i:s;if(o<0)return-1;if(le.isSupport(n))return Array.from(t).map(l=>Cn(e,l)).lastIndexOf(n,o);for(let u=o;u>0;u--)if(((a=t.get(u))==null?void 0:a.getID())===n.getID())return u;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class wo{constructor(e,t){c(this,"context");c(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,n,s){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);z.isEnabled(Be.Debug)&&z.debug(`EDIT: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} c:${n}`);const o=s?fs(s):void 0,a=this.context.issueTimeTicket(),[u,,l,h]=this.text.edit(i,n,a,o);for(const g of l)this.context.registerGCPair(g);return this.context.push(new _s(this.text.getCreatedAt(),i[0],i[1],u,n,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(h)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,n){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);z.isEnabled(Be.Debug)&&z.debug(`STYL: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} a:${JSON.stringify(n)}`);const i=fs(n),o=this.context.issueTimeTicket(),[a,u]=this.text.setStyle(s,i,o);for(const l of u)this.context.registerGCPair(l);return this.context.push(new Xs(this.text.getCreatedAt(),s[0],s[1],a,new Map(Object.entries(i)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([bt.fromStruct(e[0]),bt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class bo{constructor(e,t){c(this,"valueType");c(this,"value");c(this,"context");c(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new w(y.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),n=le.of(e,t);if(!n.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof n.getValue()}`);return this.counter.increase(n),this.context.push(ms.create(this.counter.getCreatedAt(),n,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new w(y.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function mc(r,e,t){const{type:n}=r,s=t.issueTimeTicket();if(n===Zr){Wf(r);const{value:i}=r,o=ze.create(Ae.of(s,0),n,i);e.append(o)}else{const{children:i=[]}=r,{attributes:o}=r;let a;if(typeof o=="object"&&!mf(o)){const l=fs(o);a=new rn;for(const[h,g]of Object.entries(l))a.set(h,g,s)}const u=ze.create(Ae.of(s,0),n,void 0,a);e.append(u);for(const l of i)mc(l,u,t)}}function oy(r,e){const{type:t}=e,n=r.issueTimeTicket();let s;if(e.type===Zr){const{value:i}=e;s=ze.create(Ae.of(n,0),t,i)}else if(e){const{children:i=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!mf(o)){const u=fs(o);a=new rn;for(const[l,h]of Object.entries(u))a.set(l,h,n)}s=ze.create(Ae.of(r.issueTimeTicket(),0),t,void 0,a);for(const u of i)mc(u,s,r)}return s}function Wf(r){if(!r.value.length)throw new w(y.ErrInvalidArgument,"text node cannot have empty value");return!0}function Ku(r){if(!r.length)return!0;if(r[0].type===Zr)for(const t of r){const{type:n}=t;if(n!==Zr)throw new w(y.ErrInvalidArgument,"element node and text node cannot be passed together");Wf(t)}else for(const t of r){const{type:n}=t;if(n===Zr)throw new w(y.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class To{constructor(e){c(this,"initialRoot");c(this,"context");c(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return ze.create(Ae.of(e.issueTimeTicket(),0),sp);const t=ze.create(Ae.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const n of this.initialRoot.children)mc(n,t,e);return t}getSize(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new w(y.ErrInvalidArgument,"path should not be empty");const[n,s]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),o=t?fs(t):void 0,[a]=this.tree.style([n,s],o,i);this.context.push(Qr.create(this.tree.getCreatedAt(),n,s,a,o?new Map(Object.entries(o)):new Map,i))}style(e,t,n){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),i=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=n?fs(n):void 0,[u,l]=this.tree.style([s,i],a,o);for(const h of l)this.context.registerGCPair(h);this.context.push(Qr.create(this.tree.getCreatedAt(),s,i,u,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,n){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),i=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,u]=this.tree.removeStyle([s,i],n,o);for(const l of u)this.context.registerGCPair(l);this.context.push(Qr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),s,i,a,n,o))}editInternal(e,t,n,s=0){var l;if(n.length!==0&&n[0]&&(Ku(n),n[0].type!==Zr))for(const h of n){const{children:g=[]}=h;Ku(g)}const i=this.context.getLastTimeTicket();let o=new Array;if(((l=n[0])==null?void 0:l.type)===Zr){let h="";for(const g of n){const{value:v}=g;h+=v}o.push(ze.create(Ae.of(this.context.issueTimeTicket(),0),Zr,h))}else o=n.map(h=>h&&oy(this.context,h)).filter(h=>h);const[,a,u]=this.tree.edit([e,t],o.length?o.map(h=>h==null?void 0:h.deepcopy()):void 0,s,i,()=>this.context.issueTimeTicket());for(const h of a)this.context.registerGCPair(h);return this.context.push(Zs.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,s,u,i)),!0}editByPath(e,t,n,s=0){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new w(y.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new w(y.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(i,o,n?[n]:[],s)}editBulkByPath(e,t,n,s=0){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new w(y.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new w(y.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(i,o,n,s)}edit(e,t,n,s=0){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(i,o,n?[n]:[],s)}editBulk(e,t,n,s=0){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(i,o,n,s)}toXML(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],n=this.tree.indexRangeToPosRange(t);return[n[0].toStruct(),n[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");const t=[yt.fromStruct(e[0]),yt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");const t=[yt.fromStruct(e[0]),yt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function ju(r,e){return jf(r,e)}function un(r,e){if(e){if(e instanceof le)return e;if(e instanceof Me)return jf(r,e);if(e instanceof je)return ny(r,e);if(e instanceof at)return new wo(r,e);if(e instanceof We){const t=new bo(Vt.IntegerCnt,0);return t.initialize(r,e),t}else if(e instanceof ct){const t=new To;return t.initialize(r,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function Cn(r,e){const t=un(r,e);return t instanceof le?t.getValue():t}function ro(r,e,t){let n;if(le.isSupport(e))n=le.of(e,t);else if(Array.isArray(e))n=je.create(t,de.buildArrayElements(r,e));else if(typeof e=="object")e instanceof wo?(n=at.create(gs.create(),t),e.initialize(r,n)):e instanceof bo?(n=We.create(e.getValueType(),e.getValue(),t),e.initialize(r,n)):e instanceof To?(n=ct.create(e.buildRoot(r),t),e.initialize(r,n)):n=Me.create(t,Hs.buildObjectMembers(r,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return n}const Wu=50;class ay{constructor(){c(this,"undoStack",[]);c(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Wu&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Wu&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const cy="yorkie-devtools-panel",uy="yorkie-devtools-sdk";let Yn="disconnected";const Hu=new Map,ki=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=ki);function gi(r,e){(e!=null&&e.force||Yn!=="disconnected")&&window.postMessage({source:uy,...r},"*")}function ly(r){if(!r.isEnableDevtools()||typeof window>"u"||Hu.has(r.getKey()))return;ki.set(r.getKey(),[]);const e=r.subscribe("all",t=>{t.some(n=>n.type!==Le.StatusChanged&&n.type!==Le.Snapshot&&n.type!==Le.LocalChange&&n.type!==Le.RemoteChange&&n.type!==Le.Initialized&&n.type!==Le.Watched&&n.type!==Le.Unwatched&&n.type!==Le.PresenceChanged)||(ki.get(r.getKey()).push(t),Yn==="synced"&&gi({msg:"doc::sync::partial",docKey:r.getKey(),event:t}))});Hu.set(r.getKey(),[e]),gi({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var s;if(((s=t.data)==null?void 0:s.source)!==cy)return;switch(t.data.msg){case"devtools::connect":if(Yn!=="disconnected")break;Yn="connected",gi({msg:"doc::available",docKey:r.getKey()}),z.info(`[YD] Devtools connected. Doc: ${r.getKey()}`);break;case"devtools::disconnect":Yn="disconnected",z.info(`[YD] Devtools disconnected. Doc: ${r.getKey()}`);break;case"devtools::subscribe":Yn="synced",gi({msg:"doc::sync::full",docKey:r.getKey(),events:ki.get(r.getKey())}),z.info(`[YD] Devtools subscribed. Doc: ${r.getKey()}`);break}})}var ln=(r=>(r.Detached="detached",r.Attached="attached",r.Removed="removed",r))(ln||{}),Le=(r=>(r.StatusChanged="status-changed",r.ConnectionChanged="connection-changed",r.SyncStatusChanged="sync-status-changed",r.Snapshot="snapshot",r.LocalChange="local-change",r.RemoteChange="remote-change",r.Initialized="initialized",r.Watched="watched",r.Unwatched="unwatched",r.PresenceChanged="presence-changed",r.Broadcast="broadcast",r.LocalBroadcast="local-broadcast",r))(Le||{}),ka=(r=>(r.Connected="connected",r.Disconnected="disconnected",r))(ka||{}),Ea=(r=>(r.Synced="synced",r.SyncFailed="sync-failed",r))(Ea||{});class Hf{constructor(e,t){c(this,"key");c(this,"status");c(this,"opts");c(this,"changeID");c(this,"checkpoint");c(this,"localChanges");c(this,"root");c(this,"clone");c(this,"eventStream");c(this,"eventStreamObserver");c(this,"onlineClients");c(this,"presences");c(this,"history");c(this,"internalHistory");c(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=Ws.create(),this.changeID=dp,this.checkpoint=gp,this.localChanges=[],this.eventStream=ry(n=>{this.eventStreamObserver=n}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new ay,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},ly(this)}update(e,t){if(this.getStatus()==="removed")throw new w(y.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const n=this.changeID.getActorID(),s=Xn.create(this.changeID.next(),this.clone.root,this.clone.presences.get(n)||{},t);try{const i=ju(s,this.clone.root.getObject());this.presences.has(n)||this.clone.presences.set(n,{}),this.isUpdating=!0,e(i,new Ro(s,this.clone.presences.get(n)))}catch(i){throw this.clone=void 0,i}finally{this.isUpdating=!1}if(s.hasChange()){z.isEnabled(Be.Trivial)&&z.trivial(`trying to update a local change: ${this.toJSON()}`);const i=s.getChange(),{opInfos:o,reverseOps:a}=i.execute(this.root,this.presences,se.Local),u=s.getReversePresence();u&&a.push({type:"presence",value:u}),this.localChanges.push(i),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=i.getID();const l=[];o.length>0&&l.push({type:"local-change",source:se.Local,value:{message:i.getMessage()||"",operations:o,actor:n,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:se.Local,value:{clientID:n,presence:this.getPresence(n)}}),this.publish(l),z.isEnabled(Be.Trivial)&&z.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,n,s){if(typeof e=="string"){if(typeof t!="function")throw new w(y.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type!=="initialized"&&l.type!=="watched"&&l.type!=="unwatched"&&l.type!=="presence-changed"||a(l)},n,s)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type!=="initialized"&&l.type!=="presence-changed"||l.type==="presence-changed"&&l.value.clientID!==this.changeID.getActorID()||a(l)},n,s)}if(e==="others"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type!=="watched"&&l.type!=="unwatched"&&l.type!=="presence-changed"||l.value.clientID!==this.changeID.getActorID()&&a(l)},n,s)}if(e==="connection"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="connection-changed"&&a(l)},n,s)}if(e==="status"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="status-changed"&&a(l)},n,s)}if(e==="sync"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="sync-status-changed"&&a(l)},n,s)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="local-broadcast"&&a(l)},n)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="broadcast"&&a(l)},n)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,n,s)}const i=e,o=t;return this.eventStream.subscribe(a=>{for(const u of a){if(u.type!=="local-change"&&u.type!=="remote-change")continue;const l=[];for(const h of u.value.operations)this.isSameElementOrChildOf(h.path,i)&&l.push(h);l.length&&o({...u,value:{...u.value,operations:l}})}},n,s)}if(typeof e=="function"){const i=e,o=t,a=n;return this.eventStream.subscribe(u=>{for(const l of u)l.type!=="snapshot"&&l.type!=="local-change"&&l.type!=="remote-change"||i(l)},o,a)}throw new w(y.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const n=e.split(".");return t.split(".").every((i,o)=>i===n[o])}applyChangePack(e){const t=e.hasSnapshot();for(t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),se.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();t&&this.applyChanges(this.localChanges,se.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),z.isEnabled(Be.Trivial)&&z.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:ht(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return vo.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Xn.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return ju(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,n){const{root:s,presences:i}=me.bytesToSnapshot(n);this.root=new Ws(s),this.presences=i,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.publish([{type:"snapshot",source:se.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?me.bytesToHex(n):void 0,snapshotVector:me.versionVectorToHex(t)}}])}applyChanges(e,t){z.isEnabled(Be.Debug)&&z.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),z.isEnabled(Be.Trivial)&&z.trivial(e.map(n=>`${n.getID().toTestString()} ${n.toTestString()}`).join(` -`));for(const n of e)this.applyChange(n,t);z.isEnabled(Be.Debug)&&z.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const n=[],s=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(s)){const o=e.getPresenceChange();switch(o.type){case bn.Put:n.push(this.presences.has(s)?{type:"presence-changed",source:t,value:{clientID:s,presence:o.presence}}:{type:"watched",source:se.Remote,value:{clientID:s,presence:o.presence}});break;case bn.Clear:n.push({type:"unwatched",source:se.Remote,value:{clientID:s,presence:this.getPresence(s)}}),this.removeOnlineClient(s);break}}const{opInfos:i}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),i.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;n.push(t===se.Remote?{type:"remote-change",source:t,value:{actor:s,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:o}:{type:"local-change",source:t,value:{actor:s,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:o})}n.length>0&&this.publish(n)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,n=new Set;for(const s of t)s!==this.changeID.getActorID()&&n.add(s);this.setOnlineClients(n),this.publish([{type:"initialized",source:se.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:n}=e.body.value,s=[];if(t===Mn.DOCUMENT_WATCHED)this.addOnlineClient(n),this.hasPresence(n)&&s.push({type:"watched",source:se.Remote,value:{clientID:n,presence:this.getPresence(n)}});else if(t===Mn.DOCUMENT_UNWATCHED){const i=this.getPresence(n);this.removeOnlineClient(n),i&&s.push({type:"unwatched",source:se.Remote,value:{clientID:n,presence:i}})}else if(t===Mn.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:i,payload:o}=e.body.value.body,a=new TextDecoder;s.push({type:"broadcast",value:{clientID:n,topic:i,payload:JSON.parse(a.decode(o))}})}s.length>0&&this.publish(s)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(ec),this.publish([{source:e==="removed"?se.Remote:se.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:n,snapshotVector:s}=e.value;if(!t)return;this.applySnapshot(BigInt(n),me.hexToVersionVector(s),me.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ds.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:n,presence:s}of e.value)t.add(n),this.presences.set(n,s);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:n}=e.value;this.addOnlineClient(t),this.presences.set(t,n);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:n}=e.value;this.presences.set(t,n)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new w(y.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let n=this.getRoot();for(const s of t)if(n=n[s],n===void 0)return;return n}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?ht(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?ht(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?ht(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:ht(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:ht(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,n)=>t.clientID>n.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){const n=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(n)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new w(y.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new w(y.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Xn.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof Tt)){new Ro(t,ht(this.clone.presences.get(this.changeID.getActorID()))).set(l.value,{addToHistory:!0});continue}const h=t.issueTimeTicket();l.setExecutedAt(h),t.push(l)}const n=t.getChange();n.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:s,reverseOps:i}=n.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushRedo(i),!n.hasPresenceChange()&&s.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const a=this.changeID.getActorID(),u=[];s.length>0&&u.push({type:"local-change",source:se.UndoRedo,value:{message:n.getMessage()||"",operations:s,actor:a,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&u.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(u)}redo(){if(this.isUpdating)throw new w(y.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new w(y.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Xn.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof Tt)){new Ro(t,ht(this.clone.presences.get(this.changeID.getActorID()))).set(l.value,{addToHistory:!0});continue}const h=t.issueTimeTicket();l.setExecutedAt(h),t.push(l)}const n=t.getChange();n.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:s,reverseOps:i}=n.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushUndo(i),!n.hasPresenceChange()&&s.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const a=this.changeID.getActorID(),u=[];s.length>0&&u.push({type:"local-change",source:se.UndoRedo,value:{message:n.getMessage()||"",operations:s,actor:a,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&u.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(u)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,n){const s={type:"local-broadcast",value:{topic:e,payload:t},options:n};this.publish([s])}getVersionVector(){return this.changeID.getVersionVector()}}function fy(r,e){return t=>async n=>(r&&n.header.set("x-api-key",r),e&&n.header.set("authorization",e),await t(n))}const hy="yorkie-js-sdk",dy="0.5.4",gy="Yorkie JS SDK",my="./src/yorkie.ts",py={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},yy=["dist"],vy={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},wy={node:">=18.0.0",npm:">=7.1.0"},by={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},Ty={name:"hackerwins",email:"susukang98@gmail.com"},Ay="Apache-2.0",Iy={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},Sy="https://github.com/yorkie-team/yorkie-js-sdk#readme",xy={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},ky={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Gu={name:hy,version:dy,description:gy,main:my,publishConfig:py,files:yy,scripts:vy,engines:wy,repository:by,author:Ty,license:Ay,bugs:Iy,homepage:Sy,devDependencies:xy,dependencies:ky};function Ey(){return r=>async e=>(e.header.set("x-yorkie-user-agent",Gu.name+"/"+Gu.version),await r(e))}const Cy=r=>{try{if(JSON.stringify(r)===void 0)return!1}catch{return!1}return!0};var Ei=(r=>(r.Manual="manual",r.Realtime="realtime",r.RealtimePushOnly="realtime-pushonly",r.RealtimeSyncOff="realtime-syncoff",r))(Ei||{});const mi={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Mo={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Gf{constructor(e,t){c(this,"id");c(this,"key");c(this,"status");c(this,"attachmentMap");c(this,"apiKey");c(this,"conditions");c(this,"syncLoopDuration");c(this,"reconnectStreamDelay");c(this,"retrySyncLoopDelay");c(this,"rpcClient");c(this,"taskQueue");c(this,"processing",!1);t=t||mi,this.key=t.key?t.key:Kf(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||mi.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||mi.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||mi.retrySyncLoopDelay,this.rpcClient=Sm(Hm,Wm({baseUrl:e,interceptors:[fy(t.apiKey,t.token),Ey()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),z.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw z.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),z.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw z.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==ln.Detached)throw new w(y.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((i,o)=>o.set(t.initialPresence||{}));const n=e.subscribe("local-broadcast",async i=>{var h;const{topic:o,payload:a}=i.value,u=(h=i.options)==null?void 0:h.error,l=i.options;try{await this.broadcast(e.getKey(),o,a,l)}catch(g){g instanceof Error&&(u==null||u(g))}}),s=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:me.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async i=>{const o=me.fromChangePack(i.changePack);if(e.applyChangePack(o),e.getStatus()===ln.Removed)return e;e.applyStatus(ln.Attached),this.attachmentMap.set(e.getKey(),new ey(this.reconnectStreamDelay,e,i.documentId,s,n)),s!=="manual"&&await this.runWatchLoop(e.getKey()),z.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const u=t.initialRoot;e.update(l=>{for(const[h,g]of Object.entries(u))if(!a.has(h)){const v=h;l[v]=g}})}return e}).catch(i=>{throw z.error(`[AD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}detach(e,t={}){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new w(y.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((s,i)=>i.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:n.docID,changePack:me.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=me.fromChangePack(s.changePack);return e.applyChangePack(i),e.getStatus()!==ln.Removed&&e.applyStatus(ln.Detached),this.detachInternal(e.getKey()),z.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(s=>{throw z.error(`[DD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}async changeSyncMode(e,t){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new w(y.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const s=n.syncMode;return s===t?e:(n.changeSyncMode(t),t==="manual"?(n.cancelWatchStream(),e):(t==="realtime"&&(n.remoteChangeEventReceived=!0),s==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new w(y.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(n=>{throw z.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n}))}return this.enqueueTask(async()=>{const t=[];for(const[,n]of this.attachmentMap)t.push(this.syncInternal(n,n.syncMode));return Promise.all(t).catch(n=>{throw z.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n})})}remove(e){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new w(y.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const n=me.toChangePack(e.createChangePack());return n.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:n},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=me.fromChangePack(s.changePack);e.applyChangePack(i),this.detachInternal(e.getKey()),z.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(s=>{throw z.error(`[RD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,n,s){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e);if(!i)throw new w(y.ErrDocumentNotAttached,`${e} is not attached`);if(!Cy(n))throw new w(y.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??Mo.maxRetries,a=Mo.maxBackoff;let u=0;const l=g=>Math.min(Mo.initialRetryInterval*2**g,a),h=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:i.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(n))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{z.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(g=>{if(z.error(`[BC] c:"${this.getKey()}" err:`,g),this.handleConnectError(g))if(uh(),l(u-1)),z.info(`[BC] c:"${this.getKey()}" retry attempt ${u}/${o}`);else throw z.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),g;else throw g}));return h()}runSyncLoop(){const e=()=>{if(!this.isActive()){z.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,n]of this.attachmentMap)n.needRealtimeSync()&&(n.remoteChangeEventReceived=!1,t.push(this.syncInternal(n,n.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(n=>{z.error(`[SL] c:"${this.getKey()}" sync failed:`,n),this.handleConnectError(n)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};z.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new w(y.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(n=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new w(y.ErrClientNotActivated,`${this.key} is not active`));const s=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:s.signal});return t.doc.publish([{type:Le.ConnectionChanged,value:ka.Connected}]),z.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const l of i)this.handleWatchDocumentsResponse(t,l),l.body.case==="initialization"&&o([i,s])}catch(l){t.doc.resetOnlineClients(),t.doc.publish([{type:Le.Initialized,source:se.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Le.ConnectionChanged,value:ka.Disconnected}]),z.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(l)?n():this.conditions.WatchLoop=!1,a(l)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===Mn.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(ln.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:n,docID:s}=e,i=n.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:s,changePack:me.toChangePack(i),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${n.getKey()}`}}).then(o=>{const a=me.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return n;n.applyChangePack(a),e.doc.publish([{type:Le.SyncStatusChanged,value:Ea.Synced}]),n.getStatus()===ln.Removed&&this.detachInternal(n.getKey());const u=n.getKey(),l=a.getChangeSize();return z.info(`[PP] c:"${this.getKey()}" sync d:"${u}", push:${i.getChangeSize()} pull:${l} cp:${a.getCheckpoint().toTestString()}`),n}).catch(o=>{throw n.publish([{type:Le.SyncStatusChanged,value:Ea.SyncFailed}]),z.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof we?e.code===te.Canceled||e.code===te.Unknown||e.code===te.ResourceExhausted||e.code===te.Unavailable?!0:((zu(e)===y.ErrClientNotActivated||zu(e)===y.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,n)=>{this.taskQueue.push(()=>e().then(t).catch(n)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{z.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Yf={Client:Gf,Document:Hf,Primitive:le,Text:wo,Counter:bo,Tree:To,LogLevel:Be,setLogLevel:zf,IntType:Vt.IntegerCnt,LongType:Vt.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Gf,Document:Hf,Primitive:le,Text:wo,Counter:bo,Tree:To,LogLevel:Be,setLogLevel:zf,IntType:Vt.IntegerCnt,LongType:Vt.LongCnt});const Ny=(r,e)=>{const t=r.__vccOpts||r;for(const[n,s]of e)t[n]=s;return t},Py=[{title:"Todo",cards:[{title:"Pruning document"},{title:"Clean up codes"}]},{title:"Doing",cards:[{title:"Array operations"}]},{title:"Done",cards:[{title:"Create a sample page"},{title:"Launch demo site"}]}],cn=new Yf.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),Wt=new Yf.Document(`vuejs-kanban-${new Date().toISOString().substring(0,10).replace(/-/g,"")}`,{enableDevtools:!0}),Oy={data(){return{lists:[],title:"",opened:null}},created(){this.fetchDoc()},beforeUnmount(){this.disconnect()},watch:{opened(r){this.$nextTick(function(){r===0?this.$refs.addListForm.querySelector("input").focus():r&&this.$refs.addCardForm[r-1].querySelector("input").focus(),this.title=""})}},methods:{async fetchDoc(){await cn.activate(),await cn.attach(Wt),Wt.update(r=>{r.lists||(r.lists=Py)},"create default list if not exists"),Wt.subscribe(r=>{this.lists=Wt.getRoot().lists}),await cn.sync(),this.lists=Wt.getRoot().lists},async disconnect(){await cn.deactivate()},isOpened(r){return this.opened===r},openForm(r){this.opened=r},closeForm(){this.opened=null},addCard(r){this.title!==""&&Wt.update(e=>{e.lists.getElementByID(r.getID()).cards.push({title:this.title}),this.title=""},`add new card by ${cn.getID()}`)},deleteCard(r,e){Wt.update(t=>{t.lists.getElementByID(r.getID()).cards.deleteByID(e.getID())},`delete a card by ${cn.getID()}`)},addList(){this.title!==""&&Wt.update(r=>{r.lists.push({title:this.title,cards:[]}),this.title=""},`add new list by ${cn.getID()}`)},deleteList(r){Wt.update(e=>{e.lists.deleteByID(r.getID())},`delete a list by ${cn.getID()}`)}}},Dy={class:"list"},By=["onClick"],Ry={class:"title"},Fy={class:"card"},Ly=["onClick"],Jy={key:0,class:"add-form"},My=["onKeyup"],$y={class:"buttons"},Uy=["onClick"],qy=["onClick"],Vy={class:"add-list",ref:"addListForm"},zy={key:0,class:"add-form"},Ky={class:"buttons"};function jy(r,e,t,n,s,i){return Kt(),jt(Ge,null,[(Kt(!0),jt(Ge,null,Lc(s.lists,(o,a)=>(Kt(),jt("div",Dy,[Oe("span",{class:"delete",onClick:u=>i.deleteList(o)},"❌",8,By),Oe("div",Ry,xc(o.title),1),(Kt(!0),jt(Ge,null,Lc(o.cards,u=>(Kt(),jt("div",Fy,[Oe("span",{class:"delete",onClick:l=>i.deleteCard(o,u)},"❌",8,Ly),Ll(" "+xc(u.title),1)]))),256)),Oe("div",{class:"add-card",ref_for:!0,ref:"addCardForm"},[i.isOpened(a+1)?(Kt(),jt("div",Jy,[Fc(Oe("input",{type:"text",placeholder:"Enter card title","onUpdate:modelValue":e[0]||(e[0]=u=>s.title=u),onKeyup:[ui(u=>i.addCard(o),["enter"]),e[1]||(e[1]=ui(u=>i.closeForm(),["esc"]))]},null,40,My),[[nu,s.title]]),Oe("div",$y,[Oe("input",{type:"button",value:"Add",onClick:u=>i.addCard(o)},null,8,Uy),Oe("input",{type:"button",value:"Close",class:"pull-right",onClick:e[2]||(e[2]=u=>i.closeForm())})])])):(Kt(),jt("div",{key:1,class:"add-card-opener",onClick:u=>i.openForm(a+1)}," Add another card ",8,qy))],512)]))),256)),Oe("div",Vy,[i.isOpened(0)?(Kt(),jt("div",zy,[Fc(Oe("input",{type:"text",placeholder:"Enter list title","onUpdate:modelValue":e[3]||(e[3]=o=>s.title=o),onKeyup:[e[4]||(e[4]=ui(o=>i.addList(),["enter"])),e[5]||(e[5]=ui(o=>i.closeForm(),["esc"]))]},null,544),[[nu,s.title]]),Oe("div",Ky,[Oe("input",{type:"button",value:"Add",onClick:e[6]||(e[6]=o=>i.addList())}),Oe("input",{type:"button",value:"Close",class:"pull-right",onClick:e[7]||(e[7]=o=>i.closeForm())})])])):(Kt(),jt("div",{key:1,class:"add-list-opener",onClick:e[8]||(e[8]=o=>i.openForm(0))}," Add another list "))],512)],64)}const Wy=Ny(Oy,[["render",jy]]);Sg(Wy).mount("#app"); +`));for(const n of e)this.applyChange(n,t);z.isEnabled(Be.Debug)&&z.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const n=[],s=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(s)){const o=e.getPresenceChange();switch(o.type){case bn.Put:n.push(this.presences.has(s)?{type:"presence-changed",source:t,value:{clientID:s,presence:o.presence}}:{type:"watched",source:se.Remote,value:{clientID:s,presence:o.presence}});break;case bn.Clear:n.push({type:"unwatched",source:se.Remote,value:{clientID:s,presence:this.getPresence(s)}}),this.removeOnlineClient(s);break}}const{opInfos:i}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),i.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;n.push(t===se.Remote?{type:"remote-change",source:t,value:{actor:s,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:o}:{type:"local-change",source:t,value:{actor:s,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:o})}n.length>0&&this.publish(n)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,n=new Set;for(const s of t)s!==this.changeID.getActorID()&&n.add(s);this.setOnlineClients(n),this.publish([{type:"initialized",source:se.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:n}=e.body.value,s=[];if(t===Mn.DOCUMENT_WATCHED){if(this.onlineClients.has(n)&&this.hasPresence(n))return;this.addOnlineClient(n),this.hasPresence(n)&&s.push({type:"watched",source:se.Remote,value:{clientID:n,presence:this.getPresence(n)}})}else if(t===Mn.DOCUMENT_UNWATCHED){const i=this.getPresence(n);this.removeOnlineClient(n),i&&s.push({type:"unwatched",source:se.Remote,value:{clientID:n,presence:i}})}else if(t===Mn.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:i,payload:o}=e.body.value.body,a=new TextDecoder;s.push({type:"broadcast",value:{clientID:n,topic:i,payload:JSON.parse(a.decode(o))}})}s.length>0&&this.publish(s)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(ec),this.publish([{source:e==="removed"?se.Remote:se.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:n,snapshotVector:s}=e.value;if(!t)return;this.applySnapshot(BigInt(n),me.hexToVersionVector(s),me.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ds.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:n,presence:s}of e.value)t.add(n),this.presences.set(n,s);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:n}=e.value;this.addOnlineClient(t),this.presences.set(t,n);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:n}=e.value;this.presences.set(t,n)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new w(y.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let n=this.getRoot();for(const s of t)if(n=n[s],n===void 0)return;return n}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?ht(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?ht(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?ht(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:ht(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:ht(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,n)=>t.clientID>n.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){const n=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(n)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new w(y.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new w(y.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Xn.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof Tt)){new Ro(t,ht(this.clone.presences.get(this.changeID.getActorID()))).set(l.value,{addToHistory:!0});continue}const h=t.issueTimeTicket();l.setExecutedAt(h),t.push(l)}const n=t.getChange();n.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:s,reverseOps:i}=n.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushRedo(i),!n.hasPresenceChange()&&s.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const a=this.changeID.getActorID(),u=[];s.length>0&&u.push({type:"local-change",source:se.UndoRedo,value:{message:n.getMessage()||"",operations:s,actor:a,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&u.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(u)}redo(){if(this.isUpdating)throw new w(y.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new w(y.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Xn.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof Tt)){new Ro(t,ht(this.clone.presences.get(this.changeID.getActorID()))).set(l.value,{addToHistory:!0});continue}const h=t.issueTimeTicket();l.setExecutedAt(h),t.push(l)}const n=t.getChange();n.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:s,reverseOps:i}=n.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushUndo(i),!n.hasPresenceChange()&&s.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const a=this.changeID.getActorID(),u=[];s.length>0&&u.push({type:"local-change",source:se.UndoRedo,value:{message:n.getMessage()||"",operations:s,actor:a,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&u.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(u)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,n){const s={type:"local-broadcast",value:{topic:e,payload:t},options:n};this.publish([s])}getVersionVector(){return this.changeID.getVersionVector()}}function fy(r,e){return t=>async n=>(r&&n.header.set("x-api-key",r),e&&n.header.set("authorization",e),await t(n))}const hy="yorkie-js-sdk",dy="0.5.4",gy="Yorkie JS SDK",my="./src/yorkie.ts",py={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},yy=["dist"],vy={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},wy={node:">=18.0.0",npm:">=7.1.0"},by={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},Ty={name:"hackerwins",email:"susukang98@gmail.com"},Ay="Apache-2.0",Iy={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},Sy="https://github.com/yorkie-team/yorkie-js-sdk#readme",xy={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},ky={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Gu={name:hy,version:dy,description:gy,main:my,publishConfig:py,files:yy,scripts:vy,engines:wy,repository:by,author:Ty,license:Ay,bugs:Iy,homepage:Sy,devDependencies:xy,dependencies:ky};function Ey(){return r=>async e=>(e.header.set("x-yorkie-user-agent",Gu.name+"/"+Gu.version),await r(e))}const Cy=r=>{try{if(JSON.stringify(r)===void 0)return!1}catch{return!1}return!0};var Ei=(r=>(r.Manual="manual",r.Realtime="realtime",r.RealtimePushOnly="realtime-pushonly",r.RealtimeSyncOff="realtime-syncoff",r))(Ei||{});const mi={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Mo={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Gf{constructor(e,t){c(this,"id");c(this,"key");c(this,"status");c(this,"attachmentMap");c(this,"apiKey");c(this,"conditions");c(this,"syncLoopDuration");c(this,"reconnectStreamDelay");c(this,"retrySyncLoopDelay");c(this,"rpcClient");c(this,"taskQueue");c(this,"processing",!1);t=t||mi,this.key=t.key?t.key:Kf(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||mi.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||mi.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||mi.retrySyncLoopDelay,this.rpcClient=Sm(Hm,Wm({baseUrl:e,interceptors:[fy(t.apiKey,t.token),Ey()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),z.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw z.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),z.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw z.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==ln.Detached)throw new w(y.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((i,o)=>o.set(t.initialPresence||{}));const n=e.subscribe("local-broadcast",async i=>{var h;const{topic:o,payload:a}=i.value,u=(h=i.options)==null?void 0:h.error,l=i.options;try{await this.broadcast(e.getKey(),o,a,l)}catch(g){g instanceof Error&&(u==null||u(g))}}),s=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:me.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async i=>{const o=me.fromChangePack(i.changePack);if(e.applyChangePack(o),e.getStatus()===ln.Removed)return e;e.applyStatus(ln.Attached),this.attachmentMap.set(e.getKey(),new ey(this.reconnectStreamDelay,e,i.documentId,s,n)),s!=="manual"&&await this.runWatchLoop(e.getKey()),z.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const u=t.initialRoot;e.update(l=>{for(const[h,g]of Object.entries(u))if(!a.has(h)){const v=h;l[v]=g}})}return e}).catch(i=>{throw z.error(`[AD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}detach(e,t={}){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new w(y.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((s,i)=>i.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:n.docID,changePack:me.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=me.fromChangePack(s.changePack);return e.applyChangePack(i),e.getStatus()!==ln.Removed&&e.applyStatus(ln.Detached),this.detachInternal(e.getKey()),z.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(s=>{throw z.error(`[DD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}async changeSyncMode(e,t){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new w(y.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const s=n.syncMode;return s===t?e:(n.changeSyncMode(t),t==="manual"?(n.cancelWatchStream(),e):(t==="realtime"&&(n.remoteChangeEventReceived=!0),s==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new w(y.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(n=>{throw z.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n}))}return this.enqueueTask(async()=>{const t=[];for(const[,n]of this.attachmentMap)t.push(this.syncInternal(n,n.syncMode));return Promise.all(t).catch(n=>{throw z.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n})})}remove(e){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new w(y.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const n=me.toChangePack(e.createChangePack());return n.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:n},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=me.fromChangePack(s.changePack);e.applyChangePack(i),this.detachInternal(e.getKey()),z.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(s=>{throw z.error(`[RD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,n,s){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e);if(!i)throw new w(y.ErrDocumentNotAttached,`${e} is not attached`);if(!Cy(n))throw new w(y.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??Mo.maxRetries,a=Mo.maxBackoff;let u=0;const l=g=>Math.min(Mo.initialRetryInterval*2**g,a),h=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:i.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(n))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{z.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(g=>{if(z.error(`[BC] c:"${this.getKey()}" err:`,g),this.handleConnectError(g))if(uh(),l(u-1)),z.info(`[BC] c:"${this.getKey()}" retry attempt ${u}/${o}`);else throw z.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),g;else throw g}));return h()}runSyncLoop(){const e=()=>{if(!this.isActive()){z.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,n]of this.attachmentMap)n.needRealtimeSync()&&(n.remoteChangeEventReceived=!1,t.push(this.syncInternal(n,n.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(n=>{z.error(`[SL] c:"${this.getKey()}" sync failed:`,n),this.handleConnectError(n)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};z.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new w(y.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(n=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new w(y.ErrClientNotActivated,`${this.key} is not active`));const s=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:s.signal});return t.doc.publish([{type:Le.ConnectionChanged,value:ka.Connected}]),z.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const l of i)this.handleWatchDocumentsResponse(t,l),l.body.case==="initialization"&&o([i,s])}catch(l){t.doc.resetOnlineClients(),t.doc.publish([{type:Le.Initialized,source:se.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Le.ConnectionChanged,value:ka.Disconnected}]),z.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(l)?n():this.conditions.WatchLoop=!1,a(l)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===Mn.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(ln.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:n,docID:s}=e,i=n.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:s,changePack:me.toChangePack(i),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${n.getKey()}`}}).then(o=>{const a=me.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return n;n.applyChangePack(a),e.doc.publish([{type:Le.SyncStatusChanged,value:Ea.Synced}]),n.getStatus()===ln.Removed&&this.detachInternal(n.getKey());const u=n.getKey(),l=a.getChangeSize();return z.info(`[PP] c:"${this.getKey()}" sync d:"${u}", push:${i.getChangeSize()} pull:${l} cp:${a.getCheckpoint().toTestString()}`),n}).catch(o=>{throw n.publish([{type:Le.SyncStatusChanged,value:Ea.SyncFailed}]),z.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof we?e.code===te.Canceled||e.code===te.Unknown||e.code===te.ResourceExhausted||e.code===te.Unavailable?!0:((zu(e)===y.ErrClientNotActivated||zu(e)===y.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,n)=>{this.taskQueue.push(()=>e().then(t).catch(n)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{z.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Yf={Client:Gf,Document:Hf,Primitive:le,Text:wo,Counter:bo,Tree:To,LogLevel:Be,setLogLevel:zf,IntType:Vt.IntegerCnt,LongType:Vt.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Gf,Document:Hf,Primitive:le,Text:wo,Counter:bo,Tree:To,LogLevel:Be,setLogLevel:zf,IntType:Vt.IntegerCnt,LongType:Vt.LongCnt});const Ny=(r,e)=>{const t=r.__vccOpts||r;for(const[n,s]of e)t[n]=s;return t},Py=[{title:"Todo",cards:[{title:"Pruning document"},{title:"Clean up codes"}]},{title:"Doing",cards:[{title:"Array operations"}]},{title:"Done",cards:[{title:"Create a sample page"},{title:"Launch demo site"}]}],cn=new Yf.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),Wt=new Yf.Document(`vuejs-kanban-${new Date().toISOString().substring(0,10).replace(/-/g,"")}`,{enableDevtools:!0}),Oy={data(){return{lists:[],title:"",opened:null}},created(){this.fetchDoc()},beforeUnmount(){this.disconnect()},watch:{opened(r){this.$nextTick(function(){r===0?this.$refs.addListForm.querySelector("input").focus():r&&this.$refs.addCardForm[r-1].querySelector("input").focus(),this.title=""})}},methods:{async fetchDoc(){await cn.activate(),await cn.attach(Wt),Wt.update(r=>{r.lists||(r.lists=Py)},"create default list if not exists"),Wt.subscribe(r=>{this.lists=Wt.getRoot().lists}),await cn.sync(),this.lists=Wt.getRoot().lists},async disconnect(){await cn.deactivate()},isOpened(r){return this.opened===r},openForm(r){this.opened=r},closeForm(){this.opened=null},addCard(r){this.title!==""&&Wt.update(e=>{e.lists.getElementByID(r.getID()).cards.push({title:this.title}),this.title=""},`add new card by ${cn.getID()}`)},deleteCard(r,e){Wt.update(t=>{t.lists.getElementByID(r.getID()).cards.deleteByID(e.getID())},`delete a card by ${cn.getID()}`)},addList(){this.title!==""&&Wt.update(r=>{r.lists.push({title:this.title,cards:[]}),this.title=""},`add new list by ${cn.getID()}`)},deleteList(r){Wt.update(e=>{e.lists.deleteByID(r.getID())},`delete a list by ${cn.getID()}`)}}},Dy={class:"list"},By=["onClick"],Ry={class:"title"},Fy={class:"card"},Ly=["onClick"],Jy={key:0,class:"add-form"},My=["onKeyup"],$y={class:"buttons"},Uy=["onClick"],qy=["onClick"],Vy={class:"add-list",ref:"addListForm"},zy={key:0,class:"add-form"},Ky={class:"buttons"};function jy(r,e,t,n,s,i){return Kt(),jt(Ge,null,[(Kt(!0),jt(Ge,null,Lc(s.lists,(o,a)=>(Kt(),jt("div",Dy,[Oe("span",{class:"delete",onClick:u=>i.deleteList(o)},"❌",8,By),Oe("div",Ry,xc(o.title),1),(Kt(!0),jt(Ge,null,Lc(o.cards,u=>(Kt(),jt("div",Fy,[Oe("span",{class:"delete",onClick:l=>i.deleteCard(o,u)},"❌",8,Ly),Ll(" "+xc(u.title),1)]))),256)),Oe("div",{class:"add-card",ref_for:!0,ref:"addCardForm"},[i.isOpened(a+1)?(Kt(),jt("div",Jy,[Fc(Oe("input",{type:"text",placeholder:"Enter card title","onUpdate:modelValue":e[0]||(e[0]=u=>s.title=u),onKeyup:[ui(u=>i.addCard(o),["enter"]),e[1]||(e[1]=ui(u=>i.closeForm(),["esc"]))]},null,40,My),[[nu,s.title]]),Oe("div",$y,[Oe("input",{type:"button",value:"Add",onClick:u=>i.addCard(o)},null,8,Uy),Oe("input",{type:"button",value:"Close",class:"pull-right",onClick:e[2]||(e[2]=u=>i.closeForm())})])])):(Kt(),jt("div",{key:1,class:"add-card-opener",onClick:u=>i.openForm(a+1)}," Add another card ",8,qy))],512)]))),256)),Oe("div",Vy,[i.isOpened(0)?(Kt(),jt("div",zy,[Fc(Oe("input",{type:"text",placeholder:"Enter list title","onUpdate:modelValue":e[3]||(e[3]=o=>s.title=o),onKeyup:[e[4]||(e[4]=ui(o=>i.addList(),["enter"])),e[5]||(e[5]=ui(o=>i.closeForm(),["esc"]))]},null,544),[[nu,s.title]]),Oe("div",Ky,[Oe("input",{type:"button",value:"Add",onClick:e[6]||(e[6]=o=>i.addList())}),Oe("input",{type:"button",value:"Close",class:"pull-right",onClick:e[7]||(e[7]=o=>i.closeForm())})])])):(Kt(),jt("div",{key:1,class:"add-list-opener",onClick:e[8]||(e[8]=o=>i.openForm(0))}," Add another list "))],512)],64)}const Wy=Ny(Oy,[["render",jy]]);Sg(Wy).mount("#app"); diff --git a/examples/vuejs-kanban/index.html b/examples/vuejs-kanban/index.html index 0e9fd7624..2c44af08a 100644 --- a/examples/vuejs-kanban/index.html +++ b/examples/vuejs-kanban/index.html @@ -6,7 +6,7 @@ Vite App - +